diff --git a/.github/scripts/pr-review.mjs b/.github/scripts/pr-review.mjs index 632b1df..a2eee3b 100644 --- a/.github/scripts/pr-review.mjs +++ b/.github/scripts/pr-review.mjs @@ -1,6 +1,7 @@ import { spawnSync } from "node:child_process"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { mkdtempSync, readFileSync, statSync } from "node:fs"; +import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { basename, join } from "node:path"; import { chinese, english } from "./pr-review-language.mjs"; const FILES_PER_PAGE = 100; @@ -9,6 +10,9 @@ const MAX_FILE_LENGTH = 36_000; const MAX_INLINE_FINDINGS = 6; const MAX_PREVIOUS_COMMENTS = 8; const MARKER_PREFIX = "\r?\n?/, "").trim(), 1200), inlineFindings: reviewComments.slice(0, MAX_PREVIOUS_COMMENTS).map((comment) => ({ @@ -602,11 +607,95 @@ export function configureOCR({ binary, home, language, parentEnv = process.env, return { ...baseEnv, ...credentials }; } -export async function reviewWithOCR({ binary, repo, from, to, rule, background, home, profile, language, parentEnv = process.env, processRunner = runProcess }) { +// Where OCR keeps its own state for one PR, and where the run's checkout lives. +// The key carries the PR number: one checkout holds every PR number in turn, so +// the repository directory alone means "the last run, whoever it was". The +// workflow serializes runs of one PR (cancel-in-progress), so two runs never +// share these directories at once. +export function resumeSessionDir(settings = process.env) { + const stateDirectory = settings.PR_REVIEW_STATE_DIR; + const home = settings.PR_REVIEW_SESSION_HOME?.trim(); + return join(home || (settings.LOCALAPPDATA ? join(settings.LOCALAPPDATA, "reims-go", "pr-review") : "pr-review"), + stateKey(stateDirectory, settings)); +} + +function stateKey(stateDirectory, settings) { + try { + const owner = JSON.parse(readFileSync(join(stateDirectory, "state.json"), "utf8")); + if (typeof owner.repository === "string" && Number.isInteger(owner.pr)) { + if (!REPOSITORY.test(owner.repository)) throw new Error("Invalid GitHub repository name"); + return owner.repository.split("/").join("-") + "-" + owner.pr; + } + } catch { + // Fall through to the checkout name. + } + return basename(settings.GITHUB_WORKSPACE || process.cwd()); +} + +// OCR names each session directory after the repository path: it strips the +// volume, trims leading separators, turns each separator into a dash and then +// puts the volume back with its colon underscored. Mirroring that is what lets +// this script find the session file it just asked OCR to keep. +export function encodeRepoPath(path) { + const volume = /^[A-Za-z]:/.exec(path)?.[0] ?? ""; + const body = path.slice(volume.length).split(/[/\\]+/).filter(Boolean).join("-"); + return volume.replace(":", "_") + body || "empty"; +} + +// The last session this script asked OCR to keep, and the range it covers. +// A record that cannot be read simply starts a full review again. +export function readResumeState(stateDirectory) { + try { + const record = JSON.parse(readFileSync(join(stateDirectory, RESUME_STATE_FILE), "utf8")); + return record && typeof record.session === "string" && typeof record.from === "string" && typeof record.to === "string" ? record : null; + } catch { + return null; + } +} + +// The record names the session and the commit range it was computed over. The +// session file must still exist: a cleaned-up record must not send OCR looking +// for a session that is gone. +export function revalidationOf(record, range, home, repo) { + if (!record || record.from !== range.from || record.to !== range.to || typeof record.session !== "string" || !record.session) return null; + try { + if (!statSync(join(home, ".opencodereview", "sessions", encodeRepoPath(repo), record.session + ".jsonl")).isFile()) return null; + } catch { + return null; + } + return record.session; +} + +// Only the session this run leaves behind is worth keeping; older records of +// the same PR still hold reviewed file content. +async function deleteOldSessions(home, repo, session) { + const directory = join(home, ".opencodereview", "sessions", encodeRepoPath(repo)); + let names = []; + try { + names = await readdir(directory); + } catch { + return; + } + // Only session files are managed here. Anything else in the directory is + // left alone, and keeping the records can be asked for while debugging. + if (process.env.PR_REVIEW_KEEP_SESSIONS === "true") return; + for (const name of names) { + if (name === session + ".jsonl" || !name.endsWith(".jsonl")) continue; + await rm(join(directory, name), { force: true }); + } +} + +export async function writeResumeState(stateDirectory, record) { + await mkdir(stateDirectory, { recursive: true }); + await writeFile(join(stateDirectory, RESUME_STATE_FILE), JSON.stringify(record) + "\n"); +} + +export async function reviewWithOCR({ binary, repo, from, to, rule, background, home, profile, language, resume, parentEnv = process.env, processRunner = runProcess }) { const env = configureOCR({ binary, home, language, parentEnv, processRunner }); const args = ["review", "--repo", repo, "--from", from, "--to", to, "--rule", rule, "--background-file", background, "--format", "json", "--audience", "agent", "--effort", profile.effort, "--concurrency", String(profile.concurrency), "--timeout", "10", "--max-tokens-budget", String(profile.maxTokensBudget)]; + if (resume) args.push("--resume", resume); const result = processRunner(binary, args, { cwd: home, env, timeout: 1_500_000 }); if (result.error || result.status !== 0) { // OCR exits non-zero when any item hits a provider error or timeout, but still emits the completed items. @@ -647,6 +736,21 @@ function checkedSHA(value, name) { return value.toLowerCase(); } +// Continuing an incomplete review keeps its range, so it is allowed only for +// the very revision that review was computed over. Findings it already +// published cover that revision; a new push starts a full review instead. +export function resumeTarget(previous, headSha, enabled) { + return enabled && previous?.incomplete === true && (previous.headSha ?? "").toLowerCase() === String(headSha ?? "").toLowerCase(); +} + +// An incomplete review never anchors an incremental run: it did not finish the +// range it started, so a later commit range would leave that work undone. It +// may still be continued over its own range. +export function previousReviewFor(previous, resume) { + if (!previous) return null; + return !previous.incomplete || resume ? previous : null; +} + export async function selectReviewRange({ previousReview, isManual, baseSha, headSha, mergeBase, fetchCheckpoint, isAncestor }) { const full = { from: mergeBase, to: headSha, incremental: false }; const lastHeadSha = previousReview?.headSha; @@ -782,18 +886,28 @@ export async function run() { console.log("This PR revision has already been reviewed"); return; } - const runnerTemp = required("RUNNER_TEMP"); + const resumePrevious = resumeTarget(history.previousReview, pull.head.sha, process.env.PR_REVIEW_REUSE_INCOMPLETE === "true"); + const rangePrevious = previousReviewFor(history.previousReview, resumePrevious); const trustedRoot = process.cwd(); const rule = join(trustedRoot, ".opencodereview", "rule.json"); const ruleConfig = JSON.parse(await readFile(rule, "utf8")); if (!Array.isArray(ruleConfig.exclude) || !ruleConfig.exclude.every((item) => typeof item === "string")) throw new Error("Invalid trusted OCR exclude rules"); - const repo = await mkdtemp(join(runnerTemp, "pr-repo-")); - let home; - try { - home = await mkdtemp(join(runnerTemp, "pr-review-home-")); + const stateDirectory = required("PR_REVIEW_STATE_DIR"); + await mkdir(stateDirectory, { recursive: true }); + await writeFile(join(stateDirectory, "state.json"), JSON.stringify({ repository, pr: number }) + "\n"); + // The OCR home survives between runs, so a review that stopped short continues + // from its session records instead of paying for the same files again. It + // records how to read the token (printenv), never the token itself. The + // checkout is rebuilt every run: a worktree reused across heads keeps files + // the new head deleted, and only the session records are worth keeping. + const repo = join(resumeSessionDir(), "repo"); + const home = join(resumeSessionDir(), "home"); + await rm(repo, { recursive: true, force: true }); + await mkdir(repo, { recursive: true }); + await mkdir(home, { recursive: true }); const workspace = await prepareGitWorkspace({ repo, home, repository, number, pull, token }); const range = await selectReviewRange({ - previousReview: history.previousReview, isManual, baseSha: pull.base.sha, headSha: pull.head.sha, + previousReview: rangePrevious, isManual, baseSha: pull.base.sha, headSha: pull.head.sha, mergeBase: workspace.mergeBase, fetchCheckpoint: workspace.fetchCheckpoint, isAncestor: workspace.isAncestor, }); const stats = effectiveDiffStats(git(repo, ["diff", "--numstat", "--no-renames", "-z", range.from, range.to, "--"], workspace.env).stdout, ruleConfig.exclude); @@ -807,11 +921,39 @@ export async function run() { const background = join(home, "background.md"); await writeFile(background, backgroundText({ pull, mainline, goVersion, previousReview: history.previousReview, guidelines, designGuidelines }), { mode: 0o600 }); console.log("Running OpenCodeReview: " + profile.tier + ", " + stats.files + " effective files, " + stats.lines + " changed lines" + (range.incremental ? ", incremental" : "")); - const assessment = await reviewWithOCR({ - binary: required("PR_REVIEW_OCR_BIN"), repo, from: range.from, to: range.to, rule, background, home, profile, language, - }); - console.log("OpenCodeReview finished: " + assessment.status + ", " + (Number(assessment.summary?.total_tokens) || 0) - + " of " + profile.maxTokensBudget + " budgeted tokens"); + // A partial review records which files it settled. Continuing it reuses + // those verdicts and spends the next budget on the files it never reached. + // Resuming keeps the range, which is why an explicitly reused incomplete + // review continues over the range that produced it. + const earlier = resumePrevious ? revalidationOf(readResumeState(stateDirectory), range, home, repo) : null; + // Each round returns what the session knows, so the rounds are merged by + // identity. A finding published once is published once, whichever round + // reported it. + const findings = new Map(); + let assessment; + let resumed = 0; + for (;;) { + const session = resumed === 0 ? earlier : revalidationOf(readResumeState(stateDirectory), range, home, repo); + if (resumed > 0 && !session) break; + assessment = await reviewWithOCR({ + binary: required("PR_REVIEW_OCR_BIN"), repo, from: range.from, to: range.to, rule, background, home, profile, language, resume: session, + }); + console.log("OpenCodeReview finished: " + assessment.status + ", " + (Number(assessment.summary?.total_tokens) || 0) + + " of " + profile.maxTokensBudget + " budgeted tokens" + (session ? " (resumed)" : "")); + for (const finding of assessment.comments) { + findings.set([finding.path, finding.line ?? finding.original_line ?? "", finding.content].join("\u0000"), finding); + } + if (assessment.session_id) { + await writeResumeState(stateDirectory, { session: assessment.session_id, from: range.from, to: range.to }); + } + const settled = assessment.status === "complete" || assessment.status === "success"; + if (settled || resumed >= MAX_OCR_CONTINUATIONS || !assessment.session_id) break; + if (assessment.status === "skipped" || assessment.status === "failed") break; + resumed++; + console.log("Continuing the review from session " + assessment.session_id); + } + if (assessment.session_id) await deleteOldSessions(home, repo, assessment.session_id); + assessment = { ...assessment, comments: [...findings.values()] }; const locations = new Map(); for (const file of files) { const anchors = diffAnchors(file.patch); @@ -869,9 +1011,6 @@ export async function run() { if (comments.length) review.comments = comments; await postReview(github, path, review, copy, currentPR); console.log("Review submitted"); - } finally { - await Promise.all([repo, home].filter(Boolean).map((directory) => rm(directory, { recursive: true, force: true }))); - } } if (process.argv[1]?.endsWith("pr-review.mjs")) { diff --git a/.github/scripts/pr-review.test.mjs b/.github/scripts/pr-review.test.mjs index b2e3577..85802bf 100644 --- a/.github/scripts/pr-review.test.mjs +++ b/.github/scripts/pr-review.test.mjs @@ -15,7 +15,14 @@ import { githubRequest, hasSkipCIToken, normalizeLLMBaseURL, + encodeRepoPath, parseOCRJSON, + previousReviewFor, + readResumeState, + resumeTarget, + resumeSessionDir, + revalidationOf, + writeResumeState, postReview, reviewProfile, reviewSummary, @@ -143,7 +150,9 @@ test("bot login is configurable and previous marker exposes the reviewed head an const defaultBot = extractPreviousReview(reviews.slice(0, 1)); assert.equal(defaultBot.headSha, A); const partial = { ...reviews[0], body: marker(A).replace("} -->", ",\"incomplete\":true} -->") + "\npartial review" }; - assert.equal(extractPreviousReview([partial]).headSha, null); + const partialReview = extractPreviousReview([partial]); + assert.equal(partialReview.incomplete, true); + assert.equal(partialReview.headSha, A); }); test("incremental checkpoint accepts linear history and compatible base advancement", async () => { @@ -460,3 +469,79 @@ test("GitHub non-422 failures are not swallowed", async () => { throw Object.assign(new Error("denied"), { status: 403 }); }, "/pulls/1", { comments: [{}] }, chinese), /denied/); }); + +test("a resumed OCR review passes the session id and keeps its full budget", async (t) => { + const fake = await fakeOCR(t); + await mkdir(join(fake.directory, "home"), { recursive: true }); + await reviewWithOCR(ocrOptions(fake, { resume: "11111111-2222-3333-4444-555555555555" })); + const review = (await recordedCalls(fake.record)).at(-1); + assert.deepEqual(review.args.slice(-2), ["--resume", "11111111-2222-3333-4444-555555555555"]); + assert.equal(review.args[review.args.indexOf("--max-tokens-budget") + 1], "400000"); + const fresh = await fakeOCR(t); + await mkdir(join(fresh.directory, "home"), { recursive: true }); + await reviewWithOCR(ocrOptions(fresh)); + assert.equal((await recordedCalls(fresh.record)).at(-1).args.includes("--resume"), false); +}); + +test("OCR session directories mirror the repository path", () => { + assert.equal(encodeRepoPath("/home/runner/work/repo"), "home-runner-work-repo"); + assert.equal(encodeRepoPath("D:\\a\\repo"), "D_a-repo"); + assert.equal(encodeRepoPath("D:/a/repo"), "D_a-repo"); + assert.equal(encodeRepoPath(""), "empty"); +}); + +test("a resume record applies only to the range and file it was computed over", async (t) => { + const home = await tempDirectory(t, "ocr-home-"); + const repo = join(home, "checkout"); + const session = "11111111-2222-3333-4444-555555555555"; + const directory = join(home, ".opencodereview", "sessions", encodeRepoPath(repo)); + await mkdir(directory, { recursive: true }); + const range = { from: A, to: B }; + const record = { session, from: A, to: B }; + assert.equal(revalidationOf(record, range, home, repo), null, "a record whose session file is gone must not resume"); + await writeFile(join(directory, session + ".jsonl"), "{}\n"); + assert.equal(revalidationOf(record, range, home, repo), session); + assert.equal(revalidationOf({ ...record, to: C }, range, home, repo), null); + assert.equal(revalidationOf({ ...record, from: C }, range, home, repo), null); + assert.equal(revalidationOf(null, range, home, repo), null); + await writeResumeState(join(home, "state"), record); + assert.deepEqual(readResumeState(join(home, "state")), record); + assert.equal(readResumeState(join(home, "missing")), null); +}); + +test("each pull request gets its own review state", async (t) => { + const directory = await tempDirectory(t, "ocr-state-"); + await writeFile(join(directory, "state.json"), JSON.stringify({ repository: "Nwflower/Reims-Go", pr: 163 })); + const dir = resumeSessionDir({ PR_REVIEW_STATE_DIR: directory, PR_REVIEW_SESSION_HOME: join(directory, "home") }); + assert.equal(dir, join(directory, "home", "Nwflower-Reims-Go-163")); + const other = await tempDirectory(t, "ocr-state-"); + await writeFile(join(other, "state.json"), "not json"); + assert.equal(resumeSessionDir({ PR_REVIEW_STATE_DIR: other, PR_REVIEW_SESSION_HOME: join(other, "home"), GITHUB_WORKSPACE: "/w/repo" }), + join(other, "home", "repo")); +}); + +test("an incomplete previous review is recognised and never anchors an incremental range", () => { + const marker = ''; + const reviews = [{ user: { login: "reims-go-reviewer[bot]" }, state: "COMMENTED", commit_id: B, body: marker + "\n## 自动代码审核" }]; + const previous = extractPreviousReview(reviews, [], "reims-go-reviewer[bot]"); + assert.equal(previous.incomplete, true); + assert.equal(previous.headSha, B); + const complete = [{ user: { login: "reims-go-reviewer[bot]" }, state: "COMMENTED", commit_id: B, body: marker.replace(',"incomplete":true', '') + "\n## 自动代码审核" }]; + assert.equal(extractPreviousReview(complete, [], "reims-go-reviewer[bot]").incomplete, false); +}); + +test("only the same revision may continue an incomplete review", () => { + const incomplete = { incomplete: true, headSha: B }; + assert.equal(resumeTarget(incomplete, B, true), true); + assert.equal(resumeTarget(incomplete, B.toUpperCase(), true), true); + assert.equal(resumeTarget(incomplete, B, false), false, "the switch is off by default"); + assert.equal(resumeTarget(incomplete, A, true), false, "a new push starts a full review"); + assert.equal(resumeTarget({ incomplete: false, headSha: B }, B, true), false); + assert.equal(resumeTarget(null, B, true), false); + assert.equal(previousReviewFor(incomplete, false), null, "an unfinished review cannot anchor an incremental range"); + assert.equal(previousReviewFor(incomplete, true), incomplete); + assert.equal(previousReviewFor({ incomplete: false }, false)?.incomplete, false); + assert.equal(previousReviewFor(null, true), null); + const range = previousReviewFor(incomplete, resumeTarget(incomplete, B, true)); + assert.equal(range, incomplete, "continuing keeps the range the review was computed over"); +}); diff --git a/.github/workflows/issue-triage.yml b/.github/workflows/issue-triage.yml index afaff28..a554556 100644 --- a/.github/workflows/issue-triage.yml +++ b/.github/workflows/issue-triage.yml @@ -40,7 +40,7 @@ jobs: GITHUB_TOKEN: ${{ github.token }} PR_REVIEW_LLM_KEY: ${{ secrets.PR_REVIEW_LLM_KEY }} PR_REVIEW_LLM_BASE_URL: ${{ vars.PR_REVIEW_LLM_BASE_URL || 'https://open.bigmodel.cn/api/anthropic' }} - PR_REVIEW_LLM_MODEL: ${{ vars.PR_REVIEW_LLM_MODEL || 'glm-5.4' }} + PR_REVIEW_LLM_MODEL: ${{ vars.PR_REVIEW_LLM_MODEL || 'glm-5.3-flash' }} PR_REVIEW_LLM_PROTOCOL: ${{ vars.PR_REVIEW_LLM_PROTOCOL || 'anthropic' }} PR_REVIEW_LLM_EXTRA_BODY: ${{ vars.PR_REVIEW_LLM_EXTRA_BODY }} run: node .github/scripts/issue-triage.mjs diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index 0d08873..a0ff81c 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -26,7 +26,8 @@ jobs: name: Reims Go Reviewer if: github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && (github.event_name == 'workflow_dispatch' || !github.event.pull_request.draft) runs-on: ubuntu-latest - timeout-minutes: 30 + # Up to three review rounds, each bounded by the OCR timeout. + timeout-minutes: 90 steps: - name: Create reviewer App token id: app-token @@ -59,6 +60,24 @@ jobs: path: ${{ runner.temp }}/ocr-bin key: opencodereview-${{ env.OCR_VERSION }}-${{ env.OCR_SHA256 }} + # Only the OCR session records are kept: the checkout is rebuilt each run, + # and the session records are what let a review continue where it stopped. + # A cache entry cannot be overwritten, so each run saves under its own key + # and the next run restores the newest entry with the prefix below; GitHub + # evicts entries that stay unused for seven days, and least recently used + # ones when the repository reaches its cache quota. + - name: Cache PR review sessions + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/pr-review-state/sessions + key: pr-review-sessions-${{ github.repository }}-${{ github.event.pull_request.number || inputs.pull_number }}-${{ github.run_id }} + restore-keys: | + pr-review-sessions-${{ github.repository }}-${{ github.event.pull_request.number || inputs.pull_number }}- + + - name: Ensure PR review state directories + shell: bash + run: mkdir -p "$RUNNER_TEMP/pr-review-state/sessions" + - name: Download OpenCodeReview if: steps.ocr-cache.outputs.cache-hit != 'true' shell: bash @@ -86,4 +105,7 @@ jobs: PR_REVIEW_LLM_PROTOCOL: ${{ vars.PR_REVIEW_LLM_PROTOCOL || 'anthropic' }} PR_REVIEW_LLM_EXTRA_BODY: ${{ vars.PR_REVIEW_LLM_EXTRA_BODY }} PR_REVIEW_CODE_SUGGESTIONS: ${{ vars.PR_REVIEW_CODE_SUGGESTIONS }} + PR_REVIEW_STATE_DIR: ${{ runner.temp }}/pr-review-state/sessions + PR_REVIEW_SESSION_HOME: ${{ runner.temp }}/pr-review-state/sessions + PR_REVIEW_REUSE_INCOMPLETE: "true" run: node .github/scripts/pr-review.mjs diff --git a/NOTICE.md b/NOTICE.md index 3756afa..0ac0a7c 100644 --- a/NOTICE.md +++ b/NOTICE.md @@ -5,7 +5,7 @@ License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own cod only and is separate from the portable runtime bundle it invokes as an external child process. Compatibility patches in the runtime repository are licensed under terms compatible with their target upstream projects (see [runtime patch -licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)). +licenses](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)). The Reims-Go desktop executable also incorporates open-source Go and frontend libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x` diff --git a/README.md b/README.md index c735e32..83da74e 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,7 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
Build from source -With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu). +With Go 1.26+, Node.js 22, pnpm 10 and the [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1, run `wails build` in the repository root; the binary is written to `build\bin\reims-go.exe`. The runtime is built separately by the [Reims vGPU fork](https://github.com/reims-go/reims-vgpu).
diff --git a/README.zh-CN.md b/README.zh-CN.md index b044bfe..93b42d0 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -117,7 +117,7 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
从源码构建 -需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 单独构建。 +需要 Go 1.26+、Node.js 22、pnpm 10 和 [Wails CLI](https://wails.io/docs/gettingstarted/installation) v2.17.1,在仓库根目录运行 `wails build`,产物在 `build\bin\reims-go.exe`。运行时由 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 单独构建。
diff --git a/changes/drop-mount-network-volumes-permission.json b/changes/drop-mount-network-volumes-permission.json new file mode 100644 index 0000000..3ffce83 --- /dev/null +++ b/changes/drop-mount-network-volumes-permission.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["YinLiaoCo"], + "zh": "文件拖放通过 WebDAV 挂载导入文件,而 Guest Tools 后台以 `sh` 运行。修复全新 macOS 虚拟机首次拖放时未弹出 `sh`「网络宗卷」授权提示导致失败的问题;若权限被拒,拖放会立即提示「文件拖放受限」并在连接卡显示开启路径。开启权限后,拖入访达窗口或照片时会自动重挂仍无法获取文件引用的陈旧挂载;其他挂载故障及文件剪贴板仍保留下载兜底。已有虚拟机需将 Guest Tools 更新至 `v21`。", + "en": "File drops transfer files over a WebDAV mount read by the Guest Tools background agent (`sh`). macOS now prompts for `sh` Network Volumes access when needed during a drop. If access is denied, drops fail immediately with a File drop limited toast and a Connection card notice showing where to enable it. After access is granted, drops into Finder windows or Photos automatically remount stale WebDAV mounts whose file references are unavailable. Other mount failures and file clipboard sync keep download fallback. Update Guest Tools to `v21` in existing VMs." +} diff --git a/changes/fix-suspend-stale-tmp-and-seal-retry.json b/changes/fix-suspend-stale-tmp-and-seal-retry.json new file mode 100644 index 0000000..375216c --- /dev/null +++ b/changes/fix-suspend-stale-tmp-and-seal-retry.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["reiasu2", "Nwflower"], + "zh": "自动清理无法恢复的挂起残留,避免它们阻止再次挂起,并修复 Windows 上文件仍被短暂占用时挂起封存或清理失败的问题。挂起与恢复支持存放在长路径下的虚拟机。已保存可恢复快照的虚拟机在启动时会改为拒绝并提示先恢复或放弃挂起状态,旧版启动入口同样适用,不再直接冷启动覆盖快照。", + "en": "Clear orphaned suspend files that block later suspend attempts and avoid snapshot publication or cleanup failures when Windows files are briefly still in use. Suspend and resume also support VMs stored under long paths. A VM that holds a recoverable snapshot now refuses to start and asks you to resume or discard that state first, including through the older start path, instead of cold-starting over the snapshot." +} diff --git a/changes/plugin-runtime-compatibility.json b/changes/plugin-runtime-compatibility.json new file mode 100644 index 0000000..d2ef969 --- /dev/null +++ b/changes/plugin-runtime-compatibility.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["cosimawei"], + "zh": "在插件列表和设置中提示当前运行时不支持的插件设置。", + "en": "Show which settings the active runtime does not support in the plugin list and settings dialog." +} diff --git a/changes/runtime-releases-repo.json b/changes/runtime-releases-repo.json new file mode 100644 index 0000000..e5a863d --- /dev/null +++ b/changes/runtime-releases-repo.json @@ -0,0 +1,9 @@ +{ + "group": "improvements", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "运行时改从 `reims-go/reims-vgpu` 下载。`REIMS_GO_RELEASES_REPO` 现在只影响应用更新,运行时仓库改用 `REIMS_GO_RUNTIME_RELEASES_REPO` 指定。", + "en": "Runtimes are now downloaded from `reims-go/reims-vgpu`. `REIMS_GO_RELEASES_REPO` now only affects app updates; set the runtime repository with `REIMS_GO_RUNTIME_RELEASES_REPO`." +} diff --git a/changes/segmented-highlight.json b/changes/segmented-highlight.json new file mode 100644 index 0000000..c99b673 --- /dev/null +++ b/changes/segmented-highlight.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "修复分段选项在保存期间短暂禁用后,当前选项的高亮可能消失的问题。", + "en": "Keep the highlight on the current option of a segmented control after it was briefly disabled while saving." +} diff --git a/changes/start-failure-log-lines.json b/changes/start-failure-log-lines.json new file mode 100644 index 0000000..5b348e9 --- /dev/null +++ b/changes/start-failure-log-lines.json @@ -0,0 +1,7 @@ +{ + "group": "fixes", + "order": 0, + "authors": ["Nwflower"], + "zh": "从命令行启动虚拟机失败时,一并显示 Guest Tools 和网络相关的日志。", + "en": "Include Guest Tools and network log lines when a VM fails to start from the command line." +} diff --git a/changes/theme-sounds-removed.json b/changes/theme-sounds-removed.json new file mode 100644 index 0000000..897579c --- /dev/null +++ b/changes/theme-sounds-removed.json @@ -0,0 +1,9 @@ +{ + "group": "removals", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "主题清单不再支持从未生效的 `sounds` 字段。带交互脚本的主题可以自行播放提示音。", + "en": "Theme manifests no longer accept the `sounds` field, which never took effect. Themes with an interactive script can play their own sounds." +} diff --git a/changes/vm-name-details.json b/changes/vm-name-details.json new file mode 100644 index 0000000..aa38c13 --- /dev/null +++ b/changes/vm-name-details.json @@ -0,0 +1,9 @@ +{ + "group": "fixes", + "order": 0, + "authors": [ + "Nwflower" + ], + "zh": "修复只用名称指定虚拟机时读不到 SSH 端口等设置的问题。智能体工具此前会因此误报未启用 SSH 端口转发。", + "en": "Fixed missing settings such as the SSH port when a VM is identified by name only. Agent tools used to report that SSH port forwarding was off." +} diff --git a/cmd/i18ngen/main.go b/cmd/i18ngen/main.go index 94bb026..76c1c9f 100644 --- a/cmd/i18ngen/main.go +++ b/cmd/i18ngen/main.go @@ -24,10 +24,9 @@ import ( ) var ( - allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} - goDomains = []string{"native", "macos-glossary", "core"} - feEagerDomains = []string{"core", "vm"} - feLazyDomains = []string{"wizard", "settings", "plugins"} + allDomains = []string{"core", "vm", "wizard", "settings", "plugins", "native", "macos-glossary"} + goDomains = []string{"native", "macos-glossary", "core"} + feLazyDomains = []string{"wizard", "settings", "plugins"} ) type parsedEntry struct { diff --git a/docs/architecture.md b/docs/architecture.md index ae08ef7..4caff99 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -99,6 +99,18 @@ Npcap 桥接由可停用的内置扩展提供,通过逐台虚拟机的本地 U macOS 专属逻辑集中在 `internal/macos/` 与 `frontend/src/macos/`,宿主核心通过通用驱动路由与扩展接口调用。代码库通过双向架构边界测试锁死跨界依赖白名单,任何新增跨界引用或白名单条目失效都会令测试失败,确保耦合范围只减不增。 +### 唯一入口与自动检查 + +以下事项各有一个唯一入口,对应的测试会拒绝绕开入口的新代码。Go 检查位于 `internal/archtest/`,前端检查位于 `frontend/scripts/`。 + +| 事项 | 唯一入口 | 检查 | +| :--- | :--- | :--- | +| 整体替换小文件 | `internal/atomicfile` | `file_replace_test.go` | +| 向界面发送事件 | 后端 `App.emit`,前端 `wails.ts` | `events_test.go` | +| 界面调用后端 | `App` 的导出方法,修改后重新生成 `frontend/wailsjs` | `bindings_test.go` | + +测试同时拒绝没有调用者的函数、前端导出、样式类与文案,拒绝前端模块循环引用,并限制单个 Go 函数的长度。 + ## 便携运行时与跨仓边界 便携运行时基于团队独立维护的 `reims-go/reims-vgpu` 和 `reims-go/qemu-reims-vgpu` 构建。运行时仓库固定 QEMU 子模块的提交,负责构建、依赖补丁、打包与 Alpha 发布。压缩包包含 `reims-ctl.exe`、`reims-util.exe`、QEMU、自包含运行库、实际应用的补丁和许可证全文。`manifest.json` 记录各组件的实际源码提交及补丁,调试符号单独打包分发。 [运行时维护仓库](https://github.com/reims-go/reims-vgpu) · [QEMU 维护仓库](https://github.com/reims-go/qemu-reims-vgpu) diff --git a/docs/plugin-architecture.md b/docs/plugin-architecture.md index a3e520f..2128da9 100644 --- a/docs/plugin-architecture.md +++ b/docs/plugin-architecture.md @@ -46,11 +46,13 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V 启动前钩子在单插件 2 秒、整条链路 10 秒的时限内返回启动意图(白名单内的参数片段、带命名空间前缀的环境变量、警告或阻塞理由、受控启动后动作)。宿主与所属驱动合并意图后一次性写入配置,并在虚拟机目录记录参数归属账本:插件停用或卸载时精确剥离其名下参数,用户手工填写的高级参数永不被自动剥离。连续超时或报错的外部插件自动降级并在插件页提示原因,不阻塞虚拟机启停。 +声明式 `vm.beforeStart` 规则的 `set_env` 动作可用 `envFromSettings` 将本插件命名空间内的环境变量映射到设置键。宿主按设置的应用或虚拟机作用域读取值,仅导出未标记为敏感的字符串和布尔值。两种作用域都可配置时,虚拟机值优先于应用值。规则可以用 `runtime.capabilities` 限定支持该设置的运行时。 + 未启用外部插件时,插件内核保持零额外开销:无订阅者时不构造日志等高频事件对象,不轮询插件状态,外部子进程、沙箱面板与远程市场索引一律在首次使用时惰性拉起或请求,使用内置默认主题时不注入额外样式表、不加载交互脚本接口。 ## 主题、面板桥接与契约演进 -宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标、品牌标志与事件提示音;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。 +宿主内置浅色与深色外观,同时提供三档主题扩展能力:第一档通过种子色与派生规则生成表面、文字和边框色阶,支持替换包内字体、单色图标与品牌标志;第二档提供面向公开部件类名(`rg-p-*`)与只读状态属性(`data-*`)的样式表及槽位/全窗图层状态装饰,由宿主锁定层叠顺序并清洗外部链接,且始终保护标题栏拖拽区、键盘焦点环与最小点击热区;第三档通过稳定的 `contributes.themes[].uiScript` 字段声明交互脚本,仅对获批 `ui:script` 高危权限的主题按需加载前端交互接口,提示音也由交互脚本自行播放。交互脚本运行在主窗口前端环境并共享页面 DOM(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。 已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。 diff --git a/docs/pr-review-guidelines.md b/docs/pr-review-guidelines.md index dbee270..bde5a12 100644 --- a/docs/pr-review-guidelines.md +++ b/docs/pr-review-guidelines.md @@ -10,12 +10,12 @@ | :--- | :--- | :--- | | 客户端 | GUI、CLI、虚拟机流程编排、宿主机体检及窗口集成、Guest Tools、运行时下载和安装 | `Reims-Go`。主要入口和模块见[系统架构](architecture.md)。 | | 客户端运行时适配 | 构造命令和环境、调用已发布的 CLI / QMP 接口、解析结果以及处理版本、能力或错误 | `Reims-Go`。生效行为仍由被调用的组件实现。 | -| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/yxc0915/reims-vgpu) 的实际构建提交为准。 | +| Reims vGPU 内核及控制工具 | `reims-ctl` 的配置、启动与参数语义,`reims-restore` 的恢复流程,Reims 的宿主图形、原生 VM 窗口及输入实现 | [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu)。运行时所用改动以 [Reims vGPU fork](https://github.com/reims-go/reims-vgpu) 的实际构建提交为准。 | | QEMU 虚拟化层 | WHPX / TCG、客体机器与设备模型、`reims-graphics-pci` 的 PCI 设备侧、QMP 命令实现、`qcow2` 格式与迁移机制 | [`steelbrain/qemu-reims-vgpu`](https://github.com/steelbrain/qemu-reims-vgpu)。核对构建提交中的 `vendor/qemu` gitlink 及其来源。 | | 独立上游工具 | `reims-util` 内的引导资源生成、安装镜像处理和工具自身的参数语义 | [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。按运行时锁定的提交定位。 | | 独立图形依赖 | Metal 到 Vulkan 的命令、资源和着色器转换实现 | [`steelbrain/metal2vulkan`](https://github.com/steelbrain/metal2vulkan)。按运行时锁定的提交定位。 | | 其他独立引擎 | 引擎自身的执行、翻译和固件实现 | 对应引擎的源代码仓库。客户端的驱动注册、启动参数适配和状态展示仍归 `Reims-Go`。 | -| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 | +| 运行时集成与分发 | 上游版本选取、依赖补丁、运行时编译、打包、能力清单及 Preview 发布 | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu) 的运行时流水线。构建及发布规则见[便携运行时与跨仓边界](architecture.md#便携运行时与跨仓边界)。 | 同一项功能可以涉及多个仓库。窗口安装引导调用已有运行时能力时,浮层、进度和流程编排属于客户端。若同时调整 Reims 原生窗口的事件语义,窗口实现属于 `reims-vgpu`,调用和交互留在客户端。挂起功能同理,GUI / CLI 和任务状态属于客户端,QEMU 的迁移或设备状态实现属于 QEMU;运行时再负责选取具备该能力的版本。 diff --git a/frontend/package.json b/frontend/package.json index 3fbcfb8..4e454cc 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "vite", - "test": "node --test --test-concurrency=2 scripts/test-i18n.mjs scripts/test-keymap.mjs scripts/test-plugins.mjs scripts/test-tasks.mjs scripts/test-display-presets.mjs scripts/test-endpoints.mjs scripts/test-guest-tools.mjs scripts/test-macos-boundary.mjs scripts/test-no-empty-catch.mjs scripts/test-hypervisor.mjs", + "test": "node --test --test-concurrency=2 \"scripts/test-*.mjs\"", "typecheck": "tsc --noEmit", "bundle": "vite build && node scripts/check-ui-contract.mjs", "build": "tsc --noEmit && pnpm run bundle", diff --git a/frontend/scripts/test-guest-tools.mjs b/frontend/scripts/test-guest-tools.mjs index 8909d11..0646160 100644 --- a/frontend/scripts/test-guest-tools.mjs +++ b/frontend/scripts/test-guest-tools.mjs @@ -1,36 +1,104 @@ import assert from 'node:assert/strict' -import test from 'node:test' +import test, { after, before } from 'node:test' import { loadTestModule } from './load-test-module.mjs' -test('Guest Tools offers an update when a connected guest is older than the bundled agent', async () => { +let fixture +before(async () => { // Wails reads its window bindings at import time. Static rendering uses the VM detail before the first live poll. globalThis.window = {} - try { - const { render } = await loadTestModule(` - import { createElement } from 'react' - import { renderToStaticMarkup } from 'react-dom/server.edge' - import { TooltipProvider } from './ui/controls' - import { VMPage } from './components/VMPage' + fixture = await loadTestModule(` + import { createElement } from 'react' + import { renderToStaticMarkup } from 'react-dom/server.edge' + import { TooltipProvider } from './ui/controls' + import { VMPage } from './components/VMPage' + import { ConnectionSection } from './components/vmPage/connections' + export { showHostDropAck } from './App' - export function render(installed, bundled, connected = true) { - return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(VMPage, { - locale: 'en-US', name: 'mac', driverID: '', state: 'running', macosMajor: null, - host: {}, pending: [], currentAgentVersion: bundled, - detail: { guest_tools_configured: true, guest_tools_connected: connected, guest_tools_agent_version: installed } - }))) + export function render({ locale = 'en-US', installed = 21, bundled = 21, connected = true, denied, disabled = false } = {}) { + const detail = { + guest_tools_configured: true, + guest_tools_connected: connected, + guest_tools_agent_version: installed, + guest_tools_drop_access_denied: denied, + guest_tools_disabled: disabled, } - `) - for (const [guest, bundled, connected, needsUpdate] of [ - [13, 14, true, true], [14, 14, true, false], [14, 15, true, true], - [15, 15, true, false], [16, 15, true, false], [14, 15, false, false], - [15, 14, true, false], [0, 14, true, false], [13, 14, false, false], - ]) { - const html = render(guest, bundled, connected) - const context = `guest v${guest}, bundled v${bundled}, connected=${connected}` - assert.equal(html.includes('>Update needed<'), needsUpdate, context) - assert.equal(html.includes('Update…'), needsUpdate, context) + return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(VMPage, { + locale, name: 'mac', driverID: '', state: 'running', macosMajor: null, + host: {}, pending: [], currentAgentVersion: bundled, detail, + }))) } - } finally { - delete globalThis.window + + export function renderLiveConnection(detailDenied, liveDenied) { + return renderToStaticMarkup(createElement(TooltipProvider, null, createElement(ConnectionSection, { + locale: 'en-US', vmKey: 'mac', state: 'running', pending: [], currentAgentVersion: 21, + detail: { ssh_port: 0, guest_tools_drop_access_denied: detailDenied }, + stats: { guest_tools_connected: true, guest_tools_drop_access_denied: liveDenied }, + }))) + } + `) +}) +after(() => { delete globalThis.window }) + +const permissionCopy = [ + ['en-US', 'File drop limited', 'File drops transfer via WebDAV. Enable Network Volumes for sh in macOS System Settings → Privacy & Security → Files and Folders'], + ['zh-CN', '文件拖放受限', '拖放通过 WebDAV 传输文件,请在 macOS「系统设置 → 隐私与安全性 → 文件与文件夹」中开启 sh 的「网络宗卷」权限'], +] + +test('Guest Tools offers an update when a connected guest is older than the bundled agent', () => { + for (const [installed, bundled, connected, needsUpdate] of [ + [13, 14, true, true], [14, 14, true, false], [14, 15, true, true], + [15, 15, true, false], [16, 15, true, false], [14, 15, false, false], + [15, 14, true, false], [0, 14, true, false], [13, 14, false, false], + ]) { + const html = fixture.render({ installed, bundled, connected }) + const context = `guest v${installed}, bundled v${bundled}, connected=${connected}` + assert.equal(html.includes('>Update needed<'), needsUpdate, context) + assert.equal(html.includes('Update…'), needsUpdate, context) } }) + +test('Guest Tools shows a localized idle sub-row only while connected and denied', () => { + for (const [locale, title, guidance] of permissionCopy) { + const html = fixture.render({ locale, denied: true }) + const subRow = '
' + + '' + + `${title}${guidance.replaceAll('&', '&')}
` + assert.ok(html.includes(subRow), locale) + + for (const [state, overrides] of [ + ['allowed', { denied: false }], + ['unprompted', { denied: undefined }], + ['disabled', { denied: true, disabled: true }], + ['disconnected', { denied: true, connected: false }], + ]) { + const hidden = fixture.render({ locale, ...overrides }) + assert.ok(!hidden.includes('conn-drop-access') && !hidden.includes(title), `${locale}, ${state}`) + } + } +}) + +test('Guest Tools shows the current drop permission even when detail is stale', () => { + assert.ok(fixture.renderLiveConnection(false, true).includes('conn-drop-access')) + assert.ok(!fixture.renderLiveConnection(true, false).includes('conn-drop-access')) +}) + +test('A failed Network Volumes drop shows the localized permission toast', () => { + for (const [locale, title, description] of permissionCopy) { + const toasts = [] + fixture.showHostDropAck({ status: 'failed', error: 'Network Volumes permission denied' }, locale, + (toast) => toasts.push(toast), () => assert.fail(`${locale} used the generic drop failure`)) + assert.deepEqual(toasts, [{ kind: 'error', title, description }], locale) + } +}) + +test('Other drop failures keep their details and successful or cancelled drops produce no error toast', () => { + const failures = [] + const push = () => assert.fail('unexpected permission toast') + const fail = (...args) => failures.push(args) + fixture.showHostDropAck({ status: 'failed', error: 'Placement failed' }, 'en-US', push, fail) + assert.deepEqual(failures, [['Couldn’t drop into the VM', 'Placement failed']]) + for (const status of ['placed', 'pasted', 'cancelled']) { + fixture.showHostDropAck({ status, error: 'Network Volumes permission denied' }, 'en-US', push, fail) + } + assert.equal(failures.length, 1) +}) diff --git a/frontend/scripts/test-i18n.mjs b/frontend/scripts/test-i18n.mjs index 52b22cf..fcd240b 100644 --- a/frontend/scripts/test-i18n.mjs +++ b/frontend/scripts/test-i18n.mjs @@ -20,79 +20,63 @@ function walkFiles(dir, exts) { return out } -test('lazy i18n domain keys are always backed by domain .gen imports', () => { +/** Static imports and dynamic import() targets of a source file, as absolute paths. */ +function importsOf(file) { + const src = fs.readFileSync(file, 'utf8') + const resolve = (spec) => { + const target = path.resolve(path.dirname(file), spec) + return ['', '.ts', '.tsx', '/index.ts', '/index.tsx'].map((ext) => target + ext).find((p) => fs.existsSync(p) && fs.statSync(p).isFile()) + } + const collect = (re) => [...src.matchAll(re)].map((m) => resolve(m[1])).filter((p) => p && /\.tsx?$/.test(p)) + return { + eager: collect(/^(?:import(?! type\b)|export)\b[^'"]*?['"](\.[^'"]+)['"]/gm), + lazy: collect(/\bimport\(\s*['"](\.[^'"]+)['"]\s*\)/g), + } +} + +/** Every module loaded together with entry. */ +function loadedWith(entry, imports) { + const seen = new Set([entry]) + for (const file of seen) for (const next of imports.get(file)?.eager ?? []) seen.add(next) + return seen +} + +test('every chunk registers the lazy i18n domains its keys belong to', () => { const lazyDomains = ['wizard', 'settings', 'plugins'] const keyToDomain = new Map() - for (const dom of ['core', 'vm', ...lazyDomains]) { + for (const dom of lazyDomains) { const raw = JSON.parse(fs.readFileSync(path.join(localesDir, `${dom}.json`), 'utf8')) - for (const k of Object.keys(raw)) { - if (!k.startsWith('$')) keyToDomain.set(k, dom) - } + for (const k of Object.keys(raw)) keyToDomain.set(k, dom) } + const files = walkFiles(srcDir, ['.ts', '.tsx']) + const imports = new Map(files.map((file) => [file, importsOf(file)])) + const entries = new Set([path.join(srcDir, 'main.tsx'), ...[...imports.values()].flatMap((i) => i.lazy)]) + assert.ok(entries.size > 5, 'found no lazy chunks: the import patterns no longer match') - // Known lazy-loaded chunk entry trees (loaded via React.lazy or dynamic import in App.tsx) - const lazyEntryBasenames = new Set([ - 'CreateWizard.tsx', - 'SettingsModal.tsx', - // 网络设置仅随延迟加载的 SettingsModal 进入,使用同一语言域。 - 'VMNetworkSettings.tsx', - // 由新建向导和网络设置两个延迟入口共用。 - 'NpcapDependency.tsx', - 'AffinityDialog.tsx', - 'Setup.tsx', - 'RuntimeOnline.tsx', - 'HostView.tsx', - 'ImagesPage.tsx', - 'InstallersPage.tsx', - 'PluginsPage.tsx', - 'PluginMarket.tsx', - 'PluginParts.tsx', - 'AppSettingsPage.tsx', - 'AboutPage.tsx', - 'PluginPanelFrame.tsx', - 'SchemaForm.tsx', - 'optimizations.ts', - // 仅由延迟加载的 AppSettingsPage、HostView、Setup 共用,自带 settings.gen 域注册。 - 'hypervisor.ts', - ]) - - for (const file of walkFiles(srcDir, ['.ts', '.tsx'])) { - const rel = path.relative(srcDir, file).replace(/\\/g, '/') - if (rel.startsWith('i18n/')) continue - const base = path.basename(file) - const src = fs.readFileSync(file, 'utf8') - - // Match string literals passed to t(..., 'key'), tr('key'), labelKey: 'key', detailKey: 'key', titleKey: 'key', descKey: 'key' - const referencedLazyDomains = new Set() - const callMatches = [ - ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), - ...src.matchAll(/\b(?:labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), - ] - for (const m of callMatches) { - const dom = keyToDomain.get(m[1]) - if (dom && lazyDomains.includes(dom)) { - referencedLazyDomains.add(`${dom}:${m[1]}`) + for (const entry of entries) { + const modules = [...loadedWith(entry, imports)].filter((file) => !path.relative(srcDir, file).startsWith('i18n')) + const registered = new Set() + for (const file of modules) { + for (const m of fs.readFileSync(file, 'utf8').matchAll(/i18n\/domains\/(\w+)\.gen/g)) registered.add(m[1]) + } + for (const file of modules) { + const src = fs.readFileSync(file, 'utf8') + const keys = [ + ...src.matchAll(/\b(?:tr|t)\(\s*(?:[a-zA-Z0-9_$.]+\s*,\s*)?'([a-zA-Z0-9_.]+)'/g), + ...src.matchAll(/\b(?:label|labelKey|detailKey|titleKey|descKey)\s*:\s*'([a-zA-Z0-9_.]+)'/g), + ].map((m) => m[1]) + for (const key of keys) { + const dom = keyToDomain.get(key) + assert.ok( + !dom || registered.has(dom), + `${path.relative(srcDir, file)} uses ${dom} key "${key}", but the chunk of ${path.relative(srcDir, entry)} never imports i18n/domains/${dom}.gen`, + ) } } - - if (referencedLazyDomains.size === 0) continue - - assert.ok( - lazyEntryBasenames.has(base), - `Eager module ${rel} references lazy domain keys (${[...referencedLazyDomains].join(', ')})! Either move keys to core/vm or lazy-load the module.`, - ) - - for (const item of referencedLazyDomains) { - const [dom, key] = item.split(':') - // Sub-dialogs rendered exclusively inside lazy parent chunks inherit their parent's domain registration - if (base === 'AffinityDialog.tsx' && dom === 'settings') continue - if (base === 'RuntimeOnline.tsx' && (dom === 'wizard' || dom === 'settings')) continue - assert.match( - src, - new RegExp(`i18n/domains/${dom}\\.gen`), - `Module ${rel} uses ${dom} key "${key}" without importing i18n/domains/${dom}.gen`, - ) - } + } + const eager = loadedWith(path.join(srcDir, 'main.tsx'), imports) + for (const dom of lazyDomains) { + assert.ok(!eager.has(path.join(srcDir, 'i18n', 'domains', `${dom}.gen.ts`)), `the ${dom} texts must not load with the main window`) } }) diff --git a/frontend/scripts/test-import-cycles.mjs b/frontend/scripts/test-import-cycles.mjs new file mode 100644 index 0000000..bc050a0 --- /dev/null +++ b/frontend/scripts/test-import-cycles.mjs @@ -0,0 +1,45 @@ +// Rejects import cycles in src/, type imports included: two files that import +// each other are one module split in the wrong place. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import ts from 'typescript' + +const src = path.resolve(import.meta.dirname, '..', 'src') +const rel = (file) => path.relative(src, file).split(path.sep).join('/') + +function importGraph() { + const files = fs.readdirSync(src, { recursive: true }) + .filter((name) => /\.tsx?$/.test(name)) + .map((name) => path.join(src, name)) + const known = new Set(files) + return new Map(files.map((file) => { + const { importedFiles } = ts.preProcessFile(fs.readFileSync(file, 'utf8'), true, true) + const targets = importedFiles + .filter(({ fileName }) => fileName.startsWith('.')) + .map(({ fileName }) => path.resolve(path.dirname(file), fileName)) + .map((base) => ['', '.ts', '.tsx', `${path.sep}index.ts`].map((ext) => base + ext).find((p) => known.has(p))) + .filter(Boolean) + return [file, targets] + })) +} + +test('source modules do not import each other in a cycle', () => { + const graph = importGraph() + assert.ok(graph.size > 50, `expected to scan src/, found ${graph.size} files`) + const done = new Set() + const cycles = [] + const visit = (file, trail) => { + const start = trail.indexOf(file) + if (start >= 0) { + cycles.push([...trail.slice(start), file].map(rel).join(' -> ')) + return + } + if (done.has(file)) return + for (const next of graph.get(file)) visit(next, [...trail, file]) + done.add(file) + } + for (const file of graph.keys()) visit(file, []) + assert.deepEqual(cycles, []) +}) diff --git a/frontend/scripts/test-unused-css.mjs b/frontend/scripts/test-unused-css.mjs new file mode 100644 index 0000000..11b6287 --- /dev/null +++ b/frontend/scripts/test-unused-css.mjs @@ -0,0 +1,24 @@ +// Rejects classes in app.css that no source file uses. A class built from a +// template such as `status-${kind}` counts as used by its prefix. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' + +const src = path.resolve(import.meta.dirname, '..', 'src') + +test('every class in app.css is used', () => { + const code = fs.readdirSync(src, { recursive: true }) + .filter((name) => /\.tsx?$/.test(name)) + .map((name) => fs.readFileSync(path.join(src, name), 'utf8')) + .join('\n') + const css = fs.readFileSync(path.join(src, 'styles', 'app.css'), 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/url\([^)]*\)|"[^"]*"/g, '') + + const words = new Set(code.match(/[A-Za-z_][\w-]*/g)) + const prefixes = [...code.matchAll(/([A-Za-z][\w-]*-)\$\{/g)].map((m) => m[1]) + const classes = new Set([...css.matchAll(/\.([A-Za-z_][\w-]*)/g)].map((m) => m[1])) + assert.ok(classes.size > 300, `found only ${classes.size} classes in app.css`) + assert.deepEqual([...classes].filter((c) => !words.has(c) && !prefixes.some((p) => c.startsWith(p))), []) +}) diff --git a/frontend/scripts/test-unused-exports.mjs b/frontend/scripts/test-unused-exports.mjs new file mode 100644 index 0000000..de88135 --- /dev/null +++ b/frontend/scripts/test-unused-exports.mjs @@ -0,0 +1,57 @@ +// Rejects exports in src/ that no other file uses: dead code, or an export +// keyword that only widens a module's interface. +import test from 'node:test' +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import ts from 'typescript' + +const root = path.resolve(import.meta.dirname, '..') + +function findUnusedExports() { + const { config } = ts.readConfigFile(path.join(root, 'tsconfig.json'), ts.sys.readFile) + const { fileNames, options } = ts.parseJsonConfigFileContent(config, ts.sys, root) + const service = ts.createLanguageService({ + ...ts.sys, + getCompilationSettings: () => options, + getScriptFileNames: () => fileNames, + getScriptVersion: () => '1', + getScriptSnapshot: (file) => (fs.existsSync(file) ? ts.ScriptSnapshot.fromString(fs.readFileSync(file, 'utf8')) : undefined), + getCurrentDirectory: () => root, + getDefaultLibFileName: ts.getDefaultLibFilePath, + }) + // The test and contract scripts import src modules or read them as text. A + // name counts as used only in a script that also names its module. + const scripts = fs.readdirSync(import.meta.dirname) + .filter((name) => name !== path.basename(import.meta.filename)) + .map((name) => fs.readFileSync(path.join(import.meta.dirname, name), 'utf8')) + + const unused = [] + for (const file of fileNames) { + // bridgeContract.ts also documents the message types for plugin authors. + if (file.endsWith('.gen.ts') || file.endsWith('/bridgeContract.ts')) continue + const source = service.getProgram().getSourceFile(file) + const module = path.relative(path.join(root, 'src'), file).split(path.sep).join('/').replace(/(\/index)?\.tsx?$/, '') + const users = scripts.filter((text) => text.includes(`'./${module}'`) || text.includes(`'${path.basename(file)}'`)) + for (const statement of source.statements) { + if (!ts.canHaveModifiers(statement) || !ts.getModifiers(statement)?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) continue + const names = ts.isVariableStatement(statement) + ? statement.declarationList.declarations.map((d) => d.name).filter(ts.isIdentifier) + : [statement.name].filter(Boolean) + for (const name of names) { + if (users.some((text) => new RegExp(`\\b${name.text}\\b`).test(text))) continue + const references = (service.findReferences(file, name.getStart(source)) ?? []).flatMap((r) => r.references) + if (references.every((r) => r.fileName === file)) { + unused.push(`${path.relative(root, file)}: ${name.text}`) + } + } + } + } + return { unused, files: fileNames.length } +} + +test('every export in src/ has a user outside its own file', () => { + const { unused, files } = findUnusedExports() + assert.ok(files > 50, `expected to scan src/, found ${files} files`) + assert.deepEqual(unused, []) +}) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1ed836b..7f39083 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,35 +6,38 @@ import { ElevationDialog } from './components/ElevationDialog' import { CloneDialog } from './components/CloneDialog' import { OnlineRecoveryDialog } from './macos/OnlineRecoveryDialog' import { SendTextDialog } from './components/SendTextDialog' -import type { ThemeMode } from './components/AppSettingsPage' import { LogPanel, LogTab } from './components/LogPanel' import { TitleMenus } from './components/TitleMenus' -import { UpdateCapsule, UpdatePhase } from './components/UpdateCapsule' +import { UpdateCapsule } from './components/UpdateCapsule' import { DataRootReadOnly } from './components/DataRootReadOnly' import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PAGE_IDS, PLUGINS_ID, SETTINGS_ID, Sidebar } from './components/Sidebar' -import { PluginViewHost } from './components/PluginViewHost' -import { locText } from './components/SchemaForm' -import { VMAction, VMBusyAction, VMPage } from './components/VMPage' -import { buildFallbackChain, I18nKey, localeDir, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' +import { VMPage } from './components/VMPage' +import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n' import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format' import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/endpoints' import { resolveFullscreenHotkey } from './lib/fullscreenHotkey' import { LogLine, appendLog } from './lib/logs' import { macOSMajor } from './macos/macosRelease' import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks' -import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, emitThemeEvent, notifyInteractiveThemeState, type UIStateSnapshot } from './lib/themeEngine' +import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine' +import type { UIStateSnapshot } from './lib/uiSdk' import { hasVisibleDialog } from './lib/dialogState' -import { latestVMStatsWithDriver, refreshSubscribedVMStats, refreshVMStatsWithDriver } from './lib/vmStats' +import { latestVMStats, refreshSubscribedVMStats, refreshVMStats } from './lib/vmStats' +import { useAppearance } from './lib/useAppearance' +import { useAppUpdate } from './lib/useAppUpdate' +import { useFileDrop } from './lib/useFileDrop' +import { useThemeEvents } from './lib/useThemeEvents' +import { useVMBusy } from './lib/useVMBusy' import { vmRefKey } from './lib/vmRef' import { closePluginDialog, closePluginView, emptyPluginViewState, matchViewCondition, openPluginView, pluginViewKey, prunePluginViews, type PluginViewRoute, type PluginViewState } from './lib/pluginViewRouter' import { publishPluginHostEvent } from './lib/pluginViewEvents' import { buildSafePluginAssetURL } from './lib/pluginAssets' -import { ActiveThemePayload, AppState, AppUpdateInfo, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' +import { ActiveThemePayload, AppState, CachedInstaller, CreateOpts, Locale, PluginUIContributions, Task, VMAction, VMBusyAction, VMDetail, VMInfo, VMListItem, ViewContribution } from './types' import { Button, Tip, TooltipProvider } from './ui/controls' import { ConfirmDialog, Modal } from './ui/dialog' -import { Toaster, useToasts } from './ui/toast' +import { errorToast, Toaster, type ToastInput, useToasts } from './ui/toast' import { BrandMark, ThemeDecorations, ThemeVisualsProvider } from './ui/themeVisuals' -import { api, events, OnFileDrop, OnFileDropOff, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' +import { api, DROP_NETWORK_VOLUMES_DENIED, events, WindowMinimise, WindowToggleMaximise, type ElevationPrompt } from './wails' // Opened on demand, so each is its own chunk and stays out of the startup // bundle: the wizard, VM settings and affinity dialogs, first-run setup, and @@ -47,11 +50,32 @@ const HostView = lazy(() => import('./components/HostView').then((m) => ({ defau const ImagesPage = lazy(() => import('./components/ImagesPage').then((m) => ({ default: m.ImagesPage }))) const InstallersPage = lazy(() => import('./macos/InstallersPage').then((m) => ({ default: m.InstallersPage }))) const PluginsPage = lazy(() => import('./components/PluginsPage').then((m) => ({ default: m.PluginsPage }))) +const PluginViewHost = lazy(() => import('./components/PluginViewHost').then((m) => ({ default: m.PluginViewHost }))) const AppSettingsPage = lazy(() => import('./components/AppSettingsPage').then((m) => ({ default: m.AppSettingsPage }))) const AboutPage = lazy(() => import('./components/AboutPage').then((m) => ({ default: m.AboutPage }))) const errText = (e: unknown) => parseAppError(e).summary +type HostDropAck = { status: string; error?: string } + +export function showHostDropAck( + ack: HostDropAck, + locale: Locale, + pushToast: (toast: ToastInput) => void, + fail: (title: string, error: string) => void, +) { + if (ack.status !== 'failed') return + if (ack.error === DROP_NETWORK_VOLUMES_DENIED) { + pushToast({ + kind: 'error', + title: t(locale, 'gtDropAccessLimited'), + description: t(locale, 'gtDropAccessHint'), + }) + return + } + fail(t(locale, 'failDrop'), ack.error || '') +} + const failKey: Record = { start: 'failStart', suspend: 'failSuspend', @@ -83,17 +107,6 @@ const failKey: Record = { export const App: React.FC = () => { const [state, setState] = useState(null) const [selected, setSelectedPage] = useState(HOST_ID) - const [appUpdate, setAppUpdate] = useState(null) - // Check for a new release once the app is up, then every 6 hours, so the - // sidebar's update button shows up without opening the About page. - const stateReady = !!state - useEffect(() => { - if (!stateReady) return - const check = () => { api.CheckAppUpdate(false).then(setAppUpdate).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) } - check() - const id = window.setInterval(check, 6 * 60 * 60 * 1000) - return () => window.clearInterval(id) - }, [stateReady]) const [detail, setDetail] = useState(null) // GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail). const [vmInfoLoaded, setVMInfoLoaded] = useState(null) @@ -110,26 +123,8 @@ export const App: React.FC = () => { const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null) const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState(null) const [sendTextTarget, setSendTextTarget] = useState(null) - const [busy, setBusy] = useState>({}) - const busyOpsRef = useRef>>(new Map()) - const nextBusyTokenRef = useRef(0) - const [dropping, setDropping] = useState(false) + const vmBusy = useVMBusy() const [loadError, setLoadError] = useState('') - const [themeMode, setThemeModeState] = useState(() => { - try { - const saved = localStorage.getItem('reims-go-theme') - if (saved === 'dark' || saved === 'light') return saved - } catch (e) { - console.warn('[app] read theme preference failed:', e) - } - return 'system' - }) - const [sysDark, setSysDark] = useState(() => - typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches, - ) - const [reducedMotion, setReducedMotion] = useState(() => - typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches, - ) const [pluginUI, setPluginUI] = useState(null) const [pluginViewState, setPluginViewState] = useState(emptyPluginViewState) const [pluginViewMeta, setPluginViewMeta] = useState>({}) @@ -150,50 +145,7 @@ export const App: React.FC = () => { : activeThemeContrib ? (activeThemeContrib.appearance === 'light' || activeThemeContrib.appearance === 'dark' ? activeThemeContrib.appearance : 'both') : 'light' - const canLight = themeAppearanceCap === 'both' || themeAppearanceCap === 'light' - const canDark = themeAppearanceCap === 'both' || themeAppearanceCap === 'dark' - const theme: 'light' | 'dark' = !canDark ? 'light' : !canLight ? 'dark' : (themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode) - const effectiveThemeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : themeMode - - useEffect(() => { - document.documentElement.dataset.theme = theme - events.emitTheme(theme) - }, [theme]) - - useEffect(() => { - document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full' - }, [reducedMotion]) - - useEffect(() => { - const mq = window.matchMedia?.('(prefers-color-scheme: dark)') - if (!mq) return - const onChange = (e: MediaQueryListEvent) => setSysDark(e.matches) - mq.addEventListener('change', onChange) - return () => mq.removeEventListener('change', onChange) - }, []) - - useEffect(() => { - const mq = window.matchMedia?.('(prefers-reduced-motion: reduce)') - if (!mq) return - const onChange = (e: MediaQueryListEvent) => setReducedMotion(e.matches) - mq.addEventListener('change', onChange) - return () => mq.removeEventListener('change', onChange) - }, []) - - const setThemeMode = (mode: ThemeMode) => { - setThemeModeState(mode) - try { - if (mode === 'system') localStorage.removeItem('reims-go-theme') - else localStorage.setItem('reims-go-theme', mode) - } catch (e) { - console.warn('[app] persist theme preference failed:', e) - } - } - - const toggleTheme = () => { - if (!canLight || !canDark) return - setThemeMode(theme === 'light' ? 'dark' : 'light') - } + const { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion } = useAppearance(themeAppearanceCap) // Sidebar can be hidden (Ctrl+B or the title-bar toggle); remembered per user. const [sidebarOpen, setSidebarOpen] = useState(() => { @@ -214,7 +166,7 @@ export const App: React.FC = () => { logsOpenRef.current = logsOpen const [taskMap, setTaskMap] = useState>({}) const onTaskRef = useRef<(task: Task) => void>(() => {}) - const onHostDropAckRef = useRef<(ack: { status: string; error?: string }) => void>(() => {}) + const onHostDropAckRef = useRef<(ack: HostDropAck) => void>(() => {}) const notifiedTasks = useRef(new Map()) const [setupStage, setSetupStage] = useState<'folder' | 'runtime' | null>(null) @@ -356,23 +308,24 @@ export const App: React.FC = () => { const activePluginView = routedView && viewAvailable(routedView, pluginViewState.route?.vm) ? routedView : undefined const activePluginRoute = activePluginView ? pluginViewState.route : null const renderPluginView = (route: PluginViewRoute, view: ViewContribution, dialog = false) => ( - updateViewMetadata(view, metadata)} - onOpenView={openView} - onCloseView={dialog ? () => { - setPluginViewState((current) => closePluginDialog(current, route)) - return { closed: true } - } : closeView} - onNavigate={navigateHost} - /> + + updateViewMetadata(view, metadata)} + onOpenView={openView} + onCloseView={dialog ? () => { + setPluginViewState((current) => closePluginDialog(current, route)) + return { closed: true } + } : closeView} + onNavigate={navigateHost} + /> + ) const renderVMTabs = () => { if (!selectedVM) return null @@ -434,9 +387,9 @@ export const App: React.FC = () => { let live = true for (const vm of vms) { const key = vmRefKey(vm) - api.GetVMNoteWithDriver(vm.driver_id ?? '', vm.name) + api.GetVMNote(vm.driver_id ?? '', vm.name) .then((n) => { if (live) setDisplayNames((m) => ({ ...m, [key]: (n ?? '').trim() })) }) - .catch((e) => console.warn('[app] GetVMNoteWithDriver failed:', key, e)) + .catch((e) => console.warn('[app] GetVMNote failed:', key, e)) } return () => { live = false } // eslint-disable-next-line react-hooks/exhaustive-deps @@ -557,53 +510,11 @@ export const App: React.FC = () => { : 'stable' const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => { await api.SetAppUpdateChannel(ch) - setDismissedUpdate('') - try { localStorage.removeItem('reims-go-update-dismissed') } catch (e) { console.warn('[app] clear dismissed update failed:', e) } await refresh() - try { - setAppUpdate(await api.CheckAppUpdate(true)) - } catch (e) { - setAppUpdate(null) - throw e - } + await update.recheck() } const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) } - // In-app update: one task per release; its state drives the sidebar capsule - // and the About page alike. - const updateTask = appUpdate?.has_update - ? Object.values(taskMap) - .filter((x) => x.kind === 'app-update' && x.subject === appUpdate.latest) - .sort((a, b) => b.updated_at - a.updated_at)[0] ?? null - : null - const updatePhase: UpdatePhase = !appUpdate?.has_update ? 'none' - : updateTask?.status === 'running' ? 'downloading' - : updateTask?.status === 'done' ? 'ready' - : updateTask?.status === 'failed' ? 'failed' - : 'available' - const [dismissedUpdate, setDismissedUpdate] = useState(() => { - try { return localStorage.getItem('reims-go-update-dismissed') ?? '' } catch { return '' } - }) - const dismissUpdate = () => { - if (!appUpdate) return - setDismissedUpdate(appUpdate.latest) - try { localStorage.setItem('reims-go-update-dismissed', appUpdate.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) } - } - const [confirmUpdate, setConfirmUpdate] = useState(false) - const [installingUpdate, setInstallingUpdate] = useState(false) - const downloadUpdate = () => { api.DownloadAppUpdate().catch((e) => fail(tr('updateFailed'), e)) } - const runInstallUpdate = () => { - setConfirmUpdate(false) - setInstallingUpdate(true) - api.InstallAppUpdate().catch((e) => { - setInstallingUpdate(false) - fail(tr('updateFailed'), e) - }) - } - // Restarting leaves VMs running but pauses the host-guest bridges: say so first. - const installUpdate = () => { if (runningVMCount > 0) setConfirmUpdate(true); else runInstallUpdate() } - const showUpdateCard = updatePhase !== 'none' && !(updatePhase === 'available' && dismissedUpdate === appUpdate?.latest) - // One toast after an update restart: the version changed since the last run. useEffect(() => { const v = state?.app_version @@ -638,7 +549,7 @@ export const App: React.FC = () => { // UI Contract v2 read-only document state attributes. const currentView = showSetup ? 'setup' : activePluginRoute?.location === 'sidebar' ? 'plugins' : activePluginRoute?.location === 'settings' ? 'settings' : activePluginRoute?.location === 'vm.tab' ? 'vm' : selected === HOST_ID ? 'host' : selected === INSTALLERS_ID ? 'installers' : selected === PLUGINS_ID ? 'plugins' : selected === SETTINGS_ID ? 'settings' : selected === ABOUT_ID ? 'about' : 'vm' - const isBusyAny = Object.keys(busy).length > 0 || runningTasks > 0 + const isBusyAny = Object.keys(vmBusy.busy).length > 0 || runningTasks > 0 const hasAnyError = unseenErrors > 0 || !!loadError const uiStateRef = useRef({ appearance: theme, @@ -679,43 +590,7 @@ export const App: React.FC = () => { notifyInteractiveThemeState(uiStateRef.current) }, [currentView, effectiveState, isBusyAny, hasAnyError, sidebarOpen, state?.safe_mode, locale, dir, theme, reducedMotion]) - // UI SDK event stream (ui-contract UI_CONTRACT_SDK_EVENTS). emitThemeEvent is - // a no-op unless an interactive theme is loaded; payloads carry no paths. - const selectedRef = selectedVM ? vmRefKey(selectedVM) : '' - useEffect(() => { - emitThemeEvent('view.changed', { view: currentView, vm: selectedRef }) - }, [currentView, selectedRef]) - const vmStatesRef = useRef | null>(null) - useEffect(() => { - const next: Record = {} - for (const v of vms) next[vmRefKey(v)] = state?.transitions[vmRefKey(v)] ?? v.state - const prev = vmStatesRef.current - vmStatesRef.current = next - if (!prev) return - for (const v of vms) { - const key = vmRefKey(v) - if (prev[key] !== undefined && prev[key] !== next[key]) { - const payload = { vm: key, name: v.name, driver: v.driver_id ?? '', from: prev[key], to: next[key] } - emitThemeEvent('vm.stateChanged', payload) - publishPluginHostEvent('vm.stateChanged', payload) - } - } - }, [vms, state?.transitions]) - const taskStatesRef = useRef | null>(null) - useEffect(() => { - const prev = taskStatesRef.current - const next: Record = {} - for (const t of Object.values(taskMap)) next[t.id] = { status: t.status, percent: t.percent } - taskStatesRef.current = next - if (!prev) return - for (const t of Object.values(taskMap)) { - const was = prev[t.id] - const info = { id: t.id, kind: t.kind, vm: t.vm ?? '', percent: t.percent } - if (!was && t.status === 'running') emitThemeEvent('task.started', info) - else if (was?.status === 'running' && t.status === 'running' && was.percent !== t.percent) emitThemeEvent('task.progress', info) - if ((!was || was.status === 'running') && t.status !== 'running') emitThemeEvent('task.finished', { ...info, status: t.status }) - } - }, [taskMap]) + useThemeEvents({ view: currentView, selectedVM: selectedVM ? vmRefKey(selectedVM) : '', vms, transitions: state?.transitions, tasks: taskMap }) // Refresh contributions together with the active theme after registry changes. useEffect(() => { @@ -742,7 +617,7 @@ export const App: React.FC = () => { openSettings: () => setSelected(SETTINGS_ID), focusVMWindow: (vmName) => { const vm = vmsRef.current.find((v) => vmRefKey(v) === vmName) ?? vmsRef.current.find((v) => v.name === vmName) - void api.FocusVMWindowWithDriver(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindowWithDriver failed:', vmName, e)) + void api.FocusVMWindow(vm?.driver_id ?? '', vm?.name ?? vmName).catch((e) => console.warn('[theme] FocusVMWindow failed:', vmName, e)) }, }, ) @@ -765,7 +640,7 @@ export const App: React.FC = () => { try { const logVM = name === selectedVM?.name ? selectedVM : vms.find((v) => v.name === name) const logDriverID = logVM?.driver_id ?? '' - const text = await api.ReadVMLogsWithDriver(logDriverID, name, serial) + const text = await api.ReadVMLogs(logDriverID, name, serial) if (serial) setSerialLog(text) else setQemuLog(text) } catch (e) { @@ -778,67 +653,16 @@ export const App: React.FC = () => { const loadQemu = (name?: string) => loadVMLog(false, name) const fail = (title: string, e: unknown) => { - const parsed = parseAppError(e) toasts.push({ - kind: 'error', - title, - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, title, e), action: { label: tr('viewLogs'), onClick: () => openLogs('app') }, }) } - onHostDropAckRef.current = (ack) => { - if (ack.status === 'failed') fail(tr('failDrop'), ack.error || '') - } - - // Busy state is keyed by VM reference (driver and name), so same-name VMs of - // different drivers never block each other. - const activeVMBusy = (key: string): VMBusyAction | undefined => { - const ops = busyOpsRef.current.get(key) - if (!ops || ops.size === 0) return undefined - let latest: VMBusyAction | undefined - for (const act of ops.values()) latest = act - return latest - } - - const syncBusyState = () => { - const next: Record = Object.create(null) - for (const [vmName, ops] of busyOpsRef.current) { - let latest: VMBusyAction | undefined - for (const act of ops.values()) latest = act - if (latest) next[vmName] = latest - } - setBusy(next) - } - - const beginVMBusy = (name: string, action: VMBusyAction): number | null => { - const ops = busyOpsRef.current.get(name) - if (ops && ops.size > 0) { - if (action !== 'forceStop') return null - for (const act of ops.values()) { - if (act === 'forceStop') return null - } - } - const token = ++nextBusyTokenRef.current - const vmOps = ops ?? new Map() - vmOps.set(token, action) - busyOpsRef.current.set(name, vmOps) - syncBusyState() - return token - } - - const endVMBusy = (name: string, token: number) => { - const ops = busyOpsRef.current.get(name) - if (!ops || !ops.delete(token)) return - if (ops.size === 0) busyOpsRef.current.delete(name) - syncBusyState() - } + const update = useAppUpdate({ ready: !!state, tasks: taskMap, runningVMCount, onError: (e) => fail(tr('updateFailed'), e) }) + onHostDropAckRef.current = (ack) => showHostDropAck(ack, locale, toasts.push, fail) const runVMAction = async (name: string, action: VMBusyAction, fn: () => Promise, okTitle?: string) => { - const token = beginVMBusy(name, action) + const token = vmBusy.begin(name, action) if (token === null) return try { await fn() @@ -847,14 +671,14 @@ export const App: React.FC = () => { } catch (e) { fail(tr(failKey[action]), e) } finally { - endVMBusy(name, token) + vmBusy.end(name, token) } } // Paste as keystrokes: the backend refuses text a US keyboard can't type // (ErrNotTypeable in type_flow.go), which gets a message of its own. const typeInto = async (busyKey: string, fn: () => Promise) => { - const token = beginVMBusy(busyKey, 'type') + const token = vmBusy.begin(busyKey, 'type') if (token === null) return try { const n = await fn() @@ -866,7 +690,7 @@ export const App: React.FC = () => { fail(tr('failType'), e) } } finally { - endVMBusy(busyKey, token) + vmBusy.end(busyKey, token) } } @@ -884,7 +708,7 @@ export const App: React.FC = () => { return } } - const token = beginVMBusy(busyKey, 'attachInstaller') + const token = vmBusy.begin(busyKey, 'attachInstaller') if (token === null) return try { const fileName = await api.AttachInstaller(name, picked) @@ -894,7 +718,7 @@ export const App: React.FC = () => { }) await refresh() } finally { - endVMBusy(busyKey, token) + vmBusy.end(busyKey, token) } } catch (e) { fail(tr('failAttachInstaller'), e) @@ -903,7 +727,7 @@ export const App: React.FC = () => { // Hosted VMs have no window: the primary action is their best ready endpoint. const openEndpoint = (vm: VMListItem, kind: string) => { - api.OpenVMEndpointWithDriver(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) + api.OpenVMEndpoint(vm.driver_id ?? '', vm.name, kind, '').catch((e) => fail(tr('failEndpointOpen'), e)) } const openPrimaryEndpoint = (vm: VMListItem) => { const { primary } = splitEndpoints(vm.endpoints) @@ -931,7 +755,7 @@ export const App: React.FC = () => { if (actionVM) openPrimaryEndpoint(actionVM) return } - const activeBusy = activeVMBusy(key) + const activeBusy = vmBusy.current(key) if ( activeBusy && action !== 'openFolder' @@ -941,21 +765,21 @@ export const App: React.FC = () => { return } switch (action) { - case 'start': return runVMAction(key, action, () => api.StartVMWithDriver(actionDriverID, name)) - case 'suspend': return runVMAction(key, action, () => api.SuspendVMWithDriver(actionDriverID, name), tr('toastSuspended', { name })) - case 'resume': return runVMAction(key, action, () => api.ResumeVMWithDriver(actionDriverID, name), tr('toastResumed', { name })) + case 'start': return runVMAction(key, action, () => api.StartVM(actionDriverID, name)) + case 'suspend': return runVMAction(key, action, () => api.SuspendVM(actionDriverID, name), tr('toastSuspended', { name })) + case 'resume': return runVMAction(key, action, () => api.ResumeVM(actionDriverID, name), tr('toastResumed', { name })) case 'discardSuspend': return setDiscardSuspendTarget(key) - case 'focus': return api.FocusVMWindowWithDriver(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) + case 'focus': return api.FocusVMWindow(actionDriverID, name).catch((e) => fail(tr('failFocus'), e)) case 'fullscreen': return runVMAction(key, action, async () => { - const isFullscreen = await api.ToggleVMFullscreenWithDriver(actionDriverID, name) - refreshVMStatsWithDriver(actionDriverID, name, { window_fullscreen: isFullscreen }) + const isFullscreen = await api.ToggleVMFullscreen(actionDriverID, name) + refreshVMStats(actionDriverID, name, { window_fullscreen: isFullscreen }) }) - case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshotWithDriver(actionDriverID, name), tr('toastScreenshotCopied')) - case 'stop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, false), tr('toastStopped', { name })) - case 'forceStop': return runVMAction(key, action, () => api.StopVMWithDriver(actionDriverID, name, true), tr('toastStopped', { name })) - case 'restart': return runVMAction(key, action, () => api.RestartVMWithDriver(actionDriverID, name)) - case 'eject': return runVMAction(key, action, () => api.EjectInstallerWithDriver(actionDriverID, name), tr('toastEjected')) + case 'screenshot': return runVMAction(key, action, () => api.CopyVMScreenshot(actionDriverID, name), tr('toastScreenshotCopied')) + case 'stop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, false), tr('toastStopped', { name })) + case 'forceStop': return runVMAction(key, action, () => api.StopVM(actionDriverID, name, true), tr('toastStopped', { name })) + case 'restart': return runVMAction(key, action, () => api.RestartVM(actionDriverID, name)) + case 'eject': return runVMAction(key, action, () => api.EjectInstaller(actionDriverID, name), tr('toastEjected')) case 'finishInstall': return runVMAction(key, action, () => api.FinishInstall(name), tr(isRunning ? 'toastExitRecoveryNextStart' : 'toastInstallFinished')) case 'enterRecovery': return runVMAction(key, action, () => api.EnterRecovery(name), tr(isRunning ? 'toastEnterRecoveryNextStart' : 'toastEnterRecovery')) case 'attachInstaller': return attachInstaller(key, name, isRunning) @@ -966,11 +790,11 @@ export const App: React.FC = () => { case 'upgradeNVMe': return runVMAction(key, action, () => api.UpgradeDiskToNVMe(name), tr(isRunning ? 'toastNVMeNextStart' : 'toastNVMeReady')) case 'exportDiagnostics': - return runVMAction(key, action, async () => { await api.ExportDiagnosticsWithDriver(actionDriverID, name) }, tr('toastDiagExported')) + return runVMAction(key, action, async () => { await api.ExportDiagnostics(actionDriverID, name) }, tr('toastDiagExported')) case 'cloneVM': if (!features.clone) return return setCloneSource({ name, driverID: actionDriverID }) - case 'type': return typeInto(key, () => api.TypeClipboardWithDriver(actionDriverID, name)) + case 'type': return typeInto(key, () => api.TypeClipboard(actionDriverID, name)) case 'sendText': return setSendTextTarget(key) case 'openFolder': return api.OpenVMFolder(name).catch((e) => fail(tr('failOpenFolder'), e)) @@ -1004,7 +828,7 @@ export const App: React.FC = () => { const vm = findVM(name) if (!vm) return const key = vmRefKey(vm) - if (activeVMBusy(key)) return + if (vmBusy.current(key)) return const st = state?.transitions[key] ?? vm.state if (st === 'stopped') onVMActionFor(key, 'start', false) else if (st === 'suspended') onVMActionFor(key, 'resume', false) @@ -1018,7 +842,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'delete', () => api.DeleteVMWithDriver(driverID, name, keepFiles), tr('toastDeleted', { name })) + if (name) runVMAction(key, 'delete', () => api.DeleteVM(driverID, name, keepFiles), tr('toastDeleted', { name })) } const confirmDiscardSuspend = () => { @@ -1028,7 +852,7 @@ export const App: React.FC = () => { const name = targetVM?.name ?? target const driverID = targetVM?.driver_id ?? '' const key = targetVM ? vmRefKey(targetVM) : (name ?? '') - if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspendWithDriver(driverID, name), tr('toastDiscardSuspend', { name })) + if (name) runVMAction(key, 'discardSuspend', () => api.DiscardSuspend(driverID, name), tr('toastDiscardSuspend', { name })) } const confirmOnlineRecovery = () => { @@ -1045,7 +869,7 @@ export const App: React.FC = () => { setCloneSource(null) if (!src) return runVMAction(vmRefKey({ name: src.name, driver_id: src.driverID }), 'cloneVM', async () => { - await api.CloneVMCoWWithDriver(src.driverID, src.name, cloneName) + await api.CloneVMCoW(src.driverID, src.name, cloneName) setSelected(vmRefKey({ name: cloneName, driver_id: src.driverID })) }, tr('toastCloned', { name: cloneName })) } @@ -1119,17 +943,10 @@ export const App: React.FC = () => { }) .catch((e) => { void refresh() - const parsed = parseAppError(e) - if (parsed.code === 'E_NETWORK_CREATE_BRIDGE_PENDING') { + if (parseAppError(e).code === 'E_NETWORK_CREATE_BRIDGE_PENDING') { setSelected(name) toasts.push({ - kind: 'error', - title: tr('toastCreated', { name }), - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, tr('toastCreated', { name }), e), action: { label: tr('settings'), onClick: () => { api.GetVMDetail(name).then((d) => { setDetail(d); setSelected(name); setShowSettings(true) }).catch((err) => fail(tr('failGeneric'), err)) } }, @@ -1146,13 +963,7 @@ export const App: React.FC = () => { return } toasts.push({ - kind: 'error', - title: tr('failCreate', { name }), - description: parsed.summary, - errorCode: parsed.code, - rawDetail: parsed.rawDetail, - detailsLabel: tr('errRawDetailsToggle'), - copyDetailsLabel: tr('errCopyDetails'), + ...errorToast(locale, tr('failCreate', { name }), e), action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } }, }) }) @@ -1175,7 +986,7 @@ export const App: React.FC = () => { // Global shortcuts (see docs/design-guidelines.md). Dialogs own the keyboard while open. const shortcutRef = useRef<(e: KeyboardEvent) => void>(() => {}) const appDialogOpen = showSetup || showReadOnly || showWizard || showSettings || affinityTarget || deleteTarget || - discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || confirmUpdate || closeDownloadsOpen || elevationQueue.length > 0 + discardSuspendTarget || sendTextTarget || cloneSource || onlineRecoveryTarget || update.confirming || closeDownloadsOpen || elevationQueue.length > 0 shortcutRef.current = (e: KeyboardEvent) => { if (!e.ctrlKey || e.altKey || e.metaKey) return if (appDialogOpen) return @@ -1218,46 +1029,17 @@ export const App: React.FC = () => { return () => { offRequest(); offResolved() } }, []) - // Native Wails file drag-and-drop delivery into the selected VM's shared folder. - const dropTargetRef = useRef<{ name: string; ready: boolean }>({ name: '', ready: false }) - dropTargetRef.current = { - name: selectedVM?.name ?? '', - ready: !!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, - } - useEffect(() => { - let depth = 0 - const onEnter = (e: DragEvent) => { - if (!dropTargetRef.current.ready) return - if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) } - } - const onLeave = () => { - depth = Math.max(0, depth - 1) - if (depth === 0) setDropping(false) - } - const onDropEnd = () => { depth = 0; setDropping(false) } - window.addEventListener('dragenter', onEnter) - window.addEventListener('dragleave', onLeave) - window.addEventListener('drop', onDropEnd) - OnFileDrop((_x, _y, paths) => { - depth = 0 - setDropping(false) - const cur = dropTargetRef.current - if (!cur.ready || !cur.name || !paths || paths.length === 0) return - api.DeliverPathsToGuest(cur.name, paths) - .then((delivered) => { - if (!delivered || delivered.length === 0) return - if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) }) - else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) }) - }) - .catch((e) => fail(tr('failGuestTools'), e)) - }, true) - return () => { - window.removeEventListener('dragenter', onEnter) - window.removeEventListener('dragleave', onLeave) - window.removeEventListener('drop', onDropEnd) - OnFileDropOff() - } - }, []) + // Files dropped on the window go to the selected VM's shared folder. + const dropping = useFileDrop(!!selectedVM && !!detail && !detail.has_installer && !detail.recovery_mode, (paths) => { + if (!selectedVM) return + api.DeliverPathsToGuest(selectedVM.name, paths) + .then((delivered) => { + if (!delivered || delivered.length === 0) return + if (delivered.length === 1) toasts.push({ kind: 'ok', title: tr('toastFileDelivered', { name: delivered[0] }) }) + else toasts.push({ kind: 'ok', title: tr('toastFilesDelivered', { n: delivered.length }) }) + }) + .catch((e) => fail(tr('failGuestTools'), e)) + }) return ( @@ -1277,7 +1059,7 @@ export const App: React.FC = () => { onToggleSidebar={toggleSidebar} logsOpen={logsOpen} onToggleLogs={toggleLogs} - themeMode={effectiveThemeMode} + themeMode={themeMode} canLight={canLight} canDark={canDark} onThemeMode={setThemeMode} @@ -1285,7 +1067,7 @@ export const App: React.FC = () => { name: selectedVM.name, driver_id: selectedVM.driver_id, state: effectiveState, - busy: Object.prototype.hasOwnProperty.call(busy, vmRefKey(selectedVM)), + busy: vmRefKey(selectedVM) in vmBusy.busy, graphics: detail?.name === selectedVM.name ? detail.graphics : undefined, canSuspend: canSuspendVM(selectedVM), features: selectedFeatures, @@ -1308,7 +1090,7 @@ export const App: React.FC = () => { type="button" className="theme-toggle" aria-label={tr(theme === 'light' ? 'themeSwitchDark' : 'themeSwitchLight')} - onClick={toggleTheme} + onClick={() => setThemeMode(theme === 'light' ? 'dark' : 'light')} > {theme === 'light' ?