Merge branch 'main' into fix/vm-delete-cleanup-and-dir-check

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NwflowerandClaude Opus 5.5 committed 2026-12-04 03:36:45 -07:00
commit cc1daf32d8
344 files changed
+11037 -9299

No files matched your search

+157 -18
View File
@@ -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 = "<!-- reims-pr-review ";
const MAX_OCR_CONTINUATIONS = 2;
const RESUME_STATE_FILE = "ocr-resume.json";
const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
const SKIP_CI_PATTERN = /\[(?:skip ci|ci skip|no ci|skip actions|actions skip)\]/i;
const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
const SHA = /^[0-9a-f]{40}$/i;
@@ -371,7 +375,8 @@ export function extractPreviousReview(reviews, reviewComments = [], login = "rei
const marker = parseReviewMarker(latest.body);
return {
commit: latest.commit_id || null,
headSha: marker?.incomplete ? null : marker?.head_sha ?? null,
incomplete: Boolean(marker?.incomplete),
headSha: marker?.head_sha ?? null,
baseSha: marker?.base_sha ?? null,
summary: shortText(latest.body.replace(/^<!--[^\n]*-->\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")) {
+86 -1
View File
@@ -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 = '<!-- reims-pr-review {"v":2,"head_sha":"' + B + '","base_sha":"' + A + '","main_sha":"' + A + '","incomplete":true} -->';
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");
});
+1 -1
View File
@@ -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
+23 -1
View File
@@ -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
+1 -1
View File
@@ -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`
+1 -1
View File
@@ -121,7 +121,7 @@ reims-go vm start macos-tahoe | Out-Host # Start the VM
<details>
<summary>Build from source</summary>
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).
</details>
+1 -1
View File
@@ -117,7 +117,7 @@ reims-go vm start macos-tahoe | Out-Host # 启动虚拟机
<details>
<summary>从源码构建</summary>
需要 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) 单独构建。
</details>
@@ -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."
}
@@ -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."
}
@@ -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."
}
+9
View File
@@ -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`."
}
+7
View File
@@ -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."
}
+7
View File
@@ -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."
}
+9
View File
@@ -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."
}
+9
View File
@@ -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."
}
+3 -4
View File
@@ -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 {
+12
View File
@@ -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)
+3 -1
View File
@@ -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(并非隔离沙盒),加载前宿主会自动收起桌面底层绑定全局对象。
已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。
+2 -2
View File
@@ -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;运行时再负责选取具备该能力的版本。
+1 -1
View File
@@ -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",
+94 -26
View File
@@ -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…</button>'), 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…</button>'), 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 = '<div class="conn-row conn-sub conn-drop-access">' +
'<span class="conn-status is-idle"><span class="conn-status-dot" aria-hidden="true"></span>' +
`${title}</span><span class="conn-meta">${guidance.replaceAll('&', '&amp;')}</span></div>`
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)
})
+50 -66
View File
@@ -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`)
}
})
+45
View File
@@ -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, [])
})
+24
View File
@@ -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))), [])
})
+57
View File
@@ -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, [])
})
+139 -364
View File
@@ -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<VMBusyAction, I18nKey> = {
start: 'failStart',
suspend: 'failSuspend',
@@ -83,17 +107,6 @@ const failKey: Record<VMBusyAction, I18nKey> = {
export const App: React.FC = () => {
const [state, setState] = useState<AppState | null>(null)
const [selected, setSelectedPage] = useState<string>(HOST_ID)
const [appUpdate, setAppUpdate] = useState<AppUpdateInfo | null>(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<VMDetail | null>(null)
// GetVMInfo for the selected non-macOS VM; macOS VMs use `detail` (GetVMDetail).
const [vmInfoLoaded, setVMInfoLoaded] = useState<VMInfo | null>(null)
@@ -110,26 +123,8 @@ export const App: React.FC = () => {
const [cloneSource, setCloneSource] = useState<{ name: string; driverID: string } | null>(null)
const [onlineRecoveryTarget, setOnlineRecoveryTarget] = useState<string | null>(null)
const [sendTextTarget, setSendTextTarget] = useState<string | null>(null)
const [busy, setBusy] = useState<Record<string, VMBusyAction>>({})
const busyOpsRef = useRef<Map<string, Map<number, VMBusyAction>>>(new Map())
const nextBusyTokenRef = useRef(0)
const [dropping, setDropping] = useState(false)
const vmBusy = useVMBusy()
const [loadError, setLoadError] = useState('')
const [themeMode, setThemeModeState] = useState<ThemeMode>(() => {
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<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-color-scheme: dark)').matches,
)
const [reducedMotion, setReducedMotion] = useState<boolean>(() =>
typeof window !== 'undefined' && !!window.matchMedia?.('(prefers-reduced-motion: reduce)').matches,
)
const [pluginUI, setPluginUI] = useState<PluginUIContributions | null>(null)
const [pluginViewState, setPluginViewState] = useState<PluginViewState>(emptyPluginViewState)
const [pluginViewMeta, setPluginViewMeta] = useState<Record<string, { title?: string; badge?: { text: string; tone: string } }>>({})
@@ -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<boolean>(() => {
@@ -214,7 +166,7 @@ export const App: React.FC = () => {
logsOpenRef.current = logsOpen
const [taskMap, setTaskMap] = useState<Record<string, Task>>({})
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<string, number>())
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) => (
<PluginViewHost
key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`}
view={view}
locale={locale}
appearance={theme}
assetToken={pluginUI?.asset_token ?? ''}
vm={route.vm}
dialog={dialog}
metadata={pluginViewMeta[pluginViewKey(route)]}
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
onOpenView={openView}
onCloseView={dialog ? () => {
setPluginViewState((current) => closePluginDialog(current, route))
return { closed: true }
} : closeView}
onNavigate={navigateHost}
/>
<Suspense key={`${pluginViewKey(route)}:${route.vm ?? ''}:${dialog ? 'dialog' : 'page'}`} fallback={null}>
<PluginViewHost
view={view}
locale={locale}
appearance={theme}
assetToken={pluginUI?.asset_token ?? ''}
vm={route.vm}
dialog={dialog}
metadata={pluginViewMeta[pluginViewKey(route)]}
onMetadata={(metadata) => updateViewMetadata(view, metadata)}
onOpenView={openView}
onCloseView={dialog ? () => {
setPluginViewState((current) => closePluginDialog(current, route))
return { closed: true }
} : closeView}
onNavigate={navigateHost}
/>
</Suspense>
)
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<string>(() => {
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<UIStateSnapshot>({
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<Record<string, string> | null>(null)
useEffect(() => {
const next: Record<string, string> = {}
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<Record<string, { status: string; percent: number }> | null>(null)
useEffect(() => {
const prev = taskStatesRef.current
const next: Record<string, { status: string; percent: number }> = {}
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<string, VMBusyAction> = 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<number, VMBusyAction>()
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<void>, 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<number>) => {
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 (
<ThemeVisualsProvider payload={activeThemePayload}>
@@ -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' ? <Moon size={14} aria-hidden="true" /> : <Sun size={14} aria-hidden="true" />}
</button>
@@ -1365,7 +1147,7 @@ export const App: React.FC = () => {
locale={locale}
vms={vms}
transitions={state?.transitions ?? {}}
busyActions={busy}
busyActions={vmBusy.busy}
selected={sidebarSelected}
hostReady={hostReady}
canSuspend={canSuspend}
@@ -1387,19 +1169,19 @@ export const App: React.FC = () => {
onVMContextAction={onSidebarContextAction}
downloading={Object.values(taskMap).some(isActiveInstallerTask)}
safeMode={state?.safe_mode}
updateDot={!!appUpdate?.has_update}
updateDot={!!update.info?.has_update}
pluginViews={sidebarPluginViews}
updateCard={showUpdateCard ? (
updateCard={update.shown ? (
<UpdateCapsule
locale={locale}
phase={installingUpdate ? 'ready' : updatePhase}
latest={appUpdate?.latest ?? ''}
task={updateTask}
phase={update.installing ? 'ready' : update.phase}
latest={update.info?.latest ?? ''}
task={update.task}
onOpen={() => setSelected(ABOUT_ID)}
onDownload={downloadUpdate}
onCancel={() => { if (updateTask) cancelTask(updateTask.id) }}
onInstall={installUpdate}
onDismiss={dismissUpdate}
onDownload={update.download}
onCancel={() => { if (update.task) cancelTask(update.task.id) }}
onInstall={update.install}
onDismiss={update.dismiss}
/>
) : null}
/>
@@ -1445,6 +1227,7 @@ export const App: React.FC = () => {
locale={locale}
appearance={theme}
safeMode={state.safe_mode}
runtimeCommit={state.active_runtime?.commit}
onRefresh={refresh}
onError={fail}
onThemeChanged={() => setThemeRevision((r) => r + 1)}
@@ -1471,7 +1254,7 @@ export const App: React.FC = () => {
vmInfo={vmInfo}
host={state.host}
pending={pending}
busyAction={Object.prototype.hasOwnProperty.call(busy, vmRefKey(selectedVM)) ? busy[vmRefKey(selectedVM)] : undefined}
busyAction={vmBusy.busy[vmRefKey(selectedVM)]}
onAction={onVMAction}
onPluginCommand={(pluginID, command, title) => {
const name = selectedVM.name
@@ -1485,15 +1268,7 @@ export const App: React.FC = () => {
onDelete={() => setDeleteTarget(vmRefKey(selectedVM))}
onViewLogs={() => { openLogs('serial'); loadSerial() }}
onCopy={copy}
onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeTextWithDriver(selectedVM.driver_id ?? '', selectedVM.name, text))}
onToggleBorderless={(enabled) => {
api.ToggleBorderless(selectedVM.name, enabled)
.then(() => {
toasts.push({ kind: 'ok', title: tr(effectiveState === 'running' ? 'toastBorderlessNextStart' : 'toastBorderlessUpdated') })
return refresh()
})
.catch((e) => fail(tr('failGeneric'), e))
}}
onTypeText={(text) => typeInto(vmRefKey(selectedVM), () => api.TypeText(selectedVM.driver_id ?? '', selectedVM.name, text))}
onTogglePreventSleep={(enabled) => {
api.SetGuestPreventSleep(selectedVM.name, enabled)
.then(() => {
@@ -1522,7 +1297,7 @@ export const App: React.FC = () => {
locale={locale}
locales={pluginUI?.locales}
tasks={Object.values(taskMap)}
themeMode={effectiveThemeMode}
themeMode={themeMode}
canLight={canLight}
canDark={canDark}
pluginViews={settingsPluginViews}
@@ -1538,14 +1313,14 @@ export const App: React.FC = () => {
appVersion={state.app_version}
appUpdateChannel={appUpdateChannel}
onAppUpdateChannel={setAppUpdateChannel}
appUpdate={appUpdate}
onAppUpdate={setAppUpdate}
updatePhase={updatePhase}
updateTask={updateTask}
installing={installingUpdate}
onDownloadUpdate={downloadUpdate}
onCancelUpdate={() => { if (updateTask) cancelTask(updateTask.id) }}
onInstallUpdate={installUpdate}
appUpdate={update.info}
onAppUpdate={update.setInfo}
updatePhase={update.phase}
updateTask={update.task}
installing={update.installing}
onDownloadUpdate={update.download}
onCancelUpdate={() => { if (update.task) cancelTask(update.task.id) }}
onInstallUpdate={update.install}
onCopy={copy}
onError={fail}
/>
@@ -1615,7 +1390,7 @@ export const App: React.FC = () => {
locale={locale}
detail={detail}
driverID={selectedVM?.driver_id ?? ''}
stats={latestVMStatsWithDriver(selectedVM?.driver_id ?? '', detail.name)}
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
host={state.host}
fixedModeSupported={fixedModeSupported}
optimizations={state.optimizations}
@@ -1663,11 +1438,11 @@ export const App: React.FC = () => {
</Suspense>
)}
{confirmUpdate && (
{update.confirming && (
<Modal
title={tr('updateConfirmTitle', { v: appUpdate?.latest ?? '' })}
title={tr('updateConfirmTitle', { v: update.info?.latest ?? '' })}
closeLabel={tr('close')}
onClose={() => setConfirmUpdate(false)}
onClose={() => update.cancelInstall()}
>
<div className="stack-2" style={{ padding: 'var(--sp-4)', fontSize: 'var(--fs-13)', color: 'var(--text-2)' }}>
<p style={{ margin: 0 }}>{tr('updateConfirmBody', { n: runningVMCount })}</p>
@@ -1676,8 +1451,8 @@ export const App: React.FC = () => {
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setConfirmUpdate(false)}>{tr('cancel')}</Button>
<Button variant="primary" onClick={runInstallUpdate}>{tr('updateRestart')}</Button>
<Button variant="ghost" onClick={() => update.cancelInstall()}>{tr('cancel')}</Button>
<Button variant="primary" onClick={update.confirmInstall}>{tr('updateRestart')}</Button>
</span>
</div>
</Modal>
@@ -1752,12 +1527,12 @@ export const App: React.FC = () => {
<SendTextDialog
locale={locale}
vmName={sendName}
guestToolsConnected={Boolean(latestVMStatsWithDriver(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
guestToolsConnected={Boolean(latestVMStats(sendVM?.driver_id ?? '', sendName)?.guest_tools_connected ?? (selectedIsMacOS ? detail?.guest_tools_connected : false))}
onCancel={() => setSendTextTarget(null)}
onConfirm={(text) => {
const target = sendTextTarget
setSendTextTarget(null)
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeTextWithDriver(sendVM?.driver_id ?? '', sendName, text))
typeInto(sendVM ? vmRefKey(sendVM) : target, () => api.TypeText(sendVM?.driver_id ?? '', sendName, text))
}}
/>
)
+2 -2
View File
@@ -9,13 +9,13 @@ import { Modal } from '../ui/dialog'
import { Segmented } from '../ui/settings'
import { api } from '../wails'
import { REPO_URL, siteURL } from './TitleMenus'
import type { UpdatePhase } from './UpdateCapsule'
import type { UpdatePhase } from '../lib/useAppUpdate'
import { BrandMark } from '../ui/themeVisuals'
const DISCORD_INVITE_URL = 'https://discord.gg/Tj682rW5rS'
const QQ_GROUP_ID = '1136042744'
export type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
type AppUpdateChannel = 'stable' | 'alpha' | 'dev'
interface Props {
locale: Locale
+2 -2
View File
@@ -100,7 +100,7 @@ export const AffinityDialog: React.FC<Props> = ({
let live = true
setLoading(true)
setErr('')
api.GetVMAffinityWithDriver(driverID, vmName)
api.GetVMAffinity(driverID, vmName)
.then((st) => {
if (!live) return
setStatus(st)
@@ -206,7 +206,7 @@ export const AffinityDialog: React.FC<Props> = ({
setSaving(true)
setErr('')
try {
const updated = await api.SetVMAffinityWithDriver(driverID, vmName, {
const updated = await api.SetVMAffinity(driverID, vmName, {
mode,
cpus: mode === 'custom' ? selected : [],
disable_eco_qos: disableEcoQoS,
+1 -1
View File
@@ -10,13 +10,13 @@ import {
splitFullscreenHotkey,
} from '../lib/fullscreenHotkey'
import { findOptimization, optBadgeClass, optStatusLabel } from '../lib/optimizations'
import type { ThemeMode } from '../lib/useAppearance'
import { AppState, Locale, ResolvedLocalePack, Task } from '../types'
import { Button, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PopupSelect, Segmented, Switch } from '../ui/settings'
import { api } from '../wails'
export type ThemeMode = 'light' | 'dark' | 'system'
type HostDNSMode = 'system' | 'doh'
-2
View File
@@ -8,7 +8,6 @@ import '../i18n/domains/wizard.gen'
import '../i18n/domains/settings.gen'
import { I18nKey, locText, parseAppError, t } from '../i18n'
import {
GUEST_LANG_PRESETS,
guestLangOptions,
MEMORY_MARKS,
controllerLabel,
@@ -32,7 +31,6 @@ import {
recommendedMemoryGB,
recommendedResolution,
shortGPUName,
splitLangLabel,
sshCommand,
} from '../lib/format'
import { CachedInstaller, CreateOpts, DriverSummary, HostReport, Locale, Release, Task, ValidationIssue, VMNetworkSettings } from '../types'
+1 -1
View File
@@ -13,7 +13,7 @@ export const hasGuestArt = (family: GuestFamily): boolean => ART_FAMILIES.includ
* names. macOS keeps its version artwork (VersionArt), so this returns null
* for it and for an unknown family and the caller falls back to that artwork.
*/
export const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
const GuestIcon: React.FC<{ family: GuestFamily; size?: number }> = ({ family, size = 15 }) => {
switch (family) {
case 'linux':
return <HostIcon name="guest-linux"><Terminal size={size} aria-hidden="true" /></HostIcon>
+2 -3
View File
@@ -1,15 +1,14 @@
import { Disc3, Puzzle, RefreshCw } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useState } from 'react'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { I18nKey, locText, t } from '../i18n'
import { ImageSourceContribution, Locale, PluginUIContributions } from '../types'
import { Button, IconButton } from '../ui/controls'
import { Segmented } from '../ui/settings'
import { PluginPanelFrame } from './PluginPanelFrame'
import { locText } from './SchemaForm'
import { WordmarkLoader } from './WordmarkLoader'
export interface NativeImageSourceRenderOpts {
interface NativeImageSourceRenderOpts {
refreshSignal: number
onBusyChange: (busy: boolean) => void
}
@@ -1,4 +1,3 @@
import React from 'react'
import { t } from '../i18n'
import type { ParsedAppError } from '../i18n'
import type { Locale } from '../types'
+1 -1
View File
@@ -1,4 +1,4 @@
import React, { useState } from 'react'
import { useState } from 'react'
import '../i18n/domains/settings.gen'
import { parseAppError, t } from '../i18n'
import type { ParsedAppError } from '../i18n'
+1 -2
View File
@@ -1,13 +1,12 @@
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import '../i18n/domains/plugins.gen'
import { I18nKey, t } from '../i18n'
import { I18nKey, locText, t } from '../i18n'
import { Locale, MarketBrowseResult, MarketCatalogItem, PluginInfo, ScanReport } from '../types'
import { Button, Tip } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { api, events, MarketInstallProgress } from '../wails'
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
import { locText } from './SchemaForm'
import { WordmarkLoader } from './WordmarkLoader'
// Cards are revealed in pages as the feed scrolls into view.
+2 -2
View File
@@ -1,6 +1,6 @@
import { AlertTriangle } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { getPluginMessageBundle, localeDir, parseAppError, t } from '../i18n'
import { getPluginMessageBundle, localeDir, locText, parseAppError, t } from '../i18n'
import { Locale, PanelContribution, ViewContribution } from '../types'
import { Button } from '../ui/controls'
import { ConfirmDialog } from '../ui/dialog'
@@ -12,7 +12,7 @@ import {
} from '../lib/pluginViewActions'
import { buildSafePluginAssetURL } from '../lib/pluginAssets'
import { subscribePluginHostEvents } from '../lib/pluginViewEvents'
import { locText, SchemaForm } from './SchemaForm'
import { SchemaForm } from './SchemaForm'
interface Props {
locale: Locale
+1 -2
View File
@@ -1,10 +1,9 @@
import React from 'react'
import { t } from '../i18n'
import { locText, t } from '../i18n'
import { Locale, ViewContribution } from '../types'
import { Button } from '../ui/controls'
import { Modal } from '../ui/dialog'
import { PluginPanelFrame } from './PluginPanelFrame'
import { locText } from './SchemaForm'
interface Props {
view: ViewContribution
+18 -4
View File
@@ -5,7 +5,7 @@ import {
import React, { useEffect, useMemo, useRef, useState } from 'react'
import '../i18n/domains/plugins.gen'
import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { I18nKey, locText, t } from '../i18n'
import {
ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution,
} from '../types'
@@ -16,7 +16,7 @@ import { api } from '../wails'
import { PluginMarket } from './PluginMarket'
import { PluginPanelFrame } from './PluginPanelFrame'
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts'
import { SchemaForm, locText } from './SchemaForm'
import { SchemaForm } from './SchemaForm'
// Search only earns its space once the list is long enough to scan.
const SEARCH_THRESHOLD = 12
@@ -27,6 +27,7 @@ interface Props {
locale: Locale
appearance: 'light' | 'dark'
safeMode?: boolean
runtimeCommit?: string
onRefresh: () => void
onError: (title: string, e: unknown) => void
onThemeChanged?: () => void
@@ -48,7 +49,7 @@ function hasAppSettings(p: PluginInfo): boolean {
/** Top-level Plugins & Themes management page. */
export const PluginsPage: React.FC<Props> = ({
locale, appearance, safeMode, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate,
locale, appearance, safeMode, runtimeCommit, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
@@ -63,6 +64,7 @@ export const PluginsPage: React.FC<Props> = ({
const [approveChecked, setApproveChecked] = useState(false)
const approveTargetIDRef = useRef('')
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const settingsRuntimeWarning = plugins.find((p) => p.id === settingsTarget?.id)?.runtime_warning
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const settingsSaveQueuesRef = useRef(new Map<string, Promise<void>>())
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
@@ -154,7 +156,7 @@ export const PluginsPage: React.FC<Props> = ({
onThemeChanged?.()
}
useEffect(() => { void reload() }, [safeMode])
useEffect(() => { void reload() }, [safeMode, runtimeCommit, locale])
useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab])
@@ -442,6 +444,12 @@ export const PluginsPage: React.FC<Props> = ({
<span>{alert}</span>
</div>
)}
{p.runtime_warning && (
<div className="row-sub plugin-row-alert">
<AlertTriangle size={12} aria-hidden="true" />
<span>{p.runtime_warning}</span>
</div>
)}
</div>
<div className="row-right">
{!isBuiltin && (
@@ -883,6 +891,12 @@ export const PluginsPage: React.FC<Props> = ({
onClose={() => setSettingsTarget(null)}
>
<div className="dialog-body">
{settingsRuntimeWarning && (
<div className="notice notice-warn">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{settingsRuntimeWarning}</span>
</div>
)}
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
-2
View File
@@ -5,8 +5,6 @@ import { locText, t } from '../i18n'
import { Locale, SettingProperty, SettingsSchema } from '../types'
import { NumberField, PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../ui/settings'
export { locText }
interface Props {
locale: Locale
schema: SettingsSchema
File diff suppressed because it is too large. Load diff
+1 -2
View File
@@ -3,14 +3,13 @@ import { AppWindow, Camera, CopyPlus, Cpu, Download, FolderOpen, Info, Maximize2
import React, { useRef } from 'react'
import { I18nKey, localeDir, t } from '../i18n'
import { guestFamilyOf, vmFeatures } from '../lib/endpoints'
import { Locale, VMListItem } from '../types'
import { Locale, VMAction, VMBusyAction, VMListItem } from '../types'
import { hasVisibleDialog } from '../lib/dialogState'
import { vmRefKey } from '../lib/vmRef'
import { IconButton, StatusShape, Tip, statusKind } from '../ui/controls'
import { VersionArt } from '../macos/VersionArt'
import { BrandMark, HostIcon } from '../ui/themeVisuals'
import { GuestArt, hasGuestArt } from './GuestIcon'
import type { VMAction, VMBusyAction } from './VMPage'
export const HOST_ID = '__host__'
export const INSTALLERS_ID = '__installers__'
+2 -3
View File
@@ -5,11 +5,10 @@ import { I18nKey, localeDir, t } from '../i18n'
import { hasVisibleDialog } from '../lib/dialogState'
import { VMFeatures, vmFeatures } from '../lib/endpoints'
import { useVMStats } from '../lib/vmStats'
import { Locale } from '../types'
import { Locale, VMAction } from '../types'
import { Tip } from '../ui/controls'
import type { ThemeMode } from './AppSettingsPage'
import type { ThemeMode } from '../lib/useAppearance'
import { ABOUT_ID, HOST_ID, INSTALLERS_ID, PLUGINS_ID, SETTINGS_ID } from './Sidebar'
import { VMAction } from './VMPage'
export const REPO_URL = 'https://github.com/Nwflower/Reims-Go'
+1 -1
View File
@@ -1,11 +1,11 @@
import { ArrowDownToLine, RotateCw, X } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../i18n'
import type { UpdatePhase } from '../lib/useAppUpdate'
import { Locale, Task } from '../types'
import { Tip } from '../ui/controls'
/** Where an available update is: offered, downloading, verified and ready, or failed. */
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
interface Props {
locale: Locale
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from 'react'
import { useEffect, useState } from 'react'
import '../i18n/domains/settings.gen'
import { parseAppError, t } from '../i18n'
import type { I18nKey, ParsedAppError } from '../i18n'
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,168 @@
import { Activity, Copy, Disc, FolderOpen, Keyboard, Upload } from 'lucide-react'
import React, { useId } from 'react'
import { I18nKey, t } from '../../i18n'
import { Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
import { Button, IconButton, Tip } from '../../ui/controls'
import { Switch } from '../../ui/settings'
import { HostDNSRows, useHostDNS } from './hostDNS'
import { SSHRow, useSSHAccess } from './ssh'
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
interface Props {
locale: Locale
vmKey: string
state: string
detail: VMDetail
stats: VMStats | null
pending: PendingChange[]
currentAgentVersion: number
/** macOS is still being installed, so it has no Guest Tools yet. */
installing: boolean
guestToolsLocked: boolean
canUseHostDNS: boolean
ssh: ReturnType<typeof useSSHAccess>
hostDNS: ReturnType<typeof useHostDNS>
busyAction?: VMBusyAction
onAction: (action: VMAction) => void
onCopy: (text: string) => void
onTypeText: (text: string) => void
onTogglePreventSleep: (enabled: boolean) => void
onDeliverFile: () => void
}
/** How Windows and a macOS VM reach each other: SSH, Guest Tools, shared files and DNS. */
export const ConnectionSection: React.FC<Props> = ({
locale, vmKey, state, detail, stats, pending, currentAgentVersion, installing, guestToolsLocked, canUseHostDNS, ssh, hostDNS,
busyAction, onAction, onCopy, onTypeText, onTogglePreventSleep, onDeliverFile,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const suspended = state === 'suspended'
const guestToolsHintId = useId()
const tools = !installing
if (!tools && detail.ssh_port <= 0) return null
const gtConnected = stats?.guest_tools_connected ?? detail.guest_tools_connected ?? false
const gtDropAccessDenied = stats?.guest_tools_drop_access_denied ?? detail.guest_tools_drop_access_denied ?? false
const gtMountMode = stats?.guest_tools_mount_mode || detail.guest_tools_mount_mode || ''
const gtSleepActive = stats?.guest_tools_sleep_guard ?? detail.guest_tools_sleep_active ?? false
const gtAgentVersion = stats?.guest_tools_agent_version ?? detail.guest_tools_agent_version ?? 0
const needsUpgrade = gtConnected && gtAgentVersion > 0 && gtAgentVersion < currentAgentVersion
const gtAttachPending = running && pending.some((p) => p.field === 'guest_tools' && p.to === 'attached')
// Plugin switched off: show the state and hide controls that would only fail.
const gtOff = !!detail.guest_tools_disabled
const gtAttached = detail.guest_tools_attached
const showToolsAction = !gtOff && (gtAttached || !gtConnected || needsUpgrade)
const toolsAction = gtAttached ? 'detachGuestTools' : 'attachGuestTools'
const toolsActionLabel = gtAttached ? 'detachGuestTools' : needsUpgrade ? 'gtUpdate' : 'gtInstall'
// One status word per state; how files are shared goes in the tooltip.
let gtTone: 'ok' | 'warn' | 'idle' = 'idle'
let gtStatus: string
let gtTip: string
if (gtOff) {
gtStatus = tr('gtStatusOff'); gtTip = tr('gtStatusOffTip')
} else if (needsUpgrade) {
gtTone = 'warn'; gtStatus = tr('gtStatusUpgrade'); gtTip = tr('guestToolsUpgradeHint')
} else if (gtConnected) {
gtTone = 'ok'; gtStatus = tr('gtStatusConnected')
gtTip = gtMountMode === 'webdav' ? tr('guestToolsModeWebDAV') : gtMountMode === 'sync' ? tr('guestToolsModeSync') : tr('gtStatusConnected')
} else if (detail.guest_tools_configured) {
gtStatus = running ? tr('gtStatusWaiting') : tr('gtStatusEnabled')
gtTip = tr('gtStatusWaitingTip')
} else {
gtStatus = tr('gtStatusNone'); gtTip = tr('gtNotInstalledDesc')
}
const showInstallCmd = !gtOff && detail.guest_tools_attached && !gtAttachPending && (!gtConnected || needsUpgrade)
return (
<section className="section" aria-labelledby="conn-title">
<h2 className="section-title" id="conn-title">{tr('connGroup')}</h2>
<div className="conn-list">
{detail.ssh_port > 0 && <SSHRow locale={locale} vmKey={vmKey} port={detail.ssh_port} state={ssh} onCopy={onCopy} />}
{tools && (
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">{tr('guestToolsTitle')}</span>
<Tip label={gtTip}>
<span className={`conn-status is-${gtTone}`} tabIndex={0}>
<span className="conn-status-dot" aria-hidden="true" />
{gtStatus}
</span>
</Tip>
</div>
{suspended && showToolsAction && (
<span id={guestToolsHintId} className="hint">{tr('suspendedGuestToolsHint')}</span>
)}
<div className="conn-ctrl">
{showToolsAction && (
<Button
variant={gtAttached || detail.guest_tools_configured || guestToolsLocked ? 'secondary' : 'primary'}
icon={gtAttached ? undefined : <Disc size={13} aria-hidden="true" />}
busy={busyAction === toolsAction}
disabled={busy || guestToolsLocked}
aria-describedby={suspended ? guestToolsHintId : undefined}
onClick={() => onAction(toolsAction)}
>
{tr(toolsActionLabel)}
</Button>
)}
</div>
</div>
)}
{tools && gtConnected && !gtOff && gtDropAccessDenied && (
<div className="conn-row conn-sub conn-drop-access">
<span className="conn-status is-idle">
<span className="conn-status-dot" aria-hidden="true" />
{tr('gtDropAccessLimited')}
</span>
<span className="conn-meta">{tr('gtDropAccessHint')}</span>
</div>
)}
{tools && showInstallCmd && (
<div className="conn-row conn-sub">
<div className="conn-main">
<span className="conn-meta">{tr('gtInstallSub')}</span>
</div>
<div className="conn-ctrl conn-ctrl-grow">
<div className="ssh-pill">
<code title={GUEST_TOOLS_INSTALL_CMD}>{GUEST_TOOLS_INSTALL_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(GUEST_TOOLS_INSTALL_CMD)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(GUEST_TOOLS_INSTALL_CMD)} />
)}
</div>
</div>
</div>
)}
{tools && !gtOff && (
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">{tr('sharedFolder')}</span>
<span className="conn-meta mono" title="~/Desktop/ReimsShare">~/Desktop/ReimsShare</span>
</div>
<div className="conn-ctrl">
<Button icon={<Upload size={13} aria-hidden="true" />} disabled={busy} onClick={onDeliverFile}>{tr('deliverFileShort')}</Button>
<Button icon={<FolderOpen size={13} aria-hidden="true" />} disabled={busy} onClick={() => onAction('openSharedFolder')}>{tr('openShort')}</Button>
</div>
</div>
)}
{tools && !gtOff && (
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">{tr('guestToolsPreventSleep')}</span>
{gtSleepActive && (
<span className="conn-meta ok-text"><Activity size={12} aria-hidden="true" /> {tr('guestToolsSleepActive')}</span>
)}
</div>
<div className="conn-ctrl">
<Switch label={tr('guestToolsPreventSleep')} checked={!!detail.guest_tools_prevent_sleep} onChange={onTogglePreventSleep} />
</div>
</div>
)}
{canUseHostDNS && <HostDNSRows locale={locale} detail={detail} running={running} busyAction={busyAction} state={hostDNS} onCopy={onCopy} onTypeText={onTypeText} />}
</div>
</section>
)
}
@@ -0,0 +1,137 @@
import { Code2, Copy, MonitorPlay, Pencil, Terminal } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { EndpointAction, endpointActions, endpointKey, orderEndpoints, secondaryEndpointActions } from '../../lib/endpoints'
import { Locale, VMEndpoint } from '../../types'
import { api } from '../../wails'
import { Button } from '../../ui/controls'
import { HostIcon } from '../../ui/themeVisuals'
/** The built-in icon of an endpoint kind; each is themeable by name. */
export function endpointIcon(kind: string, size: number): React.ReactNode {
return kind === 'vmconnect' || kind === 'rdp'
? <HostIcon name="remote-desktop"><MonitorPlay size={size} aria-hidden="true" /></HostIcon>
: <HostIcon name="terminal"><Terminal size={size} aria-hidden="true" /></HostIcon>
}
/** A short, user-facing description of where an endpoint points. */
function endpointDetail(ep: VMEndpoint): string {
switch (ep.kind) {
case 'ssh': return `${ep.user ? `${ep.user}@` : ''}${ep.host || '127.0.0.1'}${ep.port ? `:${ep.port}` : ''}`
case 'wsl': return ep.distro ?? ''
case 'rdp': return `${ep.host ?? ''}${ep.port ? `:${ep.port}` : ''}`
case 'vmconnect': return ep.vm ?? ''
case 'adb': return ep.serial ?? ''
default: return ''
}
}
interface Options {
locale: Locale
driverID: string
name: string
onCopy: (text: string) => void
onError: (title: string, e: unknown) => void
}
/** Runs the actions of a VM's endpoints, one at a time per endpoint. */
export function useEndpointActions({ locale, driverID, name, onCopy, onError }: Options) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [endpointBusy, setEndpointBusy] = useState('')
useEffect(() => { setEndpointBusy('') }, [driverID, name])
const runEndpointAction = (ep: VMEndpoint, action: EndpointAction | '') => {
const busyKey = `${endpointKey(ep)}:${action}`
setEndpointBusy(busyKey)
const done = () => setEndpointBusy((cur) => (cur === busyKey ? '' : cur))
if (action === 'copy') {
api.GetVMEndpointCommand(driverID, name, ep.kind)
.then((cmd) => onCopy(cmd))
.catch((e) => onError(tr('failEndpointCommand'), e))
.finally(done)
return
}
api.OpenVMEndpoint(driverID, name, ep.kind, action)
.catch((e) => onError(tr('failEndpointOpen'), e))
.finally(done)
}
const endpointActionLabel = (kind: string, action: EndpointAction): string => {
switch (action) {
case 'terminal': return tr('endpointOpenTerminal')
case 'vscode': return tr('endpointOpenVSCode')
case 'config': return tr('sshWriteConfig')
case 'edit': return tr('endpointEditConnection')
case 'shell': return tr('endpointOpenADBShell')
case 'copy': return tr('endpointCopyADB')
case 'open': return tr(kind === 'vmconnect' ? 'endpointOpenVMConnect' : 'endpointOpenRDP')
}
}
const endpointKindLabel = (kind: string): string => {
switch (kind) {
case 'ssh': return tr('endpointKindSSH')
case 'wsl': return tr('endpointKindWSL')
case 'rdp': return tr('endpointKindRDP')
case 'vmconnect': return tr('endpointKindVMConnect')
case 'adb': return tr('endpointKindADB')
default: return kind
}
}
return { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel }
}
interface SectionProps {
locale: Locale
endpoints: VMEndpoint[] | undefined
/** The endpoint already offered as the page's primary action. */
promotedEndpoint: VMEndpoint | undefined
state: ReturnType<typeof useEndpointActions>
}
export const EndpointSection: React.FC<SectionProps> = ({ locale, endpoints, promotedEndpoint, state }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { endpointBusy, runEndpointAction, endpointActionLabel, endpointKindLabel } = state
// One flat list. The endpoint promoted to the header keeps only its secondary actions here, so the
// primary action is never offered twice; every other endpoint lists all of its actions.
const rows = orderEndpoints(endpoints).flatMap((ep) => {
const promoted = promotedEndpoint === ep || (!!promotedEndpoint && endpointKey(promotedEndpoint) === endpointKey(ep))
const actions = promoted ? secondaryEndpointActions(ep.kind) : endpointActions(ep.kind)
return promoted && actions.length === 0 ? [] : [{ ep, actions }]
})
if (rows.length === 0) return null
return (
<section className="section" aria-labelledby="endpoints-title">
<h2 className="section-title" id="endpoints-title">{tr('endpointsTitle')}</h2>
<div className="conn-list">
{rows.map(({ ep, actions }) => (
<div className="conn-row" key={endpointKey(ep)}>
<div className="conn-main">
<span className="conn-title">{endpointKindLabel(ep.kind)}</span>
<span className="conn-meta mono" title={endpointDetail(ep)}>{endpointDetail(ep)}</span>
{!ep.ready && (
<span className="conn-status">
<span className="conn-status-dot" aria-hidden="true" />
{tr('endpointNotReady')}
</span>
)}
</div>
{ep.ready && actions.length > 0 && (
<div className="conn-ctrl">
{actions.map((action) => (
<Button
key={action}
icon={action === 'vscode' ? <Code2 size={13} aria-hidden="true" /> : action === 'copy' ? <Copy size={13} aria-hidden="true" /> : action === 'edit' || action === 'config' ? <Pencil size={13} aria-hidden="true" /> : endpointIcon(ep.kind, 13)}
busy={endpointBusy === `${endpointKey(ep)}:${action}`}
onClick={() => runEndpointAction(ep, action)}
>
{endpointActionLabel(ep.kind, action)}
</Button>
))}
</div>
)}
</div>
))}
</div>
</section>
)
}
+234
View File
@@ -0,0 +1,234 @@
import { Copy, Keyboard } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, parseAppError, t } from '../../i18n'
import { Locale, VMBusyAction, VMDetail } from '../../types'
import { api } from '../../wails'
import { IconButton } from '../../ui/controls'
import { Switch } from '../../ui/settings'
const HOST_DNS_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Host-DNS.command'
const HOST_DNS_DISABLE_CMD = 'sh /Volumes/REIMSTOOLS/Disable-Host-DNS.command'
interface Options {
locale: Locale
driverID: string
name: string
state: string
detail: VMDetail | null
/** Whether the VM can use the host's DNS at all. */
available: boolean
/** Guest Tools settings cannot change in the VM's current state. */
locked: boolean
onToast: (title: string) => void
onError: (title: string, e: unknown) => void
}
/** Per-VM host DNS proxy state (host_dns_flow.go). */
export function useHostDNS({ locale, driverID, name, state, detail, available, locked, onToast, onError }: Options) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const running = state === 'running'
const [hostDNS, setHostDNS] = useState<{
host_dns_enabled: boolean
host_dns_active: boolean
host_dns_config_stale: boolean
host_dns_reported: boolean
} | null>(null)
const [hostDNSLoadErr, setHostDNSLoadErr] = useState('')
const [hostDNSBusy, setHostDNSBusy] = useState(false)
const hostDNSWriteSeq = useRef(0)
useEffect(() => {
hostDNSWriteSeq.current += 1
setHostDNS(null)
setHostDNSLoadErr('')
setHostDNSBusy(false)
}, [driverID, name])
useEffect(() => {
if (!available) {
setHostDNS(null)
setHostDNSLoadErr('')
return
}
let live = true
const pull = (force = false) => {
if (!force && document.hidden) return
const seq = hostDNSWriteSeq.current
api.GetGuestToolsHostDNS(name)
.then((s) => {
if (live && seq === hostDNSWriteSeq.current) {
setHostDNS(s)
setHostDNSLoadErr('')
}
})
.catch((e) => {
console.warn('[vm] GetGuestToolsHostDNS failed:', e)
if (live && seq === hostDNSWriteSeq.current) {
setHostDNSLoadErr(parseAppError(e).summary)
}
})
}
pull(true)
const onVisible = () => {
if (!document.hidden) pull(true)
}
document.addEventListener('visibilitychange', onVisible)
const timer = running ? window.setInterval(() => pull(false), 5000) : undefined
return () => {
live = false
document.removeEventListener('visibilitychange', onVisible)
if (timer) window.clearInterval(timer)
}
}, [driverID, name, available, running, state, detail?.guest_tools_connected, detail?.guest_tools_attached])
const handleToggleHostDNS = async (enabled: boolean) => {
if (hostDNSBusy || locked || !available || hostDNS === null) return
const writeSeq = ++hostDNSWriteSeq.current
setHostDNSBusy(true)
try {
await api.SetGuestToolsHostDNS(name, enabled)
onToast(tr(enabled ? 'toastHostDNSOn' : 'toastHostDNSOff'))
try {
const next = await api.GetGuestToolsHostDNS(name)
if (writeSeq === hostDNSWriteSeq.current) {
setHostDNS(next)
setHostDNSLoadErr('')
}
} catch (e) {
console.warn('[vm] GetGuestToolsHostDNS after toggle failed:', e)
if (writeSeq === hostDNSWriteSeq.current) {
setHostDNS((prev) => ({
host_dns_enabled: enabled,
host_dns_active: prev?.host_dns_active ?? false,
host_dns_config_stale: prev?.host_dns_config_stale ?? false,
host_dns_reported: prev?.host_dns_reported ?? false,
}))
}
}
} catch (e) {
onError(tr('failGuestTools'), e)
} finally {
if (writeSeq === hostDNSWriteSeq.current) setHostDNSBusy(false)
}
}
return { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked }
}
interface RowsProps {
locale: Locale
detail: VMDetail
running: boolean
busyAction?: VMBusyAction
state: ReturnType<typeof useHostDNS>
onCopy: (text: string) => void
onTypeText: (text: string) => void
}
export const HostDNSRows: React.FC<RowsProps> = ({ locale, detail, running, busyAction, state, onCopy, onTypeText }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { hostDNS, hostDNSLoadErr, hostDNSBusy, handleToggleHostDNS, locked } = state
const busy = busyAction !== undefined
const dnsEnabled = hostDNS?.host_dns_enabled ?? false
const dnsActive = hostDNS?.host_dns_active ?? false
const dnsStale = hostDNS?.host_dns_config_stale ?? false
const dnsReported = hostDNS?.host_dns_reported ?? false
const toolsAttached = !!detail.guest_tools_attached
const disableCmd = toolsAttached
? HOST_DNS_DISABLE_CMD
: 'sh /private/etc/reims-host-dns/Disable-Host-DNS.command'
const showApplySub = dnsEnabled && (dnsStale || !dnsActive)
const showDisableSub = dnsActive || dnsStale || (dnsEnabled && running && !dnsReported)
let dnsStatus: React.ReactNode
if (hostDNSLoadErr && hostDNS === null) {
dnsStatus = <span className="conn-meta danger-text">{hostDNSLoadErr}</span>
} else if (dnsEnabled && dnsReported && dnsStale) {
dnsStatus = (
<span className="conn-status is-warn">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusStale')}
</span>
)
} else if (dnsEnabled && dnsReported && dnsActive) {
dnsStatus = (
<span className="conn-status is-ok">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusActive')}
</span>
)
} else if (dnsEnabled) {
dnsStatus = (
<span className="conn-status">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusPending')}
</span>
)
} else if (dnsReported && (dnsActive || dnsStale)) {
dnsStatus = (
<span className="conn-status is-warn">
<span className="conn-status-dot" aria-hidden="true" />
{tr('hostDNSStatusStillActive')}
</span>
)
} else {
dnsStatus = (
<span className="conn-meta" title={tr('hostDNSOffHint')}>
{tr('hostDNSOffHint')}
</span>
)
}
return (
<>
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">{tr('guestToolsHostDNS')}</span>
{dnsStatus}
</div>
<div className="conn-ctrl">
<Switch
label={tr('guestToolsHostDNS')}
checked={dnsEnabled}
disabled={busy || locked || hostDNSBusy || hostDNS === null || (dnsEnabled && (dnsActive || dnsStale))}
onChange={(checked) => void handleToggleHostDNS(checked)}
/>
</div>
</div>
{showApplySub && (
<div className="conn-row conn-sub">
<div className="conn-main">
<span className="conn-meta">
{tr(!toolsAttached ? 'hostDNSAttachHint' : dnsStale ? 'hostDNSStaleHint' : 'hostDNSApplyHint')}
</span>
</div>
{toolsAttached && (
<div className="conn-ctrl conn-ctrl-grow">
<div className="ssh-pill">
<code title={HOST_DNS_APPLY_CMD}>{HOST_DNS_APPLY_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(HOST_DNS_APPLY_CMD)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(HOST_DNS_APPLY_CMD)} />
)}
</div>
</div>
)}
</div>
)}
{showDisableSub && (
<div className="conn-row conn-sub">
<div className="conn-main">
<span className="conn-meta">{tr('hostDNSDisableCmdHint')}</span>
</div>
<div className="conn-ctrl conn-ctrl-grow">
<div className="ssh-pill">
<code title={disableCmd}>{disableCmd}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(disableCmd)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={13} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(disableCmd)} />
)}
</div>
</div>
</div>
)}
</>
)
}
@@ -0,0 +1,161 @@
import { Check, Copy, Disc, Keyboard } from 'lucide-react'
import React, { useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { Locale, VMAction, VMBusyAction, VMDetail } from '../../types'
import { Button, IconButton } from '../../ui/controls'
// Runs from reims-go's pre-extracted HFS+ helper disk (REIMSHELP), bypassing
// macOS Recovery's `installer -target` fallback to read-only `/` and missing `pkgutil`.
const OFFLINE_INSTALL_CMD = 'sh /Volumes/REIMSHELP/install.sh'
interface Props {
locale: Locale
name: string
detail: VMDetail
running: boolean
/** Whether the VM window shows the install guide, so the card only says how to start. */
installGuideEnabled: boolean
busyAction?: VMBusyAction
onAction: (action: VMAction) => void
onCopy: (text: string) => void
onTypeText: (text: string) => void
}
/** How to finish installing macOS. Its step checkboxes are kept per VM in localStorage. */
export const InstallCard: React.FC<Props> = ({ locale, name, detail, running, installGuideEnabled, busyAction, onAction, onCopy, onTypeText }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const guideKey = `reims-go-guide:${name}`
const [doneSteps, setDoneSteps] = useState<number[]>(() => {
try {
return JSON.parse(localStorage.getItem(guideKey) ?? '[]')
} catch {
return []
}
})
const toggleGuideStep = (step: number) => {
setDoneSteps((prev) => {
const next = prev.includes(step) ? prev.filter((x) => x !== step) : [...prev, step]
try { localStorage.setItem(guideKey, JSON.stringify(next)) } catch (e) { console.warn('[vm] persist guide progress failed:', e) }
return next
})
}
const hasInstaller = detail.has_installer
const isOffline = hasInstaller && /offline-installer/i.test(detail.installer_path ?? '')
const badgeKey: I18nKey = !hasInstaller
? 'guideKindBuiltIn'
: isOffline
? 'guideKindOffline'
: 'guideKindOnline'
if (installGuideEnabled) {
return (
<section className="card rg-p-card" aria-labelledby="guide-title">
<h2 className="card-title" id="guide-title">
{tr('guideTitle')}{' '}
<span className="badge rg-p-badge">{tr(badgeKey)}</span>
</h2>
<p className="card-desc">{tr('guideStartHint')}</p>
<div className="card-foot">
{!hasInstaller && (
<Button
icon={<Disc size={14} aria-hidden="true" />}
busy={busyAction === 'attachInstaller'}
disabled={busy}
onClick={() => onAction('attachInstaller')}
>
{tr('attachInstaller')}
</Button>
)}
<Button busy={busyAction === 'finishInstall'} disabled={busy} onClick={() => onAction('finishInstall')}>
{tr('finishInstall')}
</Button>
</div>
</section>
)
}
const finish = (
<Button
variant={running ? 'primary' : 'secondary'}
busy={busyAction === 'finishInstall'}
disabled={busy}
onClick={() => onAction('finishInstall')}
>
{tr('finishInstall')}
</Button>
)
// Each step's number is a checkbox the user ticks off (kept per VM).
const step = (n: number, body: React.ReactNode) => {
const done = doneSteps.includes(n)
return (
<li className={`guide-step${done ? ' is-done' : ''}`}>
<button
type="button"
className={`guide-step-btn${done ? ' done' : ''}`}
aria-pressed={done}
onClick={() => toggleGuideStep(n)}
>
{done ? <Check size={12} aria-hidden="true" /> : n}
</button>
<span className="guide-step-body">{body}</span>
</li>
)
}
return (
<section className="card rg-p-card" aria-labelledby="guide-title">
<h2 className="card-title" id="guide-title">
{tr('guideTitle')}{' '}
<span className={`badge rg-p-badge ${isOffline ? 'badge-ok' : ''}`}>{tr(badgeKey)}</span>
</h2>
{!hasInstaller ? (
<>
<ol className="guide-steps">
{step(1, tr('guideBuiltIn1'))}
{step(2, tr('guideBuiltIn2'))}
{step(3, tr('guideBuiltIn3'))}
</ol>
<div className="card-foot">
<Button
icon={<Disc size={14} aria-hidden="true" />}
busy={busyAction === 'attachInstaller'}
disabled={busy}
onClick={() => onAction('attachInstaller')}
>
{tr('attachInstaller')}
</Button>
{finish}
</div>
</>
) : isOffline ? (
<>
<ol className="guide-steps">
{step(1, tr('guideOffline1'))}
{step(2, (
<>
{tr('guideOffline2')}
<div className="cmd-line guide-cmd">
<code>{OFFLINE_INSTALL_CMD}</code>
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(OFFLINE_INSTALL_CMD)} />
{running && (
<IconButton small label={tr('typeIntoVM')} icon={<Keyboard size={14} />} busy={busyAction === 'type'} disabled={busy} onClick={() => onTypeText(OFFLINE_INSTALL_CMD)} />
)}
</div>
</>
))}
{step(3, tr('guideOffline3'))}
</ol>
<div className="card-foot">{finish}</div>
</>
) : (
<>
<ol className="guide-steps">
{step(1, tr('guideStep1'))}
{step(2, tr('guideStep2'))}
{step(3, tr('guideStep3'))}
</ol>
<div className="card-foot">{finish}</div>
</>
)}
</section>
)
}
+123
View File
@@ -0,0 +1,123 @@
import { AlertTriangle, Info, Pause } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { formatBytes, formatMemory, formatShortTime, pendingChangeText } from '../../lib/format'
import { HostReport, Locale, PendingChange, VMAction, VMBusyAction, VMDetail, VMStats } from '../../types'
import { Button } from '../../ui/controls'
interface Props {
locale: Locale
state: string
canSuspend: boolean
/** Id the disabled Resume button is described by. */
resumeHintId: string
detail: VMDetail | null
stats: VMStats | null
host: HostReport
pending: PendingChange[]
busyAction?: VMBusyAction
onAction: (action: VMAction) => void
}
/** What needs attention on the VM or its host. */
export const VMNotices: React.FC<Props> = ({ locale, state, canSuspend, resumeHintId, detail, stats, host, pending, busyAction, onAction }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const busy = busyAction !== undefined
const running = state === 'running'
const suspended = state === 'suspended'
return (
<>
{state === 'broken' && (
<div className="notice notice-error" role="alert">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('brokenHint')}</span>
</span>
</div>
)}
{suspended && (() => {
const suspTime = formatShortTime(Date.parse(detail?.suspend_info?.created_at ?? ''), locale)
const suspSize = detail?.suspend_info?.vmstate_size
? formatBytes(detail.suspend_info.vmstate_size, locale)
: (detail?.memory ? formatMemory(detail.memory, locale) : '—')
return (
<div className="notice notice-info">
<span className="notice-main">
<Pause size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{tr('suspendedNoticeTitle')}</span>
<span className="notice-sub">
{suspTime
? tr('suspendedNoticeDescWithTime', { time: suspTime, size: suspSize })
: tr('suspendedNoticeDesc', { size: suspSize })}
</span>
{!canSuspend && <span id={resumeHintId} className="notice-sub">{tr('resumeUnavailable')}</span>}
</span>
</span>
</div>
)
})()}
{pending.length > 0 && (
<div className="notice notice-info">
<span className="notice-main">
<Info size={15} className="notice-icon" aria-hidden="true" />
<span className="notice-text">
<span className="notice-title">{running ? tr('pendingRestartHint') : tr('pendingTitle')}</span>
<span className="notice-sub">{pending.map((p) => pendingChangeText(locale, p, host)).join(' · ')}</span>
</span>
</span>
{running && (
<Button busy={busyAction === 'restart'} disabled={busy} onClick={() => onAction('restart')}>
{tr('restartToApply')}
</Button>
)}
</div>
)}
{(host.data_root_drive_type === 'usb' || host.data_root_drive_type === 'removable' || host.data_root_drive_type === 'network') && (
<div className="notice">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagExternalDriveWarn', { dir: host.data_root })}</span>
</span>
</div>
)}
{stats && (stats.disk_backing_depth_warn || (stats.disk_backing_depth ?? 0) >= 2 || stats.disk_backing_broken) && (
<div className="notice">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>
{stats.disk_backing_broken
? tr('diagBackingChainBroken', { depth: stats.disk_backing_depth ?? 1 })
: tr('diagBackingChainWarn', { depth: stats.disk_backing_depth ?? 2 })}
</span>
</span>
</div>
)}
{(host.memory_load_pct ?? 0) >= 85 && (
<div className="notice">
<span className="notice-main">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagHighMemWarn', { pct: host.memory_load_pct ?? 0 })}</span>
</span>
</div>
)}
{detail && !detail.has_installer && detail.disk_controller === 'ahci' && (
<div className="notice notice-info">
<span className="notice-main">
<Info size={15} className="notice-icon" aria-hidden="true" />
<span>{tr('diagAhciUpgradeHint')}</span>
</span>
<Button busy={busyAction === 'upgradeNVMe'} disabled={busy} onClick={() => onAction('upgradeNVMe')}>
{tr('upgradeToNVMe')}
</Button>
</div>
)}
</>
)
}
+91
View File
@@ -0,0 +1,91 @@
import { AppWindow, Camera, Play } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { VMThumbnail } from '../../types'
import { api } from '../../wails'
import { Tip } from '../../ui/controls'
/**
* Screen thumbnail (thumbnail_flow.go): a fresh frame every 15 s while the VM
* runs, otherwise the last frame saved. Skipped while this window is hidden;
* the backend also skips it while the VM's own window is in front.
*/
export function useVMThumbnail(driverID: string, name: string, running: boolean, thumbnails: boolean): VMThumbnail | null {
const [thumb, setThumb] = useState<VMThumbnail | null>(null)
useEffect(() => { setThumb(null) }, [driverID, name])
useEffect(() => {
if (!thumbnails) return
let live = true
const pull = () => {
if (document.hidden) return
api.GetVMThumbnail(driverID, name)
.then((t) => { if (live && t?.data_url) setThumb(t) })
.catch((e) => console.warn('[vm] GetVMThumbnail failed:', e))
}
pull()
const timer = running ? window.setInterval(pull, 15000) : undefined
return () => { live = false; if (timer) window.clearInterval(timer) }
}, [driverID, name, running, thumbnails])
return thumb
}
/**
* The VM's own screen as its picture (as UTM and Parallels do): live while it
* runs (click to bring its window forward; a camera button copies a
* screenshot), the last frame dimmed while it is stopped (hover shows a start
* button), and its macOS version artwork until a frame exists. Each new frame
* fades in over the previous one.
*/
export const VMScreen: React.FC<{
thumb: VMThumbnail | null
art: React.ReactNode
running: boolean
startLabel: string
showLabel: string
shotLabel: string
onStart?: () => void
onShow?: () => void
onScreenshot?: () => void
}> = ({ thumb, art, running, startLabel, showLabel, shotLabel, onStart, onShow, onScreenshot }) => {
const prev = useRef<string>('')
const shown = thumb?.data_url ?? ''
const under = prev.current !== shown ? prev.current : ''
useEffect(() => { prev.current = shown }, [shown])
// The page's own buttons are the keyboard path; the screen is a pointer shortcut.
const act = onShow ?? onStart
const overlay = onShow ? (
<span className="vm-screen-chip" aria-hidden="true"><AppWindow size={13} /> {showLabel}</span>
) : onStart ? (
<span className="vm-screen-play" aria-hidden="true"><Play size={18} fill="currentColor" /></span>
) : null
return (
<div
className={`vm-display-unit${act ? ' is-actionable' : ''}`}
onClick={act}
title={onShow ? showLabel : onStart ? startLabel : undefined}
>
<div
className={`vm-screen${running ? ' is-live' : ' is-idle'}`}
style={shown && under ? { backgroundImage: `url(${under})` } : undefined}
>
{shown ? <img key={thumb?.captured_at} className="vm-screen-img" src={shown} alt="" draggable={false} /> : art}
{running && <span className="vm-screen-live" aria-hidden="true" />}
{running && shown && onScreenshot && (
<Tip label={shotLabel} side="left">
<button
type="button"
className="vm-screen-shot"
aria-label={shotLabel}
onClick={(e) => { e.stopPropagation(); onScreenshot() }}
>
<Camera size={14} aria-hidden="true" />
</button>
</Tip>
)}
{overlay}
</div>
<div className="vm-display-stand" aria-hidden="true" />
</div>
)
}
@@ -0,0 +1,191 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import { History, Plus, RotateCcw, Trash } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { formatShortTime } from '../../lib/format'
import { DiskSnapshot, Locale } from '../../types'
import { api } from '../../wails'
import { Button, IconButton, Tip } from '../../ui/controls'
import { HostIcon } from '../../ui/themeVisuals'
interface Props {
locale: Locale
driverID: string
name: string
state: string
/** False while the VM has no restore points to manage. */
shown: boolean
/** Restore points only change while the VM is stopped. */
locked: boolean
onToast: (title: string) => void
onError: (title: string, e: unknown) => void
}
/** The VM's offline restore points (snapshot_flow.go). */
export const SnapshotSection: React.FC<Props> = ({ locale, driverID, name, state, shown, locked, onToast, onError }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [snapshots, setSnapshots] = useState<DiskSnapshot[]>([])
const [creatingSnap, setCreatingSnap] = useState(false)
const [snapDraft, setSnapDraft] = useState('')
const [snapBusy, setSnapBusy] = useState('')
const [restoreTarget, setRestoreTarget] = useState<string | null>(null)
const loadSnapshots = () => {
if (!shown) { setSnapshots([]); return }
api.ListSnapshots(driverID, name).then((list) => setSnapshots(list ?? [])).catch(() => setSnapshots([]))
}
useEffect(() => {
setCreatingSnap(false)
setSnapDraft('')
setRestoreTarget(null)
loadSnapshots()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [driverID, name, shown, state])
const handleCreateSnapshot = async () => {
const label = snapDraft.trim()
if (!label) return
setSnapBusy('create')
try {
await api.CreateSnapshot(driverID, name, label)
setSnapDraft('')
setCreatingSnap(false)
onToast(tr('toastSnapshotCreated', { name: label }))
loadSnapshots()
} catch (e) {
onError(tr('failSnapshot'), e)
} finally {
setSnapBusy('')
}
}
const handleRestoreSnapshot = async (snapName: string) => {
setRestoreTarget(null)
setSnapBusy(`restore:${snapName}`)
try {
await api.RestoreSnapshot(driverID, name, snapName)
onToast(tr('toastSnapshotRestored', { name: snapName }))
loadSnapshots()
} catch (e) {
onError(tr('failSnapshot'), e)
} finally {
setSnapBusy('')
}
}
const handleDeleteSnapshot = async (snapName: string) => {
setSnapBusy(`delete:${snapName}`)
try {
await api.DeleteSnapshot(driverID, name, snapName)
onToast(tr('toastSnapshotDeleted', { name: snapName }))
loadSnapshots()
} catch (e) {
onError(tr('failSnapshot'), e)
} finally {
setSnapBusy('')
}
}
if (!shown) return null
return (
<>
<section className="section">
<div className="section-title">
<span className="hstack">
<HostIcon name="snapshot"><History size={14} aria-hidden="true" /></HostIcon>
<span>{tr('snapshotsTitle')}</span>
<span className="snap-meta-hint">· {tr('snapshotHint')}</span>
</span>
<Tip label={locked ? tr('snapshotStopFirst') : tr('snapshotCreate')}>
<span>
<Button
variant="ghost"
icon={<Plus size={13} aria-hidden="true" />}
disabled={locked || !!snapBusy}
onClick={() => setCreatingSnap((v) => !v)}
>
{tr('snapshotCreate')}
</Button>
</span>
</Tip>
</div>
<div className="conn-list">
{creatingSnap && (
<div className="snap-create-bar">
<input
className="input rg-p-input"
value={snapDraft}
maxLength={64}
spellCheck={false}
autoComplete="off"
placeholder={tr('snapshotNamePlaceholder')}
autoFocus
onChange={(e) => setSnapDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && snapDraft.trim()) { e.preventDefault(); void handleCreateSnapshot() }
if (e.key === 'Escape') { e.preventDefault(); setCreatingSnap(false) }
}}
/>
<Button variant="primary" busy={snapBusy === 'create'} disabled={!snapDraft.trim() || !!snapBusy} onClick={() => void handleCreateSnapshot()}>
{tr('save')}
</Button>
<Button variant="ghost" onClick={() => setCreatingSnap(false)}>{tr('cancel')}</Button>
</div>
)}
{snapshots.length === 0 ? (
<div className="conn-row">
<span className="conn-meta">{tr('snapshotEmpty')}</span>
</div>
) : (
snapshots.map((s) => (
<div className="conn-row" key={s.id || s.name}>
<div className="conn-main">
<span className="conn-title">{s.name}</span>
{s.created_at > 0 && <span className="conn-meta tnum">{formatShortTime(s.created_at * 1000, locale)}</span>}
</div>
<div className="conn-ctrl">
<Button
icon={<RotateCcw size={13} aria-hidden="true" />}
busy={snapBusy === `restore:${s.name}`}
disabled={locked || !!snapBusy}
onClick={() => setRestoreTarget(s.name)}
>
{tr('snapshotRestore')}
</Button>
<IconButton
small
label={tr('snapshotDelete')}
icon={<Trash size={14} />}
busy={snapBusy === `delete:${s.name}`}
disabled={locked || !!snapBusy}
onClick={() => void handleDeleteSnapshot(s.name)}
/>
</div>
</div>
))
)}
</div>
</section>
{restoreTarget && (
<Alert.Root open onOpenChange={(open) => { if (!open) setRestoreTarget(null) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog rg-p-dialog sm" data-tone="danger">
<div className="dialog-body">
<Alert.Title className="dialog-title">{tr('snapshotRestoreTitle', { name: restoreTarget })}</Alert.Title>
<Alert.Description className="dialog-desc">{tr('snapshotRestoreDesc')}</Alert.Description>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn rg-p-button btn-danger" onClick={() => void handleRestoreSnapshot(restoreTarget)}>
{tr('snapshotRestore')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)}
</>
)
}
+134
View File
@@ -0,0 +1,134 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Code2, Copy, FileCode2, Terminal, UserRound } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { sshCommand } from '../../lib/format'
import { Locale } from '../../types'
import { api } from '../../wails'
import { Button, IconButton } from '../../ui/controls'
import { ActionMenu } from '../../ui/menu'
interface Options {
locale: Locale
driverID: string
name: string
/** The remembered user belongs to the macOS connection row; other drivers keep theirs in their endpoints. */
enabled: boolean
onToast: (title: string) => void
onError: (title: string, e: unknown) => void
}
/** The SSH user remembered for the VM (.reims-go-ssh-user) and the actions that use it. */
export function useSSHAccess({ locale, driverID, name, enabled, onToast, onError }: Options) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [sshUser, setSshUser] = useState('')
const [sshUserDialog, setSshUserDialog] = useState(false)
const [sshUserDraft, setSshUserDraft] = useState('')
useEffect(() => { setSshUserDialog(false) }, [driverID, name])
useEffect(() => {
if (!enabled) { setSshUser(''); return }
let live = true
api.GetVMSSHUser(driverID, name).then((u) => { if (live) setSshUser(u ?? '') }).catch(() => { if (live) setSshUser('') })
return () => { live = false }
}, [driverID, name, enabled])
const openSSHTerminal = () => {
api.OpenSSHTerminal(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
}
const writeSSHConfig = () => {
api.WriteSSHConfig(driverID, name, sshUser)
.then((alias) => onToast(tr('toastSSHConfigWritten', { alias })))
.catch((e) => onError(tr('failSSH'), e))
}
const openVSCodeSSH = () => {
api.OpenVSCodeSSH(driverID, name, sshUser).catch((e) => onError(tr('failSSH'), e))
}
const saveSSHUser = async () => {
const next = sshUserDraft.trim()
setSshUserDialog(false)
try {
await api.SetVMSSHUser(driverID, name, next)
setSshUser(next)
onToast(tr('toastSSHUserSaved'))
} catch (e) {
onError(tr('failSSH'), e)
}
}
return { sshUser, sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, openSSHTerminal, writeSSHConfig, openVSCodeSSH, saveSSHUser }
}
type SSHAccess = ReturnType<typeof useSSHAccess>
export const SSHRow: React.FC<{ locale: Locale; vmKey: string; port: number; state: SSHAccess; onCopy: (text: string) => void }> = ({ locale, vmKey, port, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { sshUser, openSSHTerminal, writeSSHConfig, openVSCodeSSH, setSshUserDraft, setSshUserDialog } = state
const sshText = sshUser ? `ssh -p ${port} ${sshUser}@127.0.0.1` : sshCommand(port)
return (
<div className="conn-row">
<div className="conn-main">
<span className="conn-title">SSH</span>
</div>
<div className="conn-ctrl">
<div className="ssh-pill">
<code>{sshText}</code>
<IconButton small label={tr('copy')} icon={<Copy size={13} />} onClick={() => onCopy(sshText)} />
</div>
<Button icon={<Terminal size={13} aria-hidden="true" />} onClick={openSSHTerminal}>
{tr('sshOpenTerminal')}
</Button>
<ActionMenu key={vmKey} locale={locale} label={tr('sshMore')} small>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={writeSSHConfig}>
<FileCode2 size={14} /> {tr('sshWriteConfig')}
</Menu.Item>
<Menu.Item className="menu-item rg-p-menu-item" onSelect={openVSCodeSSH}>
<Code2 size={14} /> {tr('sshOpenVSCode')}
</Menu.Item>
<Menu.Separator className="menu-sep" />
<Menu.Item className="menu-item rg-p-menu-item" onSelect={() => { setSshUserDraft(sshUser); setSshUserDialog(true) }}>
<UserRound size={14} /> {tr('sshSetUser')}
</Menu.Item>
</ActionMenu>
</div>
</div>
)
}
/** Asks for the user name the SSH actions sign in with. */
export const SSHUserDialog: React.FC<{ locale: Locale; state: SSHAccess }> = ({ locale, state }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { sshUserDialog, setSshUserDialog, sshUserDraft, setSshUserDraft, saveSSHUser } = state
if (!sshUserDialog) return null
return (
<Alert.Root open onOpenChange={(open) => { if (!open) setSshUserDialog(false) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{tr('sshUserTitle')}</Alert.Title>
<Alert.Description className="dialog-desc">{tr('sshUserDesc')}</Alert.Description>
<div className="field field-spaced">
<input
className="input rg-p-input mono"
value={sshUserDraft}
spellCheck={false}
autoComplete="off"
placeholder={tr('sshUserPlaceholder')}
autoFocus
onChange={(e) => setSshUserDraft(e.target.value)}
onKeyDown={(e) => { if (e.key === 'Enter') { e.preventDefault(); void saveSSHUser() } }}
/>
</div>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild><button type="button" className="btn rg-p-button">{tr('cancel')}</button></Alert.Cancel>
<Alert.Action asChild>
<button type="button" className="btn rg-p-button btn-primary" onClick={() => void saveSSHUser()}>{tr('save')}</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
}
+156
View File
@@ -0,0 +1,156 @@
import { Cpu, Globe, HardDrive, MemoryStick, Monitor, Network } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { controllerLabel, formatBytes, formatDiskUsage, formatMemory, graphicsLabel, parseMemoryGB, resolveGuestLang } from '../../lib/format'
import { HostReport, Locale, VMDetail, VMInfo, VMStats } from '../../types'
import { Tip } from '../../ui/controls'
const GUEST_FAMILY_LABEL: Record<string, string> = { macos: 'macOS', linux: 'Linux', windows: 'Windows', android: 'Android' }
type Tone = '' | ' warn' | ' high'
const meterTone = (pct: number, warn = 75, high = 90): Tone => (pct >= high ? ' high' : pct >= warn ? ' warn' : '')
const clampPct = (v: number) => Math.min(100, Math.max(0, v))
interface Spec {
key: string
/** Shown only in the wide, single-column layout. */
label: string
icon: React.ReactNode
value: string
tip: string
/** Cells in the first row reserve a meter slot so the row keeps its height. */
meter?: { pct: number; tone: Tone; idle: boolean }
}
interface Props {
locale: Locale
running: boolean
detail: VMDetail | null
/** Non-macOS VMs: the cross-driver model. */
vmInfo?: VMInfo | null
isMacOSDriver: boolean
guestFamily: string
host: HostReport
stats: VMStats | null
}
// Summary presents each fact once in user-facing words; raw upstream values stay in "Technical details".
function vmSpecs({ locale, running, detail, vmInfo, isMacOSDriver, guestFamily, host, stats }: Props): Spec[] {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const specs: Spec[] = []
if (detail) {
const live = running && !!stats
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
const memGB = parseMemoryGB(detail.memory) ?? 0
const rss = live ? stats!.memory_rss_bytes : 0
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
const mem = formatMemory(detail.memory, locale)
specs.push(
{
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: detail.cpus }),
tip: live ? tr('specCPULiveTip', { n: detail.cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: detail.cpus }),
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
},
{
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
meter: { pct: memPct, tone: '', idle: !live },
},
{
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : controllerLabel(detail.disk_controller),
tip: diskKnown
? tr('specDiskUsage', { ctl: controllerLabel(detail.disk_controller), used: formatBytes(stats!.disk_actual_bytes, locale), max: formatBytes(stats!.disk_virtual_bytes, locale) })
: tr('specDiskTip', { ctl: controllerLabel(detail.disk_controller) }),
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
},
{
key: 'gfx', label: tr('factGraphics'), icon: <Monitor size={15} aria-hidden="true" />,
value: graphicsLabel(locale, detail, host),
tip: tr('specGraphicsTip', { gfx: graphicsLabel(locale, detail, host) }),
},
{
key: 'net', label: tr('fieldNetwork'), icon: <Network size={15} aria-hidden="true" />,
value: detail.network_mode === 'bridge' ? tr('netBridge') : detail.network_mode === 'custom' ? tr('netCustom') : detail.network ? tr('netShared') : tr('netOff'),
tip: detail.network_mode === 'bridge' ? tr('specNetBridgeTip') : !detail.network ? tr('specNetOffTip') : detail.ssh_port > 0 ? tr('specNetSSHTip', { port: detail.ssh_port }) : tr('specNetTip'),
},
)
if (detail.guest_lang) {
const lang = resolveGuestLang(locale, detail.guest_lang)
specs.push({
key: 'lang', label: tr('specLang'), icon: <Globe size={15} aria-hidden="true" />, value: lang.label,
tip: lang.detail
? tr('specLangTipDetail', { label: lang.label, detail: lang.detail })
: tr('specLangTip', { label: lang.label }),
})
}
} else if (vmInfo && !isMacOSDriver) {
// Other drivers describe a VM through the cross-driver model only.
const live = running && !!stats
const guestOS = vmInfo.guest_os
const osName = [guestOS?.distro || GUEST_FAMILY_LABEL[guestFamily] || '', guestOS?.version ?? ''].filter(Boolean).join(' ')
if (osName) {
specs.push({
key: 'os', label: tr('factGuestOS'), icon: <Monitor size={15} aria-hidden="true" />, value: osName,
tip: guestOS?.arch ? `${osName} · ${guestOS.arch}` : osName,
})
}
if ((vmInfo.cpus ?? 0) > 0) {
const cpus = vmInfo.cpus ?? 0
const cpuPct = live ? clampPct(stats!.cpu_percent || 0) : 0
specs.push({
key: 'cpu', label: tr('factCPU'), icon: <Cpu size={15} aria-hidden="true" />, value: tr('cores', { n: cpus }),
tip: live ? tr('specCPULiveTip', { n: cpus, pct: Math.round(cpuPct) }) : tr('specCPUTip', { n: cpus }),
meter: { pct: cpuPct, tone: meterTone(cpuPct), idle: !live },
})
}
if (vmInfo.memory) {
const memGB = parseMemoryGB(vmInfo.memory) ?? 0
const rss = live ? stats!.memory_rss_bytes : 0
const memPct = memGB > 0 && rss > 0 ? clampPct((rss / (memGB * 1024 ** 3)) * 100) : 0
const mem = formatMemory(vmInfo.memory, locale)
specs.push({
key: 'mem', label: tr('factMemory'), icon: <MemoryStick size={15} aria-hidden="true" />, value: mem,
tip: live && rss > 0 ? tr('specMemLiveTip', { mem, used: formatBytes(rss, locale) }) : tr('specMemTip', { mem }),
meter: { pct: memPct, tone: '', idle: !live },
})
}
if (vmInfo.disk_summary) {
const diskKnown = !!stats && stats.disk_virtual_bytes > 0 && stats.disk_actual_bytes > 0
const diskPct = diskKnown ? clampPct((stats!.disk_actual_bytes / stats!.disk_virtual_bytes) * 100) : 0
specs.push({
key: 'disk', label: tr('factDisk'), icon: <HardDrive size={15} aria-hidden="true" />,
value: diskKnown ? formatDiskUsage(stats!.disk_actual_bytes, stats!.disk_virtual_bytes, locale) : vmInfo.disk_summary,
tip: vmInfo.disk_summary,
meter: { pct: diskPct, tone: meterTone(diskPct, 85, 95), idle: !diskKnown },
})
}
}
return specs
}
export const VMSummary: React.FC<Props> = (props) => {
const specs = vmSpecs(props)
if (specs.length === 0) return null
return (
<div className={`vm-spec-card rg-p-vm-summary${props.running ? ' is-live' : ''}`} role="list" data-rg-slot="vm.card">
{specs.map((s) => (
<Tip key={s.key} label={s.tip}>
<div className="vm-spec-cell" role="listitem" tabIndex={0}>
<span className="vm-spec-icon">{s.icon}</span>
<span className="vm-spec-label">{s.label}</span>
<span className="vm-spec-val">{s.value}</span>
{s.meter && (
<span className="vm-spec-meter" data-idle={s.meter.idle || undefined} aria-hidden="true">
<span className={`meter-fill${s.meter.tone}`} style={{ transform: `scaleX(${s.meter.idle ? 0 : s.meter.pct / 100})` }} />
</span>
)}
</div>
</Tip>
))}
</div>
)
}
@@ -0,0 +1,85 @@
import { ChevronRight, Copy } from 'lucide-react'
import React from 'react'
import { I18nKey, t } from '../../i18n'
import { Locale, VMDetail, VMInfo } from '../../types'
import { IconButton } from '../../ui/controls'
interface Props {
locale: Locale
name: string
driverID: string
detail: VMDetail | null
vmInfo?: VMInfo | null
onCopy: (text: string) => void
}
/** The raw values upstream tools use for the VM, folded by default. */
export const TechInfo: React.FC<Props> = ({ locale, name, driverID, detail, vmInfo, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const copyTechSummary = () => {
if (!detail) {
if (!vmInfo) return
onCopy([
`${tr('fieldVMName')}: ${name}`,
`${tr('fieldDriver')}: ${vmInfo.driver_name || driverID}`,
...(vmInfo.disk_path ? [`${tr('fieldDisk')}: ${vmInfo.disk_path}`] : []),
...(vmInfo.directory ? [`${tr('fieldDir')}: ${vmInfo.directory}`] : []),
].join('\n'))
return
}
const rows = [
`${tr('fieldKind')}: ${detail.kind || '—'}`,
`${tr('fieldCPUModel')}: ${detail.cpu_model || 'auto'}`,
`${tr('fieldGraphicsBackend')}: ${detail.graphics}`,
...(detail.gpu && detail.gpu !== 'auto' ? [`${tr('fieldICD')}: ${detail.gpu}`] : []),
`${tr('resolution')}: ${detail.displays} × ${detail.resolution}`,
`${tr('fieldController')}: ${detail.disk_controller}`,
`${tr('fieldDisk')}: ${detail.disk}`,
`${tr('fieldNetwork')}: ${detail.network_summary || tr('off')}`,
`${tr('fieldAudio')}: ${detail.audio_raw || tr('off')}`,
...(detail.guest_lang ? [`${tr('guestLang')}: ${detail.guest_lang}`] : []),
`${tr('fieldDir')}: ${detail.directory}`,
]
onCopy(rows.join('\n'))
}
if (!detail) {
if (!vmInfo) return null
return (
<details key="driver" className="tech">
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
<div className="tech-body">
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
<dl className="kv-list">
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
<dt>{tr('fieldDriver')}</dt><dd>{vmInfo.driver_name || driverID}</dd>
{vmInfo.disk_path && (<><dt>{tr('fieldDisk')}</dt><dd className="mono">{vmInfo.disk_path}</dd></>)}
{vmInfo.directory && (<><dt>{tr('fieldDir')}</dt><dd className="mono">{vmInfo.directory}</dd></>)}
</dl>
</div>
</details>
)
}
return (
<details className="tech">
<summary><ChevronRight size={14} aria-hidden="true" /> {tr('techInfo')}</summary>
<div className="tech-body">
<IconButton small className="tech-copy" label={tr('copyTechInfo')} icon={<Copy size={14} />} onClick={copyTechSummary} />
<dl className="kv-list">
<dt>{tr('fieldVMName')}</dt><dd className="mono">{name}</dd>
<dt>{tr('fieldKind')}</dt><dd>{detail.kind || '—'}</dd>
<dt>{tr('fieldCPUModel')}</dt><dd className="mono">{detail.cpu_model || 'auto'}</dd>
<dt>{tr('fieldGraphicsBackend')}</dt><dd>{detail.graphics}</dd>
{detail.gpu && detail.gpu !== 'auto' && (<><dt>{tr('fieldICD')}</dt><dd className="mono">{detail.gpu}</dd></>)}
<dt>{tr('resolution')}</dt><dd>{detail.displays} × {detail.resolution}</dd>
<dt>{tr('fieldController')}</dt><dd>{detail.disk_controller}</dd>
<dt>{tr('fieldDisk')}</dt><dd className="mono">{detail.disk}</dd>
<dt>{tr('fieldNetwork')}</dt><dd className="mono">{detail.network_summary || tr('off')}</dd>
<dt>{tr('fieldAudio')}</dt><dd>{detail.audio_raw || tr('off')}</dd>
{detail.guest_lang && (<><dt>{tr('guestLang')}</dt><dd className="mono">{detail.guest_lang}</dd></>)}
<dt>{tr('fieldDir')}</dt><dd className="mono">{detail.directory}</dd>
</dl>
</div>
</details>
)
}
+247
View File
@@ -0,0 +1,247 @@
import { Copy } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, parseAppError, t } from '../../i18n'
import { formatBytes } from '../../lib/format'
import { DiskCompactResult, DiskResizeResult, Locale, VMStats } from '../../types'
import { Button, IconButton } from '../../ui/controls'
import { SetRow } from '../../ui/settings'
import { api } from '../../wails'
interface DiskOptions {
locale: Locale
driverID: string
vm: string
running: boolean
stats?: VMStats | null
onError: (message: string) => void
onDiskChanged?: () => void
}
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
const [resizeInput, setResizeInput] = useState('+64G')
const [diskOpBusy, setDiskOpBusy] = useState<'resize' | 'compact' | 'optimize' | ''>('')
const [resizeResult, setResizeResult] = useState<DiskResizeResult | null>(null)
const [compactResult, setCompactResult] = useState<DiskCompactResult | null>(null)
const [optimizeResult, setOptimizeResult] = useState<DiskCompactResult | null>(null)
useEffect(() => {
setResizeResult(null)
setCompactResult(null)
setOptimizeResult(null)
}, [driverID, vm])
const handleResizeDisk = async () => {
if (running || diskOpBusy || !resizeInput.trim()) return
onError('')
setDiskOpBusy('resize')
try {
const res = await api.ResizeVMDisk(driverID, vm, resizeInput.trim())
if (activeVMNameRef.current === vm) {
setResizeResult(res)
}
onDiskChanged?.()
} catch (e) {
if (activeVMNameRef.current === vm) {
onError(parseAppError(e).summary)
}
} finally {
setDiskOpBusy('')
}
}
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
const diskRewriteBaseReason = running ? tr('stopBeforeDiskOp')
: (stats?.disk_snapshot_count ?? 0) > 0 ? tr('diskRewriteSnapshots')
: (stats?.disk_backing_depth ?? 0) > 0 ? tr('diskRewriteOverlay')
: !isQcow2 ? tr('diskCompactQcow2Only')
: undefined
const compactRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'compact' ? tr('diskRewriteBusy') : undefined)
const optimizeRowReason = diskRewriteBaseReason ?? (diskOpBusy && diskOpBusy !== 'optimize' ? tr('diskRewriteBusy') : undefined)
const handleCompactDisk = async (optimize: boolean) => {
if (diskRewriteBaseReason || diskOpBusy) return
onError('')
setDiskOpBusy(optimize ? 'optimize' : 'compact')
try {
if (optimize) {
const res = await api.OptimizeVMDisk(driverID, vm)
if (activeVMNameRef.current === vm) {
setOptimizeResult(res)
setCompactResult(null)
}
} else {
const res = await api.CompactVMDisk(driverID, vm)
if (activeVMNameRef.current === vm) {
setCompactResult(res)
}
}
onDiskChanged?.()
} catch (e) {
if (activeVMNameRef.current === vm) {
onError(parseAppError(e).summary)
}
} finally {
setDiskOpBusy('')
}
}
const extendedL2 = stats?.disk_extended_l2 || optimizeResult?.extended_l2_enabled
return {
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
}
}
interface RowsProps {
locale: Locale
running: boolean
state: ReturnType<typeof useDiskMaintenance>
onCopy?: (text: string) => void
}
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
return (
<>
<SetRow
title={tr('diskResizeTitle')}
desc={tr('diskResizeDesc')}
disabled={running}
reason={tr('stopBeforeDiskOp')}
block={
<div className="stack-2">
<div className="hstack">
<div className="presets">
{['+32G', '+64G', '+128G', '256G', '512G'].map((v) => (
<button
key={v}
type="button"
className="preset"
aria-pressed={resizeInput === v}
disabled={running || !!diskOpBusy}
onClick={() => setResizeInput(v)}
>
{v}
</button>
))}
</div>
</div>
<div className="hstack">
<input
className="input rg-p-input mono input-compact"
aria-label={tr('diskResizeTitle')}
value={resizeInput}
spellCheck={false}
autoComplete="off"
disabled={running || !!diskOpBusy}
onChange={(e) => setResizeInput(e.target.value)}
placeholder="+64G / 256G"
/>
<Button
variant="secondary"
busy={diskOpBusy === 'resize'}
disabled={running || !!diskOpBusy || !resizeInput.trim()}
onClick={handleResizeDisk}
>
{tr('diskResizeAction')}
</Button>
</div>
{resizeResult && (
<div className="notice">
<div>{tr('diskResizeDone', { size: formatBytes(resizeResult.new_virtual_bytes, locale) })}</div>
<div className="cmd-line cmd-line-spaced">
<code>{resizeResult.guest_expand_cmd}</code>
{onCopy && (
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(resizeResult.guest_expand_cmd)} />
)}
</div>
</div>
)}
</div>
}
/>
<SetRow
title={tr('diskCompactTitle')}
desc={compactResult
? compactResult.reclaimed_bytes > 0
? tr('diskCompactDone', {
before: formatBytes(compactResult.before_bytes, locale),
after: formatBytes(compactResult.after_bytes, locale),
reclaimed: formatBytes(compactResult.reclaimed_bytes, locale),
})
: tr('diskCompactNoGain')
: tr('diskCompactDesc')}
disabled={!!compactRowReason}
reason={compactRowReason}
control={
<Button
variant="secondary"
busy={diskOpBusy === 'compact'}
disabled={!!compactRowReason || !!diskOpBusy}
onClick={() => handleCompactDisk(false)}
>
{tr('diskCompactAction')}
</Button>
}
/>
<SetRow
title={tr('diskOptimizeTitle')}
desc={optimizeResult ? tr('diskOptimizeDone', {
before: formatBytes(optimizeResult.before_bytes, locale),
after: formatBytes(optimizeResult.after_bytes, locale),
reclaimed: formatBytes(optimizeResult.reclaimed_bytes, locale),
status: tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeInactive'),
}) : tr(extendedL2 ? 'diskOptimizeEnabled' : 'diskOptimizeDesc')}
disabled={!extendedL2 && !!optimizeRowReason}
reason={extendedL2 ? undefined : optimizeRowReason}
control={extendedL2 ? undefined : (
<Button variant="secondary" busy={diskOpBusy === 'optimize'} disabled={!!optimizeRowReason || !!diskOpBusy} onClick={() => handleCompactDisk(true)}>
{tr('diskOptimizeAction')}
</Button>
)}
/>
</>
)
}
interface DefenderProps {
locale: Locale
dataRoot: string
onCopy?: (text: string) => void
onError: (message: string) => void
}
export const DefenderExclusionRow: React.FC<DefenderProps> = ({ locale, dataRoot, onCopy, onError }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const handleDefender = async (copy: boolean) => {
onError('')
try {
if (copy) {
const command = await api.GetDefenderExclusionCommand()
if (command) onCopy?.(command)
} else {
await api.OpenWindowsSecurityExclusions()
}
} catch (e) {
onError(parseAppError(e).summary)
}
}
return (
<SetRow
title={tr('defenderExclusionTitle')}
desc={tr('defenderExclusionDesc', { path: dataRoot })}
control={
<div className="hstack">
<Button variant="secondary" onClick={() => handleDefender(false)}>{tr('defenderOpenSecurity')}</Button>
{onCopy && <Button variant="secondary" onClick={() => handleDefender(true)}>{tr('defenderCopyCommand')}</Button>}
</div>
}
/>
)
}
@@ -0,0 +1,86 @@
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap'
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings'
import { api } from '../../wails'
/** The VM's modifier key mapping, refreshed while shown. */
export function useKeymap(vm: string, running: boolean, shown: boolean) {
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
const [{ keymap, error: keymapErr, busy: keymapBusy }, setKeymapState] = useState<KeymapState>({ keymap: null, error: '', busy: false })
const [keymapRequests] = useState(() => createKeymapRequests(api, () => activeVMNameRef.current,
(patch) => setKeymapState((state) => ({ ...state, ...patch }))))
useEffect(() => {
setKeymapState(keymapRequests.initial(vm))
}, [vm, keymapRequests])
useEffect(() => {
if (!shown) return
const { refresh, stop } = keymapRequests.watch(vm)
void refresh()
const timer = window.setInterval(refresh, 3000)
return () => { stop(); window.clearInterval(timer) }
}, [shown, vm, running, keymapRequests])
return { keymap, keymapErr, keymapBusy, write: keymapRequests.write }
}
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap> }> = ({ locale, vm, state }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { keymap, keymapErr, keymapBusy, write } = state
return (
<SetGroup title={tr('keymapGroupTitle')} note={tr('keymapGroupNote')}>
{keymapErr && <div className="notice notice-error" role="alert">{keymapErr}</div>}
{keymap && <>
<SetRow title={tr('keymapPresetTitle')} disabled={keymapBusy}
desc={keymap.preset === 'off' && !keymap.capture_host_shortcuts ? undefined
: !keymap.input_service_available ? tr('keymapInputServiceRequired')
: !keymap.running ? tr('keymapStopped')
: keymap.needs_guest_tools && !keymap.guest_connected ? tr('keymapWaiting')
: keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version
? tr('keymapUpgrade', { version: keymap.required_agent_version })
: keymap.needs_guest_tools && !keymap.guest_keymap_active ? tr('keymapPending')
: tr(keymap.hook_active ? 'keymapRunning' : 'keymapInactive')}
control={<Segmented<VMKeymapPreset> 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) => {
const request = keymapPresetUpdate(keymap, preset)
if (request) void write(vm, request)
}} />}
/>
<SetRow title={tr('keymapCaptureHostShortcutsTitle')} desc={tr('keymapCaptureHostShortcutsDesc')} disabled={keymapBusy}
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
/>
{keymap.preset === 'custom' && ([
['lwin', 'keymapHostLwin'],
['rwin', 'keymapHostRwin'],
['lalt', 'keymapHostLalt'],
['ralt', 'keymapHostRalt'],
['lctrl', 'keymapHostLctrl'],
['rctrl', 'keymapHostRctrl'],
['capslock', 'keymapHostCapslock'],
] as const satisfies readonly (readonly [VMKeymapHostModifier, I18nKey])[]).map(([modifier, label]) => (
<SetRow key={modifier} title={tr(label)} disabled={keymapBusy}
control={<PopupSelect<VMKeymapGuestModifier> label={tr(label)} value={keymap.bindings[modifier] ?? 'default'}
options={[
{ value: 'default', label: tr('keymapGuestDefault') },
{ value: 'lcmd', label: tr('keymapGuestLcmd') },
{ value: 'rcmd', label: tr('keymapGuestRcmd') },
{ value: 'lopt', label: tr('keymapGuestLopt') },
{ value: 'ropt', label: tr('keymapGuestRopt') },
{ value: 'lctrl', label: tr('keymapGuestLctrl') },
{ value: 'rctrl', label: tr('keymapGuestRctrl') },
{ value: 'esc', label: tr('keymapGuestEsc') },
{ value: 'disabled', label: tr('keymapGuestDisabled') },
]}
onChange={(target) => { void write(vm, keymapUpdate(keymap, { bindings: { [modifier]: target } })) }} />}
/>
))}
</>}
</SetGroup>
)
}
@@ -0,0 +1,64 @@
import React, { Suspense, lazy, useEffect, useRef, useState } from 'react'
import { parseAppError } from '../../i18n'
import { Locale, PluginInfo } from '../../types'
import { api } from '../../wails'
const SchemaForm = lazy(() => import('../SchemaForm').then((m) => ({ default: m.SchemaForm })))
/** Per-VM settings of the active plugins. Changes save at once, in order. */
export function useVMPluginSettings(vmKey: string, onError: (message: string) => void) {
const [vmPlugins, setVmPlugins] = useState<PluginInfo[]>([])
const [vmPluginVals, setVmPluginVals] = useState<Record<string, Record<string, unknown>>>({})
const vmPluginSettingsSaveQueues = useRef(new Map<string, Promise<void>>())
useEffect(() => {
let live = true
Promise.all([api.ListPlugins(), api.GetVMPluginSettings(vmKey)])
.then(([list, vals]) => {
if (!live) return
const activeWithVM = (list ?? []).filter((p) => (p.state === 'active' || p.state === 'degraded') && !!p.settings)
setVmPlugins(activeWithVM)
setVmPluginVals((vals ?? {}) as Record<string, Record<string, unknown>>)
})
.catch((e) => console.warn('[settings] load VM plugin settings failed:', e))
return () => { live = false }
}, [vmKey])
const updateVMPluginSetting = (pluginID: string, patch: Record<string, unknown>) => {
setVmPluginVals((prev) => ({ ...prev, [pluginID]: { ...prev[pluginID], ...patch } }))
const queueKey = JSON.stringify([pluginID, vmKey])
const previous = vmPluginSettingsSaveQueues.current.get(queueKey) ?? Promise.resolve()
const save = previous.catch((error) => {
console.warn('[settings] previous plugin save failed:', error)
}).then(() => api.SetPluginSettings(pluginID, vmKey, patch))
vmPluginSettingsSaveQueues.current.set(queueKey, save)
void save.catch((e) => onError(parseAppError(e).summary)).finally(() => {
if (vmPluginSettingsSaveQueues.current.get(queueKey) === save) {
vmPluginSettingsSaveQueues.current.delete(queueKey)
}
})
}
return { vmPlugins, vmPluginVals, updateVMPluginSetting }
}
export const VMPluginGroup: React.FC<{ locale: Locale; group: string; state: ReturnType<typeof useVMPluginSettings> }> = ({ locale, group, state }) => {
const { vmPlugins, vmPluginVals, updateVMPluginSetting } = state
const matched = vmPlugins.filter((p) => p.settings && (p.settings['x-group'] === group || Object.values(p.settings.properties ?? {}).some((prop) => prop['x-group'] === group)))
if (matched.length === 0) return null
return (
<Suspense fallback={null}>
{matched.map((p) => (
<SchemaForm
key={p.id}
locale={locale}
schema={p.settings!}
values={vmPluginVals[p.id] ?? {}}
scopeFilter="vm"
groupFilter={group}
onChange={(_, patch) => updateVMPluginSetting(p.id, patch)}
/>
))}
</Suspense>
)
}
@@ -0,0 +1,323 @@
import * as Alert from '@radix-ui/react-alert-dialog'
import { FolderPlus, Trash2 } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, parseAppError, t } from '../../i18n'
import { DriveShareSettings, Locale, SharedFolderInfo, SharedFolderMode, SharedFolderSettings, VMDetail } from '../../types'
import { Button, IconButton } from '../../ui/controls'
import { Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
import { api } from '../../wails'
/** Windows drives shared with the VM. */
export function useDriveShares(vm: string) {
const [driveSettings, setDriveSettings] = useState<DriveShareSettings | null>(null)
const [driveBusy, setDriveBusy] = useState(false)
const driveBusyRef = useRef(false)
const [driveErr, setDriveErr] = useState('')
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
useEffect(() => {
let active = true
setDriveSettings(null)
setDriveErr('')
api.GetVMDriveShareSettings(vm)
.then((settings) => { if (active) setDriveSettings(settings) })
.catch((e) => { if (active) setDriveErr(parseAppError(e).summary) })
return () => { active = false }
}, [vm])
const updateDriveShares = async (enabled: boolean, selected: string[]) => {
if (driveBusyRef.current || !driveSettings) return
driveBusyRef.current = true
setDriveBusy(true)
setDriveErr('')
try {
const next = await api.SetVMDriveShareSettings(vm, enabled, selected)
if (activeVMNameRef.current === vm) setDriveSettings(next)
} catch (e) {
if (activeVMNameRef.current === vm) setDriveErr(parseAppError(e).summary)
} finally {
driveBusyRef.current = false
setDriveBusy(false)
}
}
const selectedDrives = () => (driveSettings?.drives ?? []).filter((d) => d.selected).map((d) => d.drive)
return { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives }
}
/** Single folders shared with the VM. */
export function useSharedFolders(vm: string, locale: Locale) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [folderSettings, setFolderSettings] = useState<SharedFolderSettings | null>(null)
const [folderBusy, setFolderBusy] = useState(false)
const folderBusyRef = useRef(false)
const folderOpSeqRef = useRef(0)
const [folderErr, setFolderErr] = useState('')
const [confirmRWFolder, setConfirmRWFolder] = useState<SharedFolderInfo | null>(null)
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
useEffect(() => {
let active = true
folderOpSeqRef.current += 1
folderBusyRef.current = false
setFolderBusy(false)
setFolderSettings(null)
setFolderErr('')
setConfirmRWFolder(null)
api.GetVMSharedFolderSettings(vm)
.then((settings) => { if (active) setFolderSettings(settings) })
.catch((e) => { if (active) setFolderErr(formatFolderError(e)) })
return () => { active = false }
}, [vm])
const formatFolderIssue = (issue?: string) => {
switch (issue) {
case 'missing': return tr('folderShareIssueMissing')
case 'volume_mismatch': return tr('folderShareIssueVolumeMismatch')
case 'path_changed': return tr('folderShareIssuePathChanged')
case 'overlap': return tr('folderShareIssueOverlap')
case 'blocked': return tr('folderShareIssueBlocked')
case 'not_found': return tr('folderShareIssueNotFound')
case 'invalid_mode': return tr('folderShareIssueInvalidMode')
case 'corrupt_config': return tr('folderShareIssueCorruptConfig')
default: return ''
}
}
const formatFolderError = (e: unknown) => {
const summary = parseAppError(e).summary
const match = summary.match(/shared folder:\s*(missing|volume_mismatch|path_changed|overlap|blocked|not_found|invalid_mode|corrupt_config)\b/i)
if (match) return formatFolderIssue(match[1].toLowerCase())
return summary
}
const runFolderOp = async (op: (vm: string) => Promise<SharedFolderSettings | null>) => {
if (folderBusyRef.current || !folderSettings) return
const opSeq = ++folderOpSeqRef.current
folderBusyRef.current = true
setFolderBusy(true)
setFolderErr('')
try {
const next = await op(vm)
if (next && activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
setFolderSettings(next)
}
} catch (e) {
if (activeVMNameRef.current === vm && folderOpSeqRef.current === opSeq) {
setFolderErr(formatFolderError(e))
}
} finally {
if (folderOpSeqRef.current === opSeq) {
folderBusyRef.current = false
setFolderBusy(false)
}
}
}
const handleAddFolder = () => runFolderOp(async (vm) => {
const picked = await api.PickDirectory(tr('folderSharePickTitle'))
if (!picked || activeVMNameRef.current !== vm) return null
return api.AddVMSharedFolder(vm, picked)
})
const updateFolderMode = (folderID: string, mode: SharedFolderMode) =>
runFolderOp((vm) => api.SetVMSharedFolderMode(vm, folderID, mode))
const handleRemoveFolder = (folderID: string) =>
runFolderOp((vm) => api.RemoveVMSharedFolder(vm, folderID))
return {
folderSettings, folderBusy, folderErr, confirmRWFolder, setConfirmRWFolder, formatFolderIssue,
handleAddFolder, updateFolderMode, handleRemoveFolder,
}
}
interface SectionProps<State> {
locale: Locale
detail: VMDetail
state: State
/** Version of the connected Guest Tools agent, 0 when none is connected. */
toolsVersion: number
}
export const DriveShareSection: React.FC<SectionProps<ReturnType<typeof useDriveShares>>> = ({ locale, detail, state, toolsVersion }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { driveSettings, driveBusy, driveErr, updateDriveShares, selectedDrives } = state
return (
<SetGroup title={tr('driveShareTitle')} note={tr('driveShareReadOnly')}>
<SetRow
title={tr('driveShareMaster')}
desc={tr('driveShareMasterDesc')}
control={
<Switch
label={tr('driveShareMaster')}
checked={!!driveSettings?.enabled}
disabled={!driveSettings || driveBusy || !!detail.guest_tools_disabled}
onChange={(enabled) => void updateDriveShares(enabled, selectedDrives())}
/>
}
/>
{detail.guest_tools_disabled && <div className="notice">{tr('gtStatusOffTip')}</div>}
{driveErr && <div className="notice" role="alert">{driveErr}</div>}
{driveSettings?.enabled && selectedDrives().length > 0 &&
toolsVersion > 0 &&
toolsVersion < driveSettings.required_agent_version && (
<div className="notice">{tr('driveShareNeedsTools', { version: driveSettings.required_agent_version })}</div>
)}
{/* Drives are only worth choosing once sharing is on. */}
{driveSettings?.enabled && driveSettings.drives.map((drive) => {
const title = `Windows (${drive.drive}:)`
return (
<SetRow
key={drive.drive}
title={title}
desc={drive.system ? <span className="warn-text">{tr('driveShareSystem')}</span> : undefined}
disabled={driveBusy || !!detail.guest_tools_disabled}
control={
<Switch
label={title}
checked={drive.selected}
disabled={driveBusy}
onChange={(enabled) => {
const next = selectedDrives().filter((letter) => letter !== drive.drive)
if (enabled) next.push(drive.drive)
void updateDriveShares(driveSettings?.enabled ?? false, next)
}}
/>
}
/>
)
})}
{driveSettings && driveSettings.drives.length === 0 && (
<SetValue title={tr('driveShareTitle')} value={tr('driveShareNoDrives')} />
)}
</SetGroup>
)
}
export const SharedFolderSection: React.FC<SectionProps<ReturnType<typeof useSharedFolders>>> = ({ locale, detail, state, toolsVersion }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { folderSettings, folderBusy, folderErr, setConfirmRWFolder, formatFolderIssue, handleAddFolder, updateFolderMode, handleRemoveFolder } = state
return (
<SetGroup title={tr('folderShareTitle')} note={tr('folderShareNote')}>
<SetRow
title={tr('folderShareAddTitle')}
desc={tr('folderShareDesc')}
disabled={folderBusy || !!detail.guest_tools_disabled}
control={
<Button
variant="secondary"
icon={<FolderPlus size={14} aria-hidden="true" />}
busy={folderBusy}
disabled={!folderSettings || folderBusy || !!detail.guest_tools_disabled}
onClick={() => void handleAddFolder()}
>
{tr('folderShareAdd')}
</Button>
}
/>
{folderErr && <div className="notice" role="alert">{folderErr}</div>}
{folderSettings &&
folderSettings.folders.some((f) => f.enabled && f.available) &&
toolsVersion > 0 &&
toolsVersion < folderSettings.required_agent_version && (
<div className="notice">{tr('folderShareNeedsTools', { version: folderSettings.required_agent_version })}</div>
)}
{folderSettings && folderSettings.folders.length === 0 && (
<SetValue title={tr('folderShareListTitle')} value={tr('folderShareEmpty')} />
)}
{folderSettings?.folders.map((folder) => {
const mode: SharedFolderMode = !folder.enabled ? 'disabled' : folder.writable ? 'rw' : 'ro'
const activeMode: SharedFolderMode | undefined = folder.available ? mode : (!folder.enabled ? 'disabled' : undefined)
const issueText = !folder.available ? formatFolderIssue(folder.issue) : ''
return (
<SetRow
key={folder.id}
title={folder.name}
desc={
<>
<code className="inline-code folder-path" title={folder.host_path}>{folder.host_path}</code>
{issueText && <div className="warn-text">{issueText}</div>}
{!issueText && folder.enabled && folder.writable && (
<div className="warn-text">{tr('folderShareWritableWarn')}</div>
)}
</>
}
disabled={folderBusy || !!detail.guest_tools_disabled}
control={
<div className="hstack">
<Segmented<SharedFolderMode>
label={folder.name}
value={activeMode}
options={[
{ value: 'disabled', label: tr('folderShareModeDisabled') },
{ value: 'ro', label: tr('folderShareModeRO'), disabled: !folder.available },
{ value: 'rw', label: tr('folderShareModeRW'), disabled: !folder.available },
]}
onChange={(nextMode) => {
if (nextMode === activeMode) return
if (nextMode === 'rw') {
setConfirmRWFolder(folder)
return
}
void updateFolderMode(folder.id, nextMode)
}}
/>
<IconButton
small
label={tr('folderShareRemove')}
icon={<Trash2 size={13} />}
disabled={folderBusy || !!detail.guest_tools_disabled}
onClick={() => void handleRemoveFolder(folder.id)}
/>
</div>
}
/>
)
})}
</SetGroup>
)
}
/** Asks before the VM may change files in a shared folder. */
export const WritableFolderDialog: React.FC<{ locale: Locale; state: ReturnType<typeof useSharedFolders> }> = ({ locale, state }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { confirmRWFolder, setConfirmRWFolder, updateFolderMode } = state
if (!confirmRWFolder) return null
return (
<Alert.Root open onOpenChange={(open) => { if (!open) setConfirmRWFolder(null) }}>
<Alert.Portal>
<Alert.Overlay className="overlay" />
<Alert.Content className="dialog rg-p-dialog sm" data-tone="neutral">
<div className="dialog-body">
<Alert.Title className="dialog-title">{tr('folderShareConfirmRWTitle')}</Alert.Title>
<Alert.Description className="dialog-desc">
{tr('folderShareConfirmRWDesc', { name: confirmRWFolder.name, path: confirmRWFolder.host_path })}
</Alert.Description>
</div>
<div className="dialog-foot">
<Alert.Cancel asChild>
<button type="button" className="btn rg-p-button">{tr('cancel')}</button>
</Alert.Cancel>
<Alert.Action asChild>
<button
type="button"
className="btn rg-p-button btn-primary"
onClick={() => {
const target = confirmRWFolder
setConfirmRWFolder(null)
void updateFolderMode(target.id, 'rw')
}}
>
{tr('folderShareConfirmRWAction')}
</button>
</Alert.Action>
</div>
</Alert.Content>
</Alert.Portal>
</Alert.Root>
)
}
@@ -0,0 +1,279 @@
import { Copy, Eye, EyeOff, Shuffle } from 'lucide-react'
import React, { useEffect, useState } from 'react'
import { I18nKey, parseAppError, t } from '../../i18n'
import { Locale, SMBIOSIdentity, VMDetail } from '../../types'
import { Button, IconButton } from '../../ui/controls'
import { Modal } from '../../ui/dialog'
import { SetGroup, SetRow, SetValue } from '../../ui/settings'
import { api } from '../../wails'
function maskIdentity(v: string | undefined, head = 4, tail = 4): string {
const s = (v ?? '').trim()
if (!s) return '—'
if (s.length <= head + tail) return '•'.repeat(s.length)
return `${s.slice(0, head)}••••${s.slice(-tail)}`
}
/** The VM's SMBIOS identity and the dialog that replaces it. */
export function useSMBIOS(detail: VMDetail, running: boolean) {
const [smbios, setSmbios] = useState<SMBIOSIdentity | null>(null)
const [smbiosErr, setSmbiosErr] = useState('')
const [smbiosReveal, setSmbiosReveal] = useState(false)
const [smbiosOpen, setSmbiosOpen] = useState(false)
const [smbiosDraft, setSmbiosDraft] = useState<SMBIOSIdentity | null>(null)
const [smbiosBusy, setSmbiosBusy] = useState<'' | 'generate' | 'apply'>('')
const [smbiosModalErr, setSmbiosModalErr] = useState('')
const [smbiosApplied, setSmbiosApplied] = useState(false)
useEffect(() => {
let active = true
setSmbios(null)
setSmbiosErr('')
setSmbiosReveal(false)
setSmbiosApplied(false)
if (!detail.has_opencore) return () => { active = false }
api.GetVMSMBIOS(detail.name)
.then((id) => { if (active) setSmbios(id) })
.catch((e) => { if (active) setSmbiosErr(parseAppError(e).summary) })
return () => { active = false }
}, [detail.name, detail.has_opencore])
const smbiosLocked = running || detail.state === 'suspended' || !!detail.suspend_info
const handleGenerateSmbios = async (modelOverride?: string) => {
setSmbiosModalErr('')
setSmbiosBusy('generate')
try {
const generated = await api.GenerateVMSMBIOS(modelOverride ?? smbios?.model ?? '')
setSmbiosDraft({
model: smbios?.model || generated.model,
serial: generated.serial,
mlb: generated.mlb,
uuid: generated.uuid,
rom: smbios?.rom || '',
})
} catch (e) {
setSmbiosModalErr(parseAppError(e).summary)
} finally {
setSmbiosBusy('')
}
}
const openSmbiosRotate = () => {
if (smbiosLocked) return
setSmbiosModalErr('')
setSmbiosApplied(false)
setSmbiosOpen(true)
void handleGenerateSmbios(smbios?.model ?? '')
}
const handleApplySmbios = async () => {
if (smbiosLocked || smbiosBusy || !smbiosDraft) return
setSmbiosModalErr('')
setSmbiosBusy('apply')
try {
const updated = await api.ApplyVMSMBIOS(detail.name, {
model: smbios?.model || smbiosDraft.model || '',
serial: smbiosDraft.serial,
mlb: smbiosDraft.mlb,
uuid: smbiosDraft.uuid,
rom: smbios?.rom || '',
})
setSmbios(updated)
setSmbiosOpen(false)
setSmbiosApplied(true)
} catch (e) {
setSmbiosModalErr(parseAppError(e).summary)
} finally {
setSmbiosBusy('')
}
}
return {
smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosOpen, setSmbiosOpen, smbiosDraft,
setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosApplied, smbiosLocked, openSmbiosRotate,
handleGenerateSmbios, handleApplySmbios,
}
}
interface Props {
locale: Locale
state: ReturnType<typeof useSMBIOS>
onCopy?: (text: string) => void
}
export const SMBIOSSection: React.FC<Props> = ({ locale, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { smbios, smbiosErr, smbiosReveal, setSmbiosReveal, smbiosApplied, smbiosLocked, openSmbiosRotate } = state
return (
<SetGroup title={tr('smbiosTitle')} note={tr('smbiosCheckHint')}>
<SetRow
title={tr('smbiosTitle')}
desc={tr('smbiosDesc')}
disabled={smbiosLocked}
reason={tr('smbiosStopRequired')}
control={
<Button
variant="secondary"
icon={<Shuffle size={13} aria-hidden="true" />}
disabled={smbiosLocked || !smbios}
onClick={openSmbiosRotate}
>
{tr('smbiosRotateBtn')}
</Button>
}
/>
{smbiosErr && <div className="notice notice-error" role="alert">{tr('smbiosLoadFailed')}: {smbiosErr}</div>}
{smbiosApplied && <div className="notice" role="status">{tr('smbiosApplied')}</div>}
{smbios && (
<>
<SetValue title={tr('smbiosModel')} value={smbios.model || '—'} mono />
<SetValue
title={tr('smbiosSerial')}
mono
value={
<span className="hstack">
<span>{smbiosReveal ? smbios.serial : maskIdentity(smbios.serial, 4, 4)}</span>
<IconButton
small
label={smbiosReveal ? tr('smbiosHide') : tr('smbiosShow')}
icon={smbiosReveal ? <EyeOff size={13} /> : <Eye size={13} />}
onClick={() => setSmbiosReveal((v) => !v)}
/>
{onCopy && (
<IconButton
small
label={tr('smbiosCopySerial')}
icon={<Copy size={13} />}
onClick={() => onCopy(smbios.serial)}
/>
)}
</span>
}
/>
<SetValue title={tr('smbiosMLB')} value={smbiosReveal ? smbios.mlb : maskIdentity(smbios.mlb, 4, 4)} mono />
<SetValue title={tr('smbiosUUID')} value={smbiosReveal ? smbios.uuid : maskIdentity(smbios.uuid, 4, 4)} mono />
{smbios.rom && <SetValue title={tr('smbiosROM')} value={smbiosReveal ? smbios.rom : maskIdentity(smbios.rom, 5, 5)} mono />}
</>
)}
</SetGroup>
)
}
export const SMBIOSDialog: React.FC<Props> = ({ locale, state, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { smbios, setSmbiosOpen, smbiosDraft, setSmbiosDraft, smbiosBusy, smbiosModalErr, smbiosLocked, handleGenerateSmbios, handleApplySmbios } = state
return (
<Modal
title={tr('smbiosDialogTitle')}
subtitle={tr('smbiosDialogSub')}
closeLabel={tr('close')}
dismissable={smbiosBusy !== 'apply'}
onClose={() => setSmbiosOpen(false)}
>
<div className="dialog-body">
<div className="notice">
<span className="warn-text">{tr('smbiosWarning')}</span>
</div>
<div className="hstack">
<Button
variant="secondary"
icon={<Shuffle size={13} aria-hidden="true" />}
busy={smbiosBusy === 'generate'}
disabled={smbiosBusy === 'apply'}
onClick={() => void handleGenerateSmbios(smbios?.model ?? '')}
>
{tr('smbiosGenerate')}
</Button>
{onCopy && smbiosDraft?.serial && (
<Button
variant="ghost"
icon={<Copy size={13} aria-hidden="true" />}
disabled={!!smbiosBusy}
onClick={() => onCopy(smbiosDraft.serial)}
>
{tr('smbiosCopySerial')}
</Button>
)}
</div>
<label className="field">
<span className="field-label">{tr('smbiosSerial')}</span>
<input
className="input rg-p-input mono"
spellCheck={false}
autoComplete="off"
maxLength={12}
disabled={!!smbiosBusy}
value={smbiosDraft?.serial ?? ''}
onChange={(e) => setSmbiosDraft((prev) => ({
model: prev?.model ?? smbios?.model ?? '',
serial: e.target.value.toUpperCase(),
mlb: prev?.mlb ?? '',
uuid: prev?.uuid ?? '',
rom: prev?.rom ?? smbios?.rom ?? '',
}))}
/>
</label>
<label className="field">
<span className="field-label">{tr('smbiosMLB')}</span>
<input
className="input rg-p-input mono"
spellCheck={false}
autoComplete="off"
maxLength={17}
disabled={!!smbiosBusy}
value={smbiosDraft?.mlb ?? ''}
onChange={(e) => setSmbiosDraft((prev) => ({
model: prev?.model ?? smbios?.model ?? '',
serial: prev?.serial ?? '',
mlb: e.target.value.toUpperCase(),
uuid: prev?.uuid ?? '',
rom: prev?.rom ?? smbios?.rom ?? '',
}))}
/>
</label>
<label className="field">
<span className="field-label">{tr('smbiosUUID')}</span>
<input
className="input rg-p-input mono"
spellCheck={false}
autoComplete="off"
maxLength={36}
disabled={!!smbiosBusy}
value={smbiosDraft?.uuid ?? ''}
onChange={(e) => setSmbiosDraft((prev) => ({
model: prev?.model ?? smbios?.model ?? '',
serial: prev?.serial ?? '',
mlb: prev?.mlb ?? '',
uuid: e.target.value.toUpperCase(),
rom: prev?.rom ?? smbios?.rom ?? '',
}))}
/>
</label>
{smbios?.rom && (
<div className="srow-desc">
{tr('smbiosROM')}: <code className="inline-code">{smbios.rom}</code>
</div>
)}
<div className="srow-desc">{tr('smbiosCheckHint')}</div>
{smbiosModalErr && <div className="notice notice-error" role="alert">{smbiosModalErr}</div>}
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" disabled={smbiosBusy === 'apply'} onClick={() => setSmbiosOpen(false)}>
{tr('cancel')}
</Button>
<Button
variant="primary"
busy={smbiosBusy === 'apply'}
disabled={smbiosLocked || smbiosBusy === 'generate' || !smbiosDraft?.serial.trim() || !smbiosDraft?.mlb.trim() || !smbiosDraft?.uuid.trim()}
onClick={() => void handleApplySmbios()}
>
{tr('smbiosApply')}
</Button>
</span>
</div>
</Modal>
)
}
@@ -0,0 +1,204 @@
import React, { useEffect, useMemo, useRef, useState } from 'react'
import type { app as WailsApp } from '../../../wailsjs/go/models'
import { I18nKey, parseAppError, t } from '../../i18n'
import { humanDisplayFallbackName, humanDisplayMeta, humanDisplayTitle, sortDisplaysForPicker } from '../../lib/format'
import { DisplayInfo, HostReport, Locale } from '../../types'
import { PopupSelect, SetRow } from '../../ui/settings'
import { errorToast, type ToastInput } from '../../ui/toast'
import { api } from '../../wails'
const PRIMARY_DISPLAY_OPT = '__primary'
interface Options {
locale: Locale
driverID: string
vm: string
running: boolean
host: HostReport
shown: boolean
isBlocked: () => boolean
onToast: (toast: ToastInput) => void
}
/** The host display the VM window opens on. A change applies at once. */
export function useTargetDisplay({ locale, driverID, vm, running, host, shown, isBlocked, onToast }: Options) {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const activeVMNameRef = useRef(vm)
activeVMNameRef.current = vm
const [displayStatus, setDisplayStatus] = useState<WailsApp.VMDisplayStatus | null>(null)
const [displayBusy, setDisplayBusy] = useState(false)
const [displayErr, setDisplayErr] = useState('')
const displayBusyRef = useRef(false)
const displayReqSeqRef = useRef(0)
const connectedDisplays = useMemo<DisplayInfo[]>(
() => sortDisplaysForPicker(displayStatus?.displays ?? host.displays ?? []),
[displayStatus, host.displays],
)
const activeTargetDisplay = displayStatus
? connectedDisplays.find((d) => d.name === displayStatus.effective_display)
: host.primary_display
const displayProfile = useMemo(() => displayStatus ? {
...host,
primary_display: activeTargetDisplay,
display_presets: displayStatus.display_presets,
fullscreen_hidpi: displayStatus.fullscreen_hidpi,
hidpi_advice: displayStatus.hidpi_advice,
recommended_resolution: undefined,
} : host, [host, displayStatus, activeTargetDisplay])
const hostDisplaysSig = (host.displays ?? [])
.map((d) => `${d.name ?? ''}:${d.friendly_name ?? ''}:${d.width}x${d.height}@${d.scale_pct}:${d.refresh_hz ?? 0}:${d.work_width ?? 0}x${d.work_height ?? 0}:${d.primary ? 1 : 0}`)
.join('|')
useEffect(() => {
displayReqSeqRef.current += 1
displayBusyRef.current = false
setDisplayStatus(null)
setDisplayBusy(false)
setDisplayErr('')
}, [driverID, vm])
useEffect(() => {
let active = true
const reqSeq = displayReqSeqRef.current
if (displayBusyRef.current) return () => { active = false }
api.GetVMDisplay(driverID, vm)
.then((st) => {
if (active && displayReqSeqRef.current === reqSeq) {
setDisplayStatus(st)
setDisplayErr('')
}
})
.catch((e) => {
if (active && displayReqSeqRef.current === reqSeq) {
setDisplayErr(parseAppError(e).summary)
}
})
return () => { active = false }
}, [driverID, vm, running, hostDisplaysSig, shown])
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
const displayOptions = useMemo(() => {
const opts: Array<{ value: string; label: string; detail?: string }> = [
{
value: PRIMARY_DISPLAY_OPT,
label: tr('targetDisplayPrimaryDefault'),
},
...connectedDisplays
.filter((d): d is DisplayInfo & { name: string } => Boolean(d.name?.trim()))
.map((d, idx) => ({
value: d.name,
label: humanDisplayTitle(d, idx + 1, numberedDisplay),
detail: humanDisplayMeta(d, d.primary ? tr('hostDisplayPrimary') : undefined),
})),
]
const savedTarget = displayStatus?.target_display?.trim()
if (savedTarget && displayStatus?.fallback_to_primary) {
if (!opts.some((o) => o.value.toLowerCase() === savedTarget.toLowerCase())) {
opts.push({
value: savedTarget,
label: humanDisplayFallbackName(savedTarget, numberedDisplay),
detail: tr('targetDisplayDisconnectedOption'),
})
}
}
return opts
}, [connectedDisplays, displayStatus?.fallback_to_primary, displayStatus?.target_display, locale])
const selectedDisplayValue = useMemo(() => {
const saved = displayStatus?.target_display?.trim()
if (!saved) return PRIMARY_DISPLAY_OPT
return displayOptions.find((o) => o.value.toLowerCase() === saved.toLowerCase())?.value ?? saved
}, [displayOptions, displayStatus?.target_display])
const activeTargetDisplayTitle = useMemo(() => {
if (!activeTargetDisplay) return ''
const idx = connectedDisplays.findIndex((d) => d === activeTargetDisplay || (d.name && activeTargetDisplay.name && d.name.toLowerCase() === activeTargetDisplay.name.toLowerCase()))
return humanDisplayTitle(activeTargetDisplay, idx >= 0 ? idx + 1 : 1, numberedDisplay)
}, [activeTargetDisplay, connectedDisplays, locale])
const handleTargetDisplayChange = async (nextValue: string) => {
if (isBlocked() || displayBusyRef.current || displayStatus === null) return
const nextTarget = nextValue === PRIMARY_DISPLAY_OPT ? '' : nextValue
const currentTarget = displayStatus.target_display ?? ''
if (nextTarget.toLowerCase() === currentTarget.toLowerCase()) return
const opSeq = ++displayReqSeqRef.current
displayBusyRef.current = true
setDisplayBusy(true)
setDisplayErr('')
try {
const next = await api.SetVMDisplay(driverID, vm, nextTarget)
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
setDisplayStatus(next)
const chosenLabel = displayOptions.find((o) => o.value === nextValue)?.label
?? humanDisplayFallbackName(next.target_display, numberedDisplay)
if (next.move_error) {
onToast(errorToast(locale, tr('targetDisplayToastSaved', { display: chosenLabel }), next.move_error))
} else {
onToast({
kind: 'ok',
title: next.applied_live
? tr('targetDisplayToastMoved', { display: chosenLabel })
: tr('targetDisplayToastSaved', { display: chosenLabel }),
})
}
} catch (e) {
if (activeVMNameRef.current !== vm || displayReqSeqRef.current !== opSeq) return
onToast(errorToast(locale, tr('targetDisplaySaveFailed'), e))
} finally {
if (displayReqSeqRef.current === opSeq) {
displayBusyRef.current = false
setDisplayBusy(false)
}
}
}
return {
displayStatus, displayBusy, displayErr, connectedDisplays, activeTargetDisplay,
activeTargetDisplayTitle, displayProfile, displayOptions, selectedDisplayValue, handleTargetDisplayChange,
/** Whether a change is being saved right now, ahead of the next render. */
isBusy: () => displayBusyRef.current,
}
}
interface RowProps {
locale: Locale
running: boolean
disabled: boolean
state: ReturnType<typeof useTargetDisplay>
}
export const TargetDisplayRow: React.FC<RowProps> = ({ locale, running, disabled, state }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { displayStatus, displayBusy, displayErr, connectedDisplays, displayOptions, selectedDisplayValue, handleTargetDisplayChange } = state
const numberedDisplay = (n: number) => tr('targetDisplayNumbered', { n })
const targetDisplayDesc = displayStatus?.fallback_to_primary && displayStatus.target_display
? (
<span className="warn-text">
{tr('targetDisplayFallbackHint', {
name: humanDisplayFallbackName(displayStatus.target_display, numberedDisplay),
})}
</span>
)
: connectedDisplays.length === 0
? tr('targetDisplayNoneHint')
: connectedDisplays.length === 1
? tr('targetDisplaySingleHint')
: tr(running ? 'targetDisplayRunningHint' : 'targetDisplayStoppedHint')
return (
<SetRow
title={tr('targetDisplayTitle')}
desc={targetDisplayDesc}
error={displayErr || undefined}
disabled={disabled || displayBusy || displayStatus === null || (connectedDisplays.length === 0 && !displayStatus.target_display)}
control={
<PopupSelect
label={tr('targetDisplayTitle')}
value={selectedDisplayValue}
onChange={(v) => void handleTargetDisplayChange(v)}
options={displayOptions}
/>
}
/>
)
}
@@ -0,0 +1,158 @@
import { Check, Copy } from 'lucide-react'
import React, { useEffect, useRef, useState } from 'react'
import { I18nKey, t } from '../../i18n'
import { createVMSettingRequests, type VMSettingState } from '../../lib/vmSettingRequests'
import { Locale, VMDetail } from '../../types'
import { IconButton } from '../../ui/controls'
import { PopupSelect, SetRow } from '../../ui/settings'
import type { ToastInput } from '../../ui/toast'
import { api } from '../../wails'
type VMTimezoneStatus = Awaited<ReturnType<typeof api.GetVMTimezone>>
const GUEST_TOOLS_INSTALL_CMD = 'sh /Volumes/REIMSTOOLS/Install-Reims-Tools.command'
const GUEST_TIMEZONE_APPLY_CMD = 'sh /Volumes/REIMSTOOLS/Apply-Timezone.command'
const GUEST_TIMEZONE_PRESETS: ReadonlyArray<{ value: string; labelKey: I18nKey; detail?: string }> = [
{ value: 'Asia/Shanghai', labelKey: 'guestTimezoneShanghai', detail: 'Asia/Shanghai' },
{ value: 'Asia/Hong_Kong', labelKey: 'guestTimezoneHongKong', detail: 'Asia/Hong_Kong' },
{ value: 'Asia/Taipei', labelKey: 'guestTimezoneTaipei', detail: 'Asia/Taipei' },
{ value: 'Asia/Tokyo', labelKey: 'guestTimezoneTokyo', detail: 'Asia/Tokyo' },
{ value: 'Asia/Seoul', labelKey: 'guestTimezoneSeoul', detail: 'Asia/Seoul' },
{ value: 'Asia/Singapore', labelKey: 'guestTimezoneSingapore', detail: 'Asia/Singapore' },
{ value: 'Europe/London', labelKey: 'guestTimezoneLondon', detail: 'Europe/London' },
{ value: 'Europe/Berlin', labelKey: 'guestTimezoneBerlin', detail: 'Europe/Berlin' },
{ value: 'America/Los_Angeles', labelKey: 'guestTimezoneLosAngeles', detail: 'America/Los_Angeles' },
{ value: 'America/New_York', labelKey: 'guestTimezoneNewYork', detail: 'America/New_York' },
{ value: 'Australia/Sydney', labelKey: 'guestTimezoneSydney', detail: 'Australia/Sydney' },
{ value: 'UTC', labelKey: 'guestTimezoneUTC' },
]
/** The time zone the VM follows, refreshed while shown. */
export function useGuestTimezone(driverID: string, vm: string, running: boolean, shown: boolean) {
const vmSettingsKey = `${driverID}:${vm}`
const activeVMKeyRef = useRef(vmSettingsKey)
activeVMKeyRef.current = vmSettingsKey
const [{ value: tzStatus, error: tzErr, busy: tzBusy }, setTzState] = useState<VMSettingState<VMTimezoneStatus>>({ value: null, error: '', busy: false })
const [tzRequests] = useState(() => createVMSettingRequests<VMTimezoneStatus>(() => activeVMKeyRef.current,
(patch) => setTzState((state) => ({ ...state, ...patch }))))
useEffect(() => {
setTzState({ value: null, error: '', busy: tzRequests.isWriting(vmSettingsKey) })
}, [vmSettingsKey, tzRequests])
useEffect(() => {
if (!shown) return
const { refresh, stop } = tzRequests.watch(vmSettingsKey, () => api.GetVMTimezone(driverID, vm))
void refresh()
const timer = window.setInterval(refresh, 3000)
return () => { stop(); window.clearInterval(timer) }
}, [shown, driverID, vm, running, vmSettingsKey, tzRequests])
return {
tzStatus,
tzErr,
tzBusy,
/** Whether a change is being saved right now, ahead of the next render. */
isWriting: () => tzRequests.isWriting(vmSettingsKey),
write: (setting: string) => tzRequests.write(vmSettingsKey, () => api.SetVMTimezone(driverID, vm, setting)),
}
}
interface Props {
locale: Locale
detail: VMDetail
hostTimezone?: string
state: ReturnType<typeof useGuestTimezone>
disabled: boolean
isBlocked: () => boolean
onToast: (toast: ToastInput) => void
onCopy?: (text: string) => void
}
export const GuestTimezoneRow: React.FC<Props> = ({ locale, detail, hostTimezone, state, disabled, isBlocked, onToast, onCopy }) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const { tzStatus, tzErr, tzBusy, write } = state
const updateTimezone = async (nextSetting: string) => {
if (isBlocked() || !tzStatus) return
const currentSetting = tzStatus.mode === 'off' ? 'off' : tzStatus.mode === 'custom' ? tzStatus.timezone : 'host'
if (nextSetting === currentSetting) return
if (await write(nextSetting)) {
onToast({ kind: 'ok', title: tr('guestTimezoneSaved') })
}
}
const detectedHostTZ = tzStatus?.host_timezone || hostTimezone || ''
const tzSelectedValue = tzStatus?.mode === 'custom' ? tzStatus.timezone : tzStatus?.mode
const tzOptions = [
{ value: 'host', label: tr('guestTimezoneHost'), detail: detectedHostTZ || undefined },
...GUEST_TIMEZONE_PRESETS.map((p) => ({
value: p.value,
label: tr(p.labelKey),
detail: p.detail,
})),
...(tzStatus?.mode === 'custom' && tzStatus.timezone && !GUEST_TIMEZONE_PRESETS.some((p) => p.value === tzStatus.timezone)
? [{ value: tzStatus.timezone, label: tzStatus.timezone }]
: []),
{ value: 'off', label: tr('guestTimezoneOff') },
]
let tzDesc: React.ReactNode = tr('guestTimezoneDesc')
let tzCommand = ''
if (tzStatus) {
const tzEffective = tzStatus.effective_timezone
if (tzStatus.mode === 'off') {
tzDesc = tr('guestTimezoneOffDesc')
} else if (detail.guest_tools_disabled) {
tzDesc = <span className="warn-text">{tr('gtStatusOffTip')}</span>
} else if (!tzEffective) {
tzDesc = <span className="warn-text">{tr('guestTimezoneHostUnknown')}</span>
} else if (tzStatus.running && tzStatus.guest_connected) {
const tzFailure = tzStatus.timezone_error
? <span className="warn-text">{tr('guestTimezoneApplyFailed', { tz: tzEffective })}</span>
: null
if (tzStatus.guest_agent_version < tzStatus.required_agent_version) {
tzDesc = <span className="warn-text">{tr(detail.guest_tools_attached ? 'guestTimezoneUpgradeHint' : 'guestTimezoneUpgradeAttachHint', { version: tzStatus.required_agent_version })}</span>
if (detail.guest_tools_attached) tzCommand = GUEST_TOOLS_INSTALL_CMD
} else if (!tzStatus.helper_ready) {
const hint = tr(detail.guest_tools_attached ? 'guestTimezoneApplyHint' : 'guestTimezoneApplyAttachHint')
tzDesc = tzFailure ? <div className="stack-1">{tzFailure}<span>{hint}</span></div> : hint
if (detail.guest_tools_attached) tzCommand = GUEST_TIMEZONE_APPLY_CMD
} else if (tzFailure) {
tzDesc = tzFailure
} else if (tzStatus.guest_applied === tzEffective) {
tzDesc = <span className="ok-text"><Check size={12} aria-hidden="true" />{tr('guestTimezoneSynced', { tz: tzEffective })}</span>
} else {
tzDesc = tr('guestTimezoneSyncing', { tz: tzEffective })
}
} else if (detail.guest_tools_attached) {
tzCommand = GUEST_TOOLS_INSTALL_CMD
}
}
return (
<SetRow
title={tr('guestTimezoneTitle')}
desc={tzDesc}
disabled={!tzStatus || tzBusy || disabled}
error={tzErr || undefined}
control={
<PopupSelect
label={tr('guestTimezoneTitle')}
value={tzSelectedValue}
placeholder={tr('guestTimezoneLoading')}
onChange={updateTimezone}
options={tzOptions}
/>
}
block={tzCommand ? (
<div className="cmd-line">
<code>{tzCommand}</code>
{onCopy && (
<IconButton small label={tr('copy')} icon={<Copy size={14} />} onClick={() => onCopy(tzCommand)} />
)}
</div>
) : undefined}
/>
)
}
+4 -4
View File
@@ -6,7 +6,7 @@ import { builtinDict, registerBuiltinDomain } from './i18n/runtime'
export type { I18nKey }
export { registerBuiltinDomain }
export interface LocaleOption {
interface LocaleOption {
value: Locale
label: string
detail?: string
@@ -65,11 +65,11 @@ function primarySubtag(tag: string): string {
return idx >= 0 ? s.slice(0, idx) : s
}
export function isZhLocale(locale: Locale): boolean {
function isZhLocale(locale: Locale): boolean {
return primarySubtag(locale) === 'zh'
}
export function isCJKLocale(locale: Locale): boolean {
function isCJKLocale(locale: Locale): boolean {
const p = primarySubtag(locale)
return p === 'zh' || p === 'ja' || p === 'ko'
}
@@ -87,7 +87,7 @@ function isBuiltinLocale(locale: string): locale is BuiltinLocale {
return locale === 'zh-CN' || locale === 'en-US'
}
export function canonicalizeTag(raw: string | undefined): string {
function canonicalizeTag(raw: string | undefined): string {
if (!raw) return ''
const clean = raw.trim().split(/[.@]/)[0].replaceAll('_', '-')
const low = clean.toLowerCase()
-4
View File
@@ -177,8 +177,6 @@ export const coreZh: Record<string, string> = {
"themeSystem": "跟随系统",
"toastAffinityApplied": "处理器相关性已应用({count} 个逻辑处理器 · {mask})",
"toastAffinitySaved": "处理器相关性已保存,下次启动时生效",
"toastBorderlessNextStart": "已保存全屏启动偏好,重启虚拟机后生效",
"toastBorderlessUpdated": "已保存全屏启动偏好",
"toastCopied": "已复制",
"toastCreateCanceled": "已取消创建 {name}",
"toastCreateCanceledPartial": "已下载部分已保留,可继续下载或返回修改",
@@ -390,8 +388,6 @@ export const coreEn: Record<string, string> = {
"themeSystem": "System",
"toastAffinityApplied": "Processor affinity applied ({count} logical CPUs · {mask})",
"toastAffinitySaved": "Processor affinity saved for next start",
"toastBorderlessNextStart": "Fullscreen launch saved — applies on next restart",
"toastBorderlessUpdated": "Fullscreen launch preference saved",
"toastCopied": "Copied",
"toastCreateCanceled": "Canceled creating {name}",
"toastCreateCanceledPartial": "Downloaded progress is kept; resume anytime or edit and retry",
-6
View File
@@ -14,7 +14,6 @@ export const pluginsZh: Record<string, string> = {
"pluginBuiltinSection": "内置插件",
"pluginClearSecret": "清除",
"pluginColorSchemes": "配色方案",
"pluginColorSchemesHint": "修改种子色派生整套界面色阶",
"pluginDeleteScheme": "删除方案",
"pluginDisable": "停用",
"pluginDisableInUseBody": "停用后,这个插件管理的虚拟机会显示为「驱动不可用」,不能启动或修改。虚拟机文件和挂起状态都会保留,重新启用即可恢复。运行中的虚拟机需要先停止或挂起。",
@@ -70,7 +69,6 @@ export const pluginsZh: Record<string, string> = {
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
"pluginMarketSyncing": "正在同步插件市场",
"pluginMarketUpdate": "更新至 v{version}",
"pluginMarketUpdateShort": "更新",
"pluginMarketVersionTip": "已安装 v{installed},可更新至 v{version}",
"pluginMarketWithdrawn": "已撤回",
@@ -98,7 +96,6 @@ export const pluginsZh: Record<string, string> = {
"pluginScanHardSection": "硬性拦截项(禁止安装)",
"pluginScanInspect": "安全扫描",
"pluginScanInstallConfirm": "确认导入安装",
"pluginScanLoading": "正在扫描插件包…",
"pluginScanModalTitle": "插件静态安全报告",
"pluginScanMoreItems": "另有 {count} 项已折叠",
"pluginSchemeDefault": "默认",
@@ -139,7 +136,6 @@ export const pluginsEn: Record<string, string> = {
"pluginBuiltinSection": "Built-in plugins",
"pluginClearSecret": "Clear",
"pluginColorSchemes": "Color schemes",
"pluginColorSchemesHint": "Seed colors derive the full surface, text, and accent ramp",
"pluginDeleteScheme": "Delete scheme",
"pluginDisable": "Disable",
"pluginDisableInUseBody": "Its VMs will show as “Driver unavailable” and can’t be started or changed. Their files and any suspended state are kept; turning the plugin back on restores them. Stop or suspend any running VM first.",
@@ -195,7 +191,6 @@ export const pluginsEn: Record<string, string> = {
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
"pluginMarketSyncing": "Syncing the plugin market",
"pluginMarketUpdate": "Update to v{version}",
"pluginMarketUpdateShort": "Update",
"pluginMarketVersionTip": "v{installed} installed, v{version} available",
"pluginMarketWithdrawn": "Withdrawn",
@@ -223,7 +218,6 @@ export const pluginsEn: Record<string, string> = {
"pluginScanHardSection": "Hard blockers (install refused)",
"pluginScanInspect": "Security scan",
"pluginScanInstallConfirm": "Proceed with install",
"pluginScanLoading": "Scanning plugin package…",
"pluginScanModalTitle": "Plugin security report",
"pluginScanMoreItems": "...and {count} more",
"pluginSchemeDefault": "Default",
-46
View File
@@ -59,7 +59,6 @@ export const settingsZh: Record<string, string> = {
"affinitySummaryPCores": "仅 P 核({count} 线程 · {mask})",
"affinityTitle": "处理器核心",
"appCheckUpdate": "检查更新",
"appDownloadUpdate": "前往下载",
"appUpToDate": "已是最新",
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
@@ -169,11 +168,9 @@ export const settingsZh: Record<string, string> = {
"effectNextStart": "下次启动生效",
"enableAudio": "音频",
"enableLogs": "记录图形与串口日志",
"enableNetwork": "网络(NAT)",
"enableWHPX": "启用",
"extraArgs": "额外 QEMU 参数",
"extraArgsDesc": "原样追加到 QEMU 命令行",
"failAffinity": "设置处理器相关性失败",
"folderShareAdd": "添加目录…",
"folderShareAddTitle": "宿主机目录",
"folderShareConfirmRWAction": "改为读写",
@@ -199,9 +196,6 @@ export const settingsZh: Record<string, string> = {
"folderShareRemove": "移除目录",
"folderShareTitle": "自定义共享目录",
"folderShareWritableWarn": "读写模式:macOS 中的修改和删除会直接作用于宿主机原目录",
"footerDisk": "磁盘可用 {gb} GB",
"footerMem": "内存 {pct}%",
"footerMemAvail": "可用 {avail} GB",
"forceQuitAppButton": "强制退出",
"forceQuitAppSub": "对所有运行中的虚拟机执行硬关机,未保存的数据可能丢失。",
"forceQuitAppTitle": "强制退出 Reims-Go",
@@ -247,7 +241,6 @@ export const settingsZh: Record<string, string> = {
"groupMacOS": "macOS",
"groupPerformance": "性能",
"groupQemu": "QEMU",
"gtInstallCmd": "安装命令",
"guestLangHint": "恢复模式、设置助理和登录界面使用的语言;选美式键盘,在终端输命令不易出错",
"guestLangSettingsHint": "恢复模式、设置助理和登录界面使用的语言",
"guestLangShort": "系统语言",
@@ -279,9 +272,6 @@ export const settingsZh: Record<string, string> = {
"guestTimezoneUTC": "UTC(协调世界时)",
"guestTimezoneUpgradeAttachHint": "先在虚拟机详情页挂载 Guest Tools 镜像,即可查看升级到版本 {version} 的命令",
"guestTimezoneUpgradeHint": "在 macOS 终端运行以下命令,将 Guest Tools 升级到版本 {version}",
"guestToolsConnected": "已连接",
"guestToolsPreventSleepSub": "闲置时让 macOS 保持唤醒,立即生效",
"guestToolsReady": "已配置",
"hidpiPresetBadge": "HiDPI",
"hostAudioInput": "Windows 麦克风",
"hostAudioMissingIn": "没有检测到麦克风,macOS 录不到声音",
@@ -356,7 +346,6 @@ export const settingsZh: Record<string, string> = {
"installersDownloaded": "已下载",
"installersDownloadingForVM": "为 {vm} 下载中",
"installersDownloadingPct": "下载中 {p}%",
"installersEmpty": "还没有下载任何镜像",
"installersHint": "下载好的镜像可以重复用来新建虚拟机",
"installersKindOffline": "离线完整包",
"installersKindOnline": "在线恢复镜像",
@@ -422,10 +411,8 @@ export const settingsZh: Record<string, string> = {
"navHasIssue": "这一页有需要修改的项",
"nestedVirtDesc": "允许 macOS 运行自己的虚拟机,完全关机后再次启动时生效。",
"nestedVirtInvalid": "保存的设置无法读取,虚拟机将按默认 CPU 设置启动。",
"nestedVirtLabel": "嵌套虚拟化",
"nestedVirtUnavailable": "当前 Windows 宿主机无法通过 WHPX 提供 VMX。",
"networkBridge": "桥接",
"networkDesc": "通过 Windows 的网络连接上网",
"networkNAT": "NAT",
"networkOfflineHint": "离线安装默认关闭;看到「设置助理」后退出恢复模式并重启即可联网",
"networkTitle": "网络",
@@ -436,7 +423,6 @@ export const settingsZh: Record<string, string> = {
"npcapInstalling": "正在准备 Npcap,在弹出的官方安装向导中完成安装后将自动重新检查",
"npcapMissing": "未检测到完整安装;应用网络时自动从官网下载,也可提前安装。许可与 UAC 在官方向导确认",
"npcapStopFirst": "安装驱动前需先关闭全部虚拟机",
"offlineListFailed": "无法读取 Apple 的版本列表",
"opencore": "OpenCore",
"optAuto": "已自动开启",
"optAvailable": "可用",
@@ -449,11 +435,9 @@ export const settingsZh: Record<string, string> = {
"optPCoreSub": "仅调度到性能核({detail}),减少卡顿",
"optPCoreUnavailable": "当前处理器无大小核架构,无需开启",
"optRecommended": "推荐",
"optSchedBackground": "后台服务",
"optSchedNowBackground": "当前为「后台服务」,适合虚拟机在后台运行(影响整个 Windows)",
"optSchedNowPrograms": "当前为「程序优先」,虚拟机在后台时可能变慢,建议改为「后台服务」(影响整个 Windows)",
"optSchedOpen": "更改…",
"optSchedPrograms": "程序优先",
"optSchedSub": "选「后台服务」,虚拟机在后台时更稳定(影响整个 Windows)",
"optSchedTitle": "Windows 处理器调度",
"optUnavailable": "不可用",
@@ -462,7 +446,6 @@ export const settingsZh: Record<string, string> = {
"recommendedBadge": "推荐",
"resCustom": "自定义",
"resCustomSub": "宽 × 高",
"resFullscreen": "全屏",
"resInvalid": "格式为 宽x高,例如 2560x1600",
"resNativeBadge": "原生",
"resScaleToFitWindow": "缩放以适应窗口",
@@ -504,11 +487,6 @@ export const settingsZh: Record<string, string> = {
"sshOffDesc": "从 Windows 用 SSH 登录 macOS",
"sshPort": "SSH 转发端口",
"startAfterCreate": "创建后立即启动",
"statsCPU": "QEMU CPU",
"statsDisk": "磁盘占用",
"statsDiskSub": "实际 {actual} / 上限 {virtual}",
"statsMemory": "宿主机内存",
"statsUptime": "运行时长",
"stopBeforeDiskOp": "关机后才能操作",
"stopTimeout": "关机等待时间",
"stopTimeoutHint": "0 表示一直等待",
@@ -547,7 +525,6 @@ export const settingsZh: Record<string, string> = {
"vcpus": "虚拟处理器",
"vmDir": "存放目录",
"vmName": "名称",
"welcomeCheckHost": "先完成内核环境配置 →",
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
"welcomeTitle": "创建第一台 macOS 虚拟机",
"whpxHvOff": "Hypervisor 启动已关闭,启用后重启 Windows",
@@ -624,7 +601,6 @@ export const settingsEn: Record<string, string> = {
"affinitySummaryPCores": "P-Cores ({count}T · {mask})",
"affinityTitle": "CPU cores",
"appCheckUpdate": "Check for updates",
"appDownloadUpdate": "Download",
"appUpToDate": "Up to date",
"appUpdateAvailable": "New stable release {v} available",
"appUpdateAvailableAlpha": "New alpha release {v} available",
@@ -734,11 +710,9 @@ export const settingsEn: Record<string, string> = {
"effectNextStart": "Next start",
"enableAudio": "Audio",
"enableLogs": "Keep graphics and serial logs",
"enableNetwork": "Network (NAT)",
"enableWHPX": "Enable",
"extraArgs": "Extra QEMU arguments",
"extraArgsDesc": "Appended to the QEMU command line as is",
"failAffinity": "Could not update processor affinity",
"folderShareAdd": "Add folder…",
"folderShareAddTitle": "Host folders",
"folderShareConfirmRWAction": "Enable read-write",
@@ -764,9 +738,6 @@ export const settingsEn: Record<string, string> = {
"folderShareRemove": "Remove folder",
"folderShareTitle": "Custom shared folders",
"folderShareWritableWarn": "Read-write: changes and deletions in macOS modify the host folder directly",
"footerDisk": "Disk {gb} GB free",
"footerMem": "Memory {pct}%",
"footerMemAvail": "{avail} GB free",
"forceQuitAppButton": "Force quit",
"forceQuitAppSub": "Cuts power to running virtual machines. Unsaved data may be lost.",
"forceQuitAppTitle": "Force quit Reims-Go",
@@ -812,7 +783,6 @@ export const settingsEn: Record<string, string> = {
"groupMacOS": "macOS",
"groupPerformance": "Performance",
"groupQemu": "QEMU",
"gtInstallCmd": "Install command",
"guestLangHint": "Used by Recovery, Setup Assistant and the login window; a US keyboard layout keeps Terminal input reliable",
"guestLangSettingsHint": "Used by Recovery, Setup Assistant and the login window",
"guestLangShort": "System language",
@@ -844,9 +814,6 @@ export const settingsEn: Record<string, string> = {
"guestTimezoneUTC": "UTC",
"guestTimezoneUpgradeAttachHint": "Attach the Guest Tools image on the VM details page to see the command for updating to version {version}",
"guestTimezoneUpgradeHint": "Run the command below in macOS Terminal to update Guest Tools to version {version}",
"guestToolsConnected": "Connected",
"guestToolsPreventSleepSub": "Keeps macOS awake while idle; applies immediately",
"guestToolsReady": "Configured",
"hidpiPresetBadge": "HiDPI",
"hostAudioInput": "Windows microphone",
"hostAudioMissingIn": "No microphone found; macOS will record silence",
@@ -921,7 +888,6 @@ export const settingsEn: Record<string, string> = {
"installersDownloaded": "Downloaded",
"installersDownloadingForVM": "Downloading for {vm}",
"installersDownloadingPct": "Downloading {p}%",
"installersEmpty": "No images downloaded yet",
"installersHint": "Downloaded images can be reused for new VMs",
"installersKindOffline": "Offline installer",
"installersKindOnline": "Online recovery",
@@ -987,10 +953,8 @@ export const settingsEn: Record<string, string> = {
"navHasIssue": "This page has settings to fix",
"nestedVirtDesc": "Lets macOS run its own virtual machines. Applies on a full restart.",
"nestedVirtInvalid": "The saved setting could not be read. The VM starts with the default CPU settings.",
"nestedVirtLabel": "Nested virtualization",
"nestedVirtUnavailable": "The Windows host does not provide VMX through WHPX.",
"networkBridge": "Bridged",
"networkDesc": "Uses the Windows network connection",
"networkNAT": "NAT",
"networkOfflineHint": "Off by default for offline installs. Exit recovery and restart when Setup Assistant appears to enable networking",
"networkTitle": "Network",
@@ -1001,7 +965,6 @@ export const settingsEn: Record<string, string> = {
"npcapInstalling": "Preparing Npcap. Complete the official installer; availability will be checked afterwards",
"npcapMissing": "A complete installation was not detected. Downloaded from the official website when applying, or install now. Confirm the license and UAC in the official wizard",
"npcapStopFirst": "Shut down all VMs before installing the driver",
"offlineListFailed": "Couldn’t read Apple’s release list",
"opencore": "OpenCore",
"optAuto": "Automatic",
"optAvailable": "Available",
@@ -1014,11 +977,9 @@ export const settingsEn: Record<string, string> = {
"optPCoreSub": "Schedule QEMU on performance cores only ({detail})",
"optPCoreUnavailable": "CPU has no hybrid P/E cores",
"optRecommended": "Recommended",
"optSchedBackground": "Background services",
"optSchedNowBackground": "Set to Background services, which suits a VM running in the background (affects all of Windows)",
"optSchedNowPrograms": "Set to Programs, so the VM may slow down in the background. Background services is recommended (affects all of Windows)",
"optSchedOpen": "Change…",
"optSchedPrograms": "Programs",
"optSchedSub": "Background services keeps the VM steady in the background (affects all of Windows)",
"optSchedTitle": "Windows processor scheduling",
"optUnavailable": "Unavailable",
@@ -1027,7 +988,6 @@ export const settingsEn: Record<string, string> = {
"recommendedBadge": "Recommended",
"resCustom": "Custom",
"resCustomSub": "Width × height",
"resFullscreen": "Full screen",
"resInvalid": "Use WIDTHxHEIGHT, e.g. 2560x1600",
"resNativeBadge": "Native",
"resScaleToFitWindow": "Scale to fit window",
@@ -1069,11 +1029,6 @@ export const settingsEn: Record<string, string> = {
"sshOffDesc": "Log in to macOS over SSH from Windows",
"sshPort": "SSH forward port",
"startAfterCreate": "Start after creating",
"statsCPU": "QEMU CPU",
"statsDisk": "Disk usage",
"statsDiskSub": "{actual} actual / {virtual} max",
"statsMemory": "Host RAM",
"statsUptime": "Uptime",
"stopBeforeDiskOp": "Shut down the VM first",
"stopTimeout": "Shutdown timeout",
"stopTimeoutHint": "0 waits indefinitely",
@@ -1112,7 +1067,6 @@ export const settingsEn: Record<string, string> = {
"vcpus": "Virtual CPUs",
"vmDir": "Folder",
"vmName": "Name",
"welcomeCheckHost": "Set up Engine first →",
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
"welcomeTitle": "Create your first macOS VM",
"whpxHvOff": "Hypervisor launch is off — enable and restart Windows",
+6
View File
@@ -95,6 +95,8 @@ export const vmZh: Record<string, string> = {
"fieldVMName": "虚拟机名称",
"finishInstall": "退出恢复模式",
"gpuAuto": "自动选择 GPU",
"gtDropAccessHint": "拖放通过 WebDAV 传输文件,请在 macOS「系统设置 → 隐私与安全性 → 文件与文件夹」中开启 sh 的「网络宗卷」权限",
"gtDropAccessLimited": "文件拖放受限",
"gtInstall": "安装…",
"gtInstallSub": "在 macOS 终端里运行",
"gtNotInstalledDesc": "未安装:挂载工具盘后在 macOS 中运行安装命令",
@@ -139,6 +141,7 @@ export const vmZh: Record<string, string> = {
"hostDNSStatusPending": "待应用",
"hostDNSStatusStale": "配置已过期",
"hostDNSStatusStillActive": "macOS 代理未移除",
"nestedVirtLabel": "嵌套虚拟化",
"netBridge": "桥接网络",
"netCustom": "自定义网络",
"netOff": "无网络",
@@ -350,6 +353,8 @@ export const vmEn: Record<string, string> = {
"fieldVMName": "VM name",
"finishInstall": "Exit recovery mode",
"gpuAuto": "Automatic GPU",
"gtDropAccessHint": "File drops transfer via WebDAV. Enable Network Volumes for sh in macOS System Settings → Privacy \u0026 Security → Files and Folders",
"gtDropAccessLimited": "File drop limited",
"gtInstall": "Install…",
"gtInstallSub": "Run in macOS Terminal",
"gtNotInstalledDesc": "Not installed: attach the tools disk and run the installer in macOS",
@@ -394,6 +399,7 @@ export const vmEn: Record<string, string> = {
"hostDNSStatusPending": "Not applied",
"hostDNSStatusStale": "Config outdated",
"hostDNSStatusStillActive": "Still active in macOS",
"nestedVirtLabel": "Nested virtualization",
"netBridge": "Bridged network",
"netCustom": "Custom network",
"netOff": "No network",
+1 -1
View File
@@ -51,7 +51,7 @@ export function formatLocaleNumber(locale: string, value: number, precision = -1
const MAX_ICU_DEPTH = 16
const MAX_ICU_TEMPLATE_LEN = 16384
export function parseICU(tmpl: string): ICUNode[] | null {
function parseICU(tmpl: string): ICUNode[] | null {
if (tmpl.length > MAX_ICU_TEMPLATE_LEN) return null
if (astCache.has(tmpl)) {
return astCache.get(tmpl) ?? null
+2 -27
View File
@@ -59,7 +59,6 @@ export type I18nKey =
| "affinitySummaryPCores"
| "affinityTitle"
| "appCheckUpdate"
| "appDownloadUpdate"
| "appUpToDate"
| "appUpdateAvailable"
| "appUpdateAvailableAlpha"
@@ -245,7 +244,6 @@ export type I18nKey =
| "emptyVMs"
| "enableAudio"
| "enableLogs"
| "enableNetwork"
| "enableWHPX"
| "endpointCopyADB"
| "endpointEditConnection"
@@ -278,7 +276,6 @@ export type I18nKey =
| "factGraphics"
| "factGuestOS"
| "factMemory"
| "failAffinity"
| "failAttachInstaller"
| "failCloneVM"
| "failCreate"
@@ -346,14 +343,11 @@ export type I18nKey =
| "folderShareTitle"
| "folderShareWritableWarn"
| "fontMissingFoDHint"
| "footerDisk"
| "footerDiskLabel"
| "footerDiskTip"
| "footerDiskValue"
| "footerHostIssue"
| "footerHostIssueTip"
| "footerMem"
| "footerMemAvail"
| "footerMemLabel"
| "footerMemTip"
| "footerMemValue"
@@ -411,8 +405,9 @@ export type I18nKey =
| "groupMacOS"
| "groupPerformance"
| "groupQemu"
| "gtDropAccessHint"
| "gtDropAccessLimited"
| "gtInstall"
| "gtInstallCmd"
| "gtInstallSub"
| "gtNotInstalledDesc"
| "gtStatusConnected"
@@ -464,13 +459,10 @@ export type I18nKey =
| "guestTimezoneUTC"
| "guestTimezoneUpgradeAttachHint"
| "guestTimezoneUpgradeHint"
| "guestToolsConnected"
| "guestToolsHostDNS"
| "guestToolsModeSync"
| "guestToolsModeWebDAV"
| "guestToolsPreventSleep"
| "guestToolsPreventSleepSub"
| "guestToolsReady"
| "guestToolsSleepActive"
| "guestToolsTitle"
| "guestToolsUpgradeHint"
@@ -588,7 +580,6 @@ export type I18nKey =
| "installersDownloading"
| "installersDownloadingForVM"
| "installersDownloadingPct"
| "installersEmpty"
| "installersHint"
| "installersKindOffline"
| "installersKindOnline"
@@ -694,7 +685,6 @@ export type I18nKey =
| "netOff"
| "netShared"
| "networkBridge"
| "networkDesc"
| "networkNAT"
| "networkOfflineHint"
| "networkTitle"
@@ -712,7 +702,6 @@ export type I18nKey =
| "offlineCached"
| "offlineDownloading"
| "offlineHint"
| "offlineListFailed"
| "offlineListFailedDetail"
| "offlineLoading"
| "offlineQueued"
@@ -737,11 +726,9 @@ export type I18nKey =
| "optPCoreSub"
| "optPCoreUnavailable"
| "optRecommended"
| "optSchedBackground"
| "optSchedNowBackground"
| "optSchedNowPrograms"
| "optSchedOpen"
| "optSchedPrograms"
| "optSchedSub"
| "optSchedTitle"
| "optUnavailable"
@@ -767,7 +754,6 @@ export type I18nKey =
| "pluginBuiltinSection"
| "pluginClearSecret"
| "pluginColorSchemes"
| "pluginColorSchemesHint"
| "pluginDeleteScheme"
| "pluginDisable"
| "pluginDisableInUseBody"
@@ -823,7 +809,6 @@ export type I18nKey =
| "pluginMarketSearchPlaceholder"
| "pluginMarketStaleBanner"
| "pluginMarketSyncing"
| "pluginMarketUpdate"
| "pluginMarketUpdateShort"
| "pluginMarketVersionTip"
| "pluginMarketWithdrawn"
@@ -852,7 +837,6 @@ export type I18nKey =
| "pluginScanHardSection"
| "pluginScanInspect"
| "pluginScanInstallConfirm"
| "pluginScanLoading"
| "pluginScanModalTitle"
| "pluginScanMoreItems"
| "pluginSchemeDefault"
@@ -884,7 +868,6 @@ export type I18nKey =
| "refresh"
| "resCustom"
| "resCustomSub"
| "resFullscreen"
| "resInvalid"
| "resLooksLike"
| "resNativeBadge"
@@ -1051,11 +1034,6 @@ export type I18nKey =
| "state_stopping"
| "state_suspended"
| "state_suspending"
| "statsCPU"
| "statsDisk"
| "statsDiskSub"
| "statsMemory"
| "statsUptime"
| "step1"
| "step2"
| "step3"
@@ -1121,8 +1099,6 @@ export type I18nKey =
| "themeSystem"
| "toastAffinityApplied"
| "toastAffinitySaved"
| "toastBorderlessNextStart"
| "toastBorderlessUpdated"
| "toastCloned"
| "toastCopied"
| "toastCreateCanceled"
@@ -1208,7 +1184,6 @@ export type I18nKey =
| "vmDir"
| "vmName"
| "vulkanProbeFailed"
| "welcomeCheckHost"
| "welcomeSub"
| "welcomeTitle"
| "whpxHvOff"
+2 -2
View File
@@ -3,13 +3,13 @@
// visibility:hidden/collapse, [hidden], [inert], aria-hidden="true",
// data-state="closed") must not block global shortcuts or menu focus return.
export interface DialogLikeElement {
interface DialogLikeElement {
getAttribute(name: string): string | null
closest?(selector: string): unknown
parentElement?: DialogLikeElement | null
}
export interface ComputedVisibility {
interface ComputedVisibility {
display: string
visibility: string
}
+4 -4
View File
@@ -3,7 +3,7 @@ import type { VMEndpoint, VMInfo, VMListItem } from '../types'
// Guest family, driver capabilities and endpoint ordering for non-macOS guests.
// Everything here is pure so node:test can load it (scripts/test-endpoints.mjs).
export const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
const BUILTIN_MACOS_DRIVER = 'builtin.driver.reims-macos'
export type GuestFamily = 'macos' | 'linux' | 'windows' | 'android' | ''
@@ -85,7 +85,7 @@ export function vmFeatures(vm?: { driver_id?: string; capabilities?: readonly st
/** Highest priority first: the first ready endpoint in this order is the primary hosted action. */
export const ENDPOINT_PRIORITY = ['vmconnect', 'rdp', 'wsl', 'ssh', 'adb'] as const
export type EndpointKind = (typeof ENDPOINT_PRIORITY)[number]
type EndpointKind = (typeof ENDPOINT_PRIORITY)[number]
export type EndpointAction = 'open' | 'terminal' | 'vscode' | 'config' | 'edit' | 'shell' | 'copy'
@@ -102,7 +102,7 @@ function rank(kind: string): number {
return i < 0 ? ENDPOINT_PRIORITY.length : i
}
export function isEndpointKind(kind: string): kind is EndpointKind {
function isEndpointKind(kind: string): kind is EndpointKind {
return rank(kind) < ENDPOINT_PRIORITY.length
}
@@ -121,7 +121,7 @@ export function secondaryEndpointActions(kind: string): EndpointAction[] {
return endpointActions(kind).slice(1)
}
export interface EndpointSplit {
interface EndpointSplit {
/** The highest-priority ready endpoint; absent when none is ready. */
primary?: VMEndpoint
/** All other endpoints in priority order, never the primary one. */
+13 -15
View File
@@ -10,10 +10,6 @@ function currentDocLocale(): string {
// Human-readable values for the main view (see docs/design-guidelines.md).
// Raw values stay available under "Technical details".
export function formatNameList(locale: Locale, names: string[]): string {
return new Intl.ListFormat(locale === 'auto' ? currentDocLocale() : locale, { style: 'long', type: 'conjunction' }).format(names)
}
const MEMORY_CHOICES = [4, 6, 8, 12, 16, 24, 32, 48, 64]
/**
@@ -143,7 +139,7 @@ export function shortGPUName(name: string): string {
}
/** "1920x1080" → "1080p"; non-16:9 sizes keep "W×H". */
export function resolutionLabel(raw: string): string {
function resolutionLabel(raw: string): string {
const m = /^(\d+)\s*[x×]\s*(\d+)$/i.exec(raw ?? '')
if (!m) return raw
const w = Number(m[1]), h = Number(m[2])
@@ -171,6 +167,17 @@ export function sshCommand(port: number): string {
return `ssh -p ${port} 127.0.0.1`
}
/** A point in time as a short date and time of day; empty when it is unknown. */
export function formatShortTime(ms: number, locale: Locale): string {
if (!ms) return ''
try {
const loc = locale === 'en-XA' ? 'en-US' : locale
return new Intl.DateTimeFormat(loc, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(ms))
} catch {
return ''
}
}
export function formatBytes(bytes: number, locale?: Locale): string {
if (!bytes || bytes <= 0) return '0 B'
const units = ['B', 'KB', 'MB', 'GB', 'TB']
@@ -426,7 +433,7 @@ export function recommendedResolution(host: HostReport): string {
return rec?.resolution ?? '1920x1080'
}
export interface GuestLangPreset {
interface GuestLangPreset {
value: string
labelKey: I18nKey
detailKey?: I18nKey
@@ -472,15 +479,6 @@ export function guestLangLabel(locale: Locale, code: string | undefined): string
return detail ? `${label} (${detail})` : label
}
/**
* Split "简体中文(美式键盘,推荐)" / "Simplified Chinese (US Keyboard)" into a
* pop-up label and its grey detail, so the menu reads like macOS.
*/
export function splitLangLabel(value: string, text: string): { value: string; label: string; detail?: string } {
const m = /^(.*?)\s*[((](.*)[))]\s*$/.exec(text)
return m ? { value, label: m[1], detail: m[2] } : { value, label: text }
}
/**
* A change saved while the VM runs, as the user would say it:
* `memory 8G→16G` becomes "内存 8 GB → 16 GB". Field names come from
+8 -8
View File
@@ -1,13 +1,13 @@
export const DEFAULT_FULLSCREEN_HOTKEY = 'Ctrl+Shift+F'
export interface HotkeyModifiers {
interface HotkeyModifiers {
ctrl: boolean
shift: boolean
alt: boolean
win: boolean
}
export interface HotkeyKeyEventLike {
interface HotkeyKeyEventLike {
code?: string
key?: string
ctrlKey?: boolean
@@ -17,15 +17,15 @@ export interface HotkeyKeyEventLike {
repeat?: boolean
}
export type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved'
type FullscreenHotkeyErrorReason = 'unsupported' | 'needs_modifier' | 'reserved'
export type FullscreenHotkeyCaptureResult =
type FullscreenHotkeyCaptureResult =
| { kind: 'cancel' }
| { kind: 'ignore' }
| { kind: 'ok'; hotkey: string }
| { kind: 'error'; reason: FullscreenHotkeyErrorReason; hotkey?: string }
export type FullscreenHotkeyParseResult =
type FullscreenHotkeyParseResult =
| { ok: true; hotkey: string }
| { ok: false; reason: FullscreenHotkeyErrorReason | 'invalid'; hotkey?: string }
@@ -100,11 +100,11 @@ const CODE_TO_KEY: Record<string, string> = {
ArrowRight: 'Right',
}
export function isFunctionKey(key: string): boolean {
function isFunctionKey(key: string): boolean {
return /^F(?:[1-9]|1[0-2])$/.test(key)
}
export function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean {
function isReservedFullscreenHotkey(mods: HotkeyModifiers, key: string): boolean {
return (
(mods.ctrl && mods.alt && key === 'Delete') ||
(mods.alt && (key === 'F4' || key === 'Tab')) ||
@@ -158,7 +158,7 @@ function mapEventPrimaryKey(e: HotkeyKeyEventLike): string | null {
return normalizePrimaryToken(key, EVENT_KEY_ALIASES)
}
export function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult {
function parseFullscreenHotkey(raw: string): FullscreenHotkeyParseResult {
const input = trimGoSpace(raw) || DEFAULT_FULLSCREEN_HOTKEY
const mods: HotkeyModifiers = { ctrl: false, shift: false, alt: false, win: false }
let primary = ''
+2 -2
View File
@@ -3,7 +3,7 @@ import { I18nKey, t } from '../i18n'
import { vmRefKey } from './vmRef'
import type { Config, HostReport, Locale, Task, VMListItem } from '../types'
export interface HypervisorSettingsView {
interface HypervisorSettingsView {
supported: boolean
gateEnabled: boolean
expanded: boolean
@@ -18,7 +18,7 @@ export interface HypervisorSettingsView {
showHVCINotice: boolean
}
export interface HostWHPXSummary {
interface HostWHPXSummary {
short: string
hint: string
tone: 'ok' | 'warn'
+3 -3
View File
@@ -1,13 +1,13 @@
import { LogEntry } from '../types'
export type LogLevel = 'info' | 'warn' | 'error'
type LogLevel = 'info' | 'warn' | 'error'
export interface LogLine extends LogEntry {
id: number
level: LogLevel
}
export const MAX_LOG_LINES = 2000
const MAX_LOG_LINES = 2000
// Progress no longer reaches the log: the backend turns it into tasks
// (tasks.go, "reims:task"). Levels are still guessed from the text until the
@@ -17,7 +17,7 @@ const WARN_RE = /\bwarn(ing)?\b/i
let nextId = 1
export function classify(entry: LogEntry): LogLine {
function classify(entry: LogEntry): LogLine {
const ts = typeof entry?.ts === 'string' ? entry.ts : ''
const source = typeof entry?.source === 'string' ? entry.source : ''
const line = typeof entry?.line === 'string' ? entry.line : String(entry?.line ?? '')
+1 -1
View File
@@ -2,7 +2,7 @@ import '../i18n/domains/settings.gen'
import { I18nKey, t } from '../i18n'
import { Locale, Optimization, OptimizationStatus } from '../types'
export type KernelIrqchipMode = 'auto' | 'on' | 'off'
type KernelIrqchipMode = 'auto' | 'on' | 'off'
export function findOptimization(list: Optimization[] | undefined, id: string): Optimization | undefined {
return (list ?? []).find((o) => o.id === id)
+1 -1
View File
@@ -19,7 +19,7 @@ export interface PluginFormResult {
values?: Record<string, unknown>
}
export interface PluginViewActionHandlers {
interface PluginViewActionHandlers {
invoke(method: string, params: Record<string, unknown>): Promise<unknown>
confirm(request: PluginConfirmRequest): Promise<boolean>
showForm(request: PluginFormRequest): Promise<PluginFormResult>
+2 -2
View File
@@ -1,5 +1,5 @@
export type PluginHostEvent = 'vm.stateChanged' | 'task.updated'
export type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void
type PluginHostEvent = 'vm.stateChanged' | 'task.updated'
type PluginHostEventListener = (event: PluginHostEvent, data: unknown) => void
const listeners = new Set<PluginHostEventListener>()
+1 -1
View File
@@ -1,4 +1,4 @@
export type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog'
type PluginViewLocation = 'sidebar' | 'vm.tab' | 'settings' | 'dialog'
export interface PluginViewRoute {
pluginId: string
+2 -2
View File
@@ -93,14 +93,14 @@ export function taskInstallerKey(task: Task): string {
return `${kind}:${v}`
}
export function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean {
function matchesOnlineInstallerTitle(title: string | undefined, target: string): boolean {
const want = target.trim().toLowerCase()
if (!want) return false
const norm = (title ?? '').trim().toLowerCase().replace(/^macos\s+/, '')
return norm === want || norm.replace(/\s+/g, '-') === want
}
export function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
function matchesCachedInstaller(item: CachedInstaller, task: Task): boolean {
if (!isActiveInstallerTask(task)) return false
const kind = taskInstallerKind(task)
if (!kind || kind !== item.kind) return false
+4 -39
View File
@@ -3,6 +3,7 @@
import { UI_CONTRACT_LAYOUT_OPTIONS, UI_CONTRACT_TOKENS, type UIContractSDKEvent } from '../styles/ui-contract'
import type { ActiveThemePayload, ThemeDecoration, ThemeDecorationState, TokenDeriveRule } from '../types'
import type { ThemeSDKHostActions, UIStateSnapshot } from './uiSdk'
const LEGACY_CACHE_KEY = 'reims-go-theme-tokens-v1'
const THEME_CACHE_KEY = 'reims-go-theme-tokens-v2'
@@ -26,27 +27,6 @@ interface ThemeTokenCache {
dark?: Record<string, string>
}
export interface UIStateSnapshot {
appearance: 'light' | 'dark'
motion: 'full' | 'reduced'
locale: string
dir: 'ltr' | 'rtl'
view: string
vmName: string
vmState: string
busy: boolean
hasError: boolean
sidebarCollapsed: boolean
safeMode: boolean
vms: Array<{ name: string; state: string }>
}
export interface ThemeSDKHostActions {
toggleSidebar: () => void
openSettings: () => void
focusVMWindow: (name: string) => void
}
let activeUIScriptCleanup: (() => void) | null = null
let activeUIScriptNotifier: ((snap: UIStateSnapshot) => void) | null = null
let activeUIScriptURL = ''
@@ -86,7 +66,7 @@ function decodeCSSEscapes(s: string): string {
}
/** Validates a token key+value against the UI Contract whitelist and CSS injection rules. */
export function sanitizeTokenValue(key: string, value: string): string | null {
function sanitizeTokenValue(key: string, value: string): string | null {
if (!ALLOWED_CONTRACT_TOKENS.has(key)) return null
if (typeof value !== 'string') return null
const trimmed = value.trim()
@@ -133,7 +113,7 @@ const LAYOUT_ATTRS: Record<string, string> = {
const ALLOWED_LAYOUT = new Set<string>(UI_CONTRACT_LAYOUT_OPTIONS)
/** Writes the active theme's layout options as data-layout-* attributes; null clears them. */
export function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
function applyThemeLayout(layout: Record<string, unknown> | null | undefined): void {
const el = document.documentElement
for (const [option, attr] of Object.entries(LAYOUT_ATTRS)) {
const value = layout?.[option]
@@ -143,7 +123,7 @@ export function applyThemeLayout(layout: Record<string, unknown> | null | undefi
}
/** Verifies stylesheet has balanced braces and no unclosed strings/comments so it cannot escape `@layer theme`. */
export function isBalancedThemeCSS(css: string): boolean {
function isBalancedThemeCSS(css: string): boolean {
if (css.toLowerCase().includes('</style')) return false
let depth = 0
const n = css.length
@@ -655,18 +635,3 @@ export function disposeActiveThemeAndLocaleFonts(): void {
export function notifyInteractiveThemeState(snap: UIStateSnapshot): void {
activeUIScriptNotifier?.(snap)
}
/** Plays a theme-configured sound for an event if present (fail-silent). */
export function playThemeSound(payload: ActiveThemePayload | null, eventName: string): void {
const file = payload?.theme?.sounds?.[eventName]
if (!file || !payload?.asset_base_url) return
const safe = sanitizeRelativeAssetPath(file)
if (!safe) return
try {
const audio = new Audio(payload.asset_base_url + safe)
audio.volume = 0.35
void audio.play().catch((e) => console.warn('[theme] sound playback failed:', eventName, e))
} catch (e) {
console.warn('[theme] sound init failed:', eventName, e)
}
}
+22 -2
View File
@@ -6,9 +6,29 @@ import {
type UIContractLayer, type UIContractPart, type UIContractSDKEvent, type UIContractSlot,
} from '../styles/ui-contract'
import { hideWailsGlobals } from '../wails'
import type { ThemeSDKHostActions, UIStateSnapshot } from './themeEngine'
export interface ReimsUISDK {
export interface UIStateSnapshot {
appearance: 'light' | 'dark'
motion: 'full' | 'reduced'
locale: string
dir: 'ltr' | 'rtl'
view: string
vmName: string
vmState: string
busy: boolean
hasError: boolean
sidebarCollapsed: boolean
safeMode: boolean
vms: Array<{ name: string; state: string }>
}
export interface ThemeSDKHostActions {
toggleSidebar: () => void
openSettings: () => void
focusVMWindow: (name: string) => void
}
interface ReimsUISDK {
readonly uiApi: string
/** Stable host features (e.g. `slot.sidebar.footer`); feature-detect instead of comparing versions. */
readonly features: readonly string[]
+86
View File
@@ -0,0 +1,86 @@
import { useEffect, useState } from 'react'
import type { AppUpdateInfo, Task } from '../types'
import { api } from '../wails'
export type UpdatePhase = 'none' | 'available' | 'downloading' | 'ready' | 'failed'
const CHECK_EVERY_MS = 6 * 60 * 60 * 1000
const DISMISSED_KEY = 'reims-go-update-dismissed'
interface Options {
/** Checks start once the app is up. */
ready: boolean
tasks: Record<string, Task>
runningVMCount: number
onError: (e: unknown) => void
}
/**
* The in-app update: one task per release, whose state drives the sidebar
* capsule and the About page alike.
*/
export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options) {
const [info, setInfo] = useState<AppUpdateInfo | null>(null)
const [dismissed, setDismissed] = useState<string>(() => {
try { return localStorage.getItem(DISMISSED_KEY) ?? '' } catch { return '' }
})
const [confirming, setConfirming] = useState(false)
const [installing, setInstalling] = useState(false)
// Check once the app is up, then every 6 hours, so the sidebar's update
// button shows up without opening the About page.
useEffect(() => {
if (!ready) return
const check = () => { api.CheckAppUpdate(false).then(setInfo).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
check()
const id = window.setInterval(check, CHECK_EVERY_MS)
return () => window.clearInterval(id)
}, [ready])
const task = info?.has_update
? Object.values(tasks)
.filter((x) => x.kind === 'app-update' && x.subject === info.latest)
.sort((a, b) => b.updated_at - a.updated_at)[0] ?? null
: null
const phase: UpdatePhase = !info?.has_update ? 'none'
: task?.status === 'running' ? 'downloading'
: task?.status === 'done' ? 'ready'
: task?.status === 'failed' ? 'failed'
: 'available'
const dismiss = () => {
if (!info) return
setDismissed(info.latest)
try { localStorage.setItem(DISMISSED_KEY, info.latest) } catch (e) { console.warn('[app] persist dismissed update failed:', e) }
}
/** Forgets a dismissed release and asks again, e.g. after the update channel changed. */
const recheck = async () => {
setDismissed('')
try { localStorage.removeItem(DISMISSED_KEY) } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
try {
setInfo(await api.CheckAppUpdate(true))
} catch (e) {
setInfo(null)
throw e
}
}
const download = () => { api.DownloadAppUpdate().catch(onError) }
const confirmInstall = () => {
setConfirming(false)
setInstalling(true)
api.InstallAppUpdate().catch((e) => {
setInstalling(false)
onError(e)
})
}
// Restarting leaves VMs running but pauses the host-guest bridges: say so first.
const install = () => { if (runningVMCount > 0) setConfirming(true); else confirmInstall() }
return {
info, setInfo, task, phase, installing, confirming,
shown: phase !== 'none' && !(phase === 'available' && dismissed === info?.latest),
dismiss, recheck, download, install, confirmInstall, cancelInstall: () => setConfirming(false),
}
}
+60
View File
@@ -0,0 +1,60 @@
import { useEffect, useState } from 'react'
import { events } from '../wails'
export type ThemeMode = 'light' | 'dark' | 'system'
function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => !!window.matchMedia?.(query).matches)
useEffect(() => {
const mq = window.matchMedia?.(query)
if (!mq) return
const onChange = (e: MediaQueryListEvent) => setMatches(e.matches)
mq.addEventListener('change', onChange)
return () => mq.removeEventListener('change', onChange)
}, [query])
return matches
}
/**
* Light or dark, from the user's choice, Windows and what the active theme
* supports. The choice is remembered per user.
*/
export function useAppearance(supported: 'light' | 'dark' | 'both') {
const [mode, setMode] = useState<ThemeMode>(() => {
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 = useMediaQuery('(prefers-color-scheme: dark)')
const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')
const canLight = supported !== 'dark'
const canDark = supported !== 'light'
const themeMode: ThemeMode = !canDark ? 'light' : !canLight ? 'dark' : mode
const theme: 'light' | 'dark' = themeMode === 'system' ? (sysDark ? 'dark' : 'light') : themeMode
useEffect(() => {
document.documentElement.dataset.theme = theme
events.emitTheme(theme)
}, [theme])
useEffect(() => {
document.documentElement.dataset.motion = reducedMotion ? 'reduced' : 'full'
}, [reducedMotion])
const setThemeMode = (next: ThemeMode) => {
setMode(next)
try {
if (next === 'system') localStorage.removeItem('reims-go-theme')
else localStorage.setItem('reims-go-theme', next)
} catch (e) {
console.warn('[app] persist theme preference failed:', e)
}
}
return { theme, themeMode, canLight, canDark, setThemeMode, reducedMotion }
}
+40
View File
@@ -0,0 +1,40 @@
import { useEffect, useRef, useState } from 'react'
import { OnFileDrop, OnFileDropOff } from '../wails'
/**
* Native Wails file drag-and-drop. Returns whether files are being dragged
* over the window while it accepts them.
*/
export function useFileDrop(accepts: boolean, onDrop: (paths: string[]) => void): boolean {
const [dropping, setDropping] = useState(false)
const latest = useRef({ accepts, onDrop })
latest.current = { accepts, onDrop }
useEffect(() => {
let depth = 0
const onEnter = (e: DragEvent) => {
if (!latest.current.accepts) return
if (e.dataTransfer?.types?.includes('Files')) { depth++; setDropping(true) }
}
const onLeave = () => {
depth = Math.max(0, depth - 1)
if (depth === 0) setDropping(false)
}
const onEnd = () => { depth = 0; setDropping(false) }
window.addEventListener('dragenter', onEnter)
window.addEventListener('dragleave', onLeave)
window.addEventListener('drop', onEnd)
OnFileDrop((_x, _y, paths) => {
onEnd()
if (latest.current.accepts && paths?.length) latest.current.onDrop(paths)
}, true)
return () => {
window.removeEventListener('dragenter', onEnter)
window.removeEventListener('dragleave', onLeave)
window.removeEventListener('drop', onEnd)
OnFileDropOff()
}
}, [])
return dropping
}
+55
View File
@@ -0,0 +1,55 @@
import { useEffect, useRef } from 'react'
import type { Task, VMListItem } from '../types'
import { publishPluginHostEvent } from './pluginViewEvents'
import { emitThemeEvent } from './themeEngine'
import { vmRefKey } from './vmRef'
interface Options {
view: string
selectedVM: string
vms: VMListItem[]
transitions: Record<string, string> | undefined
tasks: Record<string, Task>
}
/**
* 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.
*/
export function useThemeEvents({ view, selectedVM, vms, transitions, tasks }: Options) {
useEffect(() => {
emitThemeEvent('view.changed', { view, vm: selectedVM })
}, [view, selectedVM])
const vmStatesRef = useRef<Record<string, string> | null>(null)
useEffect(() => {
const next: Record<string, string> = {}
for (const v of vms) next[vmRefKey(v)] = 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, transitions])
const taskStatesRef = useRef<Record<string, { status: string; percent: number }> | null>(null)
useEffect(() => {
const prev = taskStatesRef.current
const next: Record<string, { status: string; percent: number }> = {}
for (const t of Object.values(tasks)) next[t.id] = { status: t.status, percent: t.percent }
taskStatesRef.current = next
if (!prev) return
for (const t of Object.values(tasks)) {
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 })
}
}, [tasks])
}
+45
View File
@@ -0,0 +1,45 @@
import { useRef, useState } from 'react'
import type { VMBusyAction } from '../types'
/**
* The actions running on each VM, keyed by VM reference (driver and name) so
* same-name VMs of different drivers never block each other. A VM runs one
* action at a time; only a force stop may join another one.
*/
export function useVMBusy() {
const [busy, setBusy] = useState<Record<string, VMBusyAction>>(() => Object.create(null))
const running = useRef(new Map<string, Map<number, VMBusyAction>>())
const nextToken = useRef(0)
/** The VM's latest action, also ahead of the next render. */
const current = (key: string): VMBusyAction | undefined => [...(running.current.get(key)?.values() ?? [])].at(-1)
const sync = () => {
const next: Record<string, VMBusyAction> = Object.create(null)
for (const key of running.current.keys()) {
const action = current(key)
if (action) next[key] = action
}
setBusy(next)
}
/** Marks the VM busy; returns a token for `end`, or null when the action has to wait. */
const begin = (key: string, action: VMBusyAction): number | null => {
const ops = running.current.get(key) ?? new Map<number, VMBusyAction>()
if (ops.size > 0 && (action !== 'forceStop' || [...ops.values()].includes('forceStop'))) return null
const token = ++nextToken.current
ops.set(token, action)
running.current.set(key, ops)
sync()
return token
}
const end = (key: string, token: number) => {
const ops = running.current.get(key)
if (!ops?.delete(token)) return
if (ops.size === 0) running.current.delete(key)
sync()
}
return { busy, current, begin, end }
}
+1 -1
View File
@@ -1,4 +1,4 @@
export interface VMRefLike {
interface VMRefLike {
name: string
driver_id?: string
}
+5 -7
View File
@@ -21,14 +21,14 @@ const statsKey = (driverID: string, name: string) => `${driverID}:${name}`
function sample(key: string, driverID: string, name: string, entryRef: Entry) {
if (entries.get(key) !== entryRef) return
const reqSeq = ++entryRef.seq
api.GetVMStatsWithDriver(driverID, name)
api.GetVMStats(driverID, name)
.then((s) => {
if (entries.get(key) !== entryRef || reqSeq <= entryRef.appliedSeq) return
entryRef.appliedSeq = reqSeq
entryRef.last = s
entryRef.subs.forEach((f) => f(s))
})
.catch((e) => console.warn('[vmStats] GetVMStatsWithDriver failed:', key, e))
.catch((e) => console.warn('[vmStats] GetVMStats failed:', key, e))
}
function schedule(key: string, driverID: string, name: string, e: Entry) {
@@ -51,13 +51,12 @@ if (typeof document !== 'undefined') {
}
/** Latest stats seen for a VM, without subscribing (e.g. when a dialog opens). */
export function latestVMStatsWithDriver(driverID: string, name: string | undefined | null): VMStats | null {
export function latestVMStats(driverID: string, name: string | undefined | null): VMStats | null {
return name ? entries.get(statsKey(driverID, name))?.last ?? null : null
}
export function latestVMStats(name: string | undefined | null): VMStats | null { return latestVMStatsWithDriver('', name) }
/** Immediately patch cached stats (if any) and re-sample a VM's stats. */
export function refreshVMStatsWithDriver(driverID: string, name: string, patch?: Partial<VMStats>) {
export function refreshVMStats(driverID: string, name: string, patch?: Partial<VMStats>) {
const key = statsKey(driverID, name)
const e = entries.get(key)
if (!e) return
@@ -68,7 +67,6 @@ export function refreshVMStatsWithDriver(driverID: string, name: string, patch?:
}
sample(key, driverID, name, e)
}
export function refreshVMStats(name: string, patch?: Partial<VMStats>) { refreshVMStatsWithDriver('', name, patch) }
/** Re-sample all currently subscribed VMs (e.g. after a tray-triggered state change). */
export function refreshSubscribedVMStats() {
@@ -82,7 +80,7 @@ export function refreshSubscribedVMStats() {
/** Live stats for one VM; `running` picks the sampling rate. Null name: none. */
export function useVMStats(driverID: string, name: string | null, running: boolean): VMStats | null {
const [stats, setStats] = useState<VMStats | null>(() => latestVMStatsWithDriver(driverID, name))
const [stats, setStats] = useState<VMStats | null>(() => latestVMStats(driverID, name))
useEffect(() => {
if (!name) { setStats(null); return }
const key = statsKey(driverID, name)
+4 -44
View File
@@ -22,7 +22,7 @@ html, body, #root {
html:lang(ja) { line-break: strict; }
html:lang(ko) { word-break: keep-all; }
:is(:lang(zh), :lang(ja), :lang(ko)) :is(em, i) { font-style: normal; font-weight: var(--fw-medium); }
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-section-label, .sidebar-brand-name, .about-hero-text h1) {
:is(:lang(zh), :lang(ja), :lang(ko)) :is(.brand, .sidebar-head, .sidebar-brand-name, .about-hero-text h1) {
letter-spacing: var(--heading-tracking, 0em);
}
@@ -166,12 +166,6 @@ h1, h2, h3, p { margin: 0; }
font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em;
color: var(--text);
}
.sidebar-section-label {
padding: 4px 10px 4px;
font-size: var(--fs-13); font-weight: var(--fw-strong); letter-spacing: -0.01em;
color: var(--text);
}
.sidebar-sep { height: 1px; background: var(--border); margin: 8px 10px 6px; }
.sidebar-brand {
display: flex; align-items: center; gap: 9px;
padding: 2px 4px 12px 8px; min-height: 34px;
@@ -321,7 +315,6 @@ h1, h2, h3, p { margin: 0; }
.page-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-4); min-height: 34px; }
.page-title { display: flex; align-items: center; gap: 10px; min-width: 0; }
.page-title h1 { font-size: 18px; font-weight: var(--fw-strong); letter-spacing: -0.015em; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.state-text { display: inline-flex; align-items: center; gap: 6px; font-size: var(--fs-12); color: var(--text-2); white-space: nowrap; }
.actions { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
/* ── macOS Tahoe "About This Mac" Hero ─────────────────── */
@@ -466,6 +459,8 @@ h1, h2, h3, p { margin: 0; }
.conn-row.conn-sub { min-height: 40px; padding-top: 0; padding-left: 28px; }
.conn-row.conn-sub::before { display: none; }
.conn-row.conn-sub .conn-main { flex: 0 0 auto; }
.conn-row.conn-drop-access { justify-content: flex-start; }
.conn-drop-access .conn-meta { white-space: normal; }
.conn-ctrl { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
.conn-ctrl-grow { flex: 1; flex-shrink: 1; min-width: 0; justify-content: flex-end; }
.conn-ctrl .btn { height: 28px; padding: 0 11px; font-size: 12.5px; }
@@ -499,24 +494,6 @@ h1, h2, h3, p { margin: 0; }
display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); min-height: 26px;
}
.tahoe-group {
background: var(--surface-1);
border: 1px solid var(--border);
border-radius: var(--r-lg);
overflow: hidden;
}
.tahoe-row {
display: flex; align-items: center; justify-content: space-between; gap: 16px;
min-height: 40px; padding: 9px 16px;
position: relative; font-size: 13.5px;
}
.tahoe-row + .tahoe-row::before {
content: ""; position: absolute; top: 0; left: 16px; right: 16px;
height: 1px; background: var(--border);
}
.tahoe-label { color: var(--text); font-weight: var(--fw-regular); display: inline-flex; align-items: center; gap: 10px; flex-shrink: 0; }
.tahoe-value { color: var(--text-2); text-align: right; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; user-select: text; }
/* ── Buttons ───────────────────────────────────────────── */
.btn {
height: 31px; padding: 0 13px;
@@ -605,12 +582,6 @@ h1, h2, h3, p { margin: 0; }
display: flex; align-items: flex-start; gap: 12px;
font-size: var(--fs-13); color: var(--text-2); line-height: 1.55;
}
.guide-step-num {
width: 22px; height: 22px; border-radius: 50%; flex-shrink: 0; margin-top: 1px;
display: grid; place-items: center;
background: var(--accent-soft); color: var(--accent-soft-text);
font-size: var(--fs-11); font-weight: var(--fw-strong); font-variant-numeric: tabular-nums;
}
.guide-step-body { flex: 1; min-width: 0; }
.steps { margin: 0; padding-left: var(--sp-6); display: flex; flex-direction: column; gap: var(--sp-1); color: var(--text-2); font-size: var(--fs-13); }
@@ -623,8 +594,6 @@ h1, h2, h3, p { margin: 0; }
.cmd-line > svg { color: var(--text-3); flex-shrink: 0; }
.cmd-line code { flex: 1; min-width: 0; font-family: var(--font-mono); font-size: var(--fs-12); color: var(--text-code); user-select: text; overflow-wrap: anywhere; }
.cmd-line-spaced { margin-top: 6px; }
.tech-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
.tech > summary {
list-style: none; cursor: pointer; display: inline-flex; align-items: center; gap: var(--sp-1);
padding: 4px 6px; margin-left: -6px;
@@ -897,8 +866,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.status-metric.high { color: var(--danger-text); }
.status-metric.high > svg { color: var(--danger-text); }
.status-metric.ok { color: var(--ok-text); }
.status-metric-dim { color: var(--text-3); }
.status-sep { color: var(--border-strong); flex-shrink: 0; }
.status-mini-bar {
display: inline-block; width: 34px; height: 4px; border-radius: 999px;
background: var(--surface-active); overflow: hidden; flex-shrink: 0;
@@ -1065,7 +1032,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.field { display: flex; flex-direction: column; gap: 6px; }
.field-spaced { margin-top: 10px; }
.field-label { font-size: var(--fs-13); font-weight: var(--fw-medium); color: var(--text-2); }
.field-row { display: grid; grid-template-columns: 1fr 1fr; gap: var(--sp-4); }
.input, .select {
width: 100%; height: 32px; padding: 0 10px;
border-radius: var(--r-md); border: 1px solid var(--border-strong);
@@ -1377,12 +1343,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
.guide-cmd { margin-top: var(--sp-2); }
/* ── Telemetry meter (GPU compositor scaleX) ───────────── */
.resource-meter {
height: 5px;
border-radius: 999px;
background: var(--surface-active);
overflow: hidden;
}
.meter-fill {
display: block;
width: 100%;
@@ -2072,7 +2032,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
}
@media (max-width: 640px) {
.source-cards, .field-row, .review-groups { grid-template-columns: 1fr; }
.source-cards, .review-groups { grid-template-columns: 1fr; }
.review-group:last-child .review-rows { grid-template-columns: max-content 1fr; }
.vm-spec-card { grid-template-columns: repeat(2, minmax(0, 1fr)); padding: 12px 14px; }
.affinity-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
-25
View File
@@ -238,31 +238,6 @@ export const UI_CONTRACT_TOKENS = [
'--titlebar-h', '--logbar-h', '--sidebar-w', '--page-max',
] as const
export const UI_CONTRACT = {
uiApi: UI_API_VERSION,
parts: [...UI_CONTRACT_PARTS],
stateAttrs: [...UI_CONTRACT_STATE_ATTRS],
itemStates: [...UI_CONTRACT_ITEM_STATES],
slots: [...UI_CONTRACT_SLOTS],
layers: [...UI_CONTRACT_LAYERS],
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS],
icons: [...UI_CONTRACT_ICONS],
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS],
sdkEvents: [...UI_CONTRACT_SDK_EVENTS],
tokens: [...UI_CONTRACT_TOKENS],
experimental: {
parts: [...UI_CONTRACT_PARTS_EXPERIMENTAL],
stateAttrs: [...UI_CONTRACT_STATE_ATTRS_EXPERIMENTAL],
itemStates: [...UI_CONTRACT_ITEM_STATES_EXPERIMENTAL],
slots: [...UI_CONTRACT_SLOTS_EXPERIMENTAL],
layers: [...UI_CONTRACT_LAYERS_EXPERIMENTAL],
layoutOptions: [...UI_CONTRACT_LAYOUT_OPTIONS_EXPERIMENTAL],
icons: [...UI_CONTRACT_ICONS_EXPERIMENTAL],
viewLocations: [...UI_CONTRACT_VIEW_LOCATIONS_EXPERIMENTAL],
sdkEvents: [...UI_CONTRACT_SDK_EVENTS_EXPERIMENTAL],
},
}
// Stable host features advertised to themes through the UI SDK.
export const UI_CONTRACT_FEATURES: readonly string[] = [
...UI_CONTRACT_SLOTS.map((s) => `slot.${s}`),
+34 -23
View File
@@ -16,11 +16,9 @@ export type Config = Model<config.Config> & {
export type DisplayInfo = host.DisplayInfo
export type DisplayPreset = host.DisplayPreset
export type AudioInfo = host.AudioInfo
export type WHPXCapabilities = host.WHPXCapabilities
export type LogicalCPUInfo = host.LogicalCPUInfo
export type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
type GPUCompat = 'supported' | 'warn' | 'unsupported' | 'unknown'
export type GPUInfo = Omit<Model<host.GPUInfo>, 'compat'> & {
kind: 'discrete' | 'integrated' | 'virtual' | 'unknown'
@@ -41,16 +39,15 @@ export type HostReport = Omit<Model<host.Report>, 'gpus' | 'recommended_gpu'> &
recommended_gpu?: GPUInfo
}
export type RuntimeManifest = Model<runtime.Manifest>
export type InstalledRuntime = Model<runtime.Installed>
export type RemoteRuntime = Model<runtime.Remote> & {
channel: 'stable' | 'alpha'
}
export type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
export type VMPhase = 'normal' | 'installer' | 'recovery'
export type GuestOSInfo = Model<driver.GuestOSInfo>
type VMState = 'running' | 'stopped' | 'suspended' | 'broken' | 'driver_unavailable'
type VMPhase = 'normal' | 'installer' | 'recovery'
type GuestOSInfo = Model<driver.GuestOSInfo>
export type VMEndpoint = Model<driver.VMEndpoint> & {
kind: 'ssh' | 'wsl' | 'rdp' | 'vmconnect' | 'adb' | (string & {})
}
@@ -83,7 +80,6 @@ export type AppState = Omit<Model<app.AppState>, 'config' | 'host' | 'optimizati
}
export type AppUpdateInfo = version.UpdateInfo
export type SuspendInfo = reims.SuspendInfo
export type VMDetail = reims.VMDetail
export type SMBIOSIdentity = opencore.SMBIOSIdentity
export type VMStats = app.VMStats
@@ -126,7 +122,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
displays: number
}
export type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
type TaskStatus = 'running' | 'done' | 'failed' | 'canceled'
export type InstallerKind = 'offline' | 'online'
export type InstallerPhase = 'queued' | 'downloading'
@@ -155,23 +151,15 @@ export type PermissionSpec = plugin.PermissionSpec
export type SettingProperty = plugin.SettingProperty
export type SettingsSchema = plugin.SettingsSchema
export type PluginInfo = plugin.PluginInfo
export type DoctorFinding = plugin.DoctorFinding
export type ScanFinding = plugin.ScanFinding
export type ExecutableFile = plugin.ExecutableFile
export type CapabilityItem = plugin.CapabilityItem
export type ScanReport = plugin.ScanReport
export type MarketEntry = plugin.MarketEntry
export type MarketWithdrawal = plugin.MarketWithdrawal
export type MarketCatalogItem = plugin.MarketCatalogItem
export type MarketBrowseResult = plugin.MarketBrowseResult
export type TokenDeriveRule = plugin.TokenDeriveRule
export type ThemeScheme = plugin.ThemeScheme
export type ThemeDecoration = plugin.ThemeDecoration
export type ThemeDecorationState = plugin.ThemeDecorationState
export type ThemeContribution = plugin.ThemeContribution
export type CustomThemeScheme = plugin.CustomThemeScheme
export type ActiveThemePayload = plugin.ActiveThemePayload
export interface ResolvedLocaleFont {
interface ResolvedLocaleFont {
family: string
url: string
weight?: string
@@ -184,18 +172,41 @@ export type ResolvedLocalePack = Model<plugin.ResolvedLocalePack> & {
plugin_messages?: Record<string, Record<string, string>>
fonts?: ResolvedLocaleFont[]
}
export type MenuContribution = plugin.MenuContribution
export type VMCardContribution = plugin.VMCardContribution
export type PanelContribution = plugin.PanelContribution
export type ViewContribution = plugin.ViewContribution
export type ImageSourceContribution = plugin.ImageSourceContribution
export type StatusItemContribution = plugin.StatusItemContribution
export type PluginUIContributions = app.PluginUIContributions
export type DriverSummary = driver.DriverSummary
export type DriverCreateRequest = driver.CreateRequest
export type RuntimeKindSpec = runtime.KindSpec
/** A "reims:log" event (internal/app/app.go emitLog); not a Go struct, so not generated. */
export type VMAction =
| 'start'
| 'suspend'
| 'resume'
| 'discardSuspend'
| 'stop'
| 'forceStop'
| 'restart'
| 'focus'
| 'fullscreen'
| 'screenshot'
| 'eject'
| 'finishInstall'
| 'enterRecovery'
| 'attachInstaller'
| 'attachGuestTools'
| 'detachGuestTools'
| 'openSharedFolder'
| 'upgradeNVMe'
| 'exportDiagnostics'
| 'cloneVM'
| 'type'
| 'sendText'
| 'delete'
| 'openFolder'
export type VMBusyAction = VMAction | 'pluginCommand'
export interface LogEntry {
ts: string
source: string
+1 -1
View File
@@ -92,7 +92,7 @@ export const IconButton = React.forwardRef<HTMLButtonElement, IconButtonProps>(
)
IconButton.displayName = 'IconButton'
export type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
type StatusKind = 'running' | 'stopped' | 'suspended' | 'busy' | 'broken' | 'warn'
export function statusKind(state: string): StatusKind {
if (state === 'running') return 'running'
+73
View File
@@ -0,0 +1,73 @@
import * as Menu from '@radix-ui/react-dropdown-menu'
import { Ellipsis } from 'lucide-react'
import React, { useRef, useState } from 'react'
import { localeDir } from '../i18n'
import { hasVisibleDialog } from '../lib/dialogState'
import type { Locale } from '../types'
import { Tip } from './controls'
interface Props {
locale: Locale
label: string
small?: boolean
/** Runs when the menu closes; returns true after moving focus itself. */
onCloseFocus?: () => boolean
/** The menu's items. */
children: React.ReactNode
}
/**
* An ellipsis button with a menu. Focus returns to the button only after
* keyboard use: after a click it would pop the button's tooltip, and an item
* that opened a dialog needs the focus there.
*/
export const ActionMenu: React.FC<Props> = ({ locale, label, small, onCloseFocus, children }) => {
const [open, setOpen] = useState(false)
const openedByPointer = useRef(false)
const closedByPointer = useRef(false)
return (
<Menu.Root
dir={localeDir(locale)}
open={open}
onOpenChange={(next) => {
if (next) closedByPointer.current = false
setOpen(next)
}}
>
<Tip label={label} disabled={open}>
<Menu.Trigger asChild>
<button
type="button"
className={`icon-btn rg-p-icon-button${small ? ' sm' : ''}`}
aria-label={label}
onPointerDown={() => { openedByPointer.current = true }}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ' || e.key === 'ArrowDown') openedByPointer.current = false
}}
>
<Ellipsis size={small ? 14 : 15} />
</button>
</Menu.Trigger>
</Tip>
<Menu.Portal>
<Menu.Content
className="menu rg-p-menu"
align="end"
sideOffset={4}
collisionPadding={8}
onPointerDownCapture={(e) => {
if (!(e.target as HTMLElement | null)?.closest('[data-disabled]')) closedByPointer.current = true
}}
onKeyDownCapture={() => { closedByPointer.current = false }}
onPointerDownOutside={() => { closedByPointer.current = true }}
onCloseAutoFocus={(e) => {
if (onCloseFocus?.() || openedByPointer.current || closedByPointer.current || hasVisibleDialog()) e.preventDefault()
}}
>
{children}
</Menu.Content>
</Menu.Portal>
</Menu.Root>
)
}
+13 -12
View File
@@ -89,7 +89,7 @@ export const Switch: React.FC<{ checked: boolean; onChange: (v: boolean) => void
</label>
)
export interface SegOption<V> {
interface SegOption<V> {
value: V
label: string
disabled?: boolean
@@ -108,18 +108,20 @@ export function Segmented<V extends string | number>({ options, value, onChange,
wide?: boolean
}) {
const box = useRef<HTMLDivElement>(null)
const [thumb, setThumb] = useState<{ x: number; w: number } | null>(null)
const [thumb, setThumb] = useState<{ x: number; w: number; value: V } | null>(null)
const measure = () => {
const el = box.current?.querySelector<HTMLElement>('[aria-checked="true"]')
const next = el ? { x: el.offsetLeft, w: el.offsetWidth } : null
setThumb((prev) => {
if (!prev && !next) return prev
if (prev && next && prev.x === next.x && prev.w === next.w) return prev
return next
// Options disabled while something is saving keep the highlight in place.
if (!el || value === undefined) return prev?.value === value ? prev : null
if (prev?.value === value && prev.x === el.offsetLeft && prev.w === el.offsetWidth) return prev
return { x: el.offsetLeft, w: el.offsetWidth, value }
})
}
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}`).join('\x1e')
const latestMeasure = useRef(measure)
latestMeasure.current = measure
const optionsSig = options.map((o) => `${String(o.value)}\x1f${o.label}\x1f${!!o.disabled}`).join('\x1e')
const docDir = typeof document !== 'undefined' ? document.documentElement.dir : ''
// eslint-disable-next-line react-hooks/exhaustive-deps
useLayoutEffect(measure, [value, optionsSig, wide, docDir])
@@ -130,7 +132,7 @@ export function Segmented<V extends string | number>({ options, value, onChange,
if (raf) cancelAnimationFrame(raf)
raf = requestAnimationFrame(() => {
raf = 0
measure()
latestMeasure.current()
})
})
ro.observe(box.current)
@@ -138,7 +140,6 @@ export function Segmented<V extends string | number>({ options, value, onChange,
if (raf) cancelAnimationFrame(raf)
ro.disconnect()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const onKey = (e: React.KeyboardEvent) => {
@@ -247,7 +248,7 @@ function thinMarks(marks: RangeMark[], min: number, max: number, gap = 9): Range
return out
}
export interface RangeMark {
interface RangeMark {
value: number
label: string
}
@@ -326,7 +327,7 @@ export const RangeField: React.FC<RangeProps> = ({ value, min, max, step = 1, un
)
}
export interface CardOption<V> {
interface CardOption<V> {
value: V
title: string
sub?: string
@@ -362,7 +363,7 @@ export function OptionCards<V extends string>({ options, value, onChange, label,
)
}
export interface PopupOption<V> {
interface PopupOption<V> {
value: V
label: string
/** Secondary text drawn after the label in grey, e.g. a build number. */
+5 -4
View File
@@ -5,7 +5,8 @@
import React, { createContext, useContext, useEffect, useMemo, useState } from 'react'
import { createPortal } from 'react-dom'
import { locText } from '../i18n'
import { matchDecorationState, themeAssetURL, type UIStateSnapshot } from '../lib/themeEngine'
import { matchDecorationState, themeAssetURL } from '../lib/themeEngine'
import type { UIStateSnapshot } from '../lib/uiSdk'
import { UI_CONTRACT_ICONS, UI_CONTRACT_LAYERS, UI_CONTRACT_SLOTS, type UIContractIcon } from '../styles/ui-contract'
import type { ActiveThemePayload, Locale, ThemeDecoration } from '../types'
@@ -13,7 +14,7 @@ const DEFAULT_BRAND_MARK = '/logo.svg'
const KNOWN_ICONS = new Set<string>(UI_CONTRACT_ICONS)
const KNOWN_TARGETS = new Set<string>([...UI_CONTRACT_SLOTS, ...UI_CONTRACT_LAYERS])
export interface ThemeVisuals {
interface ThemeVisuals {
brandMarkURL: string
icons: Partial<Record<UIContractIcon, string>>
}
@@ -25,7 +26,7 @@ function isBuiltin(payload: ActiveThemePayload | null): boolean {
return !payload?.theme || payload.theme_id === 'builtin.theme.default'
}
export function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
function resolveThemeVisuals(payload: ActiveThemePayload | null): ThemeVisuals {
if (isBuiltin(payload)) return EMPTY
const th = payload!.theme!
const icons: Partial<Record<UIContractIcon, string>> = {}
@@ -41,7 +42,7 @@ export const ThemeVisualsProvider: React.FC<{ payload: ActiveThemePayload | null
return <ThemeVisualsContext.Provider value={value}>{children}</ThemeVisualsContext.Provider>
}
export function useThemeVisuals(): ThemeVisuals {
function useThemeVisuals(): ThemeVisuals {
return useContext(ThemeVisualsContext)
}
+17 -1
View File
@@ -3,6 +3,8 @@ import { Check, CircleCheck, CircleX, X } from 'lucide-react'
import { HostIcon } from './themeVisuals'
import { emitThemeEvent } from '../lib/themeEngine'
import React, { useCallback, useState } from 'react'
import { parseAppError, t } from '../i18n'
import type { Locale } from '../types'
import { IconButton } from './controls'
export interface ToastInput {
@@ -16,7 +18,21 @@ export interface ToastInput {
action?: { label: string; onClick: () => void }
}
export interface ToastItem extends ToastInput {
/** An error toast: the message, with the raw details folded for bug reports. */
export function errorToast(locale: Locale, title: string, e: unknown): ToastInput {
const parsed = parseAppError(e)
return {
kind: 'error',
title,
description: parsed.summary,
errorCode: parsed.code,
rawDetail: parsed.rawDetail,
detailsLabel: t(locale, 'errRawDetailsToggle'),
copyDetailsLabel: t(locale, 'errCopyDetails'),
}
}
interface ToastItem extends ToastInput {
id: number
}
+5 -6
View File
@@ -17,7 +17,7 @@ import {
import type {
ActiveThemePayload, AppState, CachedInstaller, DataRootChoice, DriverSummary,
LogEntry, MarketBrowseResult, PluginInfo, PluginUIContributions, RemoteRuntime,
RuntimeKindSpec, ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
ScanReport, Task, VMAffinityStatus, VMAffinityUpdate, VMInfo, VMNetworkSettings, VMNetworkPlan, VMKeymapStatus, VMKeymapUpdate,
} from './types'
type AnyFn = (...args: never[]) => unknown
@@ -155,10 +155,8 @@ export const api = {
InstallNpcap: boundGo.InstallNpcap as () => Promise<void>,
GetState: boundGo.GetState as () => Promise<AppState>,
GetTasks: boundGo.GetTasks as () => Promise<Task[]>,
GetVMAffinity: boundGo.GetVMAffinity as (name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMAffinityWithDriver: boundGo.GetVMAffinityWithDriver as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinityWithDriver: boundGo.SetVMAffinityWithDriver as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMAffinity: boundGo.GetVMAffinity as (driverID: string, name: string) => Promise<VMAffinityStatus>,
SetVMAffinity: boundGo.SetVMAffinity as (driverID: string, name: string, req: VMAffinityUpdate) => Promise<VMAffinityStatus>,
GetVMKeymap: boundGo.GetVMKeymap as (name: string) => Promise<VMKeymapStatus>,
GetVMInfo: boundGo.GetVMInfo as (driverID: string, name: string) => Promise<VMInfo>,
SetVMKeymap: boundGo.SetVMKeymap as (name: string, req: VMKeymapUpdate) => Promise<VMKeymapStatus>,
@@ -174,7 +172,6 @@ export const api = {
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
ListRuntimeKinds: boundGo.ListRuntimeKinds as () => Promise<RuntimeKindSpec[] | null>,
}
export interface MarketInstallProgress {
@@ -195,6 +192,8 @@ export interface ElevationPrompt {
needs_logoff?: boolean
}
export const DROP_NETWORK_VOLUMES_DENIED = 'Network Volumes permission denied'
export const events = {
onHostDrop: (cb: (payload: { vm: string; drop_id: string; delivered: string[]; skipped?: string[]; mode: string }) => void) => eventsOn('reims:host-drop', cb),
onHostDropAck: (cb: (payload: { vm: string; drop_id: string; status: string; target_kind?: string; target_label?: string; placed_names?: string[]; error?: string }) => void) => eventsOn('reims:host-drop-ack', cb),
+3 -1
View File
@@ -11,7 +11,9 @@
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true
},
"include": ["src"]
}
+42 -122
View File
@@ -34,23 +34,15 @@ export function CheckAppUpdate(arg1:boolean):Promise<version.UpdateInfo>;
export function CheckDataRoot(arg1:string):Promise<app.DataRootCheck>;
export function CloneVMCoW(arg1:string,arg2:string):Promise<void>;
export function CloneVMCoW(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CloneVMCoWWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CompactVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function CompactVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function CompactVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function CompleteSetup(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string):Promise<void>;
export function CopyVMScreenshot(arg1:string,arg2:string):Promise<void>;
export function CopyVMScreenshotWithDriver(arg1:string,arg2:string):Promise<void>;
export function CreateSnapshot(arg1:string,arg2:string):Promise<void>;
export function CreateSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CreateSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
export function CreateVM(arg1:reims.CreateOpts):Promise<void>;
@@ -60,13 +52,9 @@ export function DeleteCustomThemeScheme(arg1:string):Promise<void>;
export function DeleteInstaller(arg1:string):Promise<void>;
export function DeleteSnapshot(arg1:string,arg2:string):Promise<void>;
export function DeleteSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
export function DeleteSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function DeleteVM(arg1:string,arg2:boolean):Promise<void>;
export function DeleteVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function DeleteVM(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function DeliverFileToGuest(arg1:string):Promise<string>;
@@ -76,13 +64,7 @@ export function DetachGuestTools(arg1:string):Promise<void>;
export function DisablePlugin(arg1:string):Promise<void>;
export function DiscardSuspend(arg1:string):Promise<void>;
export function DiscardSuspendWithDriver(arg1:string,arg2:string):Promise<void>;
export function DismissTask(arg1:string):Promise<void>;
export function DoctorPlugin(arg1:string):Promise<Array<plugin.DoctorFinding>>;
export function DiscardSuspend(arg1:string,arg2:string):Promise<void>;
export function DownloadAndAttachOnlineRecovery(arg1:string,arg2:string):Promise<string>;
@@ -90,25 +72,17 @@ export function DownloadAppUpdate():Promise<string>;
export function DownloadInstaller(arg1:string):Promise<string>;
export function EjectInstaller(arg1:string):Promise<void>;
export function EjectInstallerWithDriver(arg1:string,arg2:string):Promise<void>;
export function EjectInstaller(arg1:string,arg2:string):Promise<void>;
export function EnablePlugin(arg1:string,arg2:boolean):Promise<void>;
export function EnableWHPX():Promise<void>;
export function EnterRecovery(arg1:string):Promise<void>;
export function ExportDiagnostics(arg1:string):Promise<string>;
export function ExportDiagnosticsWithDriver(arg1:string,arg2:string):Promise<string>;
export function ExportDiagnostics(arg1:string,arg2:string):Promise<string>;
export function FinishInstall(arg1:string):Promise<void>;
export function FocusVMWindow(arg1:string):Promise<void>;
export function FocusVMWindowWithDriver(arg1:string,arg2:string):Promise<void>;
export function FocusVMWindow(arg1:string,arg2:string):Promise<void>;
export function ForceQuitApp():Promise<void>;
@@ -136,17 +110,16 @@ export function GetStorageBreakdown():Promise<app.StorageBreakdown>;
export function GetTasks():Promise<Array<app.Task>>;
export function GetVMAffinity(arg1:string):Promise<app.VMAffinityStatus>;
export function GetVMAffinityWithDriver(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
export function GetVMAffinity(arg1:string,arg2:string):Promise<app.VMAffinityStatus>;
export function GetVMDetail(arg1:string):Promise<reims.VMDetail>;
export function GetVMDisplayWithDriver(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
export function GetVMDisplay(arg1:string,arg2:string):Promise<app.VMDisplayStatus>;
export function GetVMDriveShareSettings(arg1:string):Promise<app.DriveShareSettings>;
export function GetVMEndpointCommandWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
export function GetVMEndpointCommand(arg1:string,arg2:string,arg3:string):Promise<string>;
export function GetVMInfo(arg1:string,arg2:string):Promise<driver.VMInfo>;
export function GetVMKeymap(arg1:string):Promise<app.VMKeymapStatus>;
@@ -157,30 +130,21 @@ export function GetVMNetworkPlan(arg1:string,arg2:string,arg3:string):Promise<ap
export function GetVMNetworkSettings(arg1:string):Promise<app.VMNetworkSettings>;
export function GetVMNote(arg1:string):Promise<string>;
export function GetVMNoteWithDriver(arg1:string,arg2:string):Promise<string>;
export function GetVMNote(arg1:string,arg2:string):Promise<string>;
export function GetVMPluginSettings(arg1:string):Promise<Record<string, Record<string, any>>>;
export function GetVMSMBIOS(arg1:string):Promise<opencore.SMBIOSIdentity>;
export function GetVMSSHUser(arg1:string):Promise<string>;
export function GetVMSSHUserWithDriver(arg1:string,arg2:string):Promise<string>;
export function GetVMSSHUser(arg1:string,arg2:string):Promise<string>;
export function GetVMSharedFolderSettings(arg1:string):Promise<app.SharedFolderSettings>;
export function GetVMStats(arg1:string):Promise<app.VMStats>;
export function GetVMStats(arg1:string,arg2:string):Promise<app.VMStats>;
export function GetVMStatsWithDriver(arg1:string,arg2:string):Promise<app.VMStats>;
export function GetVMThumbnail(arg1:string,arg2:string):Promise<app.VMThumbnail>;
export function GetVMThumbnail(arg1:string):Promise<app.VMThumbnail>;
export function GetVMThumbnailWithDriver(arg1:string,arg2:string):Promise<app.VMThumbnail>;
export function GetVMTimezone(arg1:string):Promise<app.VMTimezoneStatus>;
export function GetVMTimezoneWithDriver(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
export function GetVMTimezone(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
export function InspectPluginArchive(arg1:string):Promise<plugin.ScanReport>;
@@ -212,38 +176,29 @@ export function ListPlugins():Promise<Array<plugin.PluginInfo>>;
export function ListRemoteRuntimes():Promise<Array<runtime.Remote>>;
export function ListRuntimeKinds():Promise<Array<runtime.KindSpec>>;
export function ListSnapshots(arg1:string):Promise<Array<driver.DiskSnapshot>>;
export function ListSnapshotsWithDriver(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
export function ListSnapshots(arg1:string,arg2:string):Promise<Array<driver.DiskSnapshot>>;
export function OpenProcessorScheduling():Promise<void>;
export function OpenQQGroup():Promise<void>;
export function OpenSSHTerminal(arg1:string,arg2:string):Promise<void>;
export function OpenSSHTerminalWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenSSHTerminal(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenSharedFolder(arg1:string):Promise<void>;
export function OpenURL(arg1:string):Promise<void>;
export function OpenVMEndpointWithDriver(arg1:string,arg2:string,arg3:string,arg4:string):Promise<void>;
export function OpenVMEndpoint(arg1:string,arg2:string,arg3:string,arg4:string):Promise<void>;
export function OpenVMFolder(arg1:string):Promise<void>;
export function OpenVSCodeSSH(arg1:string,arg2:string):Promise<void>;
export function OpenVSCodeSSHWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenVSCodeSSH(arg1:string,arg2:string,arg3:string):Promise<void>;
export function OpenWindowsCoreIsolation():Promise<void>;
export function OpenWindowsSecurityExclusions():Promise<void>;
export function OptimizeVMDisk(arg1:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDiskWithDriver(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function OptimizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskCompactResult>;
export function PanelBridgeCall(arg1:string,arg2:string,arg3:Record<string, any>):Promise<any>;
@@ -261,9 +216,7 @@ export function QuitApp():Promise<void>;
export function ReadPluginLog(arg1:string):Promise<string>;
export function ReadVMLogs(arg1:string,arg2:boolean):Promise<string>;
export function ReadVMLogsWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<string>;
export function ReadVMLogs(arg1:string,arg2:string,arg3:boolean):Promise<string>;
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
@@ -275,23 +228,15 @@ export function ReopenDataRoot(arg1:boolean):Promise<dataroot.Status>;
export function RequestClose():Promise<void>;
export function ResizeVMDisk(arg1:string,arg2:string):Promise<driver.DiskResizeResult>;
export function ResizeVMDiskWithDriver(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
export function ResizeVMDisk(arg1:string,arg2:string,arg3:string):Promise<driver.DiskResizeResult>;
export function ResolveElevationRequest(arg1:string,arg2:boolean):Promise<void>;
export function RestartVM(arg1:string):Promise<void>;
export function RestartVM(arg1:string,arg2:string):Promise<void>;
export function RestartVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string,arg3:string):Promise<void>;
export function RestoreSnapshot(arg1:string,arg2:string):Promise<void>;
export function RestoreSnapshotWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function ResumeVM(arg1:string):Promise<void>;
export function ResumeVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function ResumeVM(arg1:string,arg2:string):Promise<void>;
export function SaveCustomThemeScheme(arg1:plugin.CustomThemeScheme):Promise<void>;
@@ -327,62 +272,39 @@ export function SetRuntimeChannel(arg1:string):Promise<void>;
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
export function SetVMAffinity(arg1:string,arg2:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMAffinity(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMAffinityWithDriver(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
export function SetVMDisplayWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
export function SetVMDriveShareSettings(arg1:string,arg2:boolean,arg3:Array<string>):Promise<app.DriveShareSettings>;
export function SetVMKeymap(arg1:string,arg2:app.VMKeymapUpdate):Promise<app.VMKeymapStatus>;
export function SetVMNote(arg1:string,arg2:string):Promise<void>;
export function SetVMNoteWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMNote(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string):Promise<void>;
export function SetVMSSHUserWithDriver(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSSHUser(arg1:string,arg2:string,arg3:string):Promise<void>;
export function SetVMSharedFolderMode(arg1:string,arg2:string,arg3:string):Promise<app.SharedFolderSettings>;
export function SetVMTimezone(arg1:string,arg2:string):Promise<app.VMTimezoneStatus>;
export function SetVMTimezone(arg1:string,arg2:string,arg3:string):Promise<app.VMTimezoneStatus>;
export function SetVMTimezoneWithDriver(arg1:string,arg2:string,arg3:string):Promise<app.VMTimezoneStatus>;
export function StartVM(arg1:string,arg2:string):Promise<void>;
export function ShowMainWindow():Promise<void>;
export function StartVM(arg1:string):Promise<void>;
export function StartVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function StopVM(arg1:string,arg2:boolean):Promise<void>;
export function StopVMWithDriver(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function StopVM(arg1:string,arg2:string,arg3:boolean):Promise<void>;
export function SuggestDataRoots():Promise<Array<app.DataRootChoice>>;
export function SuggestLanguagePack():Promise<plugin.MarketCatalogItem>;
export function SuspendVM(arg1:string):Promise<void>;
export function SuspendVMWithDriver(arg1:string,arg2:string):Promise<void>;
export function SuspendVM(arg1:string,arg2:string):Promise<void>;
export function TestHostDNS(arg1:guesttools.HostDNSConfig):Promise<guesttools.HostDNSTestResult>;
export function ToggleBorderless(arg1:string,arg2:boolean):Promise<void>;
export function ToggleVMFullscreen(arg1:string,arg2:string):Promise<boolean>;
export function ToggleVMFullscreen(arg1:string):Promise<boolean>;
export function TypeClipboard(arg1:string,arg2:string):Promise<number>;
export function ToggleVMFullscreenWithDriver(arg1:string,arg2:string):Promise<boolean>;
export function TypeClipboard(arg1:string):Promise<number>;
export function TypeClipboardWithDriver(arg1:string,arg2:string):Promise<number>;
export function TypeText(arg1:string,arg2:string):Promise<number>;
export function TypeTextWithDriver(arg1:string,arg2:string,arg3:string):Promise<number>;
export function TypeText(arg1:string,arg2:string,arg3:string):Promise<number>;
export function UpgradeDiskToNVMe(arg1:string):Promise<void>;
@@ -392,6 +314,4 @@ export function ValidateCreate(arg1:reims.CreateOpts):Promise<Array<reims.Valida
export function ValidateSet(arg1:reims.SetOpts):Promise<Array<reims.ValidationIssue>>;
export function WriteSSHConfig(arg1:string,arg2:string):Promise<string>;
export function WriteSSHConfigWithDriver(arg1:string,arg2:string,arg3:string):Promise<string>;
export function WriteSSHConfig(arg1:string,arg2:string,arg3:string):Promise<string>;
Loaded 100 of 344 files, more files were not shown because too many files have changed in this diff. Show more