diff --git a/AGENTS.md b/AGENTS.md index 375e6fc..d686e4b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,6 +55,7 @@ 6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。 7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。 8. **文档维护纪律**:`docs/` 只存放当前生效的长期文档,使用单一事实来源;不写私人本机路径、日期补丁式叙事、易过时的伪代码/ASCII 草图;一次性排查、审视与排期记录留在 Issue 或 PR 中。 +9. **禁止空 `catch` 吞错**:严禁编写带有空代码块(含仅注释或空语句)的 `catch` 语句或空回调(如 `catch {}`、`catch (e) {}`、`.catch(() => {})`、`.then(..., () => {})`)把失败静默包装成成功;捕获异常后必须执行明确的错误处理(上报/展示错误、记录诊断告警、分类过滤预期错误并重抛其余异常,或显式回退状态)。该约束由 [`frontend/scripts/test-no-empty-catch.mjs`](frontend/scripts/test-no-empty-catch.mjs) 在 `pnpm --dir frontend test` 中强制校验。 ## 开源合规边界 diff --git a/CHANGELOG.md b/CHANGELOG.md index 66876c5..44f0209 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,30 @@ 本文件只记录 Reims-Go 桌面应用的变化。便携运行时(`runtime-*`)的版本另见 [Releases](https://github.com/Nwflower/Reims-Go/releases)。 +## v0.2.11 — 2026-12-01 + +### 新功能 + +- **Intel 虚拟机挂起与瞬间恢复**([#37](https://github.com/Nwflower/Reims-Go/pull/37)):支持在虚拟机运行中挂起保存内存与图形状态并在下次启动秒级恢复,采用事务化状态保存、异常回滚与多通道直接 I/O 优化。 +- **自定义共享文件夹与 WebDAV 路径隔离**([#38](https://github.com/Nwflower/Reims-Go/pull/38)、[#39](https://github.com/Nwflower/Reims-Go/pull/39)):Guest Tools 升级至 v8,支持按虚拟机配置自定义宿主机共享文件夹(含卷校验与设置页管理),并统一基于 `os.Root` 收紧 WebDAV 与回退文件同步的路径边界。 +- **内置并行下载器插件与可扩展下载器接口**([#24](https://github.com/Nwflower/Reims-Go/pull/24)、[#52](https://github.com/Nwflower/Reims-Go/pull/52)):离线安装包与镜像下载支持多线程分片并行加速,并开放 `downloaders` 插件扩展点。 +- **可插拔「镜像」页面与内置 macOS 镜像源**:将原安装包页升级为支持多插件镜像源切换的「镜像」页(`images.source` 扩展点),内置 macOS 镜像插件并接入品牌描边加载动画与服务可用性提示。 +- **插件 UI / 桥接契约锁定与主题能力升级(uiApi 2.0 / bridgeApi 1.0)**:冻结插件契约,新增主题插槽(slots)、全窗装饰层(layers)、布局选项(侧栏位置/模式、界面紧凑度、标题栏高度)以及图标与品牌标志覆写。 +- **虚拟机硬件、显示与交互增强**: + - 支持按虚拟机配置 Windows 修饰键重映射及 `Win` 键映射为 macOS `Command`([#53](https://github.com/Nwflower/Reims-Go/pull/53))。 + - 支持一键轮换 OpenCore SMBIOS 硬件标识([#47](https://github.com/Nwflower/Reims-Go/pull/47))及可选同步宿主机 SMBIOS Type 17 内存规格([#44](https://github.com/Nwflower/Reims-Go/pull/44))。 + - 支持 `qcow2` `extended_l2` 磁盘性能优化、快照改写保护与 Windows Defender 排除项引导([#56](https://github.com/Nwflower/Reims-Go/pull/56))。 + - 全屏模式与客体分辨率解耦以支持 1.5x HiDPI 缩放([#22](https://github.com/Nwflower/Reims-Go/pull/22));新增关机模式选择与一键强制退出([#51](https://github.com/Nwflower/Reims-Go/pull/51))、虚拟机关闭确认弹窗及「关于」页 Discord 社区入口([#57](https://github.com/Nwflower/Reims-Go/pull/57))。 + - 支持停用内置 macOS 客体插件并按驱动隔离虚拟机生命周期路由。 + +### 优化与修复 + +- **统一插件前端组件与视觉样式**:合并已安装列表、插件市场与首次向导中的插件图标块、信任徽标、胶囊筛选按钮与搜索框(补齐语言包图标识别与 RTL 逻辑属性),将插件危险确认弹窗、表单、复选框、错误提示条与加载骨架屏收敛至全局基础组件。 +- **修复 Apple 在线恢复镜像鉴权与离线路径展开**([#34](https://github.com/Nwflower/Reims-Go/pull/34)):修复恢复镜像下载鉴权、分区 chunklist 校验及 `reims-ctl show` 主目录路径展开问题。 +- **修复剪贴板互通与文件同步可靠性**([#28](https://github.com/Nwflower/Reims-Go/pull/28)、[#33](https://github.com/Nwflower/Reims-Go/pull/33)):加固 Windows 剪贴板锁与 DIB/PNG 回声抑制,修复回退同步删除传播、Windows 驱动器挂载认证及 CLI 直接启动时保留 Guest Tools 的问题。 +- **修复 Vulkan 诊断与 GPU 驱动发现**([#21](https://github.com/Nwflower/Reims-Go/pull/21)、[#46](https://github.com/Nwflower/Reims-Go/pull/46)):清理失效的 GPU 驱动缓存文件,从活动显示驱动包中发现缺失的 Vulkan ICD 并在向导与 `doctor` 中展示探测诊断。 +- **界面性能与工程健壮性加固**([#57](https://github.com/Nwflower/Reims-Go/pull/57)):消除软件合成模式下的弹窗卡顿,修复插件状态判定、列表错误上报与休眠虚拟机停用驱动插件问题,全面禁止空 `catch` 吞错并加入静态门禁测试;运行时发布源切换至独立的 Reims vGPU / QEMU fork 通道。 + ## v0.2.10 — 2026-11-30 ### 新功能 diff --git a/NOTICE.md b/NOTICE.md index a91772c..1b55025 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -13,6 +13,32 @@ packages, `klauspost/compress`, and `ulikunitz/xz`) under permissive licenses (MIT, BSD, ISC, and SIL OFL 1.1); see `go.mod` and `frontend/package.json` for the complete dependency list. +### go-toml v2 + +The MIT License (MIT) + +Copyright (c) 2021 - 2023 Thomas Pelletier + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +## Portable runtime + The portable runtime bundle (`reims-runtime-win-x64-.tar.zst`) contains precompiled binaries built from the following upstream open-source projects. Each runtime release ships the matching source package, `NOTICE.md`, and diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index 1aa385b..2f3f7eb 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -211,7 +211,8 @@ UI 槽位采用「声明即占有」:插件只能向宿主槽位目录(§5.1 - 只读状态订阅:非敏感的 VM 摘要、任务进度、当前视图、外观;不提供原始路径与敏感字段。 - 事件流:VM 状态变化(含过渡态)、任务开始/进度/结束、提示条出现、视图切换,供主题做转场动画,不必轮询状态。 - 宿主提供的页面观察总线、帧读写管线与按部件查询:主题不自建节点观察者,也不整页查询文档。 -- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。 +- 槽位挂载:框架无关的 DOM 挂载,不共享宿主的 React 实例,避免随宿主依赖升级断裂。按 VM 重复的槽位(`nav.item.trailing`)以 VM 引用为键挂载;全窗口图层另有专用挂载;按部件查询可取回重复部件的全部实例。 +- 声明式装饰与 SDK 挂载共用同一批槽位与图层;重复槽位里的装饰按所在 VM 自身的状态匹配。 - 受限动作:仅开放非破坏性界面动作(折叠侧栏、打开设置、前置 VM 窗口等);启停、删除、配置写入不在 SDK 中。 - 主题设置:由 `settings` Schema 定义,宿主渲染设置页。 diff --git a/frontend/package.json b/frontend/package.json index 66ecaa2..ef6431b 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -1,11 +1,11 @@ { "name": "reims-go-frontend", "private": true, - "version": "0.2.10", + "version": "0.2.11", "type": "module", "scripts": { "dev": "vite", - "test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs", + "test": "node --test scripts/test-i18n.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs", "build": "tsc --noEmit && vite build && node scripts/check-ui-contract.mjs", "preview": "vite preview" }, diff --git a/frontend/package.json.md5 b/frontend/package.json.md5 index ddd7b01..aca5166 100644 --- a/frontend/package.json.md5 +++ b/frontend/package.json.md5 @@ -1 +1 @@ -963b18fba33337becedb9d93549f159f \ No newline at end of file +d5f2fdb982362b7c1d77e7244b0a024f \ No newline at end of file diff --git a/frontend/scripts/check-ui-contract.mjs b/frontend/scripts/check-ui-contract.mjs index 4b36972..ceec94a 100644 --- a/frontend/scripts/check-ui-contract.mjs +++ b/frontend/scripts/check-ui-contract.mjs @@ -15,6 +15,7 @@ const srcDir = path.join(rootDir, 'src') const contractSrc = fs.readFileSync(path.join(srcDir, 'styles', 'ui-contract.ts'), 'utf8') const bridgeSrc = fs.readFileSync(path.join(srcDir, 'lib', 'bridgeContract.ts'), 'utf8') const tokensCss = fs.readFileSync(path.join(srcDir, 'styles', 'tokens.css'), 'utf8') +const appCss = fs.readFileSync(path.join(srcDir, 'styles', 'app.css'), 'utf8') function extractArray(src, name) { const re = new RegExp(`export const ${name} = \\[([\\s\\S]*?)\\] as const`) @@ -33,8 +34,13 @@ const uiApi = extractVersion(contractSrc, 'UI_API_VERSION') const stable = { parts: extractArray(contractSrc, 'UI_CONTRACT_PARTS'), stateAttrs: extractArray(contractSrc, 'UI_CONTRACT_STATE_ATTRS'), + itemStates: extractArray(contractSrc, 'UI_CONTRACT_ITEM_STATES'), slots: extractArray(contractSrc, 'UI_CONTRACT_SLOTS'), layers: extractArray(contractSrc, 'UI_CONTRACT_LAYERS'), + layoutOptions: extractArray(contractSrc, 'UI_CONTRACT_LAYOUT_OPTIONS'), + icons: extractArray(contractSrc, 'UI_CONTRACT_ICONS'), + viewLocations: extractArray(contractSrc, 'UI_CONTRACT_VIEW_LOCATIONS'), + sdkEvents: extractArray(contractSrc, 'UI_CONTRACT_SDK_EVENTS'), tokens: extractArray(contractSrc, 'UI_CONTRACT_TOKENS'), } const experimental = { @@ -70,6 +76,16 @@ function readSources(dir, exts) { } const allTsx = readSources(srcDir, ['.tsx']) const allCode = readSources(srcDir, ['.ts', '.tsx']) +// Per-file sources, for checks that need two things in the same component. +function sourceFiles(dir, out = []) { + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) sourceFiles(full, out) + else if (entry.name.endsWith('.tsx')) out.push(fs.readFileSync(full, 'utf8')) + } + return out +} +const tsxFiles = sourceFiles(srcDir) const hasClass = (p) => new RegExp(`(? attr.replace(/^data-/, '').replace(/-([a-z])/g, (_, c) => c.toUpperCase()) @@ -85,6 +101,26 @@ fail('stable state attributes never set', stable.stateAttrs.filter((a) => !hasAt fail('stable slots without a data-rg-slot anchor', stable.slots.filter((s) => !hasSlot(s))) fail('stable layers without a data-rg-layer element', stable.layers.filter((l) => !hasLayer(l))) fail('stable tokens missing in tokens.css', stable.tokens.filter((tk) => !tokensCss.includes(`${tk}:`))) +// An item state counts as emitted when one component carries both the part and the attribute. +fail('stable item states not emitted together with their part', stable.itemStates.filter((s) => { + const [part, attr] = s.split(':') + return !tsxFiles.some((src) => new RegExp(`(? { + if (LAYOUT_DEFAULTS.includes(o)) return false + const [opt, val] = o.split('=') + return !LAYOUT_ATTR[opt] || !appCss.includes(`[${LAYOUT_ATTR[opt]}="${val}"]`) +})) +fail('layout options with an unknown option name', [...stable.layoutOptions, ...experimental.layoutOptions].filter((o) => !LAYOUT_ATTR[o.split('=')[0]])) +// Every stable icon name is rendered through (or the status-shape map). +const controlsSrc = fs.readFileSync(path.join(srcDir, 'ui', 'controls.tsx'), 'utf8') +fail('stable icon names never rendered through HostIcon', stable.icons.filter((n) => + !allTsx.includes(`HostIcon name="${n}"`) && !(n.startsWith('vm.state.') && controlsSrc.includes(`'${n}'`)))) +// Every stable SDK event has an emitter. +fail('stable SDK events never emitted', stable.sdkEvents.filter((e) => !allCode.includes(`emitThemeEvent('${e}'`))) fail('experimental parts already emitted (promote them to UI_CONTRACT_PARTS)', experimental.parts.filter(hasClass)) fail('experimental slots already anchored (promote them to UI_CONTRACT_SLOTS)', experimental.slots.filter(hasSlot)) @@ -95,11 +131,16 @@ fail('entries listed as both stable and experimental (parts)', overlap(stable.pa fail('entries listed as both stable and experimental (state attributes)', overlap(stable.stateAttrs, experimental.stateAttrs)) fail('entries listed as both stable and experimental (slots)', overlap(stable.slots, experimental.slots)) fail('entries listed as both stable and experimental (layers)', overlap(stable.layers, experimental.layers)) +fail('entries listed as both stable and experimental (item states)', overlap(stable.itemStates, experimental.itemStates)) +fail('entries listed as both stable and experimental (layout options)', overlap(stable.layoutOptions, experimental.layoutOptions)) +fail('entries listed as both stable and experimental (icons)', overlap(stable.icons, experimental.icons)) +fail('entries listed as both stable and experimental (view locations)', overlap(stable.viewLocations, experimental.viewLocations)) +fail('entries listed as both stable and experimental (SDK events)', overlap(stable.sdkEvents, experimental.sdkEvents)) fail('bridge methods listed as both stable and experimental', overlap(bridge.methods, bridge.experimentalMethods)) fail('bridge events listed as both stable and experimental', overlap(bridge.events, bridge.experimentalEvents)) const knownParts = [...stable.parts, ...experimental.parts] -fail('item states on unknown parts', experimental.itemStates.filter((s) => !knownParts.includes(s.split(':')[0]))) +fail('item states on unknown parts', [...stable.itemStates, ...experimental.itemStates].filter((s) => !knownParts.includes(s.split(':')[0]))) for (const [name, list] of Object.entries({ ...stable, ...experimental, ...bridge })) { const dupes = list.filter((x, i) => list.indexOf(x) !== i) fail(`duplicate entries in ${name}`, dupes) @@ -125,6 +166,7 @@ write('bridge-contract.json', { }) console.log( `[ui-contract] OK (uiApi=${uiApi}, parts=${stable.parts.length}+${experimental.parts.length}x, ` + - `tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, ` + + `tokens=${stable.tokens.length}, slots=${stable.slots.length}+${experimental.slots.length}x, layers=${stable.layers.length}, ` + + `icons=${stable.icons.length}, sdkEvents=${stable.sdkEvents.length}, ` + `bridgeApi=${bridgeApi}, methods=${bridge.methods.length}+${bridge.experimentalMethods.length}x)`, ) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 7c06516..e4ddc2e 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -67,9 +67,11 @@ test('Static Guard (CRITICAL-1): lazy i18n domain keys are always backed by doma 'Setup.tsx', 'RuntimeOnline.tsx', 'HostView.tsx', + 'ImagesPage.tsx', 'InstallersPage.tsx', 'PluginsPage.tsx', 'PluginMarket.tsx', + 'PluginParts.tsx', 'AppSettingsPage.tsx', 'AboutPage.tsx', 'PluginPanelFrame.tsx', diff --git a/frontend/scripts/test-no-empty-catch.mjs b/frontend/scripts/test-no-empty-catch.mjs new file mode 100644 index 0000000..71cfbd7 --- /dev/null +++ b/frontend/scripts/test-no-empty-catch.mjs @@ -0,0 +1,396 @@ +// Guards the AGENTS.md rule forbidding empty catch blocks that silently turn +// failures into successes. Covers JS/TS/JSX/TSX/MJS/CJS via the TypeScript AST +// and PowerShell (.ps1/.psm1/.psd1) via a comment- and string-aware lexer. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import ts from 'typescript' + +const __dirname = path.dirname(fileURLToPath(import.meta.url)) +const repoRoot = path.resolve(__dirname, '..', '..') + +const JS_TS_EXTS = new Set(['.ts', '.tsx', '.mts', '.cts', '.js', '.jsx', '.mjs', '.cjs']) +const PS_EXTS = new Set(['.ps1', '.psm1', '.psd1']) +const SKIP_DIRS = new Set(['.git', '.debug', 'node_modules', 'dist', 'build', 'wailsjs']) + +function scriptKindFor(filePath) { + switch (path.extname(filePath).toLowerCase()) { + case '.tsx': return ts.ScriptKind.TSX + case '.ts': + case '.mts': + case '.cts': return ts.ScriptKind.TS + case '.jsx': return ts.ScriptKind.JSX + default: return ts.ScriptKind.JS + } +} + +function isEmptyBlock(block) { + return ts.isBlock(block) && block.statements.every((stmt) => ts.isEmptyStatement(stmt)) +} + +function isEmptyFunctionBody(expr) { + let current = expr + while (ts.isParenthesizedExpression(current)) current = current.expression + if (ts.isArrowFunction(current) || ts.isFunctionExpression(current)) { + return isEmptyBlock(current.body) + } + return false +} + +function getCalleeMethodName(callee) { + if (ts.isPropertyAccessExpression(callee)) return callee.name.text + if (ts.isElementAccessExpression(callee) && ts.isStringLiteralLike(callee.argumentExpression)) { + return callee.argumentExpression.text + } + return null +} + +/** + * Finds empty `catch` clauses and empty Promise `.catch(...)` / `.then(_, ...)` + * rejection callbacks in a JS/TS source string using the TypeScript AST. + */ +export function findEmptyCatchesInJS(sourceText, filePath = 'sample.ts') { + const sf = ts.createSourceFile(filePath, sourceText, ts.ScriptTarget.Latest, true, scriptKindFor(filePath)) + const findings = [] + + const record = (node, kind) => { + const pos = sf.getLineAndCharacterOfPosition(node.getStart(sf)) + findings.push({ + file: filePath, + line: pos.line + 1, + column: pos.character + 1, + kind, + }) + } + + function visit(node) { + if (ts.isCatchClause(node) && isEmptyBlock(node.block)) { + record(node, 'empty-catch-clause') + } else if (ts.isCallExpression(node)) { + const method = getCalleeMethodName(node.expression) + if (method === 'catch' && node.arguments.length >= 1 && isEmptyFunctionBody(node.arguments[0])) { + record(node.arguments[0], 'empty-promise-catch') + } else if (method === 'then' && node.arguments.length >= 2 && isEmptyFunctionBody(node.arguments[1])) { + record(node.arguments[1], 'empty-promise-then-reject') + } + } + ts.forEachChild(node, visit) + } + + visit(sf) + return findings +} + +function tokenizePowerShell(sourceText) { + const tokens = [] + let i = 0 + let line = 1 + let col = 1 + const len = sourceText.length + + const advance = () => { + const ch = sourceText[i++] + if (ch === '\n') { + line += 1 + col = 1 + } else { + col += 1 + } + return ch + } + + const atHereStringEnd = (quote) => { + if (sourceText[i] !== quote || sourceText[i + 1] !== '@') return false + return i === 0 || sourceText[i - 1] === '\n' + } + + while (i < len) { + const ch = sourceText[i] + const next = sourceText[i + 1] + + // Whitespace + if (ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n') { + advance() + continue + } + + // Block comment <# ... #> + if (ch === '<' && next === '#') { + advance() + advance() + while (i < len && !(sourceText[i] === '#' && sourceText[i + 1] === '>')) advance() + if (i < len) { + advance() + advance() + } + continue + } + + // Line comment # ... + if (ch === '#') { + while (i < len && sourceText[i] !== '\n') advance() + continue + } + + // Here-strings @' ... '@ and @" ... "@ + if (ch === '@' && (next === "'" || next === '"')) { + const quote = next + let look = i + 2 + while (look < len && (sourceText[look] === ' ' || sourceText[look] === '\t' || sourceText[look] === '\r')) look++ + if (look < len && sourceText[look] === '\n') { + const startLine = line + const startCol = col + while (i <= look) advance() + while (i < len && !atHereStringEnd(quote)) advance() + if (i < len) { + advance() + advance() + } + tokens.push({ type: 'string', value: '', line: startLine, column: startCol }) + continue + } + } + + // Single-quoted string ('' escapes ') + if (ch === "'") { + const startLine = line + const startCol = col + advance() + while (i < len) { + if (sourceText[i] === "'") { + advance() + if (sourceText[i] === "'") { + advance() + continue + } + break + } + advance() + } + tokens.push({ type: 'string', value: '', line: startLine, column: startCol }) + continue + } + + // Double-quoted string (` escapes next char, "" escapes ") + if (ch === '"') { + const startLine = line + const startCol = col + advance() + while (i < len) { + if (sourceText[i] === '`') { + advance() + if (i < len) advance() + continue + } + if (sourceText[i] === '"') { + advance() + if (sourceText[i] === '"') { + advance() + continue + } + break + } + advance() + } + tokens.push({ type: 'string', value: '', line: startLine, column: startCol }) + continue + } + + // Backtick escape outside strings + if (ch === '`') { + advance() + if (i < len) advance() + continue + } + + const startLine = line + const startCol = col + + // :: operator + if (ch === ':' && next === ':') { + advance() + advance() + tokens.push({ type: 'punct', value: '::', line: startLine, column: startCol }) + continue + } + + // Punctuation relevant to catch syntax + if ('{}[];,.'.includes(ch)) { + advance() + tokens.push({ type: 'punct', value: ch, line: startLine, column: startCol }) + continue + } + + // Word / identifier / parameter (e.g. -catch, catch) + if (/[A-Za-z_-]/.test(ch)) { + let word = '' + while (i < len && /[A-Za-z0-9_-]/.test(sourceText[i])) word += advance() + tokens.push({ type: 'word', value: word, line: startLine, column: startCol }) + continue + } + + // Any other token + advance() + tokens.push({ type: 'other', value: ch, line: startLine, column: startCol }) + } + + return tokens +} + +/** + * Finds empty `catch` blocks (including comment-only and semicolon-only blocks, + * with or without `[Type]` exception filters) in a PowerShell script. + */ +export function findEmptyCatchesInPowerShell(sourceText, filePath = 'sample.ps1') { + const tokens = tokenizePowerShell(sourceText) + const findings = [] + + for (let idx = 0; idx < tokens.length; idx++) { + const tok = tokens[idx] + if (tok.type !== 'word' || tok.value.toLowerCase() !== 'catch') continue + const prev = tokens[idx - 1] + if (prev && (prev.value === '.' || prev.value === '::')) continue + + // Skip optional comma-separated type filters: catch [TypeA], [TypeB] { ... } + let cursor = idx + 1 + while (cursor < tokens.length && tokens[cursor].value === '[') { + let depth = 0 + while (cursor < tokens.length) { + if (tokens[cursor].value === '[') depth++ + else if (tokens[cursor].value === ']') { + depth-- + if (depth === 0) { + cursor++ + break + } + } + cursor++ + } + if (cursor < tokens.length && tokens[cursor].value === ',') cursor++ + else break + } + + if (cursor >= tokens.length || tokens[cursor].value !== '{') continue + + // Scan block body until matching '}' + let bodyCursor = cursor + 1 + let empty = true + while (bodyCursor < tokens.length && tokens[bodyCursor].value !== '}') { + if (tokens[bodyCursor].value !== ';') { + empty = false + break + } + bodyCursor++ + } + if (empty && bodyCursor < tokens.length && tokens[bodyCursor].value === '}') { + findings.push({ + file: filePath, + line: tok.line, + column: tok.column, + kind: 'empty-ps-catch', + }) + } + } + + return findings +} + +function walkFiles(dir, out = []) { + if (!fs.existsSync(dir)) return out + for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { + if (SKIP_DIRS.has(entry.name)) continue + const full = path.join(dir, entry.name) + if (entry.isDirectory()) walkFiles(full, out) + else out.push(full) + } + return out +} + +test('detector self-test: catches all empty JS/TS catch forms and allows handled catches', () => { + const bad = [ + 'try { a() } catch {}', + 'try { a() } catch (e) {}', + 'try { a() } catch { /* comment only */ }', + 'try { a() } catch (e) {\n // comment only\n}', + 'try { a() } catch { ; ; }', + 'p.catch(() => {})', + 'p?.catch((e) => { /* noop */ })', + 'p["catch"](function () {})', + 'p.catch(async () => { ; })', + 'p.then(ok, () => {})', + 'p.then(ok, (err) => { // noop\n})', + ].join('\n') + + const badFindings = findEmptyCatchesInJS(bad, 'bad.ts') + assert.equal(badFindings.length, 11, `expected 11 findings, got ${JSON.stringify(badFindings)}`) + + const good = [ + 'const text = "try { a() } catch {} .catch(() => {})"', + '// try { a() } catch {}', + 'try { a() } catch (e) { console.warn(e) }', + 'try { a() } catch { return fallback }', + 'p.catch((e) => console.warn(e))', + 'p.catch(() => null)', + 'p.then(ok, (e) => handle(e))', + ].join('\n') + + assert.deepEqual(findEmptyCatchesInJS(good, 'good.ts'), []) +}) + +test('detector self-test: catches empty PowerShell catch blocks and ignores strings/comments', () => { + const bad = [ + 'try { foo } catch {}', + 'try { foo } Catch { # comment only\n}', + 'try { foo } catch { <# block comment #> ; }', + 'try { foo } catch [System.IO.IOException], [System.Exception] {}', + ].join('\n') + + const badFindings = findEmptyCatchesInPowerShell(bad, 'bad.ps1') + assert.equal(badFindings.length, 4, `expected 4 findings, got ${JSON.stringify(badFindings)}`) + + const good = [ + '# try { foo } catch {}', + '<# try { foo } catch {} #>', + '$s1 = "try { foo } catch {}"', + "$s2 = 'try { foo } catch {}'", + '$here = @"\ntry { foo } catch {}\n"@', + '$obj.catch { }', + 'try { foo } catch { Write-Warning $_ }', + 'try { foo } catch [System.Exception] { throw }', + ].join('\n') + + assert.deepEqual(findEmptyCatchesInPowerShell(good, 'good.ps1'), []) +}) + +test('repository has zero empty catch blocks across frontend/ and scripts/', () => { + const roots = [path.join(repoRoot, 'frontend'), path.join(repoRoot, 'scripts')] + const violations = [] + let scannedJS = 0 + let scannedPS = 0 + + for (const root of roots) { + for (const file of walkFiles(root)) { + const ext = path.extname(file).toLowerCase() + const rel = path.relative(repoRoot, file).split(path.sep).join('/') + if (JS_TS_EXTS.has(ext)) { + scannedJS += 1 + const text = fs.readFileSync(file, 'utf8') + violations.push(...findEmptyCatchesInJS(text, rel)) + } else if (PS_EXTS.has(ext)) { + scannedPS += 1 + const text = fs.readFileSync(file, 'utf8') + violations.push(...findEmptyCatchesInPowerShell(text, rel)) + } + } + } + + assert.ok(scannedJS > 0, 'expected to scan at least one JS/TS file') + assert.ok(scannedPS > 0, 'expected to scan at least one PowerShell file') + assert.deepEqual( + violations.map((v) => `${v.file}:${v.line}:${v.column} (${v.kind})`), + [], + `Empty catch blocks found (forbidden by AGENTS.md):\n${violations.map((v) => ` - ${v.file}:${v.line}:${v.column} (${v.kind})`).join('\n')}`, + ) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 97fe8ed..f6a71ad 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -17,13 +17,14 @@ import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './ import { LogLine, appendLog } from './lib/logs' import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' -import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' +import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' import { vmRefKey } from './lib/vmRef' import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' import { Toaster, useToasts } from './ui/toast' +import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise } from './wails' // Opened on demand, so each is its own chunk and stays out of the startup @@ -34,6 +35,7 @@ const SettingsModal = lazy(() => import('./components/SettingsModal').then((m) = 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 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 AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) @@ -77,7 +79,7 @@ export const App: React.FC = () => { const stateReady = !!state useEffect(() => { if (!stateReady) return - const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch(() => {}) } + 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) @@ -103,7 +105,9 @@ export const App: React.FC = () => { try { const saved = localStorage.getItem('reims-go-theme') if (saved === 'dark' || saved === 'light') return saved - } catch {} + } catch (e) { + console.warn('[app] read theme preference failed:', e) + } return 'system' }) const [sysDark, setSysDark] = useState(() => @@ -160,7 +164,9 @@ export const App: React.FC = () => { try { if (mode === 'system') localStorage.removeItem('reims-go-theme') else localStorage.setItem('reims-go-theme', mode) - } catch {} + } catch (e) { + console.warn('[app] persist theme preference failed:', e) + } } const toggleTheme = () => { @@ -173,7 +179,7 @@ export const App: React.FC = () => { try { return localStorage.getItem('reims-go-sidebar') !== 'hidden' } catch { return true } }) const toggleSidebar = () => setSidebarOpen((open) => { - try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch {} + try { localStorage.setItem('reims-go-sidebar', open ? 'hidden' : 'shown') } catch (e) { console.warn('[app] persist sidebar state failed:', e) } return !open }) @@ -236,11 +242,11 @@ export const App: React.FC = () => { } setLogLines((prev) => appendLog(prev, entry)) }) - api.GetActiveTheme().then(setActiveThemePayload).catch(() => {}) + api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e)) // Tasks: seed from the backend, then follow events. api.GetTasks().then((list) => { setTaskMap((prev) => (list ?? []).reduce(upsertTask, prev)) - }).catch(() => {}) + }).catch((e) => console.warn('[app] GetTasks failed:', e)) const offTask = events.onTask((task) => onTaskRef.current(task)) const onVisibility = () => { if (!document.hidden) { @@ -288,7 +294,7 @@ export const App: React.FC = () => { for (const vm of vms) { api.GetVMNote(vm.name) .then((n) => { if (live) setDisplayNames((m) => ({ ...m, [vm.name]: (n ?? '').trim() })) }) - .catch(() => {}) + .catch((e) => console.warn('[app] GetVMNote failed:', vm.name, e)) } return () => { live = false } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -302,7 +308,7 @@ export const App: React.FC = () => { for (const vm of vms) { api.GetVMMacOS(vm.name) .then((r) => { if (live) setReleases((m) => ({ ...m, [vm.name]: (r ?? '').trim() })) }) - .catch(() => {}) + .catch((e) => console.warn('[app] GetVMMacOS failed:', vm.name, e)) } return () => { live = false } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -381,7 +387,7 @@ export const App: React.FC = () => { const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => { await api.SetAppUpdateChannel(ch) setDismissedUpdate('') - try { localStorage.removeItem('reims-go-update-dismissed') } catch {} + 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)) @@ -410,7 +416,7 @@ export const App: React.FC = () => { const dismissUpdate = () => { if (!appUpdate) return setDismissedUpdate(appUpdate.latest) - try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch {} + 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) @@ -435,7 +441,9 @@ export const App: React.FC = () => { const last = localStorage.getItem('reims-go-last-version') if (last && last !== v) toasts.push({ kind: 'ok', title: tr('updateDoneToast', { v }) }) localStorage.setItem('reims-go-last-version', v) - } catch {} + } catch (e) { + console.warn('[app] track last app version failed:', e) + } }, [state?.app_version, pluginUI !== null]) const importRuntime = async () => { try { @@ -500,10 +508,46 @@ export const App: React.FC = () => { notifyInteractiveThemeState(uiStateRef.current) }, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme]) + // 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]) { + emitThemeEvent('vm.stateChanged', { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] }) + } + } + }, [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]) + // Apply active theme pack (zero extra CSS for builtin default theme, §5.1 & §8.1). useEffect(() => { - api.GetActiveTheme().then(setActiveThemePayload).catch(() => {}) - api.GetPluginUIContributions().then(setPluginUI).catch(() => {}) + api.GetActiveTheme().then(setActiveThemePayload).catch((e) => console.warn('[app] GetActiveTheme failed:', e)) + api.GetPluginUIContributions().then(setPluginUI).catch((e) => console.warn('[app] GetPluginUIContributions failed:', e)) }, [themeRevision, state?.safe_mode]) useEffect(() => { @@ -514,7 +558,7 @@ export const App: React.FC = () => { { toggleSidebar, openSettings: () => setSelected(SETTINGS_ID), - focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch(() => {}) }, + focusVMWindow: (vmName) => { void api.FocusVMWindow(vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) }, }, ) // eslint-disable-next-line react-hooks/exhaustive-deps @@ -982,12 +1026,14 @@ export const App: React.FC = () => { }, []) return ( +
+