diff --git a/NOTICE.md b/NOTICE.md index 3756afa..0ac0a7c 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -5,7 +5,7 @@ License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own cod only and is separate from the portable runtime bundle it invokes as an external child process. Compatibility patches in the runtime repository are licensed under terms compatible with their target upstream projects (see [runtime patch -licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)). +licenses](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)). The Reims-Go desktop executable also incorporates open-source Go and frontend libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x` diff --git a/README.md b/README.md index c735e32..83da74e 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
Build from source -With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu). +With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
diff --git a/README.zh-CN.md b/README.zh-CN.md index b044bfe..93b42d0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -117,7 +117,7 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
从源码构建 -需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 单独构建。 +需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
diff --git a/changes/runtime-releases-repo.json b/changes/runtime-releases-repo.json new file mode 100644 index 0000000..e5a863d --- /dev/null +++ b/changes/runtime-releases-repo.json @@ -0,0 +1,9 @@ +{ + "group": "improvements", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。", + "en": "Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`." +} diff --git a/changes/segmented-highlight.json b/changes/segmented-highlight.json new file mode 100644 index 0000000..c99b673 --- /dev/null +++ b/changes/segmented-highlight.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。", + "en": "Keep the highlight on the current option of a segmented control after it was briefly disabled while saving." +} diff --git a/changes/start-failure-log-lines.json b/changes/start-failure-log-lines.json new file mode 100644 index 0000000..5b348e9 --- /dev/null +++ b/changes/start-failure-log-lines.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。", + "en": "Include Guest Tools and network log lines when a VM fails to start from the command line." +} diff --git a/changes/theme-sounds-removed.json b/changes/theme-sounds-removed.json new file mode 100644 index 0000000..897579c --- /dev/null +++ b/changes/theme-sounds-removed.json @@ -0,0 +1,9 @@ +{ + "group": "removals", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。", + "en": "Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds." +} diff --git a/changes/vm-name-details.json b/changes/vm-name-details.json new file mode 100644 index 0000000..aa38c13 --- /dev/null +++ b/changes/vm-name-details.json @@ -0,0 +1,9 @@ +{ + "group": "fixes", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。", + "en": "Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off." +} diff --git a/cmd/i18ngen/main.go b/cmd/i18ngen/main.go index 94bb026..76c1c9f 100644 --- a/cmd/i18ngen/main.go +++ b/cmd/i18ngen/main.go @@ -24,10 +24,9 @@ import ( ) var ( - allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} - goDomains = []string{"native", "macos-glossary", "core"} - feEagerDomains = []string{"core", "vm"} - feLazyDomains = []string{"wizard", "settings", "plugins"} + allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} + goDomains = []string{"native", "macos-glossary", "core"} + feLazyDomains = []string{"wizard", "settings", "plugins"} ) type parsedEntry struct { diff --git a/docs/architecture.md b/docs/architecture.md index ae08ef7..4caff99 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -99,6 +99,18 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主核心通过通用驱动路由与扩展接口调用。代码库通过双向架构边界测试锁死跨界依赖白名单,任何新增跨界引用或白名单条目失效都会令测试失败,确保耦合范围只减不增。 +### 唯一入口与自动检查 + +以下事项各有一个唯一入口,对应的测试会拒绝绕开入口的新代码。Go 检查位于 `internal/archtest/`,前端检查位于 `frontend/scripts/`。 + +| 事项 | 唯一入口 | 检查 | +| :--- | :--- | :--- | +| 整体替换小文件 | `internal/atomicfile` | `file_replace_test.go` | +| 向界面发送事件 | 后端 `App.emit`,前端 `wails.ts` | `events_test.go` | +| 界面调用后端 | `App` 的导出方法,修改后重新生成 `frontend/wailsjs` | `bindings_test.go` | + +测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。 + ## 便携运行时与跨仓边界 便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 9226a51..2128da9 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -52,7 +52,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V ## 主题、面板桥接与契约演进 -宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标、品牌标志与事件提示音;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。 +宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标与品牌标志;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口,提示音也由交互脚本自行播放。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。 已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index dbee270..bde5a12 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -10,12 +10,12 @@ | :--- | :--- | :--- | | 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 | | 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 | -| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 | +| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 的实际构建提交为准。 | | QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 | | 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 | | 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 | | 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 | -| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 | +| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 | 同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。 diff --git a/frontend/package.json b/frontend/package.json index 3fbcfb8..4e454cc 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-hypervisor.mjs", + "test": "node --test --test-concurrency=2 \"scripts/test-*.mjs\"", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 52b22cf..fcd240b 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -20,79 +20,63 @@ function walkFiles(dir, exts) { return out } -test('lazy i18n domain keys are always backed by domain .gen imports', () => { +/** Static imports and dynamic import() targets of a source file, as absolute paths. */ +function importsOf(file) { + const src = fs.readFileSync(file, 'utf8') + const resolve = (spec) => { + const target = path.resolve(path.dirname(file), spec) + return ['', '.ts', '.tsx', '/index.ts', '/index.tsx'].map((ext) => target + ext).find((p) => fs.existsSync(p) && fs.statSync(p).isFile()) + } + const collect = (re) => [...src.matchAll(re)].map((m) => resolve(m[1])).filter((p) => p && /\.tsx?$/.test(p)) + return { + eager: collect(/^(?:import(?! type\b)|export)\b[^'"]*?['"](\.[^'"]+)['"]/gm), + lazy: collect(/\bimport\(\s*['"](\.[^'"]+)['"]\s*\)/g), + } +} + +/** Every module loaded together with entry. */ +function loadedWith(entry, imports) { + const seen = new Set([entry]) + for (const file of seen) for (const next of imports.get(file)?.eager ?? []) seen.add(next) + return seen +} + +test('every chunk registers the lazy i18n domains its keys belong to', () => { const lazyDomains = ['wizard', 'settings', 'plugins'] const keyToDomain = new Map() - for (const dom of ['core', 'vm', ...lazyDomains]) { + for (const dom of lazyDomains) { const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8')) - for (const k of Object.keys(raw)) { - if (!k.startsWith('$')) keyToDomain.set(k, dom) - } + for (const k of Object.keys(raw)) keyToDomain.set(k, dom) } + const files = walkFiles(srcDir, ['.ts', '.tsx']) + const imports = new Map(files.map((file) => [file, importsOf(file)])) + const entries = new Set([path.join(srcDir, 'main.tsx'), ...[...imports.values()].flatMap((i) => i.lazy)]) + assert.ok(entries.size > 5, 'found no lazy chunks: the import patterns no longer match') - // Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx) - const lazyEntryBasenames = new Set([ - 'CreateWizard.tsx', - 'SettingsModal.tsx', - // 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。 - 'VMNetworkSettings.tsx', - // 由新建向导和网络设置两个延迟入口共用。 - 'NpcapDependency.tsx', - 'AffinityDialog.tsx', - 'Setup.tsx', - 'RuntimeOnline.tsx', - 'HostView.tsx', - 'ImagesPage.tsx', - 'InstallersPage.tsx', - 'PluginsPage.tsx', - 'PluginMarket.tsx', - 'PluginParts.tsx', - 'AppSettingsPage.tsx', - 'AboutPage.tsx', - 'PluginPanelFrame.tsx', - 'SchemaForm.tsx', - 'optimizations.ts', - // 仅由延迟加载的 AppSettingsPage、HostView、Setup 共用,自带 settings.gen 域注册。 - 'hypervisor.ts', - ]) - - for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) { - const rel = path.relative(srcDir, file).replace(/\\/g, '/') - if (rel.startsWith('i18n/')) continue - const base = path.basename(file) - const src = fs.readFileSync(file, 'utf8') - - // Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key' - const referencedLazyDomains = new Set() - const callMatches = [ - ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), - ...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), - ] - for (const m of callMatches) { - const dom = keyToDomain.get(m[1]) - if (dom && lazyDomains.includes(dom)) { - referencedLazyDomains.add(`${dom}:${m[1]}`) + for (const entry of entries) { + const modules = [...loadedWith(entry, imports)].filter((file) => !path.relative(srcDir, file).startsWith('i18n')) + const registered = new Set() + for (const file of modules) { + for (const m of fs.readFileSync(file, 'utf8').matchAll(/i18n\/domains\/(\w+)\.gen/g)) registered.add(m[1]) + } + for (const file of modules) { + const src = fs.readFileSync(file, 'utf8') + const keys = [ + ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), + ...src.matchAll(/\b(?:label|labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), + ].map((m) => m[1]) + for (const key of keys) { + const dom = keyToDomain.get(key) + assert.ok( + !dom || registered.has(dom), + `${path.relative(srcDir, file)} uses ${dom} key "${key}", but the chunk of ${path.relative(srcDir, entry)} never imports i18n/domains/${dom}.gen`, + ) } } - - if (referencedLazyDomains.size === 0) continue - - assert.ok( - lazyEntryBasenames.has(base), - `Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`, - ) - - for (const item of referencedLazyDomains) { - const [dom, key] = item.split(':') - // Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration - if (base === 'AffinityDialog.tsx' && dom === 'settings') continue - if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue - assert.match( - src, - new RegExp(`i18n/domains/${dom}\\.gen`), - `Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`, - ) - } + } + const eager = loadedWith(path.join(srcDir, 'main.tsx'), imports) + for (const dom of lazyDomains) { + assert.ok(!eager.has(path.join(srcDir, 'i18n', 'domains', `${dom}.gen.ts`)), `the ${dom} texts must not load with the main window`) } }) diff --git a/frontend/scripts/test-import-cycles.mjs b/frontend/scripts/test-import-cycles.mjs new file mode 100644 index 0000000..bc050a0 --- /dev/null +++ b/frontend/scripts/test-import-cycles.mjs @@ -0,0 +1,45 @@ +// Rejects import cycles in src/, type imports included: two files that import +// each other are one module split in the wrong place. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import ts from 'typescript' + +const src = path.resolve(import.meta.dirname, '..', 'src') +const rel = (file) => path.relative(src, file).split(path.sep).join('/') + +function importGraph() { + const files = fs.readdirSync(src, { recursive: true }) + .filter((name) => /\.tsx?$/.test(name)) + .map((name) => path.join(src, name)) + const known = new Set(files) + return new Map(files.map((file) => { + const { importedFiles } = ts.preProcessFile(fs.readFileSync(file, 'utf8'), true, true) + const targets = importedFiles + .filter(({ fileName }) => fileName.startsWith('.')) + .map(({ fileName }) => path.resolve(path.dirname(file), fileName)) + .map((base) => ['', '.ts', '.tsx', `${path.sep}index.ts`].map((ext) => base + ext).find((p) => known.has(p))) + .filter(Boolean) + return [file, targets] + })) +} + +test('source modules do not import each other in a cycle', () => { + const graph = importGraph() + assert.ok(graph.size > 50, `expected to scan src/, found ${graph.size} files`) + const done = new Set() + const cycles = [] + const visit = (file, trail) => { + const start = trail.indexOf(file) + if (start >= 0) { + cycles.push([...trail.slice(start), file].map(rel).join(' -> ')) + return + } + if (done.has(file)) return + for (const next of graph.get(file)) visit(next, [...trail, file]) + done.add(file) + } + for (const file of graph.keys()) visit(file, []) + assert.deepEqual(cycles, []) +}) diff --git a/frontend/scripts/test-unused-css.mjs b/frontend/scripts/test-unused-css.mjs new file mode 100644 index 0000000..11b6287 --- /dev/null +++ b/frontend/scripts/test-unused-css.mjs @@ -0,0 +1,24 @@ +// Rejects classes in app.css that no source file uses. A class built from a +// template such as `status-${kind}` counts as used by its prefix. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' + +const src = path.resolve(import.meta.dirname, '..', 'src') + +test('every class in app.css is used', () => { + const code = fs.readdirSync(src, { recursive: true }) + .filter((name) => /\.tsx?$/.test(name)) + .map((name) => fs.readFileSync(path.join(src, name), 'utf8')) + .join('\n') + const css = fs.readFileSync(path.join(src, 'styles', 'app.css'), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/url\([^)]*\)|"[^"]*"/g, '') + + const words = new Set(code.match(/[A-Za-z_][\w-]*/g)) + const prefixes = [...code.matchAll(/([A-Za-z][\w-]*-)\$\{/g)].map((m) => m[1]) + const classes = new Set([...css.matchAll(/\.([A-Za-z_][\w-]*)/g)].map((m) => m[1])) + assert.ok(classes.size > 300, `found only ${classes.size} classes in app.css`) + assert.deepEqual([...classes].filter((c) => !words.has(c) && !prefixes.some((p) => c.startsWith(p))), []) +}) diff --git a/frontend/scripts/test-unused-exports.mjs b/frontend/scripts/test-unused-exports.mjs new file mode 100644 index 0000000..de88135 --- /dev/null +++ b/frontend/scripts/test-unused-exports.mjs @@ -0,0 +1,57 @@ +// Rejects exports in src/ that no other file uses: dead code, or an export +// keyword that only widens a module's interface. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import ts from 'typescript' + +const root = path.resolve(import.meta.dirname, '..') + +function findUnusedExports() { + const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), ts.sys.readFile) + const { fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, root) + const service = ts.createLanguageService({ + ...ts.sys, + getCompilationSettings: () => options, + getScriptFileNames: () => fileNames, + getScriptVersion: () => '1', + getScriptSnapshot: (file) => (fs.existsSync(file) ? ts.ScriptSnapshot.fromString(fs.readFileSync(file, 'utf8')) : undefined), + getCurrentDirectory: () => root, + getDefaultLibFileName: ts.getDefaultLibFilePath, + }) + // The test and contract scripts import src modules or read them as text. A + // name counts as used only in a script that also names its module. + const scripts = fs.readdirSync(import.meta.dirname) + .filter((name) => name !== path.basename(import.meta.filename)) + .map((name) => fs.readFileSync(path.join(import.meta.dirname, name), 'utf8')) + + const unused = [] + for (const file of fileNames) { + // bridgeContract.ts also documents the message types for plugin authors. + if (file.endsWith('.gen.ts') || file.endsWith('/bridgeContract.ts')) continue + const source = service.getProgram().getSourceFile(file) + const module = path.relative(path.join(root, 'src'), file).split(path.sep).join('/').replace(/(\/index)?\.tsx?$/, '') + const users = scripts.filter((text) => text.includes(`'./${module}'`) || text.includes(`'${path.basename(file)}'`)) + for (const statement of source.statements) { + if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) continue + const names = ts.isVariableStatement(statement) + ? statement.declarationList.declarations.map((d) => d.name).filter(ts.isIdentifier) + : [statement.name].filter(Boolean) + for (const name of names) { + if (users.some((text) => new RegExp(`\\b${name.text}\\b`).test(text))) continue + const references = (service.findReferences(file, name.getStart(source)) ?? []).flatMap((r) => r.references) + if (references.every((r) => r.fileName === file)) { + unused.push(`${path.relative(root, file)}: ${name.text}`) + } + } + } + } + return { unused, files: fileNames.length } +} + +test('every export in src/ has a user outside its own file', () => { + const { unused, files } = findUnusedExports() + assert.ok(files > 50, `expected to scan src/, found ${files} files`) + assert.deepEqual(unused, []) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 0d7834a..403995e 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,35 +6,38 @@ import { ElevationDialog } from './components/ElevationDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' -import type { ThemeMode } from './components/AppSettingsPage' import { LogPanel, LogTab } from './components/LogPanel' import { TitleMenus } from './components/TitleMenus' -import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule' +import { UpdateCapsule } from './components/UpdateCapsule' import { DataRootReadOnly } from './components/DataRootReadOnly' import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' -import { PluginViewHost } from './components/PluginViewHost' -import { locText } from './components/SchemaForm' -import { VMAction, VMBusyAction, VMPage } from './components/VMPage' -import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' +import { VMPage } from './components/VMPage' +import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' import { LogLine, appendLog } from './lib/logs' import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' -import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' +import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine' +import type { UIStateSnapshot } from './lib/uiSdk' import { hasVisibleDialog } from './lib/dialogState' -import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' +import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' +import { useAppearance } from './lib/useAppearance' +import { useAppUpdate } from './lib/useAppUpdate' +import { useFileDrop } from './lib/useFileDrop' +import { useThemeEvents } from './lib/useThemeEvents' +import { useVMBusy } from './lib/useVMBusy' import { vmRefKey } from './lib/vmRef' import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter' import { publishPluginHostEvent } from './lib/pluginViewEvents' import { buildSafePluginAssetURL } from './lib/pluginAssets' -import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' +import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' -import { Toaster, useToasts } from './ui/toast' +import { errorToast, Toaster, useToasts } from './ui/toast' import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' -import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' +import { api, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' // 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 @@ -47,6 +50,7 @@ const HostView = lazy(() => import('./components/HostView').then((m) => ({ defau const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage }))) const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage }))) const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage }))) +const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m) => ({ default: m.PluginViewHost }))) const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage }))) @@ -83,17 +87,6 @@ const failKey: Record = { export const App: React.FC = () => { const [state, setState] = useState(null) const [selected, setSelectedPage] = useState(HOST_ID) - const [appUpdate, setAppUpdate] = useState(null) - // Check for a new release once the app is up, then every 6 hours, so the - // sidebar's update button shows up without opening the About page. - const stateReady = !!state - useEffect(() => { - if (!stateReady) return - const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) } - check() - const id = window.setInterval(check, 6 * 60 * 60 * 1000) - return () => window.clearInterval(id) - }, [stateReady]) const [detail, setDetail] = useState(null) // GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail). const [vmInfoLoaded, setVMInfoLoaded] = useState(null) @@ -110,26 +103,8 @@ export const App: React.FC = () => { const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) - const [busy, setBusy] = useState>({}) - const busyOpsRef = useRef>>(new Map()) - const nextBusyTokenRef = useRef(0) - const [dropping, setDropping] = useState(false) + const vmBusy = useVMBusy() const [loadError, setLoadError] = useState('') - const [themeMode, setThemeModeState] = useState(() => { - try { - const saved = localStorage.getItem('reims-go-theme') - if (saved === 'dark' || saved === 'light') return saved - } catch (e) { - console.warn('[app] read theme preference failed:', e) - } - return 'system' - }) - const [sysDark, setSysDark] = useState(() => - typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches, - ) - const [reducedMotion, setReducedMotion] = useState(() => - typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches, - ) const [pluginUI, setPluginUI] = useState(null) const [pluginViewState, setPluginViewState] = useState(emptyPluginViewState) const [pluginViewMeta, setPluginViewMeta] = useState>({}) @@ -150,50 +125,7 @@ export const App: React.FC = () => { : 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 - events.emitTheme(theme) - }, [theme]) - - useEffect(() => { - document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full' - }, [reducedMotion]) - - useEffect(() => { - const mq = window.matchMedia?.('(prefers-color-scheme: dark)') - if (!mq) return - const onChange = (e: MediaQueryListEvent) => setSysDark(e.matches) - mq.addEventListener('change', onChange) - return () => mq.removeEventListener('change', onChange) - }, []) - - useEffect(() => { - const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)') - if (!mq) return - const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches) - mq.addEventListener('change', onChange) - return () => mq.removeEventListener('change', onChange) - }, []) - - const setThemeMode = (mode: ThemeMode) => { - setThemeModeState(mode) - try { - if (mode === 'system') localStorage.removeItem('reims-go-theme') - else localStorage.setItem('reims-go-theme', mode) - } catch (e) { - console.warn('[app] persist theme preference failed:', e) - } - } - - const toggleTheme = () => { - if (!canLight || !canDark) return - setThemeMode(theme === 'light' ? 'dark' : 'light') - } + const { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion } = useAppearance(themeAppearanceCap) // Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user. const [sidebarOpen, setSidebarOpen] = useState(() => { @@ -356,23 +288,24 @@ export const App: React.FC = () => { const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined const activePluginRoute = activePluginView ? pluginViewState.route : null const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => ( - updateViewMetadata(view, metadata)} - onOpenView={openView} - onCloseView={dialog ? () => { - setPluginViewState((current) => closePluginDialog(current, route)) - return { closed: true } - } : closeView} - onNavigate={navigateHost} - /> + + updateViewMetadata(view, metadata)} + onOpenView={openView} + onCloseView={dialog ? () => { + setPluginViewState((current) => closePluginDialog(current, route)) + return { closed: true } + } : closeView} + onNavigate={navigateHost} + /> + ) const renderVMTabs = () => { if (!selectedVM) return null @@ -434,9 +367,9 @@ export const App: React.FC = () => { let live = true for (const vm of vms) { const key = vmRefKey(vm) - api.GetVMNoteWithDriver(vm.driver_id ?? '', vm.name) + api.GetVMNote(vm.driver_id ?? '', vm.name) .then((n) => { if (live) setDisplayNames((m) => ({ ...m, [key]: (n ?? '').trim() })) }) - .catch((e) => console.warn('[app] GetVMNoteWithDriver failed:', key, e)) + .catch((e) => console.warn('[app] GetVMNote failed:', key, e)) } return () => { live = false } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -557,53 +490,11 @@ export const App: React.FC = () => { : 'stable' const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => { await api.SetAppUpdateChannel(ch) - setDismissedUpdate('') - try { localStorage.removeItem('reims-go-update-dismissed') } catch (e) { console.warn('[app] clear dismissed update failed:', e) } await refresh() - try { - setAppUpdate(await api.CheckAppUpdate(true)) - } catch (e) { - setAppUpdate(null) - throw e - } + await update.recheck() } const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) } - // In-app update: one task per release; its state drives the sidebar capsule - // and the About page alike. - const updateTask = appUpdate?.has_update - ? Object.values(taskMap) - .filter((x) => x.kind === 'app-update' && x.subject === appUpdate.latest) - .sort((a, b) => b.updated_at - a.updated_at)[0] ?? null - : null - const updatePhase: UpdatePhase = !appUpdate?.has_update ? 'none' - : updateTask?.status === 'running' ? 'downloading' - : updateTask?.status === 'done' ? 'ready' - : updateTask?.status === 'failed' ? 'failed' - : 'available' - const [dismissedUpdate, setDismissedUpdate] = useState(() => { - try { return localStorage.getItem('reims-go-update-dismissed') ?? '' } catch { return '' } - }) - const dismissUpdate = () => { - if (!appUpdate) return - setDismissedUpdate(appUpdate.latest) - try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) } - } - const [confirmUpdate, setConfirmUpdate] = useState(false) - const [installingUpdate, setInstallingUpdate] = useState(false) - const downloadUpdate = () => { api.DownloadAppUpdate().catch((e) => fail(tr('updateFailed'), e)) } - const runInstallUpdate = () => { - setConfirmUpdate(false) - setInstallingUpdate(true) - api.InstallAppUpdate().catch((e) => { - setInstallingUpdate(false) - fail(tr('updateFailed'), e) - }) - } - // Restarting leaves VMs running but pauses the host-guest bridges: say so first. - const installUpdate = () => { if (runningVMCount > 0) setConfirmUpdate(true); else runInstallUpdate() } - const showUpdateCard = updatePhase !== 'none' && !(updatePhase === 'available' && dismissedUpdate === appUpdate?.latest) - // One toast after an update restart: the version changed since the last run. useEffect(() => { const v = state?.app_version @@ -638,7 +529,7 @@ export const App: React.FC = () => { // UI Contract v2 read-only document state attributes. const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm' - const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0 + const isBusyAny = Object.keys(vmBusy.busy).length > 0 || runningTasks > 0 const hasAnyError = unseenErrors > 0 || !!loadError const uiStateRef = useRef({ appearance: theme, @@ -679,43 +570,7 @@ export const App: React.FC = () => { notifyInteractiveThemeState(uiStateRef.current) }, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme, reducedMotion]) - // UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is - // a no-op unless an interactive theme is loaded; payloads carry no paths. - const selectedRef = selectedVM ? vmRefKey(selectedVM) : '' - useEffect(() => { - emitThemeEvent('view.changed', { view: currentView, vm: selectedRef }) - }, [currentView, selectedRef]) - const vmStatesRef = useRef | null>(null) - useEffect(() => { - const next: Record = {} - for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state - const prev = vmStatesRef.current - vmStatesRef.current = next - if (!prev) return - for (const v of vms) { - const key = vmRefKey(v) - if (prev[key] !== undefined && prev[key] !== next[key]) { - const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] } - emitThemeEvent('vm.stateChanged', payload) - publishPluginHostEvent('vm.stateChanged', payload) - } - } - }, [vms, state?.transitions]) - const taskStatesRef = useRef | null>(null) - useEffect(() => { - const prev = taskStatesRef.current - const next: Record = {} - for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent } - taskStatesRef.current = next - if (!prev) return - for (const t of Object.values(taskMap)) { - const was = prev[t.id] - const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent } - if (!was && t.status === 'running') emitThemeEvent('task.started', info) - else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info) - if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status }) - } - }, [taskMap]) + useThemeEvents({ view: currentView, selectedVM: selectedVM ? vmRefKey(selectedVM) : '', vms, transitions: state?.transitions, tasks: taskMap }) // Refresh contributions together with the active theme after registry changes. useEffect(() => { @@ -742,7 +597,7 @@ export const App: React.FC = () => { openSettings: () => setSelected(SETTINGS_ID), focusVMWindow: (vmName) => { const vm = vmsRef.current.find((v) => vmRefKey(v) === vmName) ?? vmsRef.current.find((v) => v.name === vmName) - void api.FocusVMWindowWithDriver(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindowWithDriver failed:', vmName, e)) + void api.FocusVMWindow(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) }, }, ) @@ -765,7 +620,7 @@ export const App: React.FC = () => { try { const logVM = name === selectedVM?.name ? selectedVM : vms.find((v) => v.name === name) const logDriverID = logVM?.driver_id ?? '' - const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial) + const text = await api.ReadVMLogs(logDriverID, name, serial) if (serial) setSerialLog(text) else setQemuLog(text) } catch (e) { @@ -778,67 +633,18 @@ export const App: React.FC = () => { const loadQemu = (name?: string) => loadVMLog(false, name) const fail = (title: string, e: unknown) => { - const parsed = parseAppError(e) toasts.push({ - kind: 'error', - title, - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, title, e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') }, }) } + const update = useAppUpdate({ ready: !!state, tasks: taskMap, runningVMCount, onError: (e) => fail(tr('updateFailed'), e) }) onHostDropAckRef.current = (ack) => { if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '') } - // Busy state is keyed by VM reference (driver and name), so same-name VMs of - // different drivers never block each other. - const activeVMBusy = (key: string): VMBusyAction | undefined => { - const ops = busyOpsRef.current.get(key) - if (!ops || ops.size === 0) return undefined - let latest: VMBusyAction | undefined - for (const act of ops.values()) latest = act - return latest - } - - const syncBusyState = () => { - const next: Record = Object.create(null) - for (const [vmName, ops] of busyOpsRef.current) { - let latest: VMBusyAction | undefined - for (const act of ops.values()) latest = act - if (latest) next[vmName] = latest - } - setBusy(next) - } - - const beginVMBusy = (name: string, action: VMBusyAction): number | null => { - const ops = busyOpsRef.current.get(name) - if (ops && ops.size > 0) { - if (action !== 'forceStop') return null - for (const act of ops.values()) { - if (act === 'forceStop') return null - } - } - const token = ++nextBusyTokenRef.current - const vmOps = ops ?? new Map() - vmOps.set(token, action) - busyOpsRef.current.set(name, vmOps) - syncBusyState() - return token - } - - const endVMBusy = (name: string, token: number) => { - const ops = busyOpsRef.current.get(name) - if (!ops || !ops.delete(token)) return - if (ops.size === 0) busyOpsRef.current.delete(name) - syncBusyState() - } - const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise, okTitle?: string) => { - const token = beginVMBusy(name, action) + const token = vmBusy.begin(name, action) if (token === null) return try { await fn() @@ -847,14 +653,14 @@ export const App: React.FC = () => { } catch (e) { fail(tr(failKey[action]), e) } finally { - endVMBusy(name, token) + vmBusy.end(name, token) } } // Paste as keystrokes: the backend refuses text a US keyboard can't type // (ErrNotTypeable in type_flow.go), which gets a message of its own. const typeInto = async (busyKey: string, fn: () => Promise) => { - const token = beginVMBusy(busyKey, 'type') + const token = vmBusy.begin(busyKey, 'type') if (token === null) return try { const n = await fn() @@ -866,7 +672,7 @@ export const App: React.FC = () => { fail(tr('failType'), e) } } finally { - endVMBusy(busyKey, token) + vmBusy.end(busyKey, token) } } @@ -884,7 +690,7 @@ export const App: React.FC = () => { return } } - const token = beginVMBusy(busyKey, 'attachInstaller') + const token = vmBusy.begin(busyKey, 'attachInstaller') if (token === null) return try { const fileName = await api.AttachInstaller(name, picked) @@ -894,7 +700,7 @@ export const App: React.FC = () => { }) await refresh() } finally { - endVMBusy(busyKey, token) + vmBusy.end(busyKey, token) } } catch (e) { fail(tr('failAttachInstaller'), e) @@ -903,7 +709,7 @@ export const App: React.FC = () => { // Hosted VMs have no window: the primary action is their best ready endpoint. const openEndpoint = (vm: VMListItem, kind: string) => { - api.OpenVMEndpointWithDriver(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) + api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) } const openPrimaryEndpoint = (vm: VMListItem) => { const { primary } = splitEndpoints(vm.endpoints) @@ -931,7 +737,7 @@ export const App: React.FC = () => { if (actionVM) openPrimaryEndpoint(actionVM) return } - const activeBusy = activeVMBusy(key) + const activeBusy = vmBusy.current(key) if ( activeBusy && action !== 'openFolder' @@ -941,21 +747,21 @@ export const App: React.FC = () => { return } switch (action) { - case 'start': return runVMAction(key, action, () => api.StartVMWithDriver(actionDriverID, name)) - case 'suspend': return runVMAction(key, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name })) - case 'resume': return runVMAction(key, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name })) + case 'start': return runVMAction(key, action, () => api.StartVM(actionDriverID, name)) + case 'suspend': return runVMAction(key, action, () => api.SuspendVM(actionDriverID, name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(key, action, () => api.ResumeVM(actionDriverID, name), tr('toastResumed', { name })) case 'discardSuspend': return setDiscardSuspendTarget(key) - case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) + case 'focus': return api.FocusVMWindow(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(key, action, async () => { - const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name) - refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen }) + const isFullscreen = await api.ToggleVMFullscreen(actionDriverID, name) + refreshVMStats(actionDriverID, name, { window_fullscreen: isFullscreen }) }) - case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied')) - case 'stop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) - case 'forceStop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) - case 'restart': return runVMAction(key, action, () => api.RestartVMWithDriver(actionDriverID, name)) - case 'eject': return runVMAction(key, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected')) + case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshot(actionDriverID, name), tr('toastScreenshotCopied')) + case 'stop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, false), tr('toastStopped', { name })) + case 'forceStop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, true), tr('toastStopped', { name })) + case 'restart': return runVMAction(key, action, () => api.RestartVM(actionDriverID, name)) + case 'eject': return runVMAction(key, action, () => api.EjectInstaller(actionDriverID, name), tr('toastEjected')) case 'finishInstall': return runVMAction(key, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished')) case 'enterRecovery': return runVMAction(key, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery')) case 'attachInstaller': return attachInstaller(key, name, isRunning) @@ -966,11 +772,11 @@ export const App: React.FC = () => { case 'upgradeNVMe': return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady')) case 'exportDiagnostics': - return runVMAction(key, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported')) + return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported')) case 'cloneVM': if (!features.clone) return return setCloneSource({ name, driverID: actionDriverID }) - case 'type': return typeInto(key, () => api.TypeClipboardWithDriver(actionDriverID, name)) + case 'type': return typeInto(key, () => api.TypeClipboard(actionDriverID, name)) case 'sendText': return setSendTextTarget(key) case 'openFolder': return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e)) @@ -1004,7 +810,7 @@ export const App: React.FC = () => { const vm = findVM(name) if (!vm) return const key = vmRefKey(vm) - if (activeVMBusy(key)) return + if (vmBusy.current(key)) return const st = state?.transitions[key] ?? vm.state if (st === 'stopped') onVMActionFor(key, 'start', false) else if (st === 'suspended') onVMActionFor(key, 'resume', false) @@ -1018,7 +824,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name })) + if (name) runVMAction(key, 'delete', () => api.DeleteVM(driverID, name, keepFiles), tr('toastDeleted', { name })) } const confirmDiscardSuspend = () => { @@ -1028,7 +834,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name })) + if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspend(driverID, name), tr('toastDiscardSuspend', { name })) } const confirmOnlineRecovery = () => { @@ -1045,7 +851,7 @@ export const App: React.FC = () => { setCloneSource(null) if (!src) return runVMAction(vmRefKey({ name: src.name, driver_id: src.driverID }), 'cloneVM', async () => { - await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName) + await api.CloneVMCoW(src.driverID, src.name, cloneName) setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID })) }, tr('toastCloned', { name: cloneName })) } @@ -1119,17 +925,10 @@ export const App: React.FC = () => { }) .catch((e) => { void refresh() - const parsed = parseAppError(e) - if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') { + if (parseAppError(e).code === 'E_NETWORK_CREATE_BRIDGE_PENDING') { setSelected(name) toasts.push({ - kind: 'error', - title: tr('toastCreated', { name }), - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, tr('toastCreated', { name }), e), action: { label: tr('settings'), onClick: () => { api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err)) } }, @@ -1146,13 +945,7 @@ export const App: React.FC = () => { return } toasts.push({ - kind: 'error', - title: tr('failCreate', { name }), - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, tr('failCreate', { name }), e), action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } }, }) }) @@ -1175,7 +968,7 @@ export const App: React.FC = () => { // Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open. const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget || - discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate || closeDownloadsOpen || elevationQueue.length > 0 + discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || update.confirming || closeDownloadsOpen || elevationQueue.length > 0 shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return if (appDialogOpen) return @@ -1218,46 +1011,17 @@ export const App: React.FC = () => { return () => { offRequest(); offResolved() } }, []) - // Native Wails file drag-and-drop delivery into the selected VM's shared folder. - const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false }) - dropTargetRef.current = { - name: selectedVM?.name ?? '', - ready: !!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, - } - useEffect(() => { - let depth = 0 - const onEnter = (e: DragEvent) => { - if (!dropTargetRef.current.ready) return - if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) } - } - const onLeave = () => { - depth = Math.max(0, depth - 1) - if (depth === 0) setDropping(false) - } - const onDropEnd = () => { depth = 0; setDropping(false) } - window.addEventListener('dragenter', onEnter) - window.addEventListener('dragleave', onLeave) - window.addEventListener('drop', onDropEnd) - OnFileDrop((_x, _y, paths) => { - depth = 0 - setDropping(false) - const cur = dropTargetRef.current - if (!cur.ready || !cur.name || !paths || paths.length === 0) return - api.DeliverPathsToGuest(cur.name, paths) - .then((delivered) => { - if (!delivered || delivered.length === 0) return - if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) }) - else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) }) - }) - .catch((e) => fail(tr('failGuestTools'), e)) - }, true) - return () => { - window.removeEventListener('dragenter', onEnter) - window.removeEventListener('dragleave', onLeave) - window.removeEventListener('drop', onDropEnd) - OnFileDropOff() - } - }, []) + // Files dropped on the window go to the selected VM's shared folder. + const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => { + if (!selectedVM) return + api.DeliverPathsToGuest(selectedVM.name, paths) + .then((delivered) => { + if (!delivered || delivered.length === 0) return + if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) }) + else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) }) + }) + .catch((e) => fail(tr('failGuestTools'), e)) + }) return ( @@ -1277,7 +1041,7 @@ export const App: React.FC = () => { onToggleSidebar={toggleSidebar} logsOpen={logsOpen} onToggleLogs={toggleLogs} - themeMode={effectiveThemeMode} + themeMode={themeMode} canLight={canLight} canDark={canDark} onThemeMode={setThemeMode} @@ -1285,7 +1049,7 @@ export const App: React.FC = () => { name: selectedVM.name, driver_id: selectedVM.driver_id, state: effectiveState, - busy: Object.prototype.hasOwnProperty.call(busy, vmRefKey(selectedVM)), + busy: vmRefKey(selectedVM) in vmBusy.busy, graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, canSuspend: canSuspendVM(selectedVM), features: selectedFeatures, @@ -1308,7 +1072,7 @@ export const App: React.FC = () => { type="button" className="theme-toggle" aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')} - onClick={toggleTheme} + onClick={() => setThemeMode(theme === 'light' ? 'dark' : 'light')} > {theme === 'light' ?