From eb65b7cd4111590deb4cf28de20ac707d7904176 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8D=83=E5=B7=9D=E7=99=BD=E6=B5=AA?= <1679659@qq.com> Date: Tue, 1 Dec 2026 07:31:34 -0700 Subject: [PATCH] test: tier verification and add WebView2 smoke --- .github/workflows/ci.yml | 76 ++++++++--- .github/workflows/dev-release.yml | 43 +++--- .github/workflows/release.yml | 30 +++-- AGENTS.md | 1 + docs/testing.md | 30 +++++ frontend/package.json | 6 +- frontend/scripts/load-test-module.mjs | 20 +++ frontend/scripts/test-i18n.mjs | 141 +++----------------- frontend/scripts/test-keymap.mjs | 76 +++++++++++ frontend/scripts/test-tasks.mjs | 35 +++++ frontend/src/components/SettingsModal.tsx | 62 ++------- frontend/src/lib/vmKeymap.ts | 61 +++++++++ internal/app/installer_coordinator_test.go | 29 ++-- internal/config/config_test.go | 1 + internal/guesttools/clipboard_agent_test.go | 1 + internal/guesttools/folder_agent_test.go | 4 +- internal/guesttools/keymap_agent_test.go | 2 + internal/host/close_vm_windows_test.go | 5 +- internal/plugin/state_test.go | 59 ++++++++ internal/qmp/watcher_test.go | 5 +- main.go | 30 +++-- scripts/check-release-artifact.ps1 | 64 +++++++++ scripts/debug/debug.test.mjs | 4 +- scripts/smoke-webview2.ps1 | 97 ++++++++++++++ scripts/test.mjs | 123 +++++++++++++++++ 25 files changed, 753 insertions(+), 252 deletions(-) create mode 100644 docs/testing.md create mode 100644 frontend/scripts/load-test-module.mjs create mode 100644 frontend/scripts/test-keymap.mjs create mode 100644 frontend/scripts/test-tasks.mjs create mode 100644 frontend/src/lib/vmKeymap.ts create mode 100644 internal/plugin/state_test.go create mode 100644 scripts/check-release-artifact.ps1 create mode 100644 scripts/smoke-webview2.ps1 create mode 100644 scripts/test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 07be562..7a65549 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,12 +6,38 @@ on: pull_request: branches: [main] +concurrency: + group: ci-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +env: + GOCACHE: ${{ github.workspace }}/.debug/cache/go-build + jobs: verify: runs-on: windows-latest + outputs: + rolling: ${{ steps.rolling.outputs.publish }} steps: - uses: actions/checkout@v4 + - name: Check whether this push affects the rolling release + id: rolling + if: github.event_name == 'push' + env: + PREVIOUS_SHA: ${{ github.event.before }} + shell: pwsh + run: | + $publish = $true + if ($env:PREVIOUS_SHA -notmatch '^0+$') { + git fetch --depth=1 origin $env:PREVIOUS_SHA + if ($LASTEXITCODE -ne 0) { throw 'Could not fetch the previous main commit' } + $changed = git diff --name-only $env:PREVIOUS_SHA HEAD -- . ':(exclude)docs/**' ':(exclude)README.md' ':(exclude)README.en.md' ':(exclude)AGENTS.md' ':(exclude).github/ISSUE_TEMPLATE/**' ':(exclude).github/readme/**' + if ($LASTEXITCODE -ne 0) { throw 'Could not compare the pushed commits' } + $publish = [bool]$changed + } + "publish=$($publish.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT + - uses: actions/setup-go@v5 with: go-version-file: go.mod @@ -35,34 +61,46 @@ jobs: throw 'Could not parse Version from internal/version/version.go' } $ver = $Matches[1] - $tmp = Join-Path $env:RUNNER_TEMP "release-notes-$ver.md" + New-Item -ItemType Directory -Force -Path .debug/runs/ci | Out-Null + $tmp = Join-Path $PWD ".debug/runs/ci/release-notes-$ver.md" & ./scripts/build-release-notes.ps1 -Tag $ver -OutFile $tmp + "REIMS_APP_VERSION=$ver" >> $env:GITHUB_ENV Write-Host "PASS CHANGELOG.md contains valid release notes for $ver ($((Get-Item -LiteralPath $tmp).Length) bytes)" - - name: Frontend test & build + - name: Workspace hygiene shell: pwsh - run: | - pnpm --dir frontend install --frozen-lockfile - pnpm --dir frontend test - pnpm --dir frontend build + run: node scripts/debug/check.mjs - - name: Debug workspace hygiene check & self-test + - name: Install frontend dependencies shell: pwsh - run: | - node scripts/debug/check.mjs - node --test scripts/debug/debug.test.mjs + run: pnpm --dir frontend install --frozen-lockfile - - name: Go test & vet + - name: CI tests shell: pwsh - run: | - go test ./... - go vet ./... + run: node scripts/test.mjs ci + + - name: Bundle frontend + shell: pwsh + run: pnpm --dir frontend bundle - name: Build reims-go.exe (window + command-line mode) shell: pwsh run: | - New-Item -ItemType Directory -Force -Path build/bin | Out-Null - go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o build/bin/reims-go.exe . - # Command-line mode must still answer through a pipe from the GUI-subsystem build. - $out = & build/bin/reims-go.exe version | Out-String - if ($LASTEXITCODE -ne 0 -or $out -notmatch '^reims-go ') { throw "reims-go.exe version failed: $out" } + $env:GOTMPDIR = (Resolve-Path .debug/runs/ci).Path + $exe = '.debug/runs/ci/reims-go.exe' + go vet -tags desktop,production . + if ($LASTEXITCODE -ne 0) { throw 'Go desktop vet failed' } + go build -trimpath -tags desktop,production -ldflags "-H windowsgui" -o $exe . + if ($LASTEXITCODE -ne 0) { throw 'Go desktop build failed' } + ./scripts/check-release-artifact.ps1 -Executable $exe -Version $env:REIMS_APP_VERSION + + - name: WebView2 first-launch smoke + timeout-minutes: 3 + run: node scripts/test.mjs webview2 .debug/runs/ci/reims-go.exe + + rolling-release: + needs: verify + if: needs.verify.outputs.rolling == 'true' + permissions: + contents: write + uses: ./.github/workflows/dev-release.yml diff --git a/.github/workflows/dev-release.yml b/.github/workflows/dev-release.yml index d673d9d..571d6d0 100644 --- a/.github/workflows/dev-release.yml +++ b/.github/workflows/dev-release.yml @@ -1,16 +1,7 @@ name: Dev Release (Rolling) on: - push: - branches: - - main - paths-ignore: - - "docs/**" - - "README.md" - - "README.en.md" - - "AGENTS.md" - - ".github/ISSUE_TEMPLATE/**" - - ".github/readme/**" + workflow_call: workflow_dispatch: permissions: @@ -20,6 +11,9 @@ concurrency: group: dev-release-${{ github.ref }} cancel-in-progress: true +env: + GOCACHE: ${{ github.workspace }}/.debug/cache/go-build + jobs: dev-release: runs-on: windows-latest @@ -127,7 +121,8 @@ jobs: } catch { Write-Warning "Could not query latest stable runtime release: $_" } - $notesFile = Join-Path $env:RUNNER_TEMP "release-notes-dev.md" + New-Item -ItemType Directory -Force -Path .debug/runs/dev-release | Out-Null + $notesFile = Join-Path $PWD '.debug/runs/dev-release/release-notes-dev.md' & ./scripts/build-release-notes.ps1 ` -Tag $devVersion ` -Channel dev ` @@ -140,17 +135,18 @@ jobs: "RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append Write-Host "Generated dev release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $devVersion" - - name: Build frontend + - name: Install frontend dependencies shell: pwsh - run: | - pnpm --dir frontend install --frozen-lockfile - pnpm --dir frontend build + run: pnpm --dir frontend install --frozen-lockfile - - name: Go test & vet + - name: CI tests for manual builds + if: github.event_name == 'workflow_dispatch' shell: pwsh - run: | - go test ./... - go vet ./... + run: node scripts/test.mjs ci + + - name: Bundle frontend + shell: pwsh + run: pnpm --dir frontend bundle - name: Install Wails CLI shell: pwsh @@ -177,6 +173,15 @@ jobs: [IO.File]::WriteAllText((Join-Path $dist 'SHA256SUMS.txt'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($false)) Get-Content (Join-Path $dist 'SHA256SUMS.txt') + - name: Verify release artifacts + shell: pwsh + run: ./scripts/check-release-artifact.ps1 -Executable "dist-release/reims-go-$env:DEV_VERSION-windows-amd64.exe" -Version $env:DEV_VERSION -Package + + - name: WebView2 first-launch smoke for manual builds + if: github.event_name == 'workflow_dispatch' + timeout-minutes: 3 + run: node scripts/test.mjs webview2 "dist-release/reims-go-$env:DEV_VERSION-windows-amd64.exe" + - name: Update rolling dev GitHub Release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0a7d774..57328af 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,9 @@ on: permissions: contents: write +env: + GOCACHE: ${{ github.workspace }}/.debug/cache/go-build + jobs: release: runs-on: windows-latest @@ -76,7 +79,8 @@ jobs: } catch { Write-Warning "Could not query latest stable runtime release: $_" } - $notesFile = Join-Path $env:RUNNER_TEMP "release-notes-$tag.md" + New-Item -ItemType Directory -Force -Path .debug/runs/release | Out-Null + $notesFile = Join-Path $PWD ".debug/runs/release/release-notes-$tag.md" & ./scripts/build-release-notes.ps1 ` -Tag $tag ` -Channel $channel ` @@ -88,17 +92,17 @@ jobs: "RELEASE_NOTES_FILE=$notesFile" | Out-File -FilePath $env:GITHUB_ENV -Append Write-Host "Generated $channel release notes ($((Get-Item -LiteralPath $notesFile).Length) bytes) for $tag" - - name: Build frontend + - name: Install frontend dependencies shell: pwsh - run: | - pnpm --dir frontend install --frozen-lockfile - pnpm --dir frontend build + run: pnpm --dir frontend install --frozen-lockfile - - name: Go test & vet + - name: Release tests shell: pwsh - run: | - go test ./... - go vet ./... + run: node scripts/test.mjs release + + - name: Bundle frontend + shell: pwsh + run: pnpm --dir frontend bundle - name: Install Wails CLI shell: pwsh @@ -126,6 +130,14 @@ jobs: [IO.File]::WriteAllText((Join-Path $dist 'SHA256SUMS.txt'), ($lines -join "`n") + "`n", [Text.UTF8Encoding]::new($false)) Get-Content (Join-Path $dist 'SHA256SUMS.txt') + - name: Verify release artifacts + shell: pwsh + run: ./scripts/check-release-artifact.ps1 -Executable "dist-release/reims-go-$env:RELEASE_TAG-windows-amd64.exe" -Version $env:RELEASE_TAG -Package + + - name: WebView2 first-launch smoke + timeout-minutes: 3 + run: node scripts/test.mjs webview2 "dist-release/reims-go-$env:RELEASE_TAG-windows-amd64.exe" + - name: Publish GitHub Release env: GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/AGENTS.md b/AGENTS.md index d686e4b..021663c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -70,6 +70,7 @@ - [`docs/roadmap.md`](docs/roadmap.md) — 公开路线图与近期重点 - [`docs/architecture.md`](docs/architecture.md) — 系统架构、模块职责与安全边界 - [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案) +- [`docs/testing.md`](docs/testing.md) — 分级测试、覆盖范围、本地并发与发布校验 - [`docs/pr-review-guidelines.md`](docs/pr-review-guidelines.md) — PR 变更归属、跨仓交付与客户端独立性审查 - [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范 - [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范 diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..285ee05 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,30 @@ +# 测试 + +在仓库根目录运行。测试入口需要 Node.js 22+。前端测试首次运行前执行 `pnpm --dir frontend install --frozen-lockfile`。 + +| 场景 | 命令 | 验证内容 | +| :--- | :--- | :--- | +| 改动一个或几个 Go 包 | `node scripts/test.mjs quick go ./internal/app ./internal/qmp` | 指定包的测试,可命中 Go 缓存 | +| 改动前端 | `node scripts/test.mjs quick frontend` | 界面逻辑、国际化、架构约束和静态检查 | +| 改动持久化或升级 | `node scripts/test.mjs quick storage` | 配置和数据目录、迁移及插件状态存储,使用真实临时文件 | +| 改动调试工具 | `node scripts/test.mjs quick tooling` | 临时目录和工单工具自测 | +| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`cmd/`、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测 | +| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 | +| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 | + +GitHub CI 额外检查变更日志、工作区纪律、前端生产打包、Windows GUI 可执行文件的 `version` 输出与 WebView2 首启。`main` 的滚动版复用同一提交的 CI 测试,手动构建会跑 CI 测试并冒烟。带版本标签的发布先跑发布候选测试,再对待发布的 EXE 运行桌面冒烟。两个发布流程都在上传前验证实际 EXE 的版本、ZIP 内的文件和 SHA-256 校验和。 + +桌面冒烟需要已安装 WebView2 Runtime 的 Windows 桌面会话。测试通过 Windows UI Automation 填入独立的数据目录、点击继续,检查配置和目录指针落盘,并等待运行时设置页渲染。每次运行使用独立的 WebView2 配置目录。失败时,测试入口打印保留的目录,应用日志在其中的 `app.log`。 + +## 并发和速度 + +每次调用在 `.debug/tmp/` 创建独立的运行目录。Go 编译临时文件、测试夹具和应用状态都写入该目录,成功后清理,失败时保留路径。测试进程共享 `.debug/cache/` 下的 Go 构建缓存。新建监听服务应让 OS 分配端口,原生窗口等系统级资源也需要使用每次运行独有的标识。 + +Go 包并发默认为可用 CPU 数与 4 的较小值。多个 Agent 同时跑 Go 套件时,可通过 `REIMS_TEST_JOBS` 分配预算,例如 PowerShell 中用 `$env:REIMS_TEST_JOBS = '2'`。依赖安装和生成生产包由工作流单独执行。同一工作树需要同时生成产物时,为每个构建使用独立工作树。 + +## 覆盖和后续改进 + +- 前端的任务排序、过期事件和键盘映射由生产逻辑模块直接验证。涉及 React 交互时,优先补一条用户可观察的场景,例如切换 VM 时旧请求返回,避免按源码行或正则提取组件代码执行。 +- Go 单包验证业务规则,跨层测试保留真实接口处的代表性用例,包括 Wails 桥接、QMP、HTTP、子进程与数据迁移。异步用例用完成信号或 `testing/synctest` 验证顺序,超时用于报告卡住的测试。 +- 当前持久化使用文件。`config`、`dataroot`、`datamigrate` 和 `plugin` 测试验证真实磁盘读写、旧数据迁移、重开状态、备份和损坏处理。新增 SQL 存储时,在持久化测试中使用每次运行独立的数据库,覆盖迁移与事务失败。 +- 真实 `reims-ctl`、`qemu-img`、OpenCore 及安装镜像用例依赖各自的 `REIMS_GO_TEST_*` 输入,常规档位会跳过它们。发布涉及虚拟机或运行时时,需要在 Windows 主机验证受影响的路径,例如 VM 开关机或磁盘操作。 diff --git a/frontend/package.json b/frontend/package.json index ef6431b..93ce7b7 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,8 +5,10 @@ "type": "module", "scripts": { "dev": "vite", - "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", + "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-tasks.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs", + "typecheck": "tsc --noEmit", + "bundle": "vite build && node scripts/check-ui-contract.mjs", + "build": "tsc --noEmit && pnpm run bundle", "preview": "vite preview" }, "dependencies": { diff --git a/frontend/scripts/load-test-module.mjs b/frontend/scripts/load-test-module.mjs new file mode 100644 index 0000000..874275c --- /dev/null +++ b/frontend/scripts/load-test-module.mjs @@ -0,0 +1,20 @@ +import path from 'node:path' +import { createRequire } from 'node:module' + +const frontend = path.resolve(import.meta.dirname, '..') +// Use Vite's esbuild without installing a separate test toolchain. +const fromFrontend = createRequire(path.join(frontend, 'package.json')) +const fromVite = createRequire(fromFrontend.resolve('vite/package.json')) +const esbuild = fromVite('esbuild') + +export async function loadTestModule(source) { + const { outputFiles } = await esbuild.build({ + stdin: { contents: source, resolveDir: path.join(frontend, 'src'), loader: 'ts' }, + bundle: true, + write: false, + format: 'esm', + platform: 'browser', + target: 'es2022', + }) + return import(`data:text/javascript;base64,${Buffer.from(outputFiles[0].text).toString('base64')}`) +} diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index db695ed..454b255 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -3,38 +3,13 @@ import assert from 'node:assert/strict' import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' -import { createRequire } from 'node:module' +import { loadTestModule } from './load-test-module.mjs' const __dirname = path.dirname(fileURLToPath(import.meta.url)) const rootDir = path.resolve(__dirname, '..') const srcDir = path.join(rootDir, 'src') const localesDir = path.resolve(rootDir, '..', 'locales', 'en-US') -// Resolve esbuild from Vite's dependency tree (zero extra npm dependencies per §8.1). -const requireFromRoot = createRequire(path.join(rootDir, 'package.json')) -const vitePkgPath = requireFromRoot.resolve('vite/package.json') -const requireFromVite = createRequire(vitePkgPath) -const esbuild = requireFromVite('esbuild') - -async function loadBundledTS(entrySource) { - const result = await esbuild.build({ - stdin: { - contents: entrySource, - resolveDir: srcDir, - sourcefile: 'test-entry.ts', - loader: 'ts', - }, - bundle: true, - write: false, - format: 'esm', - platform: 'browser', - target: 'es2022', - }) - const code = result.outputFiles[0].text - const dataUrl = `data:text/javascript;base64,${Buffer.from(code, 'utf8').toString('base64')}` - return import(dataUrl) -} - function walkFiles(dir, exts) { const out = [] for (const entry of fs.readdirSync(dir, { withFileTypes: true })) { @@ -219,22 +194,22 @@ test('Static Guard (CRITICAL-4): software-composited UI avoids backdrop-filter a ) }) -test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppError (HIGH-2), RTL (L-2), and en-XA', async () => { - const mod = await loadBundledTS(` - import './i18n/domains/wizard.gen' - import './i18n/domains/settings.gen' - import './i18n/domains/plugins.gen' - export * from './i18n' - export * from './lib/format' - export * from './lib/themeEngine' - `) +const mod = await loadTestModule(` + import './i18n/domains/wizard.gen' + import './i18n/domains/settings.gen' + import './i18n/domains/plugins.gen' + export * from './i18n' + export * from './lib/format' + export * from './lib/themeEngine' +`) - // 1. Built-in bilingual + ICU plural + decimal formatting +test('memory sizes use the active locale’s decimal separator', () => { assert.equal(mod.formatMemory('16G', 'en-US'), '16 GB') assert.equal(mod.formatMemory('1536M', 'de-DE'), '1,5 GB') +}) - // 2. H-3 & HIGH-9: Functional plugin L10n (has_ui_messages: false) must NOT pollute host UI locales, - // while full language pack (has_ui_messages: true) activates properly. +test('plugin translations can be used without adding a host UI locale', (t) => { + t.after(() => mod.setPluginLocales([])) mod.setPluginLocales([ { locale: 'de-DE', @@ -266,17 +241,16 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr assert.equal(mod.t('ja-JP', 'sidebarSettings'), '設定') assert.equal(mod.tPlugin('acme.de', 'de-DE', 'btn.run', { n: 3 }), 'Ausführen (3)') assert.equal(mod.getPluginMessageBundle('acme.de', 'ja-JP')['btn.run'], '実行 ({n})') +}) - // 3. Pseudo-locale en-XA wraps host & plugin strings in ⟦...⟧ and preserves placeholders +test('the pseudo-locale marks host and plugin strings and preserves placeholders', () => { const pseudoHost = mod.t('en-XA', 'cores', { n: 8 }) assert.ok(pseudoHost.startsWith('⟦') && pseudoHost.endsWith('⟧') && pseudoHost.includes('8'), `bad pseudoHost: ${pseudoHost}`) const pseudoPlugin = mod.tPlugin('acme.de', 'en-XA', 'btn.run', { n: 5 }, 'Run ({n})') assert.ok(pseudoPlugin.startsWith('⟦') && pseudoPlugin.includes('5'), `bad pseudoPlugin: ${pseudoPlugin}`) +}) - // Reset plugin locales - mod.setPluginLocales([]) - - // 4. HIGH-2: parseAppError handles suffix & prefix [E_CODE], multi-line summaries, codeless [detail], and Error objects +test('bridge errors preserve their code, summary and diagnostic detail', () => { const codedSuffix = mod.parseAppError('First summary line\nSecond summary line [E_VM_BUSY]\n[detail] raw trace line 1\nline 2') assert.equal(codedSuffix.code, 'E_VM_BUSY') assert.equal(codedSuffix.summary, 'First summary line\nSecond summary line') @@ -295,19 +269,20 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr const objErr = mod.parseAppError({ message: 'Timeout [E_NET]' }) assert.equal(objErr.code, 'E_NET') assert.equal(objErr.summary, 'Timeout') +}) - // 5. L-2: 8-subtag RTL parity with Go backend +test('text direction and guest language presets resolve from locale identifiers', () => { for (const rtl of ['ar-SA', 'he-IL', 'iw-IL', 'fa-IR', 'ur-PK', 'ps-AF', 'dv-MV', 'yi']) { assert.equal(mod.isRTLLocale(rtl), true, `expected RTL for ${rtl}`) } assert.equal(mod.isRTLLocale('en-US'), false) assert.equal(mod.isRTLLocale('zh-TW'), false) - // 6. LOW-5: resolveGuestLang structured preset lookup without punctuation splitting const zhGuest = mod.resolveGuestLang('zh-CN', 'zh-Hans:0') assert.ok(zhGuest.label.length > 0 && zhGuest.detail && zhGuest.detail.length > 0) +}) - // 7. HIGH-1: Theme seed token derivation enforces WCAG 2.1 AA contrast on bright vs dark accents +test('theme accents retain WCAG AA contrast on light and dark surfaces', () => { const hslContrast = (hslStr, surfaceLum) => { const m = hslStr.match(/hsl\(\s*(\d+)\s+(\d+)%\s+(\d+)%\s*\)/) assert.ok(m, `unexpected hsl string: ${hslStr}`) @@ -332,77 +307,3 @@ test('Runtime i18n v2: ICU formatting, ghost-locale isolation (H-3), parseAppErr assert.equal(appleBlue['--accent-text'], '#ffffff') assert.ok(hslContrast(appleBlue['--accent-soft-text'], 0.015) >= 4.5, `appleBlue dark contrast too low: ${appleBlue['--accent-soft-text']}`) }) - - -test('VM keymap preserves preset bindings and isolates pending writes by VM', async () => { - const source = fs.readFileSync(path.join(srcDir, 'components/SettingsModal.tsx'), 'utf8') - const normalized = source.replaceAll('\r\n', '\n') - const effects = normalized.slice( - normalized.indexOf(' useEffect(() => {\n setKeymap(null)'), - normalized.indexOf(' const updateDriveShares'), - ) - const preset = normalized.match(/onChange=\{(\(preset\) => \{\n\s+if \(preset === keymap\.preset\)[\s\S]*?\n\s+\})\} \/>/)?.[1] - assert.ok(effects.includes('const updateKeymap') && preset) - const { render } = await loadBundledTS(` - export function render({ detail, api, useEffect, window, activeVMNameRef, keymapWrite, - keymapRevision, setKeymap, setKeymapErr, setKeymapBusy, parseAppError, keymap }) { - const cat = 'input' - const running = true - ${effects} - return ${preset} - } - `) - let finishWrite - const writes = [] - const reads = [] - const state = {} - let failRead = true - const context = { - api: { - SetVMKeymap(name, req) { - writes.push([name, req]) - return new Promise((resolve) => { finishWrite = resolve }) - }, - async GetVMKeymap(name) { - reads.push(name) - if (name === 'b' && failRead) throw Error('temporary') - return { preset: 'off', bindings: {} } - }, - }, - useEffect(effect) { - const cleanup = effect() - if (cleanup) this.cleanups.push(cleanup) - }, - cleanups: [], - window: { setInterval(refresh) { this.refresh = refresh }, clearInterval() {} }, - activeVMNameRef: { current: 'a' }, - keymapWrite: { current: new Set() }, - keymapRevision: { current: new Map() }, - setKeymap(value) { state.keymap = value }, - setKeymapErr(value) { state.error = value }, - setKeymapBusy(value) { state.busy = value }, - parseAppError: (error) => ({ summary: error.message }), - } - context.useEffect = context.useEffect.bind(context) - const bindings = { lwin: 'lcmd' } - const change = render({ ...context, detail: { name: 'a' }, keymap: { preset: 'win_to_cmd', bindings } }) - change('win_to_cmd') - assert.deepEqual(writes, []) - change('custom') - assert.deepEqual(writes, [['a', { preset: 'custom', bindings }]]) - context.cleanups.pop()() - context.activeVMNameRef.current = 'b' - const changeB = render({ ...context, detail: { name: 'b' }, keymap: { preset: 'custom', bindings } }) - changeB('custom') - assert.equal(writes.length, 1) - assert.deepEqual(reads, ['a', 'b']) - assert.equal(state.busy, false) - await new Promise(setImmediate) - assert.equal(state.error, 'temporary') - failRead = false - await context.window.refresh() - assert.equal(state.error, '') - finishWrite({ preset: 'custom', bindings }) - await new Promise(setImmediate) - assert.deepEqual(state.keymap, { preset: 'off', bindings: {} }) -}) diff --git a/frontend/scripts/test-keymap.mjs b/frontend/scripts/test-keymap.mjs new file mode 100644 index 0000000..343efa6 --- /dev/null +++ b/frontend/scripts/test-keymap.mjs @@ -0,0 +1,76 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { loadTestModule } from './load-test-module.mjs' + +const { createKeymapRequests, keymapPresetUpdate } = await loadTestModule(`export * from './lib/vmKeymap'`) +const off = { preset: 'off', bindings: {} } +const custom = { preset: 'custom', bindings: { lwin: 'lcmd' } } + +test('switching to custom preserves the previous preset bindings', () => { + const preset = { ...custom, preset: 'win_to_cmd' } + assert.equal(keymapPresetUpdate(preset, 'win_to_cmd'), undefined) + assert.deepEqual(keymapPresetUpdate(preset, 'custom'), custom) + assert.deepEqual(keymapPresetUpdate(off, 'custom'), { preset: 'custom', bindings: {} }) +}) + +test('a pending write for one VM does not block or overwrite another VM', async () => { + const saved = Promise.withResolvers() + const writes = [] + let active = 'a' + let state = {} + const requests = createKeymapRequests({ + async GetVMKeymap(name) { + assert.equal(name, 'b') + return off + }, + SetVMKeymap(name, request) { + writes.push([name, request]) + return saved.promise + }, + }, () => active, (patch) => Object.assign(state, patch)) + + const write = requests.write('a', custom) + await requests.write('a', off) + assert.deepEqual(writes, [['a', custom]]) + assert.equal(state.busy, true) + + active = 'b' + state = requests.initial('b') + await requests.watch('b').refresh() + saved.resolve(custom) + await write + assert.deepEqual(state, { keymap: off, busy: false, error: '' }) + assert.equal(requests.initial('a').busy, false) +}) + +test('a failed keymap read recovers on the next refresh', async () => { + let fail = true + const state = {} + const requests = createKeymapRequests({ + async GetVMKeymap() { + if (fail) throw new Error('temporary') + return off + }, + }, () => 'vm', (patch) => Object.assign(state, patch)) + const watch = requests.watch('vm') + await watch.refresh() + assert.equal(state.error, 'temporary') + fail = false + await watch.refresh() + assert.deepEqual(state, { keymap: off, error: '' }) +}) + +test('a read started before a write cannot restore the old keymap', async () => { + const previousRead = Promise.withResolvers() + const state = {} + const requests = createKeymapRequests({ + GetVMKeymap: () => previousRead.promise, + SetVMKeymap: async () => custom, + }, () => 'vm', (patch) => Object.assign(state, patch)) + + const read = requests.watch('vm').refresh() + await requests.write('vm', custom) + previousRead.resolve(off) + await read + assert.deepEqual(state, { keymap: custom, busy: false, error: '' }) +}) diff --git a/frontend/scripts/test-tasks.mjs b/frontend/scripts/test-tasks.mjs new file mode 100644 index 0000000..cfdc483 --- /dev/null +++ b/frontend/scripts/test-tasks.mjs @@ -0,0 +1,35 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { loadTestModule } from './load-test-module.mjs' + +const { currentTask, findActiveOfflineTask, pruneFinishedTasks, upsertTask } = + await loadTestModule(`export * from './lib/tasks'`) + +const task = (id, overrides = {}) => ({ + id, kind: 'vm-create', subject: id, status: 'running', started_at: 10, updated_at: 20, + installer_kind: 'offline', installer_version: '26.7.3', installer_phase: 'downloading', ...overrides, +}) + +test('late progress cannot replace a newer completed task', () => { + const completed = task('vm', { status: 'done', updated_at: 30 }) + const tasks = { vm: completed } + assert.deepEqual(upsertTask(tasks, task('vm')), tasks) + assert.deepEqual(pruneFinishedTasks(tasks, 30), tasks) + assert.deepEqual(pruneFinishedTasks(tasks, 31), {}) +}) + +test('the status bar favors active work over a newer queued download', () => { + const vm = task('vm') + const queued = task('queued', { installer_phase: 'queued', updated_at: 25 }) + const finished = task('done', { status: 'done', updated_at: 30 }) + assert.deepEqual(currentTask({ queued, vm, finished }), { task: vm, running: 2 }) +}) + +test('one installer download represents the VM creations waiting for it', () => { + const download = task('download', { kind: 'installer-download', started_at: 15 }) + const vm = task('vm', { vm: 'vm one' }) + const other = task('other', { installer_version: '15.8.3' }) + assert.deepEqual(findActiveOfflineTask([vm, other, download], '26.7.3'), { + primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'], + }) +}) diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx index 80f26e7..e4cdf42 100644 --- a/frontend/src/components/SettingsModal.tsx +++ b/frontend/src/components/SettingsModal.tsx @@ -31,6 +31,7 @@ import { } from '../lib/format' import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations' import { useVMStats } from '../lib/vmStats' +import { createKeymapRequests, keymapPresetUpdate, type KeymapState } from '../lib/vmKeymap' import { DiskCompactResult, DiskResizeResult, DisplayInfo, DriveShareSettings, HostReport, Locale, Optimization, PluginInfo, SetOpts, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, SMBIOSIdentity, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types' import { Button, IconButton } from '../ui/controls' import { Modal } from '../ui/dialog' @@ -39,7 +40,7 @@ import type { ToastInput } from '../ui/toast' import { api } from '../wails' import type { app as WailsApp } from '../../wailsjs/go/models' import { formatAffinitySummary } from './AffinityDialog' -import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier, VMKeymapStatus, VMKeymapUpdate } from '../types' +import type { VMKeymapPreset, VMKeymapHostModifier, VMKeymapGuestModifier } from '../types' const SchemaForm = lazy(() => import('./SchemaForm').then((m) => ({ default: m.SchemaForm }))) @@ -193,11 +194,9 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats const [displayErr, setDisplayErr] = useState('') const displayBusyRef = useRef(false) const displayReqSeqRef = useRef(0) - const [keymap, setKeymap] = useState(null) - const [keymapErr, setKeymapErr] = useState('') - const [keymapBusy, setKeymapBusy] = useState(false) - const keymapWrite = useRef(new Set()) - const keymapRevision = useRef(new Map()) + const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState({ keymap: null, error: '', busy: false }) + const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current, + (patch) => setKeymapState((state) => ({ ...state, ...patch })))) const [vmPlugins, setVmPlugins] = useState([]) const [vmPluginVals, setVmPluginVals] = useState>>({}) const vmSettingsKey = `${driverID}:${detail.name}` @@ -447,51 +446,16 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats } useEffect(() => { - setKeymap(null) - setKeymapBusy(keymapWrite.current.has(detail.name)) - setKeymapErr('') - }, [detail.name]) + setKeymapState(keymapRequests.initial(detail.name)) + }, [detail.name, keymapRequests]) useEffect(() => { if (cat !== 'input') return - let active = true - let pending = false - const refresh = async () => { - if (pending || keymapWrite.current.has(detail.name)) return - const revision = keymapRevision.current.get(detail.name) - pending = true - try { - const next = await api.GetVMKeymap(detail.name) - if (active && revision === keymapRevision.current.get(detail.name)) { - setKeymap(next) - setKeymapErr('') - } - } catch (e) { - if (active && revision === keymapRevision.current.get(detail.name)) setKeymapErr(parseAppError(e).summary) - } finally { - pending = false - } - } + const { refresh, stop } = keymapRequests.watch(detail.name) void refresh() const timer = window.setInterval(refresh, 3000) - return () => { active = false; window.clearInterval(timer) } - }, [cat, detail.name, running]) - - const updateKeymap = (req: VMKeymapUpdate) => { - const name = detail.name - if (keymapWrite.current.has(name)) return - keymapRevision.current.set(name, (keymapRevision.current.get(name) ?? 0) + 1) - keymapWrite.current.add(name) - setKeymapBusy(true) - setKeymapErr('') - void api.SetVMKeymap(name, req) - .then((next) => { if (activeVMNameRef.current === name) setKeymap(next) }) - .catch((e) => { if (activeVMNameRef.current === name) setKeymapErr(parseAppError(e).summary) }) - .finally(() => { - keymapWrite.current.delete(name) - if (activeVMNameRef.current === name) setKeymapBusy(false) - }) - } + return () => { stop(); window.clearInterval(timer) } + }, [cat, detail.name, running, keymapRequests]) const updateDriveShares = async (enabled: boolean, selected: string[]) => { if (driveBusyRef.current || !driveSettings) return @@ -1527,8 +1491,8 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats control={ label={tr('keymapPresetTitle')} value={keymap.preset} options={[{ value: 'off', label: tr('keymapPresetOff') }, { value: 'win_to_cmd', label: tr('keymapPresetWinToCmd') }, { value: 'swap_alt_win', label: tr('keymapPresetSwapAltWin') }, { value: 'custom', label: tr('keymapPresetCustom') }]} onChange={(preset) => { - if (preset === keymap.preset) return - updateKeymap({ preset, bindings: preset === 'custom' && keymap.preset !== 'off' ? keymap.bindings : {} }) + const request = keymapPresetUpdate(keymap, preset) + if (request) void keymapRequests.write(detail.name, request) }} />} /> {keymap.preset === 'custom' && ([ @@ -1553,7 +1517,7 @@ export const SettingsModal: React.FC = ({ locale, detail, driverID, stats { value: 'esc', label: tr('keymapGuestEsc') }, { value: 'disabled', label: tr('keymapGuestDisabled') }, ]} - onChange={(target) => updateKeymap({ preset: 'custom', bindings: { ...keymap.bindings, [modifier]: target } })} />} + onChange={(target) => { void keymapRequests.write(detail.name, { preset: 'custom', bindings: { ...keymap.bindings, [modifier]: target } }) }} />} /> ))} } diff --git a/frontend/src/lib/vmKeymap.ts b/frontend/src/lib/vmKeymap.ts new file mode 100644 index 0000000..51564df --- /dev/null +++ b/frontend/src/lib/vmKeymap.ts @@ -0,0 +1,61 @@ +import { parseAppError } from '../i18n' +import type { VMKeymapPreset, VMKeymapStatus, VMKeymapUpdate } from '../types' + +type KeymapAPI = { + GetVMKeymap(name: string): Promise + SetVMKeymap(name: string, request: VMKeymapUpdate): Promise +} + +export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean } + +export function keymapPresetUpdate(current: VMKeymapStatus, preset: VMKeymapPreset): VMKeymapUpdate | undefined { + if (preset === current.preset) return undefined + return { preset, bindings: preset === 'custom' && current.preset !== 'off' ? current.bindings : {} } +} + +export function createKeymapRequests(api: KeymapAPI, activeVM: () => string, update: (patch: Partial) => void) { + const writes = new Set() + const revisions = new Map() + + return { + initial(name: string): KeymapState { + return { keymap: null, error: '', busy: writes.has(name) } + }, + watch(name: string) { + let active = true + let pending = false + return { + async refresh() { + if (!active || pending || writes.has(name)) return + const revision = revisions.get(name) + const current = () => active && activeVM() === name && revision === revisions.get(name) + pending = true + try { + const keymap = await api.GetVMKeymap(name) + if (current()) update({ keymap, error: '' }) + } catch (error) { + if (current()) update({ error: parseAppError(error).summary }) + } finally { + pending = false + } + }, + stop() { active = false }, + } + }, + async write(name: string, request: VMKeymapUpdate) { + if (writes.has(name)) return + revisions.set(name, (revisions.get(name) ?? 0) + 1) + writes.add(name) + update({ busy: true, error: '' }) + try { + const keymap = await api.SetVMKeymap(name, request) + if (activeVM() === name) update({ keymap }) + } catch (error) { + if (activeVM() === name) update({ error: parseAppError(error).summary }) + } finally { + writes.delete(name) + if (activeVM() === name) update({ busy: false }) + } + }, + } +} diff --git a/internal/app/installer_coordinator_test.go b/internal/app/installer_coordinator_test.go index b4b90f6..d01e5f7 100644 --- a/internal/app/installer_coordinator_test.go +++ b/internal/app/installer_coordinator_test.go @@ -5,6 +5,7 @@ import ( "errors" "sync/atomic" "testing" + "testing/synctest" "time" "github.com/Nwflower/reims-go/internal/macos/installer" @@ -87,6 +88,10 @@ func TestInstallerCoordinatorForwardDedupAndQueueing(t *testing.T) { } func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) { + synctest.Test(t, testInstallerCoordinatorJoinAndCancel) +} + +func testInstallerCoordinatorJoinAndCancel(t *testing.T) { sent := newTestTasks(t) newTestCoordinator(t) a := &App{} @@ -115,19 +120,13 @@ func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) { }() // Wait until vm-create mirrors progress. - deadline := time.Now().Add(2 * time.Second) + synctest.Wait() mirrored := false - for time.Now().Before(deadline) { - for _, task := range tasks.list() { - if task.ID == vmID && task.InstallerVersion == "26.7.3" && task.Percent == 40 { - mirrored = true - break - } - } - if mirrored { + for _, task := range tasks.list() { + if task.ID == vmID && task.InstallerVersion == "26.7.3" && task.Percent == 40 { + mirrored = true break } - time.Sleep(10 * time.Millisecond) } if !mirrored { t.Fatalf("vm-create did not mirror in-progress download: %+v", *sent) @@ -163,7 +162,7 @@ func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) { } done2 <- err }() - time.Sleep(30 * time.Millisecond) + synctest.Wait() installerDownloads.complete(dlRun, &installer.Result{Version: "26.7.3", Image: "C:/ok.img"}, nil) select { case err := <-done2: @@ -181,6 +180,10 @@ func TestInstallerCoordinatorReverseJoinAndIndependentVMCancel(t *testing.T) { } func TestInstallerCoordinatorPauseStandaloneCancelsWaitingVMAndTakeoverOnVMCancel(t *testing.T) { + synctest.Test(t, testInstallerCoordinatorPauseAndTakeover) +} + +func testInstallerCoordinatorPauseAndTakeover(t *testing.T) { newTestTasks(t) newTestCoordinator(t) a := &App{} @@ -196,7 +199,7 @@ func TestInstallerCoordinatorPauseStandaloneCancelsWaitingVMAndTakeoverOnVMCance }) done1 <- err }() - time.Sleep(30 * time.Millisecond) + synctest.Wait() installerDownloads.complete(dlRun, nil, context.Canceled) if err := <-done1; !errors.Is(err, context.Canceled) { t.Fatalf("waiting vm err = %v, want context.Canceled", err) @@ -219,7 +222,7 @@ func TestInstallerCoordinatorPauseStandaloneCancelsWaitingVMAndTakeoverOnVMCance } doneB <- err }() - time.Sleep(30 * time.Millisecond) + synctest.Wait() installerDownloads.complete(vmARun, nil, context.Canceled) select { case err := <-doneB: diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 51b9d86..d95dc1f 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -19,6 +19,7 @@ func isolate(t *testing.T) (legacy string) { t.Setenv("HOME", cfgHome) } t.Setenv("REIMS_GO_DATA_ROOT", "") + t.Setenv("REIMS_GO_LOCATION_FILE", "") legacy = filepath.Join(t.TempDir(), "legacy") old := legacyDataRoot legacyDataRoot = func() string { return legacy } diff --git a/internal/guesttools/clipboard_agent_test.go b/internal/guesttools/clipboard_agent_test.go index 98b920a..1a0a382 100644 --- a/internal/guesttools/clipboard_agent_test.go +++ b/internal/guesttools/clipboard_agent_test.go @@ -36,6 +36,7 @@ func TestGuestAgentClipboardScript(t *testing.T) { "guest_only_after_switch", "cold_guest_only", "cold_304", "empty_text_and_png_fallback", } { t.Run(name, func(t *testing.T) { + t.Parallel() tmp := t.TempDir() script := filepath.Join(tmp, "clipboard-test.sh") code := "set -eu\n" + agent[start:end] + clipboardShellFixture diff --git a/internal/guesttools/folder_agent_test.go b/internal/guesttools/folder_agent_test.go index 290333b..33ec082 100644 --- a/internal/guesttools/folder_agent_test.go +++ b/internal/guesttools/folder_agent_test.go @@ -22,6 +22,7 @@ func TestGuestAgentFolderMounts(t *testing.T) { } run := func(t *testing.T, script string, args ...string) { t.Helper() + t.Parallel() cmd := exec.Command(sh, args...) cmd.Dir = t.TempDir() if err := os.WriteFile(filepath.Join(cmd.Dir, "mount_webdav"), []byte(folderMountWebDAV), 0o755); err != nil { @@ -38,9 +39,6 @@ func TestGuestAgentFolderMounts(t *testing.T) { !strings.Contains(install, "Reims Guest Tools 8 installed and connected!") { t.Fatal("missing Guest Tools version 10") } - for name, script := range map[string]string{"agent": agent, "uninstaller": uninstall, "installer": install} { - t.Run(name+"_syntax", func(t *testing.T) { run(t, script, "-n") }) - } mounts := scriptSection(t, agent, "urlencode() {", "\nhash_file() {") + scriptSection(t, agent, "\ndrive_mount_failures=", "\nreport_status() {") t.Run("reconcile", func(t *testing.T) { diff --git a/internal/guesttools/keymap_agent_test.go b/internal/guesttools/keymap_agent_test.go index 328fc22..eed06eb 100644 --- a/internal/guesttools/keymap_agent_test.go +++ b/internal/guesttools/keymap_agent_test.go @@ -27,6 +27,7 @@ func TestGuestAgentKeymapScript(t *testing.T) { } for _, input := range []string{"(null)", "(\n)", "({ HIDKeyboardModifierMappingSrc = 30064771184; HIDKeyboardModifierMappingDst = 30064771299; })"} { t.Run(input, func(t *testing.T) { + t.Parallel() dir := t.TempDir() fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") fixture += "\nprintf '%s\\n' \"$1\" > state\nsync_keymap_carrier '{}'\n" @@ -52,6 +53,7 @@ func TestGuestAgentKeymapScript(t *testing.T) { } for _, teardown := range []string{"disable", "exit", "uninstall"} { t.Run(teardown, func(t *testing.T) { + t.Parallel() dir := t.TempDir() fixture := keymapShellFixture + strings.ReplaceAll(agent[start:end], "/usr/bin/hidutil", "hidutil") + keymapShellExercise if teardown == "uninstall" { diff --git a/internal/host/close_vm_windows_test.go b/internal/host/close_vm_windows_test.go index ccc59a0..46416da 100644 --- a/internal/host/close_vm_windows_test.go +++ b/internal/host/close_vm_windows_test.go @@ -57,10 +57,11 @@ func TestVMCloseConfirmation(t *testing.T) { } { ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) result := make(chan error, 1) + name := fmt.Sprintf("%s-%d", tc.name, os.Getpid()) go func() { - result <- exerciseVMCloseDialog(ctx, owner, tc.name, tc.button, tc.canSuspend) + result <- exerciseVMCloseDialog(ctx, owner, name, tc.button, tc.canSuspend) }() - choice, err := ConfirmVMClose(ctx, owner, tc.name, i18n.ZhCN, "dark", tc.canSuspend) + choice, err := ConfirmVMClose(ctx, owner, name, i18n.ZhCN, "dark", tc.canSuspend) deadline := ctx.Err() cancel() if probeErr := <-result; probeErr != nil || err != nil || choice != tc.want || deadline != nil { diff --git a/internal/plugin/state_test.go b/internal/plugin/state_test.go new file mode 100644 index 0000000..7c9f34a --- /dev/null +++ b/internal/plugin/state_test.go @@ -0,0 +1,59 @@ +package plugin_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/Nwflower/reims-go/internal/plugin" +) + +func TestStateStorePersistsSettingsAcrossReopen(t *testing.T) { + dir := t.TempDir() + store := plugin.NewStateStore(dir) + state, err := store.Load() + if err != nil { + t.Fatal(err) + } + const id = "test.settings" + state.Plugins[id] = &plugin.PluginRecord{ID: id, Enabled: true, AppSettings: map[string]any{"enabled": true}} + if err := store.Save(state); err != nil { + t.Fatal(err) + } + state.Plugins[id].Enabled = false + if err := store.Save(state); err != nil { + t.Fatal(err) + } + state, err = plugin.NewStateStore(dir).Load() + if err != nil { + t.Fatal(err) + } + if rec := state.Plugins[id]; rec == nil || rec.Enabled || rec.AppSettings["enabled"] != true { + t.Fatalf("reopened plugin = %+v", rec) + } + backup, err := os.ReadFile(store.Path() + ".bak") + if err != nil { + t.Fatal(err) + } + restoreDir := t.TempDir() + if err := os.WriteFile(filepath.Join(restoreDir, plugin.StateFileName), backup, 0o600); err != nil { + t.Fatal(err) + } + previous, err := plugin.NewStateStore(restoreDir).Load() + if err != nil { + t.Fatal(err) + } + if rec := previous.Plugins[id]; rec == nil || !rec.Enabled { + t.Fatalf("backup plugin = %+v", rec) + } +} + +func TestStateStoreReportsCorruption(t *testing.T) { + store := plugin.NewStateStore(t.TempDir()) + if err := os.WriteFile(store.Path(), []byte(`{"plugins":`), 0o600); err != nil { + t.Fatal(err) + } + if state, err := store.Load(); err == nil || state != nil { + t.Fatalf("corrupt JSON loaded as %+v, error: %v", state, err) + } +} diff --git a/internal/qmp/watcher_test.go b/internal/qmp/watcher_test.go index 8d3d0b2..011b9ff 100644 --- a/internal/qmp/watcher_test.go +++ b/internal/qmp/watcher_test.go @@ -68,7 +68,7 @@ func TestRebootSocketPathFallback(t *testing.T) { func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { t.Helper() - sockPath := filepath.Join(t.TempDir(), "reims-go-reboot.sock") + const sockPath = "reims-go-reboot.sock" ln, err := net.Listen("unix", sockPath) if err != nil { t.Fatal(err) @@ -95,6 +95,9 @@ func runMockQMPUnix(t *testing.T, eventJSON string) (bool, error) { } func TestWatchForGuestReset(t *testing.T) { + // Unix socket addresses have a small byte limit. The isolated working + // directory lets the mock and watcher use the same short relative address. + t.Chdir(t.TempDir()) reset, err := runMockQMPUnix(t, `{"event":"SHUTDOWN","data":{"guest":true,"reason":"guest-reset"}}`) if err != nil || !reset { t.Fatalf("guest-reset: got reset=%v err=%v, want true nil", reset, err) diff --git a/main.go b/main.go index 67fc8f9..b45a9f8 100644 --- a/main.go +++ b/main.go @@ -57,20 +57,24 @@ func main() { } app.RegisterLicenseTexts(licenseText, noticeText) desktopApp, hooks := app.New(trayIconPNG, launch) + // A simulated first launch must open its own window even when an installed + // instance is already running. The test mode requires a separate location file. + instanceLock := &options.SingleInstanceLock{ + UniqueId: cli.InstanceID, + OnSecondInstanceLaunch: hooks.OnSecondInstanceLaunch, + } + if os.Getenv("REIMS_GO_FIRST_RUN") == "1" { + instanceLock = nil + } err := wails.Run(&options.App{ - Title: "Reims-Go", - StartHidden: launch.Background, - // One window per user. A second launch — double-click, or `reims-go vm - // start` handing a VM over — goes to the running one instead. - SingleInstanceLock: &options.SingleInstanceLock{ - UniqueId: cli.InstanceID, - OnSecondInstanceLaunch: hooks.OnSecondInstanceLaunch, - }, - Width: 1120, - Height: 740, - MinWidth: 920, - MinHeight: 600, - Frameless: true, + Title: "Reims-Go", + StartHidden: launch.Background, + SingleInstanceLock: instanceLock, + Width: 1120, + Height: 740, + MinWidth: 920, + MinHeight: 600, + Frameless: true, DragAndDrop: &options.DragAndDrop{ EnableFileDrop: true, DisableWebViewDrop: true, diff --git a/scripts/check-release-artifact.ps1 b/scripts/check-release-artifact.ps1 new file mode 100644 index 0000000..5470737 --- /dev/null +++ b/scripts/check-release-artifact.ps1 @@ -0,0 +1,64 @@ +#Requires -Version 7.0 +param( + [Parameter(Mandatory)] [string]$Executable, + [Parameter(Mandatory)] [string]$Version, + [switch]$Package +) + +$ErrorActionPreference = 'Stop' +$exe = Get-Item -LiteralPath $Executable +$start = [Diagnostics.ProcessStartInfo]::new($exe.FullName) +$start.ArgumentList.Add('version') +$start.UseShellExecute = $false +$start.CreateNoWindow = $true +$start.RedirectStandardOutput = $true +$start.RedirectStandardError = $true +$process = [Diagnostics.Process]::Start($start) +try { + $stdout = $process.StandardOutput.ReadToEndAsync() + $stderr = $process.StandardError.ReadToEndAsync() + if (-not $process.WaitForExit(15000)) { + $process.Kill($true) + throw "$($exe.Name) version timed out" + } + $actual = $stdout.GetAwaiter().GetResult().Trim() + if ($process.ExitCode -ne 0 -or $actual -cne "reims-go $Version") { + throw "$($exe.Name) version returned '$actual' (exit $($process.ExitCode)): $($stderr.GetAwaiter().GetResult())" + } +} finally { + $process.Dispose() +} + +if ($Package) { + $zip = Get-Item -LiteralPath ([IO.Path]::ChangeExtension($exe.FullName, '.zip')) + $exeHash = (Get-FileHash -LiteralPath $exe.FullName -Algorithm SHA256).Hash + $zipHash = (Get-FileHash -LiteralPath $zip.FullName -Algorithm SHA256).Hash + $expected = @("$($exeHash.ToLowerInvariant()) $($exe.Name)", "$($zipHash.ToLowerInvariant()) $($zip.Name)") + $sums = @(Get-Content -LiteralPath (Join-Path $exe.DirectoryName 'SHA256SUMS.txt')) + if ($sums.Count -ne $expected.Count -or (Compare-Object $expected $sums -CaseSensitive)) { + throw 'SHA256SUMS.txt does not match the EXE and ZIP' + } + + $archive = [IO.Compression.ZipFile]::OpenRead($zip.FullName) + try { + $required = @($exe.Name, 'LICENSE', 'NOTICE.md') + if ($archive.Entries.Count -ne $required.Count -or (Compare-Object $required @($archive.Entries.FullName) -CaseSensitive)) { + throw 'ZIP must contain the EXE, LICENSE and NOTICE.md at its root' + } + foreach ($name in $required) { + $entry = $archive.GetEntry($name).Open() + try { + $hash = (Get-FileHash -InputStream $entry -Algorithm SHA256).Hash + $source = if ($name -eq $exe.Name) { $exeHash } else { + (Get-FileHash -LiteralPath (Join-Path $PSScriptRoot "../$name") -Algorithm SHA256).Hash + } + if ($hash -cne $source) { throw "ZIP entry $name differs from its source file" } + } finally { + $entry.Dispose() + } + } + } finally { + $archive.Dispose() + } +} +Write-Host "PASS $($exe.Name) $Version" diff --git a/scripts/debug/debug.test.mjs b/scripts/debug/debug.test.mjs index c9c8110..626e6ca 100644 --- a/scripts/debug/debug.test.mjs +++ b/scripts/debug/debug.test.mjs @@ -5,7 +5,7 @@ import fs from 'node:fs' import path from 'node:path' import test from 'node:test' import { checkDebugHygiene } from './check.mjs' -import { DEBUG_HOMES, resolveStorageRoot } from './paths.mjs' +import { DEBUG_HOMES, REPO_ROOT, resolveStorageRoot } from './paths.mjs' import { TEMPORARY_RETENTION_MS, createTemporaryFiles } from './temporary-files.mjs' import { createWorkStore } from './work-store.mjs' import { createWorkCli } from './work.mjs' @@ -143,7 +143,7 @@ test('checkDebugHygiene: rejects stray .debug entries and concrete debug citatio }) test('tmp.mjs run CLI: cleans up on success and preserves evidence on failure', () => { - const tmpCli = path.join(STORAGE, 'scripts', 'debug', 'tmp.mjs') + const tmpCli = path.join(REPO_ROOT, 'scripts', 'debug', 'tmp.mjs') const ok = spawnSync(process.execPath, [tmpCli, 'run', 'cli-ok', '--', process.execPath, '-e', 'process.exit(0)'], { encoding: 'utf8', diff --git a/scripts/smoke-webview2.ps1 b/scripts/smoke-webview2.ps1 new file mode 100644 index 0000000..43c2b57 --- /dev/null +++ b/scripts/smoke-webview2.ps1 @@ -0,0 +1,97 @@ +#Requires -Version 5.1 +param([Parameter(Mandatory)] [string]$Executable) + +$ErrorActionPreference = 'Stop' +if (!$env:REIMS_TMP_DIR) { throw 'Run with node scripts/test.mjs webview2 ' } +Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes + +$labels = Get-Content -Raw -Encoding UTF8 -LiteralPath (Join-Path $PSScriptRoot '../locales/en-US/wizard.json') | ConvertFrom-Json +$scratch = $env:REIMS_TMP_DIR +$dataRoot = Join-Path $scratch 'data' +$location = Join-Path $scratch 'location.json' +$start = [Diagnostics.ProcessStartInfo]::new((Get-Item -LiteralPath $Executable).FullName) +$start.WorkingDirectory = $scratch +$start.UseShellExecute = $false +$start.RedirectStandardOutput = $true +$start.RedirectStandardError = $true +$settings = @{ + REIMS_GO_FIRST_RUN = '1' + REIMS_GO_LOCATION_FILE = $location + REIMS_GO_DATA_ROOT = $dataRoot + REIMS_GO_LANG = 'en-US' + REIMS_GO_PLUGIN_MARKET_URL = 'off' + # Refuse external requests while exercising the offline wizard. + HTTP_PROXY = 'http://127.0.0.1:0' + HTTPS_PROXY = 'http://127.0.0.1:0' + NO_PROXY = '' + # The Wails loader uses APPDATA for its default WebView2 profile. + APPDATA = (Join-Path $scratch 'roaming') + LOCALAPPDATA = (Join-Path $scratch 'local') +} +New-Item -ItemType Directory -Path $settings.APPDATA, $settings.LOCALAPPDATA | Out-Null +foreach ($name in $settings.Keys) { $start.EnvironmentVariables[$name] = $settings[$name] } + +function Wait-Element { + param([string]$Name, [System.Windows.Automation.ControlType]$Type, [int]$Seconds = 10, [switch]$Enabled) + + $ae = [System.Windows.Automation.AutomationElement] + $conditions = @([System.Windows.Automation.PropertyCondition]::new($ae::NameProperty, $Name)) + if ($Type) { $conditions += [System.Windows.Automation.PropertyCondition]::new($ae::ControlTypeProperty, $Type) } + if ($Enabled) { $conditions += [System.Windows.Automation.PropertyCondition]::new($ae::IsEnabledProperty, $true) } + $condition = if ($conditions.Count -eq 1) { $conditions[0] } else { + [System.Windows.Automation.AndCondition]::new([System.Windows.Automation.Condition[]]$conditions) + } + $watch = [Diagnostics.Stopwatch]::StartNew() + while ($watch.Elapsed.TotalSeconds -lt $Seconds) { + $app.Refresh() + if ($app.HasExited) { throw "Reims-Go exited before '$Name' (exit $($app.ExitCode))" } + if ($app.MainWindowHandle -ne [IntPtr]::Zero) { + $window = $ae::FromHandle($app.MainWindowHandle) + $element = $window.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $condition) + if ($element) { return $element } + } + Start-Sleep -Milliseconds 150 + } + throw "Timed out waiting for '$Name' in Reims-Go (PID $($app.Id))" +} + +$app = [Diagnostics.Process]::Start($start) +$stdout = $app.StandardOutput.ReadToEndAsync() +$stderr = $app.StandardError.ReadToEndAsync() +$passed = $false +try { + $button = [System.Windows.Automation.ControlType]::Button + $invoke = [System.Windows.Automation.InvokePattern]::Pattern + $value = [System.Windows.Automation.ValuePattern]::Pattern + + Wait-Element -Name $labels.setupTitle -Seconds 45 | Out-Null + Wait-Element -Name $labels.setupContinue -Type $button -Enabled | Out-Null + if (Test-Path -LiteralPath $location) { throw 'Setup persisted a location before confirmation' } + + $other = Wait-Element -Name $labels.setupOther -Type $button -Enabled + $other.GetCurrentPattern($invoke).Invoke() + $field = Wait-Element -Name $labels.setupOther -Type ([System.Windows.Automation.ControlType]::Edit) -Enabled + $field.GetCurrentPattern($value).SetValue($dataRoot) + $next = Wait-Element -Name $labels.setupContinue -Type $button -Enabled + $next.GetCurrentPattern($invoke).Invoke() + + Wait-Element -Name $labels.setupRuntimeTitle | Out-Null + foreach ($file in @($location, (Join-Path $dataRoot 'reims-go.json'))) { + $saved = Get-Content -Raw -Encoding UTF8 -LiteralPath $file | ConvertFrom-Json + if ($saved.data_root -cne $dataRoot) { throw "Unexpected data folder in $file" } + } + $passed = $true +} finally { + try { + if (!$app.HasExited) { + & taskkill.exe /PID $app.Id /T /F | Out-Null + if (!$app.WaitForExit(10000)) { throw "Could not stop Reims-Go smoke process $($app.Id)" } + } + $log = $stdout.GetAwaiter().GetResult() + $stderr.GetAwaiter().GetResult() + [IO.File]::WriteAllText((Join-Path $scratch 'app.log'), $log) + if (!$passed -and $log) { Write-Host $log } + } finally { + $app.Dispose() + } +} +Write-Host 'PASS WebView2 first launch, custom folder persisted, runtime setup rendered' diff --git a/scripts/test.mjs b/scripts/test.mjs new file mode 100644 index 0000000..9e7dde9 --- /dev/null +++ b/scripts/test.mjs @@ -0,0 +1,123 @@ +#!/usr/bin/env node +import { spawn } from 'node:child_process' +import fs from 'node:fs' +import { availableParallelism } from 'node:os' +import path from 'node:path' +import { cachePath, REPO_ROOT, resolveStorageRoot } from './debug/paths.mjs' +import { createTemporaryFiles } from './debug/temporary-files.mjs' + +const frontend = path.join(REPO_ROOT, 'frontend') +const goTrees = ['./cmd/...', './internal/...', './pkg/...', './scripts/...'] +const hostInputs = [ + 'REIMS_GO_TEST_CTL', 'REIMS_GO_TEST_QEMU_IMG', 'REIMS_GO_TEST_OPENCORE', 'REIMS_GO_TEST_OFFLINE_IMG', +] +const usage = `Usage: node scripts/test.mjs + quick go ./internal/ [./pkg/ ...] + quick frontend | storage | tooling + ci + release + webview2 + +Set REIMS_TEST_JOBS to cap Go package concurrency (default: at most 4).` + +function run(label, command, args, env, cwd = REPO_ROOT) { + console.log(`[test] ${label}`) + return new Promise((resolve, reject) => { + const child = spawn(command, args, { cwd, env, stdio: 'inherit' }) + child.once('error', reject) + child.once('close', (code, signal) => { + if (code === 0) resolve() + else reject(new Error(`${label} failed (${signal ?? `exit ${code}`})`)) + }) + }) +} + +function select(args) { + const [profile, area, ...packages] = args + if ((profile === 'ci' || profile === 'release') && args.length === 1) return { profile } + if (profile === 'webview2' && args.length === 2) return { profile, executable: path.resolve(area) } + if (profile !== 'quick') throw new Error(usage) + if (area === 'go' && packages.length > 0) { + for (const pkg of packages) { + if (!/^\.\/(?:[\w-]+\/)*[\w-]+$/.test(pkg)) { + throw new Error(`Invalid Go package ${pkg}. Use a path such as ./internal/config.`) + } + const directory = path.join(REPO_ROOT, pkg) + if (!fs.statSync(directory, { throwIfNoEntry: false })?.isDirectory()) { + throw new Error(`Go package directory does not exist: ${pkg}`) + } + } + return { profile, area, packages } + } + if (['frontend', 'storage', 'tooling'].includes(area) && packages.length === 0) return { profile, area } + throw new Error(usage) +} + +async function main(args) { + if (args[0] === '--help' || args[0] === '-h') return console.log(usage) + const { profile, area, packages, executable } = select(args) + const jobs = Number(process.env.REIMS_TEST_JOBS ?? Math.min(4, availableParallelism())) + if (!Number.isSafeInteger(jobs) || jobs < 1) throw new Error('REIMS_TEST_JOBS must be a positive integer') + + const root = resolveStorageRoot() + const files = createTemporaryFiles(root) + const directory = files.create(`test-${profile}`, process.pid) + const started = performance.now() + console.log(`[test] ${profile}${area ? ` ${area}` : ''} in ${directory}`) + try { + const env = { + ...process.env, + TEMP: directory, + TMP: directory, + TMPDIR: directory, + GOTMPDIR: directory, + GOCACHE: cachePath(root, 'go-build'), + GOMAXPROCS: String(jobs), + REIMS_TMP_DIR: directory, + REIMS_GO_DATA_ROOT: path.join(directory, 'data'), + REIMS_GO_LOCATION_FILE: path.join(directory, 'location.json'), + REIMS_GO_FIRST_RUN: '', + REIMS_CTL_CONFIG_DIR: path.join(directory, 'ctl-config'), + REIMS_CTL_DATA_DIR: path.join(directory, 'ctl-data'), + } + for (const key of hostInputs) env[key] = '' + + const go = (targets, flags = []) => run('Go', 'go', ['test', '-timeout=3m', `-p=${jobs}`, ...flags, ...targets], env) + const front = (script) => run(`Frontend ${script}`, process.execPath, ['--run', script], env, frontend) + const tooling = () => run('Tooling', process.execPath, ['--test', 'scripts/debug/debug.test.mjs'], env) + + if (profile === 'webview2') { + if (process.platform !== 'win32') throw new Error('WebView2 smoke requires Windows') + await run('WebView2 first launch', 'powershell.exe', [ + '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', 'scripts/smoke-webview2.ps1', executable, + ], env) + } else if (profile === 'quick') { + if (area === 'go') await go(packages) + if (area === 'storage') { + await go(['./internal/config', './internal/dataroot', './internal/datamigrate']) + await go(['./internal/plugin'], ['-run=^TestStateStore']) + } + if (area === 'frontend') await front('test') + if (area === 'tooling') await tooling() + } else { + await front('test') + await front('typecheck') + const flags = profile === 'release' ? ['-count=1', '-shuffle=on', '-tags=desktop,production'] : [] + await go(goTrees, ['-vet=all', ...flags]) + await tooling() + } + + files.close(directory) + console.log(`[test] PASS in ${((performance.now() - started) / 1000).toFixed(2)}s`) + } catch (error) { + console.error(`[test] Evidence kept in ${directory}`) + throw error + } +} + +try { + await main(process.argv.slice(2)) +} catch (error) { + console.error(`[test] ${error.message}`) + process.exitCode = 1 +}