Compare commits
46
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2f7f33b53f | ||
|
|
714070f5ac | ||
|
|
33253318c4 | ||
|
|
bd4e85af1a | ||
|
|
668b93f493 | ||
|
|
95236d624c | ||
|
|
652bf50e8d | ||
|
|
7529171600 | ||
|
|
f4395a1f28 | ||
|
|
87e7ac8774 | ||
|
|
bd7c9abaa3 | ||
|
|
3d5c6cb826 | ||
|
|
7e1afcfd9b | ||
|
|
a4fb1c6db6 | ||
|
|
04f0d8d096 | ||
|
|
3837e72644 | ||
|
|
3e5b0d7e6c | ||
|
|
1433602f14 | ||
|
|
ed1a0ba254 | ||
|
|
d40327e724 | ||
|
|
a11d08cb9b | ||
|
|
3020137a9e | ||
|
|
2658949f05 | ||
|
|
b3b66c9306 | ||
|
|
fc3f35f6af | ||
|
|
0830bf5856 | ||
|
|
5aca93a862 | ||
|
|
717b324cf2 | ||
|
|
fcff64669f | ||
|
|
d41b29e345 | ||
|
|
2031a27627 | ||
|
|
1eb06a404f | ||
|
|
6fa1b5853b | ||
|
|
c5c5922acb | ||
|
|
98763160f6 | ||
|
|
781f129fc1 | ||
|
|
14cb98255a | ||
|
|
9d06e8db05 | ||
|
|
4053ffb60c | ||
|
|
69ec8e1cbf | ||
|
|
8d7bcd8fbd | ||
|
|
c40b8aafdc | ||
|
|
43291667a6 | ||
|
|
33e28520b7 | ||
|
|
d5841f0f70 | ||
|
|
d74868589d |
No files matched your search
+1
-1
@@ -10,7 +10,7 @@
|
||||
{
|
||||
"name": "wails-dev-firstrun",
|
||||
"runtimeExecutable": "pwsh",
|
||||
"runtimeArgs": ["-NoProfile", "-Command", "$env:REIMS_GO_FIRST_RUN='1'; $env:REIMS_GO_LOCATION_FILE='D:/Build/Temp/reims-firstrun/location.json'; wails dev -browser=false"],
|
||||
"runtimeArgs": ["-NoProfile", "-Command", "New-Item -ItemType Directory -Force .debug/runs/reims-firstrun | Out-Null; $env:REIMS_GO_FIRST_RUN='1'; $env:REIMS_GO_LOCATION_FILE='.debug/runs/reims-firstrun/location.json'; wails dev -browser=false"],
|
||||
"port": 34115
|
||||
}
|
||||
]
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
## 变更说明
|
||||
|
||||
- 用户可观察的行为变化
|
||||
- 实现归属仓库与关联的跨仓提交或运行时版本(纯本仓改动可填无)
|
||||
- 变更位置与责任仓库,附上游证据(仓库、commit、文件及行号;纯本仓改动可填无)
|
||||
- 跨仓依赖:关联 PR、合并顺序与运行时要求(无跨仓依赖可填无)
|
||||
- 旧版或缺失运行时下的兼容与降级表现(不涉及运行时可填不适用)
|
||||
|
||||
## 模型与 Agent 申报
|
||||
## 模型与编程工具申报
|
||||
|
||||
<!-- 请逐行填写参与代码编写的实际模型和 Agent。模型格式为 model: 提供方/模型名称,Agent 格式为 agent: 名称。 -->
|
||||
<!-- 请逐行填写参与代码编写的实际模型与编程工具,不要放在代码块或 HTML 注释内。
|
||||
模型格式:model: 提供方/模型名称(例如 model: deepseek/deepseek-R1 或 model: google/Gemini 4 Neon)
|
||||
编程工具格式:tool: 名称(例如 tool: Cursor、tool: Claude Code、tool: WorkBuddy、tool: 豆包;兼容旧的 agent: 写法) -->
|
||||
|
||||
## 验证记录
|
||||
|
||||
|
||||
@@ -52,9 +52,6 @@ jobs:
|
||||
cache: pnpm
|
||||
cache-dependency-path: frontend/pnpm-lock.yaml
|
||||
|
||||
- name: Test GitHub automation scripts
|
||||
run: node --test ".github/scripts/*.test.mjs"
|
||||
|
||||
- name: Verify CHANGELOG.md matches current version
|
||||
shell: pwsh
|
||||
run: |
|
||||
|
||||
@@ -66,4 +66,4 @@ jobs:
|
||||
PR_REVIEW_LLM_MODEL: ${{ vars.PR_REVIEW_LLM_MODEL || 'glm-5.4' }}
|
||||
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/code-diagnosis.mjs
|
||||
run: node scripts/ci/code-diagnosis.mjs
|
||||
@@ -34,7 +34,7 @@ jobs:
|
||||
ref: ${{ github.workflow_sha }}
|
||||
persist-credentials: false
|
||||
sparse-checkout-cone-mode: false
|
||||
sparse-checkout: /.github/scripts/
|
||||
sparse-checkout: /scripts/ci/
|
||||
- name: Triage issue
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
@@ -43,4 +43,4 @@ jobs:
|
||||
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
|
||||
run: node scripts/ci/issue-triage.mjs
|
||||
@@ -1,4 +1,4 @@
|
||||
name: PR Model and Agent Declaration
|
||||
name: PR Model and Coding Tool Declaration
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
@@ -20,8 +20,8 @@ jobs:
|
||||
ref: ${{ github.workflow_sha }}
|
||||
persist-credentials: false
|
||||
sparse-checkout-cone-mode: false
|
||||
sparse-checkout: /.github/scripts/pr-model.mjs
|
||||
- name: Check the model and agent declarations
|
||||
sparse-checkout: /scripts/ci/pr-model.mjs
|
||||
- name: Check the model and coding tool declarations
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: node .github/scripts/pr-model.mjs
|
||||
run: node scripts/ci/pr-model.mjs
|
||||
@@ -46,8 +46,8 @@ jobs:
|
||||
persist-credentials: false
|
||||
sparse-checkout-cone-mode: false
|
||||
sparse-checkout: |
|
||||
/.github/scripts/pr-review.mjs
|
||||
/.github/scripts/pr-review-language.mjs
|
||||
/scripts/ci/pr-review.mjs
|
||||
/scripts/ci/pr-review-language.mjs
|
||||
/.opencodereview/rule.json
|
||||
/docs/pr-review-guidelines.md
|
||||
/docs/design-guidelines.md
|
||||
@@ -108,4 +108,4 @@ jobs:
|
||||
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
|
||||
run: node scripts/ci/pr-review.mjs
|
||||
@@ -2,6 +2,7 @@
|
||||
"exclude": [
|
||||
"frontend/wailsjs/**",
|
||||
"frontend/src/i18n/domains/*.gen.ts",
|
||||
"frontend/src/components/*.gen.ts",
|
||||
"go.sum",
|
||||
"**/package-lock.json",
|
||||
"**/pnpm-lock.yaml"
|
||||
|
||||
@@ -40,11 +40,11 @@ Reims-Go 发布的便携运行时基于团队独立维护的 `reims-go/reims-vgp
|
||||
7. 捕获异常后必须执行上报错误、记录诊断告警或回退状态等明确处理,前端测试会自动拦截空异常捕获块。
|
||||
8. `docs/` 只存放当前生效且删掉会影响编码的文档,采用主谓清晰的简单句说明现状,不写本机路径、排期历史、内部变量函数名或「粗体标题加冒号」的口号句式。
|
||||
|
||||
## PR 模型与 Agent 申报
|
||||
## PR 模型与编程工具申报
|
||||
|
||||
提交新 PR 时,请在描述中逐行如实申报参与代码编写的模型和 Agent。模型使用 `model: 提供方/模型名称`,例如 `model: deepseek/deepseek-R1`。Agent 使用 `agent: 名称`,例如 `agent: WorkBuddy` 或 `agent: 豆包`。请填写实际使用的名称。
|
||||
提交新 PR 时,在描述正文逐行如实申报参与代码编写的模型和编程工具。行格式与示例只写在 [PR 模板](.github/PULL_REQUEST_TEMPLATE.md),由 [`scripts/ci/pr-model.mjs`](scripts/ci/pr-model.mjs) 校验。
|
||||
|
||||
缺少模型或 Agent 申报的 PR 直接关闭。纯人工编写的提交不予合并。此规则仅适用于生效后新建的 PR,已创建的 PR 继续按原规则处理。
|
||||
缺少模型或编程工具申报的 PR 直接关闭。纯人工编写的提交不予合并。此规则仅适用于生效后新建的 PR,已创建的 PR 继续按原规则处理。
|
||||
|
||||
## 版本变更与开源合规
|
||||
|
||||
@@ -54,4 +54,31 @@ Reims-Go 自身代码采用 [Apache-2.0](LICENSE) 协议。便携运行时以独
|
||||
|
||||
## 文档导航
|
||||
|
||||
开始处理用户任务前,先通过 [AI 文档索引](AI-DOCS.md) 定位修改目标涉及的领域,并阅读对应的规范。跨领域任务须查阅各相关规范。
|
||||
开始处理用户任务前,先按下表定位修改目标涉及的领域,并阅读对应的规范。跨领域任务须查阅各相关规范。任务范围变化时,先补读新领域的规范。
|
||||
|
||||
### 仓库规范
|
||||
|
||||
| 涉及领域 | 文档名称 | 位置 |
|
||||
| :--- | :--- | :--- |
|
||||
| 核心分层、跨仓归属、运行时契约和数据迁移 | 系统架构 | [docs/architecture.md](docs/architecture.md) |
|
||||
| 运行时下载、安装、版本门槛和分发 | 运行时客户端版本兼容规范 | [docs/runtime-client-compatibility.md](docs/runtime-client-compatibility.md) |
|
||||
| 界面、状态模型、生产文案和操作反馈 | 产品与界面设计规范 | [docs/design-guidelines.md](docs/design-guidelines.md) |
|
||||
| 插件、驱动扩展接口、权限和分发 | 插件系统架构 | [docs/plugin-architecture.md](docs/plugin-architecture.md) |
|
||||
| 测试选择、构建检查、冒烟和并发隔离 | 测试 | [docs/testing.md](docs/testing.md) |
|
||||
| 网络模式、Npcap 桥接、出口热切和驱动安装 | 网络管理 | [docs/networking.md](docs/networking.md) |
|
||||
| 提交、PR 描述、跨仓审查、合并检查、Issue 分诊和定期代码诊断 | PR 变更归属审查与 GitHub 自动化 | [docs/pr-review-guidelines.md](docs/pr-review-guidelines.md) |
|
||||
| PR 验证记录和合并前核对 | PR 模板 | [.github/PULL_REQUEST_TEMPLATE.md](.github/PULL_REQUEST_TEMPLATE.md) |
|
||||
| 用户可见变更、更新日志与发布说明 | 更新日志编写与发布 | [docs/changelog.md](docs/changelog.md) |
|
||||
| 开源许可、依赖声明和运行时分发合规 | Apache License 2.0、Third-Party Notices | [LICENSE](LICENSE) · [NOTICE.md](NOTICE.md) |
|
||||
|
||||
### 专题与关联仓库
|
||||
|
||||
| 涉及领域 | 文档名称 | 位置 |
|
||||
| :--- | :--- | :--- |
|
||||
| 挂起恢复所用运行时的编号和兼容判定 | Alpha 运行时编号与挂起兼容性规范 | [reims-go/reims-vgpu 的 packaging/windows-runtime/versioning.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) |
|
||||
| 运行时源码、依赖补丁和补丁退役 | 运行时源码与依赖补丁 | [reims-go/reims-vgpu 的 packaging/windows-runtime/patches/README.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) |
|
||||
| FileVault 开机输入与启动镜像 | FileVault 开机输入镜像构建 | [scripts/filevault-input/README.md](scripts/filevault-input/README.md) |
|
||||
| 虚拟机系统盘性能测量 | 系统盘小文件 I/O 基准与采样工具 | [scripts/io-bench/README.md](scripts/io-bench/README.md) |
|
||||
| 跨会话工单与 Agent 交接 | 调试工单模板 | [scripts/debug/work-template.md](scripts/debug/work-template.md) |
|
||||
|
||||
项目总览见 [English](README.md) 和 [简体中文](README.zh-CN.md)。已发布的客户端变更见 [CHANGELOG.md](CHANGELOG.md)。新增、移动或废止规范时同步更新本节。
|
||||
-32
@@ -1,32 +0,0 @@
|
||||
# AI 任务文档索引
|
||||
|
||||
开始处理用户任务前,先阅读 [AGENTS.md](AGENTS.md)。根据任务的修改目标定位可能涉及的领域,阅读下表对应的规范和相关章节,再修改文件或执行验证。跨领域任务须阅读各相关规范。任务范围变化时,先补读新领域的规范。
|
||||
|
||||
## 仓库规范
|
||||
|
||||
| 涉及领域 | 文档名称 | 位置 |
|
||||
| :--- | :--- | :--- |
|
||||
| 任务范围、存储、调试目录、安全和合规 | 仓库协作规则 | [AGENTS.md](AGENTS.md) |
|
||||
| 核心分层、跨仓归属、运行时契约和数据迁移 | 系统架构 | [docs/architecture.md](docs/architecture.md) |
|
||||
| 运行时下载、安装、版本门槛和分发 | 运行时客户端版本兼容规范 | [docs/runtime-client-compatibility.md](docs/runtime-client-compatibility.md) |
|
||||
| 界面、状态模型、生产文案和操作反馈 | 产品与界面设计规范 | [docs/design-guidelines.md](docs/design-guidelines.md) |
|
||||
| 插件、驱动扩展接口、权限和分发 | 插件系统架构 | [docs/plugin-architecture.md](docs/plugin-architecture.md) |
|
||||
| 测试选择、构建检查、冒烟和并发隔离 | 测试 | [docs/testing.md](docs/testing.md) |
|
||||
| 网络模式、Npcap 桥接、出口热切和驱动安装 | 网络管理 | [docs/networking.md](docs/networking.md) |
|
||||
| 提交、PR 描述、跨仓审查和合并检查 | PR 变更归属审查 | [docs/pr-review-guidelines.md](docs/pr-review-guidelines.md) |
|
||||
| Issue 分诊、恶意内容拦截和定期代码诊断 | Issue 自动化 | [docs/issue-automation.md](docs/issue-automation.md) |
|
||||
| PR 验证记录和合并前核对 | PR 模板 | [.github/PULL_REQUEST_TEMPLATE.md](.github/PULL_REQUEST_TEMPLATE.md) |
|
||||
| 用户可见变更、更新日志与发布说明 | 更新日志编写与发布 | [docs/changelog.md](docs/changelog.md) |
|
||||
| 开源许可、依赖声明和运行时分发合规 | Apache License 2.0、Third-Party Notices | [LICENSE](LICENSE) · [NOTICE.md](NOTICE.md) |
|
||||
|
||||
## 专题与关联仓库
|
||||
|
||||
| 涉及领域 | 文档名称 | 位置 |
|
||||
| :--- | :--- | :--- |
|
||||
| 挂起恢复所用运行时的编号和兼容判定 | Alpha 运行时编号与挂起兼容性规范 | [reims-go/reims-vgpu 的 packaging/windows-runtime/versioning.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/versioning.md) |
|
||||
| 运行时源码、依赖补丁和补丁退役 | 运行时源码与依赖补丁 | [reims-go/reims-vgpu 的 packaging/windows-runtime/patches/README.md](https://github.com/reims-go/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) |
|
||||
| FileVault 开机输入与启动镜像 | FileVault 开机输入镜像构建 | [scripts/filevault-input/README.md](scripts/filevault-input/README.md) |
|
||||
| 虚拟机系统盘性能测量 | 系统盘小文件 I/O 基准与采样工具 | [scripts/io-bench/README.md](scripts/io-bench/README.md) |
|
||||
| 跨会话工单与 Agent 交接 | 调试工单模板 | [scripts/debug/work-template.md](scripts/debug/work-template.md) |
|
||||
|
||||
项目总览见 [English](README.md) 和 [简体中文](README.zh-CN.md)。已发布的客户端变更见 [CHANGELOG.md](CHANGELOG.md)。新增、移动或废止规范时同步更新本索引。
|
||||
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 539 141" width="539" height="141" role="img" aria-label="Reims-Go"><g transform="translate(4 107)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#f4f5fa"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#f4f5fa"/><path d="M133.5 -64.5V-7.5" stroke="#f4f5fa"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#f4f5fa"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#f4f5fa"/><path d="M340.5 -36H358.5" stroke="#5d6382"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
@@ -1 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 539 141" width="539" height="141" role="img" aria-label="Reims-Go"><g transform="translate(4 107)"><defs><linearGradient id="wm" gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0"><stop offset="0" stop-color="#3b8cff"/><stop offset="0.5" stop-color="#6d5dfc"/><stop offset="1" stop-color="#ff7a9a"/></linearGradient><linearGradient id="wmb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffd43b"/><stop offset="1" stop-color="#ff9f0a"/></linearGradient></defs><g fill="none" stroke-width="15" stroke-linecap="round" stroke-linejoin="round"><path d="M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5" stroke="#16182e"/><path d="M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93" stroke="#16182e"/><path d="M133.5 -64.5V-7.5" stroke="#16182e"/><circle cx="133.5" cy="-94" r="9" fill="#ff7a9a"/><path d="M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5" stroke="#16182e"/><path d="M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98" stroke="#16182e"/><path d="M340.5 -36H358.5" stroke="#a3a8bf"/><path d="M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01" stroke="url(#wm)"/><path d="M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25" stroke="url(#wm)"/><path d="M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01" stroke="url(#wm)"/></g></g></svg>
|
||||
|
Before Width: | Height: | Size: 1.4 KiB |
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "修复在处理器核心弹窗中勾选核心、切换模式或调整 EcoQoS 开关后,未保存前因后台状态刷新自动跳回旧配置的问题。",
|
||||
"en": "Preserve unsaved core selections, mode changes, and EcoQoS toggles in the CPU cores dialog when background host refreshes occur."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "应用内更新改为直接读取 GitHub Releases 接口返回的 `assets[].digest` 校验安装包 SHA-256,不再额外下载 `SHA256SUMS.txt`(该文件计划在 v0.3 退役)。",
|
||||
"en": "Verify in-app update downloads directly against the `assets[].digest` SHA-256 returned by the GitHub Releases API instead of fetching `SHA256SUMS.txt` (planned for retirement in v0.3)."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "适配新版运行时移除 `reims-ctl set --capture` 参数,按运行时能力隐藏「点击窗口时捕获键鼠」并避免新建、克隆与保存设置报错,同时将修饰键状态行独立显示并明确「拦截宿主机全局热键」用途与立即生效说明。",
|
||||
"en": "Detect whether the active runtime supports `reims-ctl set --capture` so newer runtimes omit `--capture` during create, clone, and settings updates and hide the retired capture toggle, while moving modifier-key status to its own row and clarifying global host hotkey blocking."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "手动打开更高版本的 Windows 客户端时,自动退出正在运行的旧客户端并在原位置更新,原来的快捷方式仍可使用。",
|
||||
"en": "Opening a newer Windows client now closes the running older client and updates its executable in place so existing shortcuts still work."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "将「剪贴板互通」的全部配置项从虚拟机设置迁移到插件页的插件配置中统一管理,并在升级时按显式关闭与更严格限制优先的规则自动迁移旧的单虚拟机配置。",
|
||||
"en": "Move all Clipboard Sync settings from VM settings into the plugin configuration on the Plugins page, automatically migrating legacy per-VM settings on upgrade with explicit-off and stricter limits taking precedence."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复克隆虚拟机没有主机 SSH 端口转发的问题。源虚拟机开启端口转发时,克隆出的虚拟机现在会占用源端口之后的一个空闲端口,因此 MCP 临时会话与克隆上的 SSH 相关工具(`guest_exec`、`guest_wait_ready`、`test_run` 等)可以正常连接客体。源虚拟机未开启转发时克隆仍不开启。",
|
||||
"en": "Fix cloned VMs having no host SSH port forward. When the source VM forwards SSH, a clone now takes the next free port after the source port, so SSH-based guest tools such as `guest_exec`, `guest_wait_ready`, and `test_run` work on MCP temporary sessions and other clones. A source without forwarding still yields a clone without one."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复 MCP 临时克隆无法自动输入登录密码、SSH 用户名常为空的问题。克隆不保存自己的虚拟机设置,现在它读取 `login_password` 和 `username` 时会回退到来源虚拟机,且仅在来源虚拟机仍开启「允许 AI 访问」时生效;撤销来源的授权后克隆立即失去回退。密码不会复制进克隆,克隆销毁后不留存副本。虚拟机未保存登录密码时,解锁会提示去 MCP 服务设置里填写,而不是返回内部错误。",
|
||||
"en": "Fix MCP temporary clones failing to type the login password and often reporting an empty SSH username. A clone keeps no VM settings of its own, so reads of `login_password` and `username` now fall back to the source VM, and only while the source still allows AI access; revoking access on the source removes the fallback immediately. The password is never copied into the clone, so disposing it leaves no copy behind. When a VM has no saved login password, unlock now asks you to set it in the MCP Service settings instead of returning an internal error."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复宿主机存在多份 Vulkan ICD 驱动清单或重复枚举同一张显卡时,内核页与虚拟机设置页重复显示同一块显卡且缺失驱动版本号的问题。",
|
||||
"en": "Deduplicate repeated Vulkan physical device entries on the Runtime and VM settings pages when the same GPU is enumerated multiple times."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "清理 macOS 独立应用窗口边角残留的桌面画面。拖动标题栏中部即可移动 Windows 窗口,拖动期间保留上一帧,避免闪出来宾桌面。",
|
||||
"en": "Remove stray desktop pixels from the corners of separate macOS app windows. Drag the middle of the title bar to move the Windows window. The last frame stays visible during the move to prevent the guest desktop from flashing through."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "修复 Guest Tools 窗口上报进程崩溃导致的「打开独立应用窗口」失败。已有虚拟机请重新安装 Guest Tools,更新至 `v22`。",
|
||||
"en": "Fix a Guest Tools window reporter crash that prevented macOS apps from opening in separate windows. Reinstall Guest Tools in existing VMs to update to `v22`."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "MCP 插件接口按连接区分会话,客户端断开后会通知插件释放仍按住的输入;截图支持按源分辨率裁剪局部区域,按键支持单独按住和松开,关机支持强制停止,读取恢复点列表只需读取权限。",
|
||||
"en": "The MCP plugin interface now scopes each client connection as its own session and notifies the plugin when a client disconnects so held input is released. Screenshots can crop a region at source resolution, keys can be held and released individually, shutdown can force-stop, and listing restore points needs only read permission."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "插件支持在清单中声明颜色令牌与 SVG 前景图标并迁移全部内置插件,插件页新增「上架插件」入口,市场卡片展示 GitHub Star 数与下载量,语言包脚手架默认仅生成目标语言标题与精简描述。",
|
||||
"en": "Support custom icon tone tokens and monochrome SVG foregrounds in plugin manifests (migrating all built-in plugins), add a Submit plugin button to the Plugins page, display GitHub star and download counts on market cards, and scaffold language packs with concise native-locale metadata."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["reiasu2"],
|
||||
"zh": "在 Windows 上从插件市场安装、重装插件或导入本地 ZIP 插件包时,若杀毒软件实时防护短暂占用刚解压的插件可执行文件,自动短暂重试,避免报 `Access is denied` 失败。",
|
||||
"en": "When installing or reinstalling a plugin from the market or importing a local ZIP package on Windows, briefly retry if real-time antivirus protection holds newly extracted plugin executables open so installation does not fail with `Access is denied`."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "插件日志并入应用日志并标明插件包名,不再使用单独的日志窗口。",
|
||||
"en": "Show plugin logs in the app log, labeled with the plugin ID, instead of a separate log window."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "插件市场不再隐藏 Alpha 通道插件(改为展示 `Alpha` 标签),安装与更新时弹出版本选择清单,支持按综合(发布日与下载量)、Star、下载量与最新发布排序,并将带主页的插件标题设为可跳转超链接。",
|
||||
"en": "Show Alpha plugins directly in the marketplace with an `Alpha` tag instead of hiding them, open a version picker when installing or updating, add sorting by Recommended (recency + downloads), Stars, Downloads, and Recently updated, and make plugin titles clickable links to their homepage."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "已安装插件的安全扫描结论改为在权限提示中显示。",
|
||||
"en": "Show the security scan result of installed plugins in their permissions tooltip."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "插件自带的设置面板改为从该插件的设置按钮打开,不再排在插件页底部。",
|
||||
"en": "Open a plugin's own settings panel from its settings button instead of the bottom of the Plugins page."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复手动移动数据目录并在设置或首启界面重新选择新目录后,因虚拟机注册表保留旧路径导致无法启动虚拟机的问题。",
|
||||
"en": "Fix VMs failing to start after moving the data folder and reselecting its new location by updating stale paths in the VM registry."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "手动切换到旧版运行时后,在内核页将当前运行时标注为不是最新并提示切换,同时将最新标签标注在实际最新版本旁 (#151)。",
|
||||
"en": "Mark the active runtime as not latest with a switch hint when an older runtime is selected on the Engine page, and place the Latest badge on the actual newest installed runtime (#151)."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "下载速度低于 1 MB/s 时改以 KB/s 显示,精简关于页与更新通道文案,默认同步宿主机内存规格并将外观与语言设置分组置顶,更新检查按通道缓存 5 分钟且切换通道时不再禁用控件。",
|
||||
"en": "Display download speeds below 1 MB/s in KB/s, tighten About page and update channel copy, sync host memory SMBIOS specs by default and move Appearance & language to the top of Settings, cache update checks per channel for 5 minutes, and keep the update channel selector interactive while switching."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "新建虚拟机时在左侧栏显示正在创建的条目,并在主界面直接展示创建进度、步骤说明与取消入口 (#120)。",
|
||||
"en": "Show in-progress VM creation in the sidebar and display its progress, current step, and cancel action directly in the main view (#120)."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "new",
|
||||
"order": 0,
|
||||
"authors": ["yxc0915"],
|
||||
"zh": "为 Windows Q35 虚拟机新增原生块设备直通模式(支持物理磁盘或分区就地挂载、`--disk-cache` 主机缓存策略配置,以及配合便携运行时新版 QEMU 的 Win32 原生 IOCP/WHPX/NVMe 性能优化)。",
|
||||
"en": "Add Windows raw disk/partition in-place mounting and per-VM `--disk-cache` policy support, paired with the Win32 native IOCP AIO, WHPX doorbell/fast-MMIO, and NVMe runtime optimizations."
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
# Issue 自动化
|
||||
|
||||
## 自动分诊
|
||||
|
||||
[Issue Triage](../.github/workflows/issue-triage.yml) 在 Issue 新建时运行一次。它提示报告者补充信息,列出疑似重复和路线图中的相关计划,并说明问题或功能是否更适合上游引擎或插件。没有可补充的内容时不评论。
|
||||
|
||||
- 模型没有工具,只返回固定的分类值和 Issue 编号。评论全部使用脚本内的固定文案,Issue 中的文字不会进入评论。
|
||||
- 维护者创建的 Issue、带 `roadmap` 或 `official` 标签的 Issue 以及机器人创建的 Issue 不送审。其他路线图 Issue 只提供编号和标题,供查重使用。
|
||||
- 垃圾信息、钓鱼、恶意下载和针对 AI 的注入内容,须由模型引用原文并经两次独立判断一致,才会关闭并添加 `invalid` 标签。判断不一致或作者有已合并的贡献时,只在 Actions 中提醒维护者。
|
||||
- 需要补充信息的 Issue 会添加 `question` 标签。
|
||||
|
||||
## 定期代码诊断
|
||||
|
||||
[Code Diagnosis](../.github/workflows/code-diagnosis.yml) 在北京时间每周一和周四 2 点扫描 `main` 的一个代码区域,各区域依次轮换。扫描只读取仓库代码,不读取 Issue 和评论。
|
||||
|
||||
- 问题须引用文件中真实存在的代码,并经模型二次复核,才会创建 Issue。每次最多创建两个,未关闭的诊断 Issue 达到六个时暂停。
|
||||
- 涉及安全的问题不公开,只在 Actions 中提示数量和代码区域。
|
||||
- 移动或重命名代码目录时,同步更新 [`code-diagnosis.mjs`](../.github/scripts/code-diagnosis.mjs) 中的区域列表。
|
||||
|
||||
## 配置与手动运行
|
||||
|
||||
两个工作流沿用 [PR 自动审核](pr-review-guidelines.md#4-自动审核)的模型密钥和变量,仅支持 `anthropic` 协议。两者都可以在 Actions 页面手动运行,默认只输出结果,勾选 `publish` 后才会发布。
|
||||
@@ -29,14 +29,15 @@ flowchart TB
|
||||
1. 除编译期内置扩展外,客户端不在主进程内加载动态库或运行第三方脚本(交互主题受信任脚本除外),用户也无需额外安装外部脚本运行时。
|
||||
2. Apache-2.0 客户端本体与外部组件仅通过独立子进程和协议交互,插件包、私有数据、缓存与日志全部隔离在数据目录的 `plugins/` 下。
|
||||
3. 插件无权读取硬件序列号、UUID、ROM 或 MAC 地址,无权静默触发管理员提权或系统重启,也无权直接改写 `vm.toml`;插件贡献的排障数据一律经宿主脱敏后才写入排障包。
|
||||
4. 插件的标准错误输出和异常审计记录在桌面端同时写入应用日志,来源标为 `plugin:<插件 ID>`,每个插件单独限流。成功的常规宿主调用只写入 `plugins/logs/` 下的插件日志文件。
|
||||
|
||||
内置虚拟机交互服务默认启用,通过宿主控制台代理串行处理每台虚拟机的 QMP 操作,每次操作后关闭连接,并与虚拟机生命周期操作共用锁。桌面文本输入期间暂停后台缩略图捕获。该服务不实现 MCP 协议。
|
||||
|
||||
内置 macOS 应用窗口插件默认关闭,依赖 Guest Tools 传输与虚拟机交互服务。用户启用后可在运行中的 macOS 虚拟机操作菜单中打开前台应用窗口。停用插件会移除操作入口并关闭独立窗口。
|
||||
|
||||
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||
L3 插件可在清单 `contributes.channels` 中声明 `jsonl` 通道。桌面端的 `plugin connect` 经 Windows 当前用户限定的命名管道转发消息,不开放 TCP 或 HTTP MCP 监听。每条连接带一个会话标识,宿主随 `channel/<通道>/message` 一并转发,插件按会话区分请求 ID 和取消。连接结束后,宿主向正在运行的 Sidecar 发送 `channel/<通道>/closed` 通知,插件据此取消该连接的调用并释放按住的输入。官方 MCP 插件实现工具、虚拟机状态与桌面控制,以及通过 SSH/SFTP 的客体命令和文件传输。
|
||||
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
|
||||
Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 VM 目录。读取 VM 状态和恢复点列表要求 `vm:read`,截图要求 `vm:screen`,输入要求 `qmp:write`,VM 启停要求 `vm:control`。截图可指定一块区域,区域坐标默认按源分辨率计算,也可附带参考图像尺寸,由宿主换算到源分辨率。宿主在全分辨率帧上裁剪区域后再缩放。按键可单独按住和松开,释放接口一次抬起指定的按键和鼠标键;驱动控制台只支持按键单击。关机可指定强制停止。Host API 审核插件权限并记录方法名,不把输入文本写入审计日志。开机、登录和切换显示时画面可能是纯色,此时截图照常返回该帧并标记 `blank`,插件据此继续等待,而不是当作失败。登录密码由 Windows DPAPI 保护,宿主只提供按设置键名键入的操作,不向 MCP 插件返回明文。插件自己的下载器敏感设置仅在下载请求中解密并传给该插件进程。
|
||||
|
||||
## 生命周期、参数账本与资源预算
|
||||
|
||||
@@ -56,7 +57,7 @@ Sidecar 的控制台 Host API 只接受 VM 引用,不接受 QMP 套接字或 V
|
||||
|
||||
已激活的外部主题在重启客户端和升级插件后自动保留,并在脚本变更重新批准后带版本哈希参数重载;仅停用或卸载所属主题插件时回退内置默认主题并清空当前配色方案,安全模式或命令行停用无关插件不会影响当前主题。从市场安装并启用主题插件时,仅当当前仍处于内置默认主题才自动切换为该插件的首个主题,不覆盖用户已选的其他外部主题。
|
||||
|
||||
自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。`contributes.views` 可在侧栏、VM 标签页、全局设置页或对话框中挂载完整视图,视图随插件作用域注册和释放,停用后自动回退到对应内置页面。视图的 `when` 支持 `vmState==<状态>` 与 `theme==<light|dark>`,条件不满足时宿主隐藏入口和页面。`minWidth` 设置页面的最小宽度,空间不足时横向滚动。
|
||||
自定义界面优先采用 JSON Schema 声明式设置(支持标记敏感项、全局或按虚拟机作用域及生效时机);确需自绘界面的插件使用 `sandbox="allow-scripts"` 且禁联网的沙箱 `iframe`,通过消息桥请求通知、通用虚拟机列表、插件自有命令与多语种词包,所有本地 HTTP 服务均拒绝来自沙箱 `iframe` 或空来源的跨站请求。`settings.plugin` 槽位的面板与声明式设置一起显示在插件的设置弹窗中。`contributes.views` 可在侧栏、VM 标签页、全局设置页或对话框中挂载完整视图,视图随插件作用域注册和释放,停用后自动回退到对应内置页面。视图的 `when` 支持 `vmState==<状态>` 与 `theme==<light|dark>`,条件不满足时宿主隐藏入口和页面。`minWidth` 设置页面的最小宽度,空间不足时横向滚动。
|
||||
|
||||
页面可通过 `ui.confirm` 请求确认框,通过 `ui.showForm` 打开声明式表单,通过 `ui.copy` 复制文本,通过 `ui.openExternal` 打开经宿主校验的 HTTPS 外链,并使用 `ui.setTitle`、`ui.setBadge` 更新当前视图元数据。`ui.openView` 仅打开本插件声明的视图,`ui.close` 关闭当前视图或顶层对话框,`ui.navigate` 进入内置宿主页面;这些操作不会关闭应用窗口。确认框使用 `ui:notify` 权限,其他界面动作使用 `ui:slot` 权限。
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
# PR 变更归属审查
|
||||
# PR 变更归属审查与 GitHub 自动化
|
||||
|
||||
> 以产生行为的实现为准。先定位改动发生在哪个组件,再决定提交仓库和验证范围。桌面或 CLI 是否有入口,只决定客户端是否也需要改动。
|
||||
|
||||
@@ -28,22 +28,11 @@
|
||||
|
||||
## 3. PR 描述与合并检查
|
||||
|
||||
提交者在 PR 描述中附上以下信息。纯文档或纯客户端改动可将无关字段写为「不适用」。
|
||||
提交者按 [PR 模板](../.github/PULL_REQUEST_TEMPLATE.md) 填写描述,模板是描述结构的唯一来源。纯文档或纯客户端改动可将无关字段写为「不适用」。
|
||||
|
||||
```markdown
|
||||
## 变更归属
|
||||
|
||||
- 用户可见行为
|
||||
- 变更位置与责任仓库
|
||||
- 上游证据(仓库、commit、文件及行号)
|
||||
- 跨仓依赖(关联 PR、合并顺序、运行时要求)
|
||||
- 旧版或缺失运行时的表现
|
||||
|
||||
## 验证
|
||||
|
||||
- 已通过的检查及运行时版本
|
||||
- 待验证场景及其影响
|
||||
```
|
||||
- 变更说明写明用户可见行为、变更位置与责任仓库、上游证据(仓库、commit、文件及行号)、跨仓依赖(关联 PR、合并顺序、运行时要求)和旧版或缺失运行时的表现。
|
||||
- 模型与编程工具申报按模板注释逐行填写,缺少申报的 PR 会被 [`pr-model.mjs`](../scripts/ci/pr-model.mjs) 直接关闭。
|
||||
- 验证记录写明已通过的检查及运行时版本,以及待验证场景及其影响。
|
||||
|
||||
审查者在合并前核对以下各项。
|
||||
|
||||
@@ -96,3 +85,26 @@ OCR 输出中的 `critical`、`high`、`medium` 且非 style/documentation 问
|
||||
如果公开仓库的 Actions 事件策略阻止 `pull_request_target`,由仓库管理员在 **Settings → Actions → Policies** 为 `.github/workflows/pr-review.yml` 配置允许该事件的策略。[GitHub 事件策略文档](https://docs.github.com/en/actions/how-tos/administer/control-workflow-execution)
|
||||
|
||||
工作流合入默认分支并配置密钥后,可在 **Actions → PR Review → Run workflow** 输入一个开放 PR 的编号。手动重审始终使用完整 PR 区间并允许再次发布。缺少 LLM Key 时跳过,二进制校验、模型请求或发布失败时在 Actions 中显示失败。
|
||||
|
||||
## 5. Issue 自动化与定期代码诊断
|
||||
|
||||
### 自动分诊
|
||||
|
||||
[Issue Triage](../.github/workflows/issue-triage.yml) 在 Issue 新建时运行一次。它提示报告者补充信息,列出疑似重复和路线图中的相关计划,并说明问题或功能是否更适合上游引擎或插件。没有可补充的内容时不评论。
|
||||
|
||||
- 模型没有工具,只返回固定的分类值和 Issue 编号。评论全部使用脚本内的固定文案,Issue 中的文字不会进入评论。
|
||||
- 维护者创建的 Issue、带 `roadmap` 或 `official` 标签的 Issue 以及机器人创建的 Issue 不送审。其他路线图 Issue 只提供编号和标题,供查重使用。
|
||||
- 垃圾信息、钓鱼、恶意下载和针对 AI 的注入内容,须由模型引用原文并经两次独立判断一致,才会关闭并添加 `invalid` 标签。判断不一致或作者有已合并的贡献时,只在 Actions 中提醒维护者。
|
||||
- 需要补充信息的 Issue 会添加 `question` 标签。
|
||||
|
||||
### 定期代码诊断
|
||||
|
||||
[Code Diagnosis](../.github/workflows/code-diagnosis.yml) 在北京时间每周一和周四 2 点扫描 `main` 的一个代码区域,各区域依次轮换。扫描只读取仓库代码,不读取 Issue 和评论。
|
||||
|
||||
- 问题须引用文件中真实存在的代码,并经模型二次复核,才会创建 Issue。每次最多创建两个,未关闭的诊断 Issue 达到六个时暂停。
|
||||
- 涉及安全的问题不公开,只在 Actions 中提示数量和代码区域。
|
||||
- 移动或重命名代码目录时,同步更新 [`code-diagnosis.mjs`](../scripts/ci/code-diagnosis.mjs) 中的区域列表。
|
||||
|
||||
### 配置与手动运行
|
||||
|
||||
两个工作流沿用 [PR 自动审核](#4-自动审核) 的模型密钥和变量,仅支持 `anthropic` 协议。两者都可以在 Actions 页面手动运行,默认只输出结果,勾选 `publish` 后才会发布。
|
||||
+2
-1
@@ -8,7 +8,8 @@
|
||||
| 改动前端 | `node scripts/test.mjs quick frontend` | 界面逻辑、国际化、架构约束和静态检查 |
|
||||
| 改动持久化或升级 | `node scripts/test.mjs quick storage` | 配置和数据目录、迁移及插件状态存储,使用真实临时文件 |
|
||||
| 改动调试工具 | `node scripts/test.mjs quick tooling` | 临时目录和工单工具自测 |
|
||||
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`cmd/`、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测 |
|
||||
| 改动 GitHub 自动化脚本 | `node scripts/test.mjs quick automation` | `scripts/ci/` 下 PR 审核、Issue 分诊、代码诊断和申报校验脚本的自测 |
|
||||
| 跨模块改动或提 PR | `node scripts/test.mjs ci` | 前端测试和类型检查、`cmd/`、`internal/`、`pkg/`、`scripts/` 下的 Go 测试与 vet、调试工具自测、GitHub 自动化脚本自测 |
|
||||
| 核对发布候选 | `node scripts/test.mjs release` | 使用 `desktop,production` 构建标签运行同一套 Go 检查,禁用测试结果缓存并随机化用例顺序 |
|
||||
| Windows 桌面冒烟 | `node scripts/test.mjs webview2 build/bin/reims-go.exe` | 启动已构建的客户端,在真实 WebView2 中完成首启数据目录设置 |
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// scripts/brand/wordmark.py is the single source of the icon and the wordmark
|
||||
// geometry: it copies assets/logo.svg into public/ and generates
|
||||
// wordmark.gen.ts. Neither copy may be edited by hand.
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
|
||||
const repoRoot = path.resolve(import.meta.dirname, '..', '..')
|
||||
|
||||
test('frontend/public/logo.svg is the copy of assets/logo.svg', () => {
|
||||
const source = fs.readFileSync(path.join(repoRoot, 'assets', 'logo.svg'))
|
||||
const served = fs.readFileSync(path.join(repoRoot, 'frontend', 'public', 'logo.svg'))
|
||||
assert.ok(source.equals(served), 'run python scripts/brand/wordmark.py to refresh frontend/public/logo.svg')
|
||||
})
|
||||
|
||||
test('the frontend wordmark geometry is generated', () => {
|
||||
const generated = fs.readFileSync(path.join(repoRoot, 'frontend', 'src', 'components', 'wordmark.gen.ts'), 'utf8')
|
||||
assert.match(generated, /^\/\/ Code generated by scripts\/brand\/wordmark\.py; DO NOT EDIT\./)
|
||||
assert.match(generated, /export const WORDMARK_STROKES: WordmarkStroke\[\] = \[/)
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { createKeymapRequests, keymapPresetUpdate, keymapUpdate } = await loadTestModule(`export * from './lib/vmKeymap'`)
|
||||
const { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets } = await loadTestModule(`export * from './lib/vmKeymap'`)
|
||||
const off = { preset: 'off', bindings: {}, capture_host_shortcuts: false }
|
||||
const custom = { preset: 'custom', bindings: { lwin: 'lcmd' }, capture_host_shortcuts: true }
|
||||
|
||||
@@ -89,3 +89,62 @@ test('a read started before a write cannot restore the old keymap', async () =>
|
||||
await read
|
||||
assert.deepEqual(state, { keymap: custom, busy: false, error: '' })
|
||||
})
|
||||
|
||||
test('visibleKeymapPresets hides win_to_cmd on modern runtimes unless already selected', () => {
|
||||
assert.deepEqual(visibleKeymapPresets('off', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('swap_alt_win', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('custom', false), ['off', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('win_to_cmd', false), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('off', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
assert.deepEqual(visibleKeymapPresets('swap_alt_win', true), ['off', 'win_to_cmd', 'swap_alt_win', 'custom'])
|
||||
})
|
||||
|
||||
test('keymapStatusHint returns null when both preset and shortcut capture are off', () => {
|
||||
const base = {
|
||||
preset: 'off',
|
||||
bindings: {},
|
||||
capture_host_shortcuts: false,
|
||||
needs_guest_tools: false,
|
||||
guest_connected: true,
|
||||
guest_agent_version: 5,
|
||||
required_agent_version: 5,
|
||||
input_service_available: true,
|
||||
guest_keymap_active: true,
|
||||
hook_active: true,
|
||||
running: true,
|
||||
}
|
||||
assert.equal(keymapStatusHint(base), null)
|
||||
})
|
||||
|
||||
test('keymapStatusHint resolves priority when only capture_host_shortcuts is enabled', () => {
|
||||
const base = {
|
||||
preset: 'off',
|
||||
bindings: {},
|
||||
capture_host_shortcuts: true,
|
||||
needs_guest_tools: false,
|
||||
guest_connected: false,
|
||||
guest_agent_version: 0,
|
||||
required_agent_version: 4,
|
||||
input_service_available: true,
|
||||
guest_keymap_active: false,
|
||||
hook_active: true,
|
||||
running: true,
|
||||
}
|
||||
assert.deepEqual(keymapStatusHint(base), { key: 'keymapRunning' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, hook_active: false }), { key: 'keymapInactive' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, running: false }), { key: 'keymapStopped' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, input_service_available: false, running: false }), { key: 'keymapInputServiceRequired' })
|
||||
assert.deepEqual(keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: false }), { key: 'keymapWaiting' })
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 3, required_agent_version: 4 }),
|
||||
{ key: 'keymapUpgrade', vars: { version: 4 } },
|
||||
)
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: false }),
|
||||
{ key: 'keymapPending' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
keymapStatusHint({ ...base, needs_guest_tools: true, guest_connected: true, guest_agent_version: 4, required_agent_version: 4, guest_keymap_active: true }),
|
||||
{ key: 'keymapRunning' },
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { describeRuntimeStatus, sameRuntimeId } = await loadTestModule(`export * from './lib/runtimeStatus'`)
|
||||
|
||||
const rt = (commit, active = false) => ({
|
||||
commit,
|
||||
active,
|
||||
path: `/runtimes/${commit}`,
|
||||
manifest: { qemu_version: 'QEMU 11.1.90' },
|
||||
})
|
||||
|
||||
const remote = (commit) => ({
|
||||
commit,
|
||||
channel: 'stable',
|
||||
archive_size: 100,
|
||||
})
|
||||
|
||||
test('sameRuntimeId matches full and short commits with matching revision suffix', () => {
|
||||
assert.equal(sameRuntimeId('6a1f03f', '6a1f03f862b4'), true)
|
||||
assert.equal(sameRuntimeId('3731afd-p3', '3731afd-p4'), false)
|
||||
assert.equal(sameRuntimeId('3731afd-p3', '3731afd9-p3'), true)
|
||||
})
|
||||
|
||||
test('active runtime matching remote latest is up to date', () => {
|
||||
const s = describeRuntimeStatus([rt('6a1f03f', true), rt('2df30ff', false)], remote('6a1f03f'))
|
||||
assert.equal(s.activeIsLatest, true)
|
||||
assert.equal(s.latestInstalled, true)
|
||||
assert.equal(s.updatable, false)
|
||||
assert.equal(s.switchRecommended, false)
|
||||
})
|
||||
|
||||
test('switching to an older runtime while latest is installed flags not-latest instead of up-to-date', () => {
|
||||
const s = describeRuntimeStatus([rt('2df30ff', true), rt('6a1f03f', false)], remote('6a1f03f'))
|
||||
assert.equal(s.activeIsLatest, false)
|
||||
assert.equal(s.latestInstalled, true)
|
||||
assert.equal(s.updatable, false)
|
||||
assert.equal(s.switchRecommended, true)
|
||||
})
|
||||
|
||||
test('missing remote latest marks runtime as updatable', () => {
|
||||
const s = describeRuntimeStatus([rt('2df30ff', true)], remote('6a1f03f'))
|
||||
assert.equal(s.activeIsLatest, false)
|
||||
assert.equal(s.latestInstalled, false)
|
||||
assert.equal(s.updatable, true)
|
||||
assert.equal(s.switchRecommended, false)
|
||||
})
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { currentTask, findActiveOfflineTask, pruneFinishedTasks, upsertTask } =
|
||||
const { creatingVMTasks, currentTask, findActiveOfflineTask, pruneFinishedTasks, taskDetail, upsertTask } =
|
||||
await loadTestModule(`export * from './lib/tasks'`)
|
||||
|
||||
const task = (id, overrides = {}) => ({
|
||||
@@ -33,3 +33,20 @@ test('one installer download represents the VM creations waiting for it', () =>
|
||||
primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'],
|
||||
})
|
||||
})
|
||||
|
||||
test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
|
||||
assert.equal(taskDetail(task('slow', { done: 5e6, total: 50e6, rate: 512e3 })), '5 MB / 50 MB · 512 KB/s')
|
||||
assert.equal(taskDetail(task('tiny', { done: 1e6, total: 10e6, rate: 200 })), '1 MB / 10 MB · 1 KB/s')
|
||||
assert.equal(taskDetail(task('fast', { done: 2e9, total: 10e9, rate: 12.5e6 })), '2.0 GB / 10.0 GB · 12.5 MB/s')
|
||||
assert.equal(taskDetail(task('gig', { done: 2e9, total: 10e9, rate: 1.2e9 })), '2.0 GB / 10.0 GB · 1.2 GB/s')
|
||||
})
|
||||
|
||||
test('creatingVMTasks lists only running vm-create tasks not yet present in vms, oldest first', () => {
|
||||
const first = task('t1', { subject: 'macos-a', started_at: 10 })
|
||||
const second = task('t2', { subject: 'macos-b', started_at: 20 })
|
||||
const registered = task('t3', { subject: 'macos-ready', started_at: 5 })
|
||||
const finished = task('t4', { subject: 'macos-done', status: 'done', started_at: 1 })
|
||||
const download = task('t5', { kind: 'installer-download', subject: '26.7.3', started_at: 2 })
|
||||
const got = creatingVMTasks({ second, first, registered, finished, download }, new Set(['macos-ready']))
|
||||
assert.deepEqual(got.map((x) => x.subject), ['macos-a', 'macos-b'])
|
||||
})
|
||||
+70
-8
@@ -11,6 +11,7 @@ import { TitleMenus } from './components/TitleMenus'
|
||||
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 { CreatingVMView } from './components/CreatingVMView'
|
||||
import { VMPage } from './components/VMPage'
|
||||
import { buildFallbackChain, I18nKey, localeDir, locText, parseAppError, resolveActiveLocale, setPluginLocales, t } from './i18n'
|
||||
import { defaultGuestLang, recommendedMemoryGB, recommendedResolution } from './lib/format'
|
||||
@@ -18,7 +19,7 @@ import { isMacOSDriver, liveVMInfo, splitEndpoints, vmFeatures } from './lib/end
|
||||
import { resolveFullscreenHotkey } from './lib/fullscreenHotkey'
|
||||
import { LogLine, appendLog, createLogLine } from './lib/logs'
|
||||
import { macOSMajor } from './macos/macosRelease'
|
||||
import { currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { creatingVMTasks, currentTask, finishedTaskTTL, isActiveInstallerTask, pruneFinishedTasks, upsertTask } from './lib/tasks'
|
||||
import { applyActiveLocaleFonts, applyActiveTheme, disposeActiveThemeAndLocaleFonts, notifyInteractiveThemeState } from './lib/themeEngine'
|
||||
import type { UIStateSnapshot } from './lib/uiSdk'
|
||||
import { hasVisibleDialog } from './lib/dialogState'
|
||||
@@ -113,6 +114,7 @@ export const App: React.FC = () => {
|
||||
const [detailRevision, setDetailRevision] = useState(0)
|
||||
const [showWizard, setShowWizard] = useState(false)
|
||||
const [wizardDraft, setWizardDraft] = useState<WizardDraft | null>(null)
|
||||
const [pendingCreates, setPendingCreates] = useState<string[]>([])
|
||||
const [showSettings, setShowSettings] = useState(false)
|
||||
const [affinityTarget, setAffinityTarget] = useState<{ name: string; driverID: string } | null>(null)
|
||||
const [affinityVersion, setAffinityVersion] = useState(0)
|
||||
@@ -238,10 +240,22 @@ export const App: React.FC = () => {
|
||||
}, [refresh])
|
||||
|
||||
const vms = state?.vms ?? []
|
||||
const existingVMNames = new Set(vms.map((v) => v.name))
|
||||
const creatingTasks = creatingVMTasks(taskMap, existingVMNames)
|
||||
const creatingByName = new Map(creatingTasks.map((t) => [t.subject, t]))
|
||||
const creatingItems: { name: string; task?: Task }[] = [
|
||||
...creatingTasks.map((t) => ({ name: t.subject, task: t })),
|
||||
...pendingCreates
|
||||
.filter((name) => !existingVMNames.has(name) && !creatingByName.has(name))
|
||||
.map((name) => ({ name })),
|
||||
]
|
||||
const runningVMCount = vms.filter((v) => (state?.transitions[vmRefKey(v)] ?? v.state) === 'running').length
|
||||
const selectedVM = !PAGE_IDS.includes(selected)
|
||||
? vms.find((v) => vmRefKey(v) === selected) ?? vms.find((v) => v.name === selected)
|
||||
: undefined
|
||||
const selectedCreating = !selectedVM && !PAGE_IDS.includes(selected)
|
||||
? creatingItems.find((item) => item.name === selected)
|
||||
: undefined
|
||||
|
||||
const selectedIsMacOS = !!selectedVM && isMacOSDriver(selectedVM.driver_id)
|
||||
const selectedTransition = state?.transitions[selectedVM ? vmRefKey(selectedVM) : '']
|
||||
@@ -354,8 +368,12 @@ export const App: React.FC = () => {
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM || !selectedIsMacOS) { setDetail(null); return }
|
||||
api.GetVMDetail(selectedVM.name).then(setDetail).catch(() => setDetail(null))
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision])
|
||||
let live = true
|
||||
api.GetVMDetail(selectedVM.name)
|
||||
.then((d) => { if (live) setDetail(d) })
|
||||
.catch(() => { if (live) setDetail(null) })
|
||||
return () => { live = false }
|
||||
}, [selectedVM?.name, selectedVM?.driver_id, selectedVM?.state, selectedTransition, selectedIsMacOS, detailRevision, state?.active_runtime?.commit, state?.runtime_capture_supported])
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedVM || selectedIsMacOS) { setVMInfoLoaded(null); return }
|
||||
@@ -473,6 +491,7 @@ export const App: React.FC = () => {
|
||||
const effectiveState = selectedVM ? (state?.transitions[vmRefKey(selectedVM)] ?? selectedVM.state) : ''
|
||||
const pending = selectedVM ? (state?.pending_changes[vmRefKey(selectedVM)] ?? []) : []
|
||||
const fixedModeSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'display-fixed-mode') ?? false
|
||||
const diskCacheSupported = state?.active_runtime?.manifest.capabilities?.some((c) => c.trim().toLowerCase() === 'win32-native-aio') ?? false
|
||||
const hostReady = !!state && state.host.whpx === 'ready' && !!state.active_runtime
|
||||
const canSuspend = state?.can_suspend ?? false
|
||||
const fullscreenHotkey = state?.config.fullscreen_hotkey_enabled
|
||||
@@ -516,13 +535,40 @@ export const App: React.FC = () => {
|
||||
const setChannel = (alpha: boolean) => {
|
||||
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
|
||||
}
|
||||
const appChannelSeqRef = useRef(0)
|
||||
const appChannelPendingRef = useRef<'stable' | 'alpha' | 'dev' | null>(null)
|
||||
const appChannelFlushRef = useRef<Promise<void> | null>(null)
|
||||
const appUpdateChannel = state?.config.app_update_channel === 'alpha' || state?.config.app_update_channel === 'dev'
|
||||
? state.config.app_update_channel
|
||||
: 'stable'
|
||||
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
|
||||
await api.SetAppUpdateChannel(ch)
|
||||
await refresh()
|
||||
await update.recheck()
|
||||
const seq = ++appChannelSeqRef.current
|
||||
setState((prev) => (prev ? { ...prev, config: { ...prev.config, app_update_channel: ch } } : prev))
|
||||
appChannelPendingRef.current = ch
|
||||
if (!appChannelFlushRef.current) {
|
||||
appChannelFlushRef.current = (async () => {
|
||||
while (appChannelPendingRef.current !== null) {
|
||||
const target = appChannelPendingRef.current
|
||||
appChannelPendingRef.current = null
|
||||
await api.SetAppUpdateChannel(target)
|
||||
}
|
||||
})().finally(() => {
|
||||
appChannelFlushRef.current = null
|
||||
})
|
||||
}
|
||||
try {
|
||||
await appChannelFlushRef.current
|
||||
} catch (e) {
|
||||
if (appChannelSeqRef.current === seq) {
|
||||
appChannelPendingRef.current = null
|
||||
void refresh()
|
||||
throw e
|
||||
}
|
||||
return
|
||||
}
|
||||
if (appChannelSeqRef.current !== seq) return
|
||||
await update.recheck(false)
|
||||
if (appChannelSeqRef.current === seq) void refresh()
|
||||
}
|
||||
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
||||
|
||||
@@ -942,13 +988,15 @@ export const App: React.FC = () => {
|
||||
setShowWizard(true)
|
||||
}
|
||||
|
||||
// The wizard closes as soon as the create starts; progress lives in the status bar
|
||||
// (vm-create task). On failure or cancel the toast offers returning to the wizard.
|
||||
// The wizard closes as soon as the create starts; progress shows in the sidebar,
|
||||
// main view, and status bar. On failure or cancel the toast offers returning to the wizard.
|
||||
const submitCreate = (payload: CreateOpts, draft: WizardDraft) => {
|
||||
setShowWizard(false)
|
||||
setWizardDraft(null)
|
||||
const name = payload.name
|
||||
const hasDownload = payload.source_mode === 'offline' || payload.source_mode === 'apple'
|
||||
setPendingCreates((prev) => (prev.includes(name) ? prev : [...prev, name]))
|
||||
setSelected(name)
|
||||
api.CreateVM(payload)
|
||||
.then(() => {
|
||||
toasts.push({ kind: 'ok', title: tr('toastCreated', { name }) })
|
||||
@@ -981,6 +1029,9 @@ export const App: React.FC = () => {
|
||||
action: { label: tr('backToEdit'), onClick: () => { setWizardDraft(draft); setShowWizard(true) } },
|
||||
})
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingCreates((prev) => prev.filter((item) => item !== name))
|
||||
})
|
||||
}
|
||||
|
||||
const copy = async (text: string) => {
|
||||
@@ -1185,6 +1236,7 @@ export const App: React.FC = () => {
|
||||
safeMode={state?.safe_mode}
|
||||
updateDot={!!update.info?.has_update}
|
||||
pluginViews={sidebarPluginViews}
|
||||
creatingVMs={creatingItems.map((item) => ({ name: item.name, percent: item.task?.percent ?? -1 }))}
|
||||
updateCard={update.shown ? (
|
||||
<UpdateCapsule
|
||||
locale={locale}
|
||||
@@ -1249,6 +1301,14 @@ export const App: React.FC = () => {
|
||||
onOpenView={openView}
|
||||
onNavigate={navigateHost}
|
||||
/>
|
||||
) : selectedCreating ? (
|
||||
<CreatingVMView
|
||||
locale={locale}
|
||||
name={selectedCreating.name}
|
||||
task={selectedCreating.task}
|
||||
onCancel={cancelTask}
|
||||
onViewLogs={() => openLogs('app')}
|
||||
/>
|
||||
) : selectedVM ? (
|
||||
<>
|
||||
{renderVMTabs()}
|
||||
@@ -1391,6 +1451,7 @@ export const App: React.FC = () => {
|
||||
locale={locale}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
captureSupported={state.runtime_capture_supported}
|
||||
tasks={Object.values(taskMap)}
|
||||
draft={wizardDraft}
|
||||
onClose={() => { setShowWizard(false); setWizardDraft(null) }}
|
||||
@@ -1408,6 +1469,7 @@ export const App: React.FC = () => {
|
||||
stats={latestVMStats(selectedVM?.driver_id ?? '', detail.name)}
|
||||
host={state.host}
|
||||
fixedModeSupported={fixedModeSupported}
|
||||
diskCacheSupported={diskCacheSupported}
|
||||
optimizations={state.optimizations}
|
||||
running={effectiveState === 'running'}
|
||||
onCopy={copy}
|
||||
|
||||
@@ -43,7 +43,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [switchingChannel, setSwitchingChannel] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [qqInstalled, setQQInstalled] = useState<boolean | null>(null)
|
||||
const [openingQQ, setOpeningQQ] = useState(false)
|
||||
@@ -128,54 +127,53 @@ export const AboutPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const handleChannelChange = async (next: AppUpdateChannel) => {
|
||||
if (next === appUpdateChannel || switchingChannel) return
|
||||
setSwitchingChannel(true)
|
||||
if (next === appUpdateChannel) return
|
||||
setUpdateErr('')
|
||||
try {
|
||||
await onAppUpdateChannel(next)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setSwitchingChannel(false)
|
||||
}
|
||||
}
|
||||
|
||||
const version = appVersion ?? appUpdate?.current ?? ''
|
||||
const visibleUpdate = appUpdate && (!appUpdate.channel || appUpdate.channel === appUpdateChannel) ? appUpdate : null
|
||||
const visiblePhase: UpdatePhase = visibleUpdate ? updatePhase : 'none'
|
||||
const version = appVersion ?? visibleUpdate?.current ?? ''
|
||||
const pct = updateTask && updateTask.percent >= 0 ? Math.round(updateTask.percent) : null
|
||||
const updateAvailableKey: I18nKey = appUpdate?.channel === 'dev'
|
||||
const updateAvailableKey: I18nKey = visibleUpdate?.channel === 'dev'
|
||||
? 'appUpdateAvailableDev'
|
||||
: appUpdate?.channel === 'alpha'
|
||||
: visibleUpdate?.channel === 'alpha'
|
||||
? 'appUpdateAvailableAlpha'
|
||||
: 'appUpdateAvailable'
|
||||
|
||||
let updateSub: React.ReactNode = null
|
||||
if (updatePhase === 'downloading') {
|
||||
if (visiblePhase === 'downloading') {
|
||||
updateSub = (
|
||||
<>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: appUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: visibleUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<span className="progress rg-p-progress about-update-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${(pct ?? 0) / 100})` }} />
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
} else if (updatePhase === 'ready') {
|
||||
updateSub = <div className="row-sub">{tr('updateReadySub', { v: appUpdate?.latest ?? '' })}</div>
|
||||
} else if (updatePhase === 'failed') {
|
||||
} else if (visiblePhase === 'ready') {
|
||||
updateSub = <div className="row-sub">{tr('updateReadySub', { v: visibleUpdate?.latest ?? '' })}</div>
|
||||
} else if (visiblePhase === 'failed') {
|
||||
updateSub = <div className="row-sub warn-text" title={updateTask?.error}>{tr('updateFailedSub')}</div>
|
||||
} else if (appUpdate?.has_update) {
|
||||
updateSub = <div className="row-sub">{tr(updateAvailableKey, { v: appUpdate.latest })}</div>
|
||||
} else if (visibleUpdate?.has_update) {
|
||||
updateSub = <div className="row-sub">{tr(updateAvailableKey, { v: visibleUpdate.latest })}</div>
|
||||
} else if (updateErr) {
|
||||
updateSub = <div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
}
|
||||
|
||||
let updateAction: React.ReactNode
|
||||
if (updatePhase === 'downloading') {
|
||||
if (visiblePhase === 'downloading') {
|
||||
updateAction = <Button onClick={onCancelUpdate}>{tr('updateCancel')}</Button>
|
||||
} else if (updatePhase === 'ready') {
|
||||
} else if (visiblePhase === 'ready') {
|
||||
updateAction = <Button variant="primary" busy={installing} onClick={onInstallUpdate}>{tr('updateRestart')}</Button>
|
||||
} else if (updatePhase === 'failed') {
|
||||
} else if (visiblePhase === 'failed') {
|
||||
updateAction = <Button variant="primary" icon={<RotateCw size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateRetry')}</Button>
|
||||
} else if (updatePhase === 'available') {
|
||||
} else if (visiblePhase === 'available') {
|
||||
updateAction = <Button variant="primary" icon={<Download size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateDownloadInstall')}</Button>
|
||||
} else {
|
||||
updateAction = <Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>{tr('appCheckUpdate')}</Button>
|
||||
@@ -197,15 +195,15 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{version}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
{visibleUpdate && !visibleUpdate.has_update && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{updateSub}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && appUpdate.page_url && (
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(appUpdate.page_url!)}>
|
||||
{visibleUpdate?.has_update && visibleUpdate.page_url && (
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(visibleUpdate.page_url!)}>
|
||||
{tr('updateReleaseNotes')}
|
||||
</Button>
|
||||
)}
|
||||
@@ -229,9 +227,9 @@ export const AboutPage: React.FC<Props> = ({
|
||||
value={appUpdateChannel}
|
||||
onChange={(v) => void handleChannelChange(v)}
|
||||
options={[
|
||||
{ value: 'stable' as AppUpdateChannel, label: tr('appUpdateChannelStable'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'alpha' as AppUpdateChannel, label: tr('appUpdateChannelAlpha'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'dev' as AppUpdateChannel, label: tr('appUpdateChannelDev'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'stable' as AppUpdateChannel, label: tr('appUpdateChannelStable'), disabled: updatePhase === 'downloading' || installing },
|
||||
{ value: 'alpha' as AppUpdateChannel, label: tr('appUpdateChannelAlpha'), disabled: updatePhase === 'downloading' || installing },
|
||||
{ value: 'dev' as AppUpdateChannel, label: tr('appUpdateChannelDev'), disabled: updatePhase === 'downloading' || installing },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -245,7 +243,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpWebsite')}</div>
|
||||
<div className="row-sub">{tr('aboutWebsiteSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(siteURL(locale))}>
|
||||
@@ -256,7 +253,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpProjectPage')}</div>
|
||||
<div className="row-sub">{tr('aboutProjectSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(REPO_URL)}>
|
||||
@@ -267,7 +263,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpReportIssue')}</div>
|
||||
<div className="row-sub">{tr('aboutIssueSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/issues`)}>
|
||||
@@ -278,7 +273,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutLicensesTitle')}</div>
|
||||
<div className="row-sub">{tr('aboutLicensesSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={() => void openLicenses()}>
|
||||
@@ -292,7 +286,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutDiscord')}</div>
|
||||
<div className="row-sub">{tr('aboutDiscordSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{onCopy && (
|
||||
@@ -320,9 +313,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-sub">{tr('aboutQQNotInstalledSub')}</div>
|
||||
) : qqLaunchErr ? (
|
||||
<div className="row-sub" title={qqLaunchErr}>{tr('aboutQQLaunchFailed')}</div>
|
||||
) : (
|
||||
<div className="row-sub">{tr('aboutQQGroupSub')}</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{qqInstalled && !qqLaunchErr ? (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { AlertTriangle, Check, Cpu } from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/settings.gen'
|
||||
import { I18nKey, parseAppError, t } from '../i18n'
|
||||
import { HostReport, Locale, LogicalCPUInfo, VMAffinityMode, VMAffinityStatus } from '../types'
|
||||
@@ -85,12 +85,15 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const topology = useMemo(() => buildTopology(host), [host])
|
||||
const allIndices = useMemo(() => topology.map((c) => c.index), [topology])
|
||||
const allIndicesRef = useRef(allIndices)
|
||||
allIndicesRef.current = allIndices
|
||||
const hasSMT = useMemo(() => topology.some((c) => c.smt), [topology])
|
||||
|
||||
const [status, setStatus] = useState<VMAffinityStatus | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [saving, setSaving] = useState(false)
|
||||
const [err, setErr] = useState('')
|
||||
const [reloadSeq, setReloadSeq] = useState(0)
|
||||
|
||||
const [mode, setMode] = useState<VMAffinityMode>('auto')
|
||||
const [selected, setSelected] = useState<number[]>(allIndices)
|
||||
@@ -98,6 +101,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
setStatus(null)
|
||||
setLoading(true)
|
||||
setErr('')
|
||||
api.GetVMAffinity(driverID, vmName)
|
||||
@@ -107,7 +111,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
setMode(st.mode || 'auto')
|
||||
const initial = st.mode === 'custom' && st.cpus?.length > 0
|
||||
? st.cpus
|
||||
: (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndices)
|
||||
: (st.effective_cpus?.length > 0 ? st.effective_cpus : allIndicesRef.current)
|
||||
setSelected([...initial].sort((a, b) => a - b))
|
||||
setDisableEcoQoS(st.disable_eco_qos)
|
||||
})
|
||||
@@ -118,13 +122,16 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
if (live) setLoading(false)
|
||||
})
|
||||
return () => { live = false }
|
||||
}, [vmName, allIndices])
|
||||
}, [driverID, vmName, reloadSeq])
|
||||
|
||||
const locked = loading || saving || !status
|
||||
const loadFailed = !loading && !status && !!err
|
||||
const selectedSet = useMemo(() => new Set(selected), [selected])
|
||||
const effectiveVCPUs = status?.vcpus || vcpus
|
||||
const maskHex = useMemo(() => maskHexFromCPUs(selected), [selected])
|
||||
|
||||
const applyPreset = (nextMode: VMAffinityMode) => {
|
||||
if (locked) return
|
||||
setMode(nextMode)
|
||||
setErr('')
|
||||
switch (nextMode) {
|
||||
@@ -150,6 +157,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const toggleCPU = (idx: number) => {
|
||||
if (locked) return
|
||||
setMode('custom')
|
||||
setErr('')
|
||||
setSelected((prev) => {
|
||||
@@ -161,6 +169,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const pickCustomList = (list: number[]) => {
|
||||
if (locked) return
|
||||
setMode('custom')
|
||||
setErr('')
|
||||
setSelected([...new Set(list)].sort((a, b) => a - b))
|
||||
@@ -178,12 +187,12 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
return out
|
||||
}, [topology])
|
||||
|
||||
const modeOptions: { value: VMAffinityMode; label: string }[] = [
|
||||
{ value: 'auto', label: tr('affinityModeAuto') },
|
||||
{ value: 'all', label: tr('affinityModeAll') },
|
||||
...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores') }] : []),
|
||||
...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE') }] : []),
|
||||
{ value: 'custom', label: tr('affinityModeCustom') },
|
||||
const modeOptions: { value: VMAffinityMode; label: string; disabled?: boolean }[] = [
|
||||
{ value: 'auto', label: tr('affinityModeAuto'), disabled: locked },
|
||||
{ value: 'all', label: tr('affinityModeAll'), disabled: locked },
|
||||
...(host.has_hybrid_cores ? [{ value: 'pcores' as const, label: tr('affinityModePCores'), disabled: locked }] : []),
|
||||
...((host.lpe_core_count ?? 0) > 0 ? [{ value: 'non_lpe' as const, label: tr('affinityModeNonLPE'), disabled: locked }] : []),
|
||||
{ value: 'custom', label: tr('affinityModeCustom'), disabled: locked },
|
||||
]
|
||||
|
||||
const modeHintKey: Record<VMAffinityMode, I18nKey> = {
|
||||
@@ -199,6 +208,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
const allSelected = selected.length === allIndices.length && allIndices.length > 0
|
||||
|
||||
const handleSave = async () => {
|
||||
if (locked) return
|
||||
if (emptyCustom) {
|
||||
setErr(tr('affinityNeedOne'))
|
||||
return
|
||||
@@ -254,7 +264,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<button
|
||||
type="button"
|
||||
className={`affinity-chip${allSelected ? ' is-active' : ''}`}
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onClick={() => pickCustomList(allSelected ? [allIndices[0]] : allIndices)}
|
||||
>
|
||||
{tr('affinitySelectAll')}
|
||||
@@ -263,7 +273,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onClick={() => pickCustomList(physicalOnlyList)}
|
||||
>
|
||||
{tr('affinityPhysicalOnly')}
|
||||
@@ -273,7 +283,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onClick={() => pickCustomList(allIndices.filter((i) => i !== 0))}
|
||||
>
|
||||
{tr('affinityExcludeCPU0')}
|
||||
@@ -283,7 +293,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier === 'p').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityOnlyPCores')}
|
||||
@@ -293,7 +303,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<button
|
||||
type="button"
|
||||
className="affinity-chip"
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onClick={() => pickCustomList(topology.filter((c) => c.tier !== 'lpe').map((c) => c.index))}
|
||||
>
|
||||
{tr('affinityAvoidLPE')}
|
||||
@@ -311,7 +321,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
type="button"
|
||||
role="checkbox"
|
||||
aria-checked={checked}
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
className={`affinity-cpu${checked ? ' is-checked' : ''}${cpu.tier === 'lpe' ? ' is-lpe' : ''}`}
|
||||
onClick={() => toggleCPU(cpu.index)}
|
||||
>
|
||||
@@ -357,12 +367,21 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<Switch
|
||||
label={tr('affinityEcoQoS')}
|
||||
checked={disableEcoQoS}
|
||||
disabled={loading || saving}
|
||||
disabled={locked}
|
||||
onChange={setDisableEcoQoS}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{err && <div className="notice notice-error" role="alert">{err}</div>}
|
||||
{err && (
|
||||
<div className="notice notice-error" role="alert">
|
||||
<span className="notice-main">{err}</span>
|
||||
{loadFailed && (
|
||||
<Button onClick={() => setReloadSeq((n) => n + 1)}>
|
||||
{tr('installersRetry')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="dialog-foot">
|
||||
@@ -370,7 +389,7 @@ export const AffinityDialog: React.FC<Props> = ({
|
||||
<Button
|
||||
variant="primary"
|
||||
busy={saving}
|
||||
disabled={loading || emptyCustom}
|
||||
disabled={loading || !status || emptyCustom}
|
||||
onClick={() => void handleSave()}
|
||||
>
|
||||
{status?.running ? tr('affinityApplyNow') : tr('affinitySave')}
|
||||
|
||||
@@ -123,9 +123,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const missingFontScript = state.missing_font_hint || ''
|
||||
const memSpecLabel = host.memory_spec?.speed_mhz
|
||||
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
@@ -491,6 +488,49 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('themeLabel')}</div>
|
||||
{(!canDark || !canLight) && (
|
||||
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
|
||||
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
|
||||
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsGeneral')}</div>
|
||||
<div className="list">
|
||||
@@ -524,24 +564,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('syncHostMemorySMBIOS')}</div>
|
||||
<div className="row-sub">
|
||||
{memSpecLabel
|
||||
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
|
||||
: tr('syncHostMemorySMBIOSUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('syncHostMemorySMBIOS')}
|
||||
disabled={!memSpecLabel}
|
||||
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
|
||||
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('minimizeToTray')}</div>
|
||||
@@ -826,49 +848,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('themeLabel')}</div>
|
||||
{(!canDark || !canLight) && (
|
||||
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
|
||||
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
|
||||
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{pluginViews.length > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('sidebarPlugins')}</div>
|
||||
|
||||
@@ -53,6 +53,7 @@ interface Props {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
fixedModeSupported?: boolean
|
||||
captureSupported?: boolean
|
||||
tasks?: Task[]
|
||||
draft?: WizardDraft | null
|
||||
onClose: () => void
|
||||
@@ -80,7 +81,7 @@ const SOURCES: { mode: 'offline' | 'apple' | 'installer' | 'disk'; icon: LucideI
|
||||
{ mode: 'disk', icon: HardDrive, title: 'srcDiskTitle', sub: 'srcDiskSub' },
|
||||
]
|
||||
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, tasks = [], draft, onClose, onSubmit }) => {
|
||||
export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported = false, captureSupported = false, tasks = [], draft, onClose, onSubmit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [step, setStep] = useState(draft?.step ?? 1)
|
||||
// Once the user has reached the review step, keep validating so step markers stay current.
|
||||
@@ -126,7 +127,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
resolution: recommendedResolution(host),
|
||||
displays: 1,
|
||||
borderless: false,
|
||||
capture: false,
|
||||
...(captureSupported ? { capture: false } : {}),
|
||||
audio: true,
|
||||
network: false,
|
||||
network_mode: 'off',
|
||||
@@ -159,6 +160,9 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
|
||||
const buildPayload = (): CreateOpts => {
|
||||
const p: CreateOpts = { ...opts, offline: opts.source_mode === 'offline' }
|
||||
if (!captureSupported) {
|
||||
delete p.capture
|
||||
}
|
||||
if (p.source_mode === 'offline') {
|
||||
p.installer = ''
|
||||
p.disk = ''
|
||||
@@ -229,7 +233,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
.finally(() => { if (live) setChecking(false) })
|
||||
}, 200)
|
||||
return () => { live = false; clearTimeout(timer) }
|
||||
}, [step, reviewed, opts, validationRefresh])
|
||||
}, [step, reviewed, opts, validationRefresh, captureSupported])
|
||||
|
||||
const pickDir = async () => {
|
||||
const dir = await api.PickDirectory(tr('vmDir'))
|
||||
@@ -668,11 +672,13 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
title={tr('enableAudio')}
|
||||
control={<Switch label={tr('enableAudio')} checked={!!opts.audio} onChange={(audio) => set({ audio })} />}
|
||||
/>
|
||||
<SetRow
|
||||
title={tr('captureInput')}
|
||||
desc={tr('captureInputHint')}
|
||||
control={<Switch label={tr('captureInput')} checked={!!opts.capture} onChange={(capture) => set({ capture })} />}
|
||||
/>
|
||||
{captureSupported && (
|
||||
<SetRow
|
||||
title={tr('captureInput')}
|
||||
desc={tr('captureInputHint')}
|
||||
control={<Switch label={tr('captureInput')} checked={!!opts.capture} onChange={(capture) => set({ capture })} />}
|
||||
/>
|
||||
)}
|
||||
<SetRow
|
||||
title={tr('fullscreenLaunch')}
|
||||
desc={opts.borderless ? tr('fullscreenDecoupledHint') : tr('fullscreenLaunchHint')}
|
||||
@@ -702,6 +708,7 @@ export const CreateWizard: React.FC<Props> = ({ locale, host, fixedModeSupported
|
||||
locale={locale}
|
||||
host={host}
|
||||
opts={opts}
|
||||
captureSupported={captureSupported}
|
||||
networkUplink={networkAdapters?.find((adapter) => adapter.guid === opts.uplink_guid)?.name}
|
||||
issues={issues}
|
||||
checking={checking}
|
||||
@@ -765,6 +772,7 @@ interface ReviewProps {
|
||||
locale: Locale
|
||||
host: HostReport
|
||||
opts: CreateOpts
|
||||
captureSupported: boolean
|
||||
issues: ValidationIssue[]
|
||||
checking: boolean
|
||||
command: string
|
||||
@@ -780,7 +788,7 @@ type Row = { label: string; value: string; mono?: boolean }
|
||||
const fileName = (p?: string) => (p ?? '').split(/[\\/]/).pop() || (p ?? '')
|
||||
|
||||
/** Step ⑤: what will be created, grouped by the step that set it, with the CLI equivalent folded away. */
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
|
||||
const Review: React.FC<ReviewProps> = ({ locale, host, opts, captureSupported, issues, checking, command, onEdit, onName, onDir, onPickDir, onStartAfter, networkUplink }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const onOff = (b?: boolean) => tr(b ? 'summaryOn' : 'off')
|
||||
@@ -835,7 +843,7 @@ const Review: React.FC<ReviewProps> = ({ locale, host, opts, issues, checking, c
|
||||
...graphicsRows,
|
||||
{ label: tr('fieldAudio'), value: onOff(opts.audio) },
|
||||
{ label: tr('fieldNetwork'), value: opts.network_mode === 'bridge' ? `${tr('networkBridge')} · ${networkUplink ?? tr('bridgeUplink')}` : tr((opts.network_mode ?? (opts.network ? 'nat' : 'off')) === 'off' ? 'off' : 'networkNAT') },
|
||||
{ label: tr('captureInput'), value: onOff(opts.capture) },
|
||||
...(captureSupported ? [{ label: tr('captureInput'), value: onOff(opts.capture) }] : []),
|
||||
{ label: tr('summarySSH'), value: opts.ssh_port ? tr('summarySSHPort', { n: opts.ssh_port }) : tr('off') },
|
||||
{ label: tr('summaryLogs'), value: onOff(opts.logs) },
|
||||
],
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import { LoaderCircle, Terminal, X } from 'lucide-react'
|
||||
import React from 'react'
|
||||
import '../i18n/domains/vm.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { taskDetail, taskTitle } from '../lib/tasks'
|
||||
import { Locale, Task } from '../types'
|
||||
import { Button, StatusShape } from '../ui/controls'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
name: string
|
||||
task?: Task
|
||||
onCancel?: (taskId: string) => void
|
||||
onViewLogs: () => void
|
||||
}
|
||||
|
||||
export const CreatingVMView: React.FC<Props> = ({ locale, name, task, onCancel, onViewLogs }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const percent = task && typeof task.percent === 'number' ? task.percent : -1
|
||||
const detail = task ? taskDetail(task) : ''
|
||||
const stepText = task?.step?.trim() || tr('creatingPreparing')
|
||||
const heading = task ? taskTitle(locale, task) : tr('taskCreate', { name })
|
||||
|
||||
return (
|
||||
<div className="page">
|
||||
<div className="page-head">
|
||||
<div>
|
||||
<h1 className="page-title">{name}</h1>
|
||||
<div className="page-sub hstack">
|
||||
<StatusShape kind="busy" />
|
||||
<span>{tr('state_creating')}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="hstack">
|
||||
<Button variant="ghost" icon={<Terminal size={14} aria-hidden="true" />} onClick={onViewLogs}>
|
||||
{tr('viewLogs')}
|
||||
</Button>
|
||||
{task?.cancelable && onCancel && (
|
||||
<Button variant="secondary" icon={<X size={14} aria-hidden="true" />} onClick={() => onCancel(task.id)}>
|
||||
{tr('cancelCreate')}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('creatingProgressTitle')}</div>
|
||||
<div className="list">
|
||||
<div className="row creating-row">
|
||||
<div className="creating-head">
|
||||
<span className="row-title hstack">
|
||||
<LoaderCircle size={15} className="spin" aria-hidden="true" />
|
||||
<span>{heading}</span>
|
||||
</span>
|
||||
{percent >= 0 && <span className="task-pct mono">{Math.floor(percent)}%</span>}
|
||||
</div>
|
||||
{percent >= 0 && (
|
||||
<span className="progress rg-p-progress creating-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${Math.max(0, Math.min(1, percent / 100))})` }} />
|
||||
</span>
|
||||
)}
|
||||
<div className="row-sub">
|
||||
{stepText}
|
||||
{detail ? ` · ${detail}` : ''}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import { AppState, Locale, StorageBreakdown, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
import { Switch } from '../ui/settings'
|
||||
import { api } from '../wails'
|
||||
import { sameRuntimeId } from '../lib/runtimeStatus'
|
||||
import { RuntimeOnline } from './RuntimeOnline'
|
||||
|
||||
interface Props {
|
||||
@@ -30,6 +31,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
const [enabling, setEnabling] = useState(false)
|
||||
const [savingASLR, setSavingASLR] = useState(false)
|
||||
const [confirmDelete, setConfirmDelete] = useState('')
|
||||
const [latestRuntimeCommit, setLatestRuntimeCommit] = useState('')
|
||||
const [removing, setRemoving] = useState('')
|
||||
const [storage, setStorage] = useState<StorageBreakdown | null>(null)
|
||||
const { host, config, runtimes } = state
|
||||
@@ -215,6 +217,7 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
onChannel={onChannel}
|
||||
onInstall={onInstallRuntime}
|
||||
onCancel={onCancelTask}
|
||||
onLatestCommit={setLatestRuntimeCommit}
|
||||
/>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
@@ -228,7 +231,12 @@ export const HostView: React.FC<Props> = ({ state, locale, onRefresh, onNewVM, o
|
||||
{(runtimes ?? []).filter((rt) => !rt.active).map((rt) => (
|
||||
<div className="row" key={rt.commit}>
|
||||
<div className="row-main">
|
||||
<div className="row-title"><span className="mono">{rt.commit}</span></div>
|
||||
<div className="row-title">
|
||||
<span className="mono">{rt.commit}</span>
|
||||
{latestRuntimeCommit && sameRuntimeId(rt.commit, latestRuntimeCommit) && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeLatestBadge')}</span>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-sub">{rt.manifest.qemu_version.replace(/^QEMU emulator version\s*/i, 'QEMU ')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import {
|
||||
Boxes, Clipboard, Compass, Cpu, Disc3, Globe, Keyboard,
|
||||
Layers, Monitor, Palette, Puzzle, RotateCcw,
|
||||
Boxes, Globe, Layers, Monitor, Palette, Puzzle,
|
||||
} from 'lucide-react'
|
||||
import React from 'react'
|
||||
import { PermissionSpec } from '../types'
|
||||
import { PermissionSpec, PluginIcon } from '../types'
|
||||
|
||||
export interface PluginVisualSource {
|
||||
id?: string
|
||||
kind?: string
|
||||
system?: boolean
|
||||
tier?: string
|
||||
icon?: PluginIcon
|
||||
locales?: string[]
|
||||
permissions?: Array<PermissionSpec | string>
|
||||
}
|
||||
@@ -21,12 +21,25 @@ export interface PluginVisual {
|
||||
|
||||
const ICON_SIZES = { sm: 16, md: 18, lg: 20 } as const
|
||||
|
||||
/**
|
||||
* Single visual resolver for both installed plugins (PluginInfo) and market
|
||||
* entries (MarketEntry), so a plugin keeps the same icon and colour across
|
||||
* Market, Installed and first-run setup.
|
||||
*/
|
||||
export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): PluginVisual {
|
||||
const PLUGIN_ICON_TONES = new Set([
|
||||
'indigo', 'purple', 'sky', 'rose', 'emerald', 'amber', 'teal', 'slate',
|
||||
])
|
||||
|
||||
function normalizeTone(tone?: string): string {
|
||||
const t = (tone ?? '').trim().toLowerCase()
|
||||
return PLUGIN_ICON_TONES.has(t) ? t : ''
|
||||
}
|
||||
|
||||
function toSafeSvgMaskUrl(raw?: string): string {
|
||||
const s = (raw ?? '').trim()
|
||||
if (!s) return ''
|
||||
const lower = s.toLowerCase()
|
||||
if (!lower.startsWith('<svg') || !lower.includes('</svg>')) return ''
|
||||
if (/<script\b|\bon[a-z]+\s*=|javascript:|<foreignobject\b/i.test(s)) return ''
|
||||
return `url("data:image/svg+xml,${encodeURIComponent(s)}")`
|
||||
}
|
||||
|
||||
function fallbackVisual(src: PluginVisualSource, iconSize: number): PluginVisual {
|
||||
if (src.system) return { tone: 'indigo', icon: <Boxes size={iconSize} aria-hidden="true" /> }
|
||||
switch (src.kind) {
|
||||
case 'theme': return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
@@ -34,41 +47,46 @@ export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): Plu
|
||||
case 'driver':
|
||||
case 'runtime': return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
const id = (src.id ?? '').toLowerCase()
|
||||
const perms = new Set((src.permissions ?? []).map((x) => (typeof x === 'string' ? x : x.name)))
|
||||
if ((src.locales?.length ?? 0) > 0 || id.includes('lang') || id.includes('locale')) {
|
||||
if ((src.locales?.length ?? 0) > 0) {
|
||||
return { tone: 'sky', icon: <Globe size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('theme') || perms.has('ui:script')) {
|
||||
if (perms.has('ui:script')) {
|
||||
return { tone: 'purple', icon: <Palette size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('driver') || perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
if (perms.has('driver:vm') || perms.has('runtime:provider')) {
|
||||
return { tone: 'indigo', icon: <Monitor size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('clipboard') || perms.has('host:clipboard')) {
|
||||
return { tone: 'sky', icon: <Clipboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('ime') || id.includes('input') || id.includes('wheel') || perms.has('input:filter')) {
|
||||
return { tone: 'rose', icon: <Keyboard size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('reboot')) {
|
||||
return { tone: 'amber', icon: <RotateCcw size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('whpx') || id.includes('irq')) {
|
||||
return { tone: 'emerald', icon: <Cpu size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('guide')) {
|
||||
return { tone: 'teal', icon: <Compass size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (id.includes('offline') || id.includes('installer') || id.includes('helper') || id.includes('image')) {
|
||||
return { tone: 'teal', icon: <Disc3 size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
if (src.tier === 'L3') {
|
||||
return { tone: 'slate', icon: <Layers size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
return { tone: 'teal', icon: <Puzzle size={iconSize} aria-hidden="true" /> }
|
||||
}
|
||||
|
||||
/**
|
||||
* Single visual resolver for both installed plugins (PluginInfo) and market
|
||||
* entries (MarketEntry), prioritizing declared icon tone + monochrome SVG
|
||||
* foreground with a kind-based fallback for legacy plugins.
|
||||
*/
|
||||
export function resolvePluginVisual(src: PluginVisualSource, iconSize = 20): PluginVisual {
|
||||
const fb = fallbackVisual(src, iconSize)
|
||||
const tone = normalizeTone(src.icon?.tone) || fb.tone
|
||||
const maskUrl = toSafeSvgMaskUrl(src.icon?.svg)
|
||||
if (maskUrl) {
|
||||
const style: React.CSSProperties = {
|
||||
width: iconSize,
|
||||
height: iconSize,
|
||||
WebkitMaskImage: maskUrl,
|
||||
maskImage: maskUrl,
|
||||
}
|
||||
return {
|
||||
tone,
|
||||
icon: <span className="plugin-app-icon-svg" style={style} aria-hidden="true" />,
|
||||
}
|
||||
}
|
||||
return { tone, icon: fb.icon }
|
||||
}
|
||||
|
||||
/** App Store-inspired squircle icon tile shared by Market, Installed and Setup. */
|
||||
export const PluginAppIcon: React.FC<{
|
||||
plugin?: PluginVisualSource
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import { AlertTriangle, Check, Download, ShieldAlert } from 'lucide-react'
|
||||
import { AlertTriangle, Check, Download, ShieldAlert, Star } from 'lucide-react'
|
||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
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 { PopupSelect } from '../ui/settings'
|
||||
import { api, events, MarketInstallProgress } from '../wails'
|
||||
import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge, RiskList } from './PluginParts'
|
||||
import { WordmarkLoader } from './WordmarkLoader'
|
||||
@@ -25,6 +26,56 @@ const KIND_LABELS: Record<string, I18nKey> = {
|
||||
runtime: 'pluginMarketKindRuntime',
|
||||
}
|
||||
|
||||
type MarketSortMode = 'composite' | 'stars' | 'downloads' | 'recent'
|
||||
|
||||
function formatCompactCount(n: number): string {
|
||||
if (n >= 10000) return `${(n / 1000).toFixed(0)}k`
|
||||
if (n >= 1000) return `${(n / 1000).toFixed(1).replace(/\.0$/, '')}k`
|
||||
return String(n)
|
||||
}
|
||||
|
||||
function formatByteSize(bytes?: number): string {
|
||||
if (!bytes || bytes <= 0) return ''
|
||||
if (bytes >= 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
|
||||
if (bytes >= 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`
|
||||
return `${bytes} B`
|
||||
}
|
||||
|
||||
function formatShortDate(iso?: string): string {
|
||||
if (!iso) return ''
|
||||
const ms = Date.parse(iso)
|
||||
if (Number.isNaN(ms)) return ''
|
||||
return new Date(ms).toISOString().slice(0, 10)
|
||||
}
|
||||
|
||||
function parseTimestamp(iso?: string): number {
|
||||
if (!iso) return 0
|
||||
const ms = Date.parse(iso)
|
||||
return Number.isNaN(ms) ? 0 : ms
|
||||
}
|
||||
|
||||
function compositeScore(item: MarketCatalogItem, nowMs: number): number {
|
||||
const ts = parseTimestamp(item.entry.updated_at)
|
||||
const ageDays = ts > 0 ? Math.max(0, (nowMs - ts) / 86400000) : 3650
|
||||
const recency = ts > 0 ? 10 / (1 + ageDays / 30) : 0
|
||||
const downloads = Math.log1p(Math.max(0, item.entry.downloads ?? 0)) * 2
|
||||
return recency + downloads
|
||||
}
|
||||
|
||||
function entryReleases(item: MarketCatalogItem) {
|
||||
const e = item.entry
|
||||
if (e.releases && e.releases.length > 0) return e.releases
|
||||
return [{
|
||||
version: e.version,
|
||||
channel: e.channel || 'stable',
|
||||
download_url: e.download_url,
|
||||
sha256: e.sha256,
|
||||
size_bytes: e.size_bytes,
|
||||
published_at: e.updated_at,
|
||||
changelog: e.changelog,
|
||||
}]
|
||||
}
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
safeMode?: boolean
|
||||
@@ -50,6 +101,8 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [query, setQuery] = useState('')
|
||||
const [kind, setKind] = useState('')
|
||||
const [sortBy, setSortBy] = useState<MarketSortMode>('composite')
|
||||
const [versionPick, setVersionPick] = useState<{ item: MarketCatalogItem; selected: string } | null>(null)
|
||||
const [result, setResult] = useState<MarketBrowseResult | null>(null)
|
||||
const [syncing, setSyncing] = useState(false)
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
@@ -79,7 +132,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
const started = Date.now()
|
||||
if (force) setRefreshing(true)
|
||||
try {
|
||||
const res = await api.BrowsePluginMarket(q, k, false, force)
|
||||
const res = await api.BrowsePluginMarket(q, k, true, force)
|
||||
if (force) {
|
||||
const wait = MIN_REFRESH_MS - (Date.now() - started)
|
||||
if (wait > 0) await new Promise((r) => window.setTimeout(r, wait))
|
||||
@@ -146,7 +199,40 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
setProgress((prev) => prev[p.id] ? { ...prev, [p.id]: p } : prev)
|
||||
}), [])
|
||||
|
||||
const items = result?.items ?? []
|
||||
const items = useMemo(() => {
|
||||
const raw = result?.items ?? []
|
||||
if (raw.length <= 1) return raw
|
||||
const nowMs = Date.now()
|
||||
return [...raw].sort((a, b) => {
|
||||
if (a.update_available !== b.update_available) return a.update_available ? -1 : 1
|
||||
switch (sortBy) {
|
||||
case 'stars': {
|
||||
const d = (b.entry.stars ?? 0) - (a.entry.stars ?? 0)
|
||||
if (d !== 0) return d
|
||||
break
|
||||
}
|
||||
case 'downloads': {
|
||||
const d = (b.entry.downloads ?? 0) - (a.entry.downloads ?? 0)
|
||||
if (d !== 0) return d
|
||||
break
|
||||
}
|
||||
case 'recent': {
|
||||
const d = parseTimestamp(b.entry.updated_at) - parseTimestamp(a.entry.updated_at)
|
||||
if (d !== 0) return d
|
||||
break
|
||||
}
|
||||
case 'composite':
|
||||
default: {
|
||||
const d = compositeScore(b, nowMs) - compositeScore(a, nowMs)
|
||||
if (Math.abs(d) > 1e-6) return d
|
||||
break
|
||||
}
|
||||
}
|
||||
const dl = (b.entry.downloads ?? 0) - (a.entry.downloads ?? 0)
|
||||
if (dl !== 0) return dl
|
||||
return a.entry.id.localeCompare(b.entry.id)
|
||||
})
|
||||
}, [result?.items, sortBy])
|
||||
const shown = items.slice(0, visible)
|
||||
const hasMore = items.length > visible
|
||||
|
||||
@@ -191,13 +277,22 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
advancePrompt()
|
||||
}
|
||||
|
||||
const install = async (item: MarketCatalogItem) => {
|
||||
const openVersionPicker = (item: MarketCatalogItem) => {
|
||||
const list = entryReleases(item)
|
||||
const defaultVer = list.find((r) => r.version === item.entry.version)?.version ?? list[0]?.version ?? item.entry.version
|
||||
setVersionPick({ item, selected: defaultVer })
|
||||
}
|
||||
|
||||
const install = async (item: MarketCatalogItem, version?: string) => {
|
||||
const id = item.entry.id
|
||||
if (installingRef.current.has(id)) return
|
||||
installingRef.current.add(id)
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: item.entry.size_bytes ?? 0 } }))
|
||||
const rel = entryReleases(item).find((r) => r.version === version)
|
||||
setProgress((prev) => ({ ...prev, [id]: { id, phase: 'download', done: 0, total: rel?.size_bytes ?? item.entry.size_bytes ?? 0 } }))
|
||||
try {
|
||||
const info = await api.InstallMarketPlugin(id, false)
|
||||
const info = version
|
||||
? await api.InstallMarketPluginVersion(id, version)
|
||||
: await api.InstallMarketPlugin(id, true)
|
||||
await onChanged({})
|
||||
if (info && !info.enabled) {
|
||||
if (promptTargetIDRef.current) {
|
||||
@@ -277,7 +372,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
return (
|
||||
<Tip label={tr('pluginMarketVersionTip', { installed: item.installed_version ?? '', version: e.version })}>
|
||||
<span>
|
||||
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
<Button className="market-btn" variant="primary" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
|
||||
{tr('pluginMarketUpdateShort')}
|
||||
</Button>
|
||||
</span>
|
||||
@@ -285,7 +380,7 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
)
|
||||
}
|
||||
return (
|
||||
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => void install(item)}>
|
||||
<Button className="market-btn" disabled={!!safeMode} icon={<Download size={13} aria-hidden="true" />} onClick={() => openVersionPicker(item)}>
|
||||
{tr('pluginMarketInstall')}
|
||||
</Button>
|
||||
)
|
||||
@@ -299,12 +394,27 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
return (
|
||||
<section className="section plugin-market">
|
||||
<div className="market-toolbar">
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginMarketSearchPlaceholder')}
|
||||
wide
|
||||
/>
|
||||
<div className="market-toolbar-top">
|
||||
<PluginSearchInput
|
||||
value={query}
|
||||
onChange={setQuery}
|
||||
placeholder={tr('pluginMarketSearchPlaceholder')}
|
||||
wide
|
||||
/>
|
||||
<div className="market-sort">
|
||||
<PopupSelect
|
||||
label={tr('pluginMarketSortLabel')}
|
||||
value={sortBy}
|
||||
onChange={(v) => setSortBy(v as MarketSortMode)}
|
||||
options={[
|
||||
{ value: 'composite', label: tr('pluginMarketSortComposite') },
|
||||
{ value: 'stars', label: tr('pluginMarketSortStars') },
|
||||
{ value: 'downloads', label: tr('pluginMarketSortDownloads') },
|
||||
{ value: 'recent', label: tr('pluginMarketSortRecent') },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{facets.length > 1 && (
|
||||
<div className="market-kinds" role="radiogroup" aria-label={tr('pluginMarketKindAll')}>
|
||||
{[{ kind: '', count: 0 }, ...facets].map((f) => (
|
||||
@@ -365,11 +475,52 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
<div className="market-card-head">
|
||||
<PluginAppIcon plugin={e} size="lg" />
|
||||
<div className="market-card-titles">
|
||||
<h3 className="market-card-name" title={locText(e.name, locale, e.id)}>{locText(e.name, locale, e.id)}</h3>
|
||||
{(() => {
|
||||
const title = locText(e.name, locale, e.id)
|
||||
const rawHref = (e.homepage || e.readme_url || '').trim()
|
||||
const href = /^https:\/\//i.test(rawHref) ? rawHref : ''
|
||||
return (
|
||||
<h3 className="market-card-name" title={href || title}>
|
||||
{href ? (
|
||||
<a
|
||||
className="plugin-title-link"
|
||||
href={href}
|
||||
onClick={(ev) => {
|
||||
ev.preventDefault()
|
||||
void api.OpenURL(href).catch((err) => onError(tr('failGeneric'), err))
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</a>
|
||||
) : title}
|
||||
</h3>
|
||||
)
|
||||
})()}
|
||||
<div className="market-card-byline">
|
||||
<PluginTrustBadge locale={locale} trust={e.trust} publisher={e.publisher} />
|
||||
<span className="market-card-dot" aria-hidden="true">·</span>
|
||||
<span className="market-card-version">v{e.version}</span>
|
||||
{e.channel === 'alpha' && (
|
||||
<span className="market-alpha-badge">{tr('pluginMarketAlphaTag')}</span>
|
||||
)}
|
||||
{(e.stars ?? 0) > 0 && (
|
||||
<>
|
||||
<span className="market-card-dot" aria-hidden="true">·</span>
|
||||
<span className="market-card-stat" title={`${e.stars} stars`}>
|
||||
<Star size={11} aria-hidden="true" />
|
||||
{formatCompactCount(e.stars!)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
{(e.downloads ?? 0) > 0 && (
|
||||
<>
|
||||
<span className="market-card-dot" aria-hidden="true">·</span>
|
||||
<span className="market-card-stat" title={`${e.downloads} downloads`}>
|
||||
<Download size={11} aria-hidden="true" />
|
||||
{formatCompactCount(e.downloads!)}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className="market-card-action">{action(item)}</div>
|
||||
@@ -385,6 +536,73 @@ export const PluginMarket: React.FC<Props> = ({
|
||||
</>
|
||||
)}
|
||||
|
||||
{versionPick && (
|
||||
<Modal
|
||||
title={tr('pluginMarketPickVersionTitle')}
|
||||
subtitle={locText(versionPick.item.entry.name, locale, versionPick.item.entry.id)}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setVersionPick(null)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<div className="market-version-list" role="radiogroup" aria-label={tr('pluginMarketPickVersionTitle')}>
|
||||
{entryReleases(versionPick.item).map((rel) => {
|
||||
const selected = versionPick.selected === rel.version
|
||||
const isCurrent = versionPick.item.installed && versionPick.item.installed_version === rel.version
|
||||
const notes = locText(rel.changelog, locale, '')
|
||||
const date = formatShortDate(rel.published_at)
|
||||
const size = formatByteSize(rel.size_bytes)
|
||||
return (
|
||||
<label
|
||||
key={rel.version}
|
||||
className={`market-version-opt${selected ? ' is-selected' : ''}`}
|
||||
>
|
||||
<input
|
||||
type="radio"
|
||||
name="market-version"
|
||||
checked={selected}
|
||||
onChange={() => setVersionPick({ ...versionPick, selected: rel.version })}
|
||||
/>
|
||||
<div className="market-version-main">
|
||||
<div className="market-version-head">
|
||||
<span className="market-card-version">v{rel.version}</span>
|
||||
{rel.channel === 'alpha' && (
|
||||
<span className="market-alpha-badge">{tr('pluginMarketAlphaTag')}</span>
|
||||
)}
|
||||
{isCurrent && (
|
||||
<span className="market-version-current">{tr('pluginMarketCurrentVersion')}</span>
|
||||
)}
|
||||
<span className="market-version-meta">
|
||||
{[date, size].filter(Boolean).join(' · ')}
|
||||
</span>
|
||||
</div>
|
||||
{notes && <p className="market-version-notes">{notes}</p>}
|
||||
</div>
|
||||
</label>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
<span className="hstack">
|
||||
<Button variant="ghost" onClick={() => setVersionPick(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={!versionPick.selected || !!safeMode}
|
||||
icon={<Download size={13} aria-hidden="true" />}
|
||||
onClick={() => {
|
||||
const target = versionPick
|
||||
setVersionPick(null)
|
||||
void install(target.item, target.selected)
|
||||
}}
|
||||
>
|
||||
{tr('pluginMarketPickVersionInstall')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{prompt && (
|
||||
<Modal
|
||||
title={tr('pluginEnablePromptTitle', { name: locText(prompt.name, locale, prompt.id) })}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette,
|
||||
RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2,
|
||||
AlertTriangle, CheckCircle2, ExternalLink, FolderOpen, PackagePlus, Palette,
|
||||
RefreshCw, Settings2, ShieldAlert, Sparkles, Trash2,
|
||||
} from 'lucide-react'
|
||||
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import '../i18n/domains/plugins.gen'
|
||||
@@ -22,6 +22,7 @@ import { SchemaForm } from './SchemaForm'
|
||||
const SEARCH_THRESHOLD = 12
|
||||
// A manual refresh spins at least this long so the click visibly lands.
|
||||
const MIN_SPIN_MS = 500
|
||||
const PLUGIN_MARKET_SUBMIT_URL = 'https://github.com/reims-go/plugins#如何上架插件'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
@@ -67,17 +68,14 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
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)
|
||||
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
|
||||
const [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
|
||||
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(null)
|
||||
|
||||
// Static risk scan modal state (pre-install .zip preview or installed plugin scan)
|
||||
const [scanModal, setScanModal] = useState<{
|
||||
mode: 'archive' | 'installed'
|
||||
archivePath?: string
|
||||
report: ScanReport
|
||||
} | null>(null)
|
||||
// Static risk scan of a .zip, shown before it is installed
|
||||
const [scanModal, setScanModal] = useState<{ archivePath: string; report: ScanReport } | null>(null)
|
||||
// Scan verdicts of installed plugins by id, filled when their permission tooltip opens
|
||||
const [scanVerdicts, setScanVerdicts] = useState<Record<string, string>>({})
|
||||
const [scanBusy, setScanBusy] = useState(false)
|
||||
|
||||
// Mount the market (and touch the network) only after its tab is opened.
|
||||
@@ -99,6 +97,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
api.GetActiveTheme(),
|
||||
])
|
||||
setPlugins(list ?? [])
|
||||
setScanVerdicts({})
|
||||
setContribs(ui)
|
||||
setActiveTheme(th)
|
||||
return { ui, th }
|
||||
@@ -223,7 +222,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
if (!path) return
|
||||
setScanBusy(true)
|
||||
const report = await api.InspectPluginArchive(path)
|
||||
setScanModal({ mode: 'archive', archivePath: path, report })
|
||||
setScanModal({ archivePath: path, report })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailScan'), e)
|
||||
} finally {
|
||||
@@ -232,7 +231,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const confirmInstallScannedArchive = async () => {
|
||||
if (!scanModal || scanModal.mode !== 'archive' || !scanModal.archivePath || scanModal.report.hard_blocked) return
|
||||
if (!scanModal || scanModal.report.hard_blocked) return
|
||||
const archivePath = scanModal.archivePath
|
||||
setScanBusy(true)
|
||||
try {
|
||||
@@ -247,16 +246,15 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const inspectInstalledPlugin = async (p: PluginInfo) => {
|
||||
setScanBusy(true)
|
||||
const loadScanVerdict = async (p: PluginInfo) => {
|
||||
if (scanVerdicts[p.id]) return
|
||||
let verdict = tr('pluginFailScan')
|
||||
try {
|
||||
const report = await api.ScanInstalledPlugin(p.id)
|
||||
setScanModal({ mode: 'installed', report })
|
||||
verdict = locText((await api.ScanInstalledPlugin(p.id)).headline, locale, verdict)
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailScan'), e)
|
||||
} finally {
|
||||
setScanBusy(false)
|
||||
console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e)
|
||||
}
|
||||
setScanVerdicts((current) => ({ ...current, [p.id]: verdict }))
|
||||
}
|
||||
|
||||
const linkDevDir = async () => {
|
||||
@@ -287,7 +285,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
|
||||
const openPluginSettings = async (p: PluginInfo) => {
|
||||
try {
|
||||
const vals = await api.GetPluginSettings(p.id, '')
|
||||
const vals = hasAppSettings(p) ? await api.GetPluginSettings(p.id, '') : null
|
||||
setSettingsValues((vals ?? {}) as Record<string, unknown>)
|
||||
setSettingsTarget(p)
|
||||
} catch (e) {
|
||||
@@ -316,15 +314,6 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
}
|
||||
}
|
||||
|
||||
const openPluginLog = async (p: PluginInfo) => {
|
||||
try {
|
||||
const txt = await api.ReadPluginLog(p.id)
|
||||
setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') })
|
||||
} catch (e) {
|
||||
onError(tr('pluginFailReadLog'), e)
|
||||
}
|
||||
}
|
||||
|
||||
const selectTheme = async (themeID: string, schemeID = '') => {
|
||||
try {
|
||||
await api.SetActiveTheme(themeID, schemeID)
|
||||
@@ -385,7 +374,9 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale])
|
||||
const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale])
|
||||
const themes = contribs?.themes ?? []
|
||||
const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin')
|
||||
const settingsPanelsOf = (id: string) => contribs?.asset_token
|
||||
? (contribs.panels ?? []).filter((panel) => panel.slot === 'settings.plugin' && panel.pluginId === id)
|
||||
: []
|
||||
const presetSchemes = activeTheme?.theme?.schemes ?? []
|
||||
const customSchemes = (activeTheme?.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme?.theme_id)
|
||||
const activeCount = useMemo(() => plugins.filter((p) => p.state === 'active').length, [plugins])
|
||||
@@ -423,7 +414,26 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<PluginAppIcon plugin={p} size="md" />
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
|
||||
{(() => {
|
||||
const title = locText(p.name, locale, p.id)
|
||||
const rawHref = (p.homepage || '').trim()
|
||||
const href = /^https:\/\//i.test(rawHref) ? rawHref : ''
|
||||
return href ? (
|
||||
<a
|
||||
className="plugin-row-name plugin-title-link"
|
||||
href={href}
|
||||
title={href}
|
||||
onClick={(ev) => {
|
||||
ev.preventDefault()
|
||||
void api.OpenURL(href).catch((err) => onError(tr('failGeneric'), err))
|
||||
}}
|
||||
>
|
||||
{title}
|
||||
</a>
|
||||
) : (
|
||||
<span className="plugin-row-name">{title}</span>
|
||||
)
|
||||
})()}
|
||||
{stateBadge(p)}
|
||||
</div>
|
||||
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
|
||||
@@ -431,11 +441,16 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<div className="row-sub plugin-row-meta">
|
||||
<PluginTrustBadge locale={locale} trust={p.trust} publisher={p.publisher} />
|
||||
<span className="mono">v{p.version}</span>
|
||||
{perms.length > 0 && (
|
||||
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
|
||||
<span>{tr('pluginPermCount', { count: perms.length })}</span>
|
||||
</Tip>
|
||||
)}
|
||||
<Tip
|
||||
label={[
|
||||
tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') || '—' }),
|
||||
scanVerdicts[p.id],
|
||||
].filter(Boolean).join('\n')}
|
||||
>
|
||||
<span tabIndex={0} onPointerEnter={() => void loadScanVerdict(p)} onFocus={() => void loadScanVerdict(p)}>
|
||||
{tr('pluginPermCount', { count: perms.length })}
|
||||
</span>
|
||||
</Tip>
|
||||
</div>
|
||||
)}
|
||||
{alert && (
|
||||
@@ -452,15 +467,9 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{!isBuiltin && (
|
||||
<IconButton label={tr('pluginScanInspect')} icon={<Shield size={15} />} onClick={() => void inspectInstalledPlugin(p)} />
|
||||
)}
|
||||
{hasAppSettings(p) && (
|
||||
{(hasAppSettings(p) || settingsPanelsOf(p.id).length > 0) && (
|
||||
<IconButton label={tr('pluginSettings')} icon={<Settings2 size={15} />} onClick={() => void openPluginSettings(p)} />
|
||||
)}
|
||||
{p.log_path && (
|
||||
<IconButton label={tr('pluginViewLog')} icon={<Terminal size={15} />} onClick={() => void openPluginLog(p)} />
|
||||
)}
|
||||
{p.removable && (
|
||||
<IconButton
|
||||
disabled={p.in_use || busyID === p.id}
|
||||
@@ -626,6 +635,12 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
onClick={() => activeTab === 'market' ? setMarketRefresh((n) => n + 1) : void manualReload()}
|
||||
/>
|
||||
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
|
||||
<Button
|
||||
icon={<ExternalLink size={14} aria-hidden="true" />}
|
||||
onClick={() => void api.OpenURL(PLUGIN_MARKET_SUBMIT_URL).catch((e) => onError(tr('failGeneric'), e))}
|
||||
>
|
||||
{tr('pluginSubmitBtn')}
|
||||
</Button>
|
||||
<Button variant="primary" disabled={scanBusy} icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
|
||||
{tr('pluginImportBtn')}
|
||||
</Button>
|
||||
@@ -802,30 +817,13 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</section>
|
||||
)}
|
||||
|
||||
{settingsPanels.length > 0 && contribs?.asset_token ? (
|
||||
<section className="section" data-rg-slot="settings.plugin">
|
||||
<div className="section-title">{tr('pluginPanelsSection')}</div>
|
||||
{settingsPanels.map((panel) => (
|
||||
<PluginPanelFrame
|
||||
key={`${panel.pluginId}:${panel.id}`}
|
||||
locale={locale}
|
||||
panel={panel}
|
||||
assetToken={contribs.asset_token!}
|
||||
appearance={appearance}
|
||||
onOpenView={onOpenView}
|
||||
onNavigate={onNavigate}
|
||||
/>
|
||||
))}
|
||||
</section>
|
||||
) : (
|
||||
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
|
||||
)}
|
||||
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
|
||||
</>
|
||||
)}
|
||||
|
||||
{scanModal && (
|
||||
<Modal
|
||||
title={scanModal.mode === 'archive' ? tr('pluginScanArchiveTitle') : tr('pluginScanModalTitle')}
|
||||
title={tr('pluginScanArchiveTitle')}
|
||||
subtitle={scanModal.report.plugin_id ? `${locText(scanModal.report.name, locale, scanModal.report.plugin_id)} · v${scanModal.report.version || '—'}` : scanModal.archivePath}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => { if (!scanBusy) setScanModal(null) }}
|
||||
@@ -838,20 +836,14 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
{scanModal.report.tier ? `${scanModal.report.tier} · ${scanModal.report.trust || 'community'}` : ''}
|
||||
</span>
|
||||
<span className="hstack">
|
||||
{scanModal.mode === 'archive' ? (
|
||||
<>
|
||||
<Button variant="ghost" disabled={scanBusy} onClick={() => setScanModal(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={scanBusy || scanModal.report.hard_blocked}
|
||||
onClick={() => void confirmInstallScannedArchive()}
|
||||
>
|
||||
{scanModal.report.hard_blocked ? tr('pluginScanBlockedBtn') : tr('pluginScanInstallConfirm')}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button variant="primary" onClick={() => setScanModal(null)}>{tr('pluginDone')}</Button>
|
||||
)}
|
||||
<Button variant="ghost" disabled={scanBusy} onClick={() => setScanModal(null)}>{tr('cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={scanBusy || scanModal.report.hard_blocked}
|
||||
onClick={() => void confirmInstallScannedArchive()}
|
||||
>
|
||||
{scanModal.report.hard_blocked ? tr('pluginScanBlockedBtn') : tr('pluginScanInstallConfirm')}
|
||||
</Button>
|
||||
</span>
|
||||
</div>
|
||||
</Modal>
|
||||
@@ -883,7 +875,7 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{settingsTarget && settingsTarget.settings && (
|
||||
{settingsTarget && (
|
||||
<Modal
|
||||
title={locText(settingsTarget.name, locale, settingsTarget.id)}
|
||||
subtitle={tr('pluginGlobalSettings')}
|
||||
@@ -897,13 +889,27 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
<span>{settingsRuntimeWarning}</span>
|
||||
</div>
|
||||
)}
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={settingsTarget.settings}
|
||||
values={settingsValues}
|
||||
scopeFilter="app"
|
||||
onChange={(_, patch) => void savePluginSettings(patch)}
|
||||
/>
|
||||
{hasAppSettings(settingsTarget) && (
|
||||
<SchemaForm
|
||||
locale={locale}
|
||||
schema={settingsTarget.settings!}
|
||||
values={settingsValues}
|
||||
scopeFilter="app"
|
||||
onChange={(_, patch) => void savePluginSettings(patch)}
|
||||
/>
|
||||
)}
|
||||
{settingsPanelsOf(settingsTarget.id).map((panel) => (
|
||||
<PluginPanelFrame
|
||||
key={panel.id}
|
||||
locale={locale}
|
||||
panel={panel}
|
||||
assetToken={contribs!.asset_token!}
|
||||
appearance={appearance}
|
||||
// Both lead out of this dialog, so it must not stay on top.
|
||||
onOpenView={onOpenView && ((view, vm) => { setSettingsTarget(null); onOpenView(view, vm) })}
|
||||
onNavigate={onNavigate && ((target) => { setSettingsTarget(null); onNavigate(target) })}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<div className="dialog-foot">
|
||||
<span />
|
||||
@@ -961,18 +967,6 @@ export const PluginsPage: React.FC<Props> = ({
|
||||
/>
|
||||
)}
|
||||
|
||||
{logTarget && (
|
||||
<Modal
|
||||
title={tr('pluginLogTitle', { id: logTarget.id })}
|
||||
closeLabel={tr('close')}
|
||||
onClose={() => setLogTarget(null)}
|
||||
>
|
||||
<div className="dialog-body">
|
||||
<pre className="plugin-log-pre mono selectable">{logTarget.text}</pre>
|
||||
</div>
|
||||
</Modal>
|
||||
)}
|
||||
|
||||
{schemeEditorOpen && (
|
||||
<Modal
|
||||
title={tr('pluginSchemeModalTitle')}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Download, LoaderCircle, Pause, RefreshCw } from 'lucide-react'
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import '../i18n/domains/wizard.gen'
|
||||
import { I18nKey, t } from '../i18n'
|
||||
import { describeRuntimeStatus } from '../lib/runtimeStatus'
|
||||
import { taskDetail } from '../lib/tasks'
|
||||
import { InstalledRuntime, Locale, RemoteRuntime, Task } from '../types'
|
||||
import { Button, IconButton } from '../ui/controls'
|
||||
@@ -16,6 +17,7 @@ interface Props {
|
||||
onChannel: (alpha: boolean) => void
|
||||
onInstall: (commit: string) => void
|
||||
onCancel: (taskId: string) => void
|
||||
onLatestCommit?: (commit: string) => void
|
||||
}
|
||||
|
||||
const gb = (b: number) => (b >= 1e9 ? `${(b / 1e9).toFixed(1)} GB` : `${Math.ceil(b / 1e6)} MB`)
|
||||
@@ -27,7 +29,7 @@ const shortQemu = (v: string) => v.replace(/^QEMU emulator version\s*/i, 'QEMU '
|
||||
* The runtime rows: the active runtime and whether it is current (or, with
|
||||
* none installed, the newest release to install), then the alpha switch.
|
||||
*/
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel }) => {
|
||||
export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, task, onChannel, onInstall, onCancel, onLatestCommit }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [remote, setRemote] = useState<RemoteRuntime[] | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
@@ -43,16 +45,13 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
return () => { live = false }
|
||||
}, [channel, task?.status === 'done', reload])
|
||||
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latest = remote?.[0]
|
||||
const sameRuntimeId = (a: string, b: string) => {
|
||||
const [baseA, revA = ''] = a.split('-', 2)
|
||||
const [baseB, revB = ''] = b.split('-', 2)
|
||||
return revA === revB && (baseA.startsWith(baseB) || baseB.startsWith(baseA))
|
||||
}
|
||||
const isInstalled = (c: string) => installed.some((i) => sameRuntimeId(i.commit, c))
|
||||
const { active, latestCommit, activeIsLatest, updatable, switchRecommended } = describeRuntimeStatus(installed, latest)
|
||||
const running = task?.status === 'running'
|
||||
const updatable = !!latest && !isInstalled(latest.commit)
|
||||
|
||||
useEffect(() => {
|
||||
onLatestCommit?.(latestCommit)
|
||||
}, [latestCommit, onLatestCommit])
|
||||
|
||||
let sub: React.ReactNode
|
||||
if (running && task) {
|
||||
@@ -67,6 +66,12 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<span>{task.percent >= 0 ? `${Math.floor(task.percent)}%` : ''} {taskDetail(task)}</span>
|
||||
</div>
|
||||
)
|
||||
} else if (switchRecommended && active && latest) {
|
||||
sub = (
|
||||
<div className="row-sub">
|
||||
{shortQemu(active.manifest.qemu_version)} · {tr('runtimeRecommendLatest', { v: latest.commit })}
|
||||
</div>
|
||||
)
|
||||
} else if (active && !updatable) {
|
||||
sub = <div className="row-sub">{shortQemu(active.manifest.qemu_version)}</div>
|
||||
} else if (error) {
|
||||
@@ -107,7 +112,9 @@ export const RuntimeOnline: React.FC<Props> = ({ locale, channel, installed, tas
|
||||
<Button variant="primary" icon={<Download size={14} />} onClick={() => onInstall(latest!.commit)}>
|
||||
{tr(active ? 'runtimeUpdate' : 'runtimeInstall')}
|
||||
</Button>
|
||||
) : !running && active && remote ? (
|
||||
) : !running && switchRecommended ? (
|
||||
<span className="badge rg-p-badge badge-warn">{tr('runtimeNotLatest')}</span>
|
||||
) : !running && active && activeIsLatest ? (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('runtimeUpToDate')}</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
} from '../lib/format'
|
||||
import { applyKernelIrqchip, findOptimization, kernelIrqchipHint, parseKernelIrqchip } from '../lib/optimizations'
|
||||
import { useVMStats } from '../lib/vmStats'
|
||||
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats } from '../types'
|
||||
import { HostReport, Locale, Optimization, SetOpts, ValidationIssue, VMAffinityStatus, VMDetail, VMStats, DiskCache } from '../types'
|
||||
import { Button } from '../ui/controls'
|
||||
import { Modal } from '../ui/dialog'
|
||||
import { NumberField, OptionCards, PopupSelect, RangeField, ScreenArt, Segmented, SetGroup, SetRow, SetValue, Switch } from '../ui/settings'
|
||||
@@ -36,6 +36,7 @@ import { api } from '../wails'
|
||||
import { formatAffinitySummary } from './AffinityDialog'
|
||||
import { VMNetworkSettings } from './VMNetworkSettings'
|
||||
import { DefenderExclusionRow, DiskMaintenanceRows, useDiskMaintenance } from './vmSettings/disk'
|
||||
import { DiskCacheRow } from './vmSettings/diskCache'
|
||||
import { KeymapSection, useKeymap } from './vmSettings/keymap'
|
||||
import { useVMPluginSettings, VMPluginGroup } from './vmSettings/plugins'
|
||||
import { DriveShareSection, SharedFolderSection, useDriveShares, useSharedFolders, WritableFolderDialog } from './vmSettings/sharing'
|
||||
@@ -72,6 +73,7 @@ const FIELD_CAT: Record<Field, Cat> = {
|
||||
displays: 'display',
|
||||
borderless: 'display',
|
||||
disk_controller: 'storage',
|
||||
disk_cache: 'storage',
|
||||
network: 'storage',
|
||||
ssh_port: 'storage',
|
||||
capture: 'input',
|
||||
@@ -101,6 +103,7 @@ function same(field: Field, a: SetOpts[Field], b: SetOpts[Field]): boolean {
|
||||
case 'log_level':
|
||||
case 'extra_args':
|
||||
case 'audio_backend':
|
||||
case 'disk_cache':
|
||||
case 'guest_lang': return String(a ?? '').trim() === String(b ?? '').trim()
|
||||
default: return a === b
|
||||
}
|
||||
@@ -117,9 +120,10 @@ function baseline(detail: VMDetail, host: HostReport): SetOpts {
|
||||
graphics: detail.graphics,
|
||||
displays: detail.displays || 1,
|
||||
disk_controller: detail.disk_controller,
|
||||
disk_cache: (detail.disk_cache as DiskCache) || 'default',
|
||||
resolution: detail.resolution,
|
||||
borderless: detail.borderless,
|
||||
capture: detail.capture,
|
||||
...(detail.capture_supported ? { capture: detail.capture } : {}),
|
||||
gpu: icd ?? (detail.gpu || 'auto'),
|
||||
logs: detail.logs,
|
||||
log_level: detail.log_level,
|
||||
@@ -140,6 +144,7 @@ interface Props {
|
||||
stats?: VMStats | null
|
||||
host: HostReport
|
||||
fixedModeSupported?: boolean
|
||||
diskCacheSupported?: boolean
|
||||
optimizations?: Optimization[]
|
||||
running: boolean
|
||||
onCopy?: (text: string) => void
|
||||
@@ -153,7 +158,7 @@ interface Props {
|
||||
onSaved: () => void
|
||||
}
|
||||
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
|
||||
export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats, host, fixedModeSupported = false, diskCacheSupported = false, optimizations, running, onCopy, onDiskChanged, onOpenAffinity, affinityVersion = 0, onHostChanged, onToast, onClose, onSaved }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const irqOpt = findOptimization(optimizations, 'kernel_irqchip')
|
||||
const base = useMemo(() => baseline(detail, host), [detail, host])
|
||||
@@ -172,7 +177,7 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
const smbios = useSMBIOS(detail, running)
|
||||
const keymap = useKeymap(detail.name, running, cat === 'input')
|
||||
const plugins = useVMPluginSettings(`${driverID}:${detail.name}`, setErr)
|
||||
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, running, stats, onError: setErr, onDiskChanged })
|
||||
const disk = useDiskMaintenance({ locale, driverID, vm: detail.name, diskPath: detail.disk, running, stats, onError: setErr, onDiskChanged })
|
||||
const timezone = useGuestTimezone(driverID, detail.name, running, cat === 'general')
|
||||
const display = useTargetDisplay({
|
||||
locale, driverID, vm: detail.name, running, host, shown: cat === 'display', onToast,
|
||||
@@ -201,13 +206,22 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
setCustomLog(!!base.log_level && !(LOG_LEVELS as readonly string[]).includes(base.log_level))
|
||||
}, [base])
|
||||
|
||||
useEffect(() => {
|
||||
setForm((f) => {
|
||||
if (!detail.capture_supported) {
|
||||
return f.capture === undefined ? f : { ...f, capture: undefined }
|
||||
}
|
||||
return f.capture === undefined ? { ...f, capture: detail.capture } : f
|
||||
})
|
||||
}, [detail.capture_supported, detail.capture])
|
||||
|
||||
const set = (patch: Partial<SetOpts>) => {
|
||||
edited.current = true
|
||||
setForm((f) => ({ ...f, ...patch }))
|
||||
const touched = Object.keys(patch)
|
||||
setIssues((list) => list.filter((i) => !touched.includes(i.field)))
|
||||
}
|
||||
const dirty = (f: Field) => !same(f, form[f], base[f])
|
||||
const dirty = (f: Field) => (f === 'capture' && !detail.capture_supported ? false : !same(f, form[f], base[f]))
|
||||
const reset = (f: Field) => () => {
|
||||
set({ [f]: base[f] } as Partial<SetOpts>)
|
||||
if (f === 'resolution' || f === 'borderless') setCustomRes(false)
|
||||
@@ -681,6 +695,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<DiskCacheRow
|
||||
locale={locale}
|
||||
value={(form.disk_cache as DiskCache) || 'default'}
|
||||
dirty={dirty('disk_cache')}
|
||||
supported={diskCacheSupported}
|
||||
reason={tr('diskCacheRequiresRuntime')}
|
||||
onReset={reset('disk_cache')}
|
||||
resetLabel={tr('resetField')}
|
||||
error={issueOf('disk_cache')}
|
||||
onChange={(disk_cache) => set({ disk_cache })}
|
||||
/>
|
||||
<DiskMaintenanceRows locale={locale} running={running} state={disk} onCopy={onCopy} />
|
||||
{host.defender_realtime_active && <DefenderExclusionRow locale={locale} dataRoot={host.data_root} onCopy={onCopy} onError={setErr} />}
|
||||
</SetGroup>
|
||||
@@ -725,15 +750,17 @@ export const SettingsModal: React.FC<Props> = ({ locale, detail, driverID, stats
|
||||
|
||||
const input = (
|
||||
<>
|
||||
<SetGroup title={tr('catInput')}>
|
||||
<SetRow
|
||||
{...rowProps('capture')}
|
||||
title={tr('captureInput')}
|
||||
desc={tr('captureInputHint')}
|
||||
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
<KeymapSection locale={locale} vm={detail.name} state={keymap} />
|
||||
{detail.capture_supported && (
|
||||
<SetGroup title={tr('catInput')}>
|
||||
<SetRow
|
||||
{...rowProps('capture')}
|
||||
title={tr('captureInput')}
|
||||
desc={tr('captureInputHint')}
|
||||
control={<Switch label={tr('captureInput')} checked={!!form.capture} onChange={(capture) => set({ capture })} />}
|
||||
/>
|
||||
</SetGroup>
|
||||
)}
|
||||
<KeymapSection locale={locale} vm={detail.name} state={keymap} captureSupported={detail.capture_supported} />
|
||||
<VMPluginGroup locale={locale} group="keyboard" state={plugins} />
|
||||
<SetGroup title={tr('catAudio')} note={tr('audioTroubleshootNote')}>
|
||||
<SetRow
|
||||
|
||||
@@ -49,15 +49,17 @@ interface Props {
|
||||
updateDot?: boolean
|
||||
/** Declared plugin pages shown after the built-in Plugins entry. */
|
||||
pluginViews?: { id: string; title: string; badge?: string; icon?: string }[]
|
||||
/** VMs currently being created (not yet in `vms`). */
|
||||
creatingVMs?: { name: string; percent: number }[]
|
||||
}
|
||||
|
||||
export const Sidebar: React.FC<Props> = ({
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [],
|
||||
locale, vms, transitions, busyActions = {}, selected, hostReady, canSuspend, onSelect, displayNames = {}, macosMajors = {}, onActivate, onNew, onVMContextAction, downloading, safeMode, updateCard, updateDot, pluginViews = [], creatingVMs = [],
|
||||
}) => {
|
||||
const tr = (k: I18nKey) => t(locale, k)
|
||||
const listRef = useRef<HTMLDivElement>(null)
|
||||
const ctxOpenedByPointerRef = useRef(false)
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), INSTALLERS_ID, PLUGINS_ID, ...pluginViews.map((view) => view.id), HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
const ids = [...vms.map((v) => vmRefKey(v)), ...creatingVMs.map((v) => v.name), INSTALLERS_ID, PLUGINS_ID, ...pluginViews.map((view) => view.id), HOST_ID, SETTINGS_ID, ABOUT_ID]
|
||||
|
||||
// Listbox keyboard model: ↑/↓/Home/End move selection and focus together.
|
||||
const onKeyDown = (e: React.KeyboardEvent) => {
|
||||
@@ -131,7 +133,7 @@ export const Sidebar: React.FC<Props> = ({
|
||||
</div>
|
||||
<div className="nav rg-p-nav" role="listbox" aria-label={tr('sidebarVMs')} ref={listRef} onKeyDown={onKeyDown}>
|
||||
<div className="nav-group rg-p-nav-group nav-vms" role="group" aria-label={tr('sidebarVMs')}>
|
||||
{vms.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.length === 0 && creatingVMs.length === 0 && <div className="nav-empty rg-p-empty" data-rg-slot="empty.state">{tr('emptyVMs')}</div>}
|
||||
{vms.map((vm) => {
|
||||
const key = vmRefKey(vm)
|
||||
const st = transitions[key] ?? vm.state
|
||||
@@ -261,6 +263,18 @@ export const Sidebar: React.FC<Props> = ({
|
||||
</Ctx.Root>
|
||||
)
|
||||
})}
|
||||
{creatingVMs.map((item) => navBtn(
|
||||
item.name,
|
||||
item.name,
|
||||
<VersionArt shape="tile" major={null} name={item.name} />,
|
||||
'nav-icon-art',
|
||||
t(locale, 'state_creating'),
|
||||
statusKind('creating'),
|
||||
undefined,
|
||||
undefined,
|
||||
{ state: 'creating', driver: '', busy: true, family: 'macos' },
|
||||
item.percent >= 0 ? `${Math.floor(item.percent)}%` : undefined,
|
||||
))}
|
||||
</div>
|
||||
<div className="nav-group rg-p-nav-group nav-system" role="group" aria-label={tr('sidebarSystem')}>
|
||||
{navBtn(
|
||||
|
||||
@@ -534,7 +534,7 @@ export const VMPage: React.FC<Props> = ({
|
||||
<span className="sep">·</span>
|
||||
<kbd>Ctrl+Alt+G</kbd> {tr('shortcutBarRelease')}
|
||||
</p>
|
||||
) : detail.capture ? (
|
||||
) : (!detail.capture_supported || detail.capture) ? (
|
||||
<p className="vm-footnote">
|
||||
<kbd>Ctrl+Alt+Win</kbd> {tr('shortcutBarRelease')}
|
||||
</p>
|
||||
|
||||
@@ -1,23 +1,14 @@
|
||||
import React, { useEffect, useId, useRef } from 'react'
|
||||
import {
|
||||
WORDMARK_GRADIENT,
|
||||
WORDMARK_ORIGIN,
|
||||
WORDMARK_STROKES,
|
||||
WORDMARK_STROKE_WIDTH,
|
||||
WORDMARK_VIEWBOX,
|
||||
} from './wordmark.gen'
|
||||
|
||||
// Strokes of the Reims-Go wordmark (scripts/brand/wordmark.py), in pen order.
|
||||
// Coordinates sit in the generator's baseline frame (translate 4 107).
|
||||
type Stroke =
|
||||
| { kind: 'path'; d: string; ink: 'ink' | 'dash' | 'brand' }
|
||||
| { kind: 'dot'; cx: number; cy: number; r: number }
|
||||
|
||||
const STROKES: Stroke[] = [
|
||||
{ kind: 'path', ink: 'ink', d: 'M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M133.5 -64.5V-7.5' },
|
||||
{ kind: 'dot', cx: 133.5, cy: -94, r: 9 },
|
||||
{ kind: 'path', ink: 'ink', d: 'M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98' },
|
||||
{ kind: 'path', ink: 'dash', d: 'M340.5 -36H358.5' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01' },
|
||||
]
|
||||
// Geometry comes from scripts/brand/wordmark.py through wordmark.gen.ts: the
|
||||
// strokes are in pen order, in the generator's baseline frame.
|
||||
|
||||
// Pen timing, in ms. Writing speed is constant, so long strokes take longer.
|
||||
const PX_PER_MS = 0.62
|
||||
@@ -101,20 +92,20 @@ export const WordmarkLoader: React.FC<Props> = ({ width = 168, label, className
|
||||
<svg
|
||||
ref={svgRef}
|
||||
className="wordmark-loader-svg"
|
||||
viewBox="0 0 539 141"
|
||||
viewBox={`0 0 ${WORDMARK_VIEWBOX.width} ${WORDMARK_VIEWBOX.height}`}
|
||||
width={width}
|
||||
height={Math.round((width * 141) / 539)}
|
||||
height={Math.round((width * WORDMARK_VIEWBOX.height) / WORDMARK_VIEWBOX.width)}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<defs>
|
||||
<linearGradient id={gid} gradientUnits="userSpaceOnUse" x1="376" y1="0" x2="531" y2="0">
|
||||
<stop offset="0" stopColor="#3b8cff" />
|
||||
<stop offset="0.5" stopColor="#6d5dfc" />
|
||||
<stop offset="1" stopColor="#ff7a9a" />
|
||||
<linearGradient id={gid} gradientUnits="userSpaceOnUse" x1={WORDMARK_GRADIENT.x1} y1="0" x2={WORDMARK_GRADIENT.x2} y2="0">
|
||||
{WORDMARK_GRADIENT.stops.map((color, i) => (
|
||||
<stop key={color} offset={i / (WORDMARK_GRADIENT.stops.length - 1)} stopColor={color} />
|
||||
))}
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<g transform="translate(4 107)" fill="none" strokeWidth="15" strokeLinecap="round" strokeLinejoin="round">
|
||||
{STROKES.map((s, i) => s.kind === 'dot' ? (
|
||||
<g transform={`translate(${WORDMARK_ORIGIN.x} ${WORDMARK_ORIGIN.y})`} fill="none" strokeWidth={WORDMARK_STROKE_WIDTH} strokeLinecap="round" strokeLinejoin="round">
|
||||
{WORDMARK_STROKES.map((s, i) => s.kind === 'dot' ? (
|
||||
<circle
|
||||
key={i}
|
||||
data-stroke=""
|
||||
|
||||
@@ -11,14 +11,20 @@ interface DiskOptions {
|
||||
locale: Locale
|
||||
driverID: string
|
||||
vm: string
|
||||
diskPath?: string
|
||||
running: boolean
|
||||
stats?: VMStats | null
|
||||
onError: (message: string) => void
|
||||
onDiskChanged?: () => void
|
||||
}
|
||||
|
||||
function isWindowsRawDevicePath(disk?: string): boolean {
|
||||
const s = (disk ?? '').trim().replace(/\//g, '\\')
|
||||
return /^\\\\\.\\(physicaldrive|harddiskvolume|harddisk|volume\{)|^\\\\\?\\volume\{/i.test(s)
|
||||
}
|
||||
|
||||
/** Resizing, compacting and optimizing the VM's disk, one at a time. */
|
||||
export function useDiskMaintenance({ locale, driverID, vm, running, stats, onError, onDiskChanged }: DiskOptions) {
|
||||
export function useDiskMaintenance({ locale, driverID, vm, diskPath, 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
|
||||
@@ -53,7 +59,10 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
|
||||
}
|
||||
}
|
||||
|
||||
const isQcow2 = !stats?.disk_format || stats.disk_format === 'qcow2'
|
||||
const isRawDevice = isWindowsRawDevicePath(diskPath)
|
||||
const resizeDisabled = running || isRawDevice
|
||||
const resizeReason = isRawDevice ? tr('diskResizeRawDisabled') : tr('stopBeforeDiskOp')
|
||||
const isQcow2 = !isRawDevice && (!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')
|
||||
@@ -93,7 +102,7 @@ export function useDiskMaintenance({ locale, driverID, vm, running, stats, onErr
|
||||
|
||||
return {
|
||||
resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2,
|
||||
compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
|
||||
resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,16 +113,16 @@ interface RowsProps {
|
||||
onCopy?: (text: string) => void
|
||||
}
|
||||
|
||||
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, state, onCopy }) => {
|
||||
export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running: _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
|
||||
const { resizeInput, setResizeInput, diskOpBusy, resizeResult, compactResult, optimizeResult, extendedL2, resizeDisabled, resizeReason, compactRowReason, optimizeRowReason, handleResizeDisk, handleCompactDisk } = state
|
||||
return (
|
||||
<>
|
||||
<SetRow
|
||||
title={tr('diskResizeTitle')}
|
||||
desc={tr('diskResizeDesc')}
|
||||
disabled={running}
|
||||
reason={tr('stopBeforeDiskOp')}
|
||||
disabled={resizeDisabled}
|
||||
reason={resizeReason}
|
||||
block={
|
||||
<div className="stack-2">
|
||||
<div className="hstack">
|
||||
@@ -124,7 +133,7 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
|
||||
type="button"
|
||||
className="preset"
|
||||
aria-pressed={resizeInput === v}
|
||||
disabled={running || !!diskOpBusy}
|
||||
disabled={resizeDisabled || !!diskOpBusy}
|
||||
onClick={() => setResizeInput(v)}
|
||||
>
|
||||
{v}
|
||||
@@ -139,14 +148,14 @@ export const DiskMaintenanceRows: React.FC<RowsProps> = ({ locale, running, stat
|
||||
value={resizeInput}
|
||||
spellCheck={false}
|
||||
autoComplete="off"
|
||||
disabled={running || !!diskOpBusy}
|
||||
disabled={resizeDisabled || !!diskOpBusy}
|
||||
onChange={(e) => setResizeInput(e.target.value)}
|
||||
placeholder="+64G / 256G"
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
busy={diskOpBusy === 'resize'}
|
||||
disabled={running || !!diskOpBusy || !resizeInput.trim()}
|
||||
disabled={resizeDisabled || !!diskOpBusy || !resizeInput.trim()}
|
||||
onClick={handleResizeDisk}
|
||||
>
|
||||
{tr('diskResizeAction')}
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import React from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { DiskCache, Locale } from '../../types'
|
||||
import { Segmented, SetRow } from '../../ui/settings'
|
||||
|
||||
interface Props {
|
||||
locale: Locale
|
||||
value: DiskCache
|
||||
dirty: boolean
|
||||
supported?: boolean
|
||||
reason?: string
|
||||
onReset: () => void
|
||||
resetLabel: string
|
||||
error?: string
|
||||
onChange: (cache: DiskCache) => void
|
||||
}
|
||||
|
||||
export const DiskCacheRow: React.FC<Props> = ({ locale, value, dirty, supported = true, reason, onReset, resetLabel, error, onChange }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const baseDesc = value === 'writeback'
|
||||
? tr('diskCacheDescWriteback')
|
||||
: value === 'none'
|
||||
? tr('diskCacheDescNone')
|
||||
: value === 'unsafe'
|
||||
? tr('diskCacheDescUnsafe')
|
||||
: tr('diskCacheDescDefault')
|
||||
const rowDisabled = !supported && value === 'default'
|
||||
const disableNonDefault = !supported
|
||||
const desc = !supported && value !== 'default' && reason
|
||||
? `${baseDesc} · ${reason}`
|
||||
: baseDesc
|
||||
|
||||
return (
|
||||
<SetRow
|
||||
field="disk_cache"
|
||||
dirty={dirty}
|
||||
disabled={rowDisabled}
|
||||
reason={reason}
|
||||
onReset={onReset}
|
||||
resetLabel={resetLabel}
|
||||
error={error}
|
||||
title={tr('diskCacheTitle')}
|
||||
desc={desc}
|
||||
control={
|
||||
<Segmented
|
||||
label={tr('diskCacheTitle')}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
options={[
|
||||
{ value: 'default', label: tr('diskCacheOptionDefault') },
|
||||
{ value: 'writeback', label: tr('diskCacheOptionWriteback'), disabled: disableNonDefault },
|
||||
{ value: 'none', label: tr('diskCacheOptionNone'), disabled: disableNonDefault },
|
||||
{ value: 'unsafe', label: tr('diskCacheOptionUnsafe'), disabled: disableNonDefault },
|
||||
]}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -1,10 +1,17 @@
|
||||
import React, { useEffect, useRef, useState } from 'react'
|
||||
import { I18nKey, t } from '../../i18n'
|
||||
import { createKeymapRequests, keymapPresetUpdate, keymapUpdate, type KeymapState } from '../../lib/vmKeymap'
|
||||
import { createKeymapRequests, keymapPresetUpdate, keymapStatusHint, keymapUpdate, visibleKeymapPresets, type KeymapState } from '../../lib/vmKeymap'
|
||||
import { Locale, VMKeymapGuestModifier, VMKeymapHostModifier, VMKeymapPreset } from '../../types'
|
||||
import { PopupSelect, Segmented, SetGroup, SetRow, Switch } from '../../ui/settings'
|
||||
import { PopupSelect, Segmented, SetGroup, SetRow, SetValue, Switch } from '../../ui/settings'
|
||||
import { api } from '../../wails'
|
||||
|
||||
const PRESET_LABEL: Record<VMKeymapPreset, I18nKey> = {
|
||||
off: 'keymapPresetOff',
|
||||
win_to_cmd: 'keymapPresetWinToCmd',
|
||||
swap_alt_win: 'keymapPresetSwapAltWin',
|
||||
custom: 'keymapPresetCustom',
|
||||
}
|
||||
|
||||
/** The VM's modifier key mapping, refreshed while shown. */
|
||||
export function useKeymap(vm: string, running: boolean, shown: boolean) {
|
||||
const activeVMNameRef = useRef(vm)
|
||||
@@ -28,24 +35,20 @@ export function useKeymap(vm: string, running: boolean, shown: boolean) {
|
||||
return { keymap, keymapErr, keymapBusy, write: keymapRequests.write }
|
||||
}
|
||||
|
||||
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap> }> = ({ locale, vm, state }) => {
|
||||
export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: ReturnType<typeof useKeymap>; captureSupported: boolean }> = ({ locale, vm, state, captureSupported }) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const { keymap, keymapErr, keymapBusy, write } = state
|
||||
const statusHint = keymap ? keymapStatusHint(keymap) : null
|
||||
const presetOptions = keymap
|
||||
? visibleKeymapPresets(keymap.preset, captureSupported).map((value) => ({ value, label: tr(PRESET_LABEL[value]) }))
|
||||
: []
|
||||
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')}
|
||||
<SetRow title={tr('keymapPresetTitle')} desc={tr('keymapPresetDesc')} disabled={keymapBusy}
|
||||
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') }]}
|
||||
options={presetOptions}
|
||||
onChange={(preset) => {
|
||||
const request = keymapPresetUpdate(keymap, preset)
|
||||
if (request) void write(vm, request)
|
||||
@@ -55,6 +58,9 @@ export const KeymapSection: React.FC<{ locale: Locale; vm: string; state: Return
|
||||
control={<Switch label={tr('keymapCaptureHostShortcutsTitle')} checked={keymap.capture_host_shortcuts}
|
||||
onChange={(capture_host_shortcuts) => { void write(vm, keymapUpdate(keymap, { capture_host_shortcuts })) }} />}
|
||||
/>
|
||||
{statusHint && (
|
||||
<SetValue title={tr('keymapStatusTitle')} value={tr(statusHint.key, statusHint.vars)} />
|
||||
)}
|
||||
{keymap.preset === 'custom' && ([
|
||||
['lwin', 'keymapHostLwin'],
|
||||
['rwin', 'keymapHostRwin'],
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// Code generated by scripts/brand/wordmark.py; DO NOT EDIT.
|
||||
// Run "python scripts/brand/wordmark.py" after changing the wordmark.
|
||||
|
||||
export type WordmarkInk = 'ink' | 'dash' | 'brand'
|
||||
|
||||
export type WordmarkStroke =
|
||||
| { kind: 'path'; ink: WordmarkInk; d: string }
|
||||
| { kind: 'dot'; cx: number; cy: number; r: number }
|
||||
|
||||
/** viewBox of the wordmark, in generator units. */
|
||||
export const WORDMARK_VIEWBOX = { width: 539, height: 141 }
|
||||
|
||||
/** Translation that puts the generator's baseline frame into the viewBox. */
|
||||
export const WORDMARK_ORIGIN = { x: 4, y: 107 }
|
||||
|
||||
export const WORDMARK_STROKE_WIDTH = 15
|
||||
|
||||
/** Horizontal extent of the brand gradient on the baseline. */
|
||||
export const WORDMARK_GRADIENT = { x1: 376, x2: 531, stops: ['#3b8cff', '#6d5dfc', '#ff7a9a'] }
|
||||
|
||||
/** Strokes in pen order, in the generator's baseline frame. */
|
||||
export const WORDMARK_STROKES: WordmarkStroke[] = [
|
||||
{ kind: 'path', ink: 'ink', d: 'M7.5 -7.5V-36A24 28.5 0 0 1 31.5 -64.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M50.5 -36H107.5A28.5 28.5 0 1 0 100.18 -16.93' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M133.5 -64.5V-7.5' },
|
||||
{ kind: 'dot', cx: 133.5, cy: -94, r: 9 },
|
||||
{ kind: 'path', ink: 'ink', d: 'M159.5 -7.5V-36A22 28.5 0 0 1 203.5 -36V-7.5M203.5 -36A22 28.5 0 0 1 247.5 -36V-7.5' },
|
||||
{ kind: 'path', ink: 'ink', d: 'M311.05 -59.02A21 14.25 0 0 0 273.5 -50.25A21 14.25 0 0 0 294.5 -36A21 14.25 0 0 1 315.5 -21.75A21 14.25 0 0 1 277.95 -12.98' },
|
||||
{ kind: 'path', ink: 'dash', d: 'M340.5 -36H358.5' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -36A28.5 28.5 0 1 1 440.5 -36.01' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M440.5 -64.5V0A28.5 22.5 0 0 1 387.32 11.25' },
|
||||
{ kind: 'path', ink: 'brand', d: 'M523.5 -36A28.5 28.5 0 1 1 523.5 -36.01' },
|
||||
]
|
||||
@@ -34,7 +34,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginFailLoadSettings": "读取插件设置失败",
|
||||
"pluginFailMarketInstall": "安装市场插件失败",
|
||||
"pluginFailMarketLoad": "加载插件市场失败",
|
||||
"pluginFailReadLog": "读取插件日志失败",
|
||||
"pluginFailRemove": "卸载插件失败",
|
||||
"pluginFailSaveScheme": "保存配色方案失败",
|
||||
"pluginFailSaveSettings": "保存插件设置失败",
|
||||
@@ -48,8 +47,8 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginInUse": "使用中不可卸载",
|
||||
"pluginLinkDevBtn": "链接插件开发目录",
|
||||
"pluginLinkDevTitle": "链接本地开发插件目录",
|
||||
"pluginLogEmpty": "暂无日志记录",
|
||||
"pluginLogTitle": "{id} — 日志",
|
||||
"pluginMarketAlphaTag": "Alpha",
|
||||
"pluginMarketCurrentVersion": "当前已安装",
|
||||
"pluginMarketDownloading": "下载中",
|
||||
"pluginMarketEmpty": "当前插件市场暂无可用条目,你仍可导入本地 .zip 插件包或配置自定义市场索引地址",
|
||||
"pluginMarketFeedEnd": "共 {count} 个插件",
|
||||
@@ -65,8 +64,15 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginMarketKindTheme": "主题",
|
||||
"pluginMarketKindTool": "工具",
|
||||
"pluginMarketLoading": "正在读取插件市场",
|
||||
"pluginMarketPickVersionInstall": "安装此版本",
|
||||
"pluginMarketPickVersionTitle": "选择安装版本",
|
||||
"pluginMarketRefresh": "刷新索引",
|
||||
"pluginMarketSearchPlaceholder": "搜索市场插件、作者或标签",
|
||||
"pluginMarketSortComposite": "综合排序",
|
||||
"pluginMarketSortDownloads": "最多下载",
|
||||
"pluginMarketSortLabel": "排序方式",
|
||||
"pluginMarketSortRecent": "最新发布",
|
||||
"pluginMarketSortStars": "最多 Star",
|
||||
"pluginMarketStaleBanner": "远程插件市场暂不可达,当前显示本地缓存或内置回退索引",
|
||||
"pluginMarketSyncing": "正在同步插件市场",
|
||||
"pluginMarketUpdateShort": "更新",
|
||||
@@ -75,7 +81,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginMarketWithdrawnInstalledWarn": "已安装插件 {id} 已从市场撤回:{reason}",
|
||||
"pluginMarketWithdrawnInstead": "建议改用:{target}",
|
||||
"pluginNewScheme": "新建配色方案",
|
||||
"pluginPanelsSection": "插件面板",
|
||||
"pluginPermCount": "{count, plural, other {# 项权限}}",
|
||||
"pluginPermissionsLabel": "权限:{list}",
|
||||
"pluginPublisherLicense": "发布者 / 许可",
|
||||
@@ -94,9 +99,7 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginScanBlockedBtn": "已拦截,无法安装",
|
||||
"pluginScanCapabilitiesSection": "能力与权限说明",
|
||||
"pluginScanHardSection": "硬性拦截项(禁止安装)",
|
||||
"pluginScanInspect": "安全扫描",
|
||||
"pluginScanInstallConfirm": "确认导入安装",
|
||||
"pluginScanModalTitle": "插件静态安全报告",
|
||||
"pluginScanMoreItems": "另有 {count} 项已折叠",
|
||||
"pluginSchemeDefault": "默认",
|
||||
"pluginSchemeModalTitle": "新建配色方案",
|
||||
@@ -108,6 +111,7 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginStateDegraded": "已降级",
|
||||
"pluginStateFailed": "故障",
|
||||
"pluginStatePending": "等待依赖",
|
||||
"pluginSubmitBtn": "上架插件",
|
||||
"pluginSurfaceSeed": "画布种子色(可选)",
|
||||
"pluginTabInstalled": "已安装",
|
||||
"pluginTabMarket": "市场",
|
||||
@@ -120,7 +124,6 @@ export const pluginsZh: Record<string, string> = {
|
||||
"pluginTrustDev": "开发",
|
||||
"pluginTrustOfficial": "官方",
|
||||
"pluginTrustVerified": "已审核",
|
||||
"pluginViewLog": "查看日志",
|
||||
}
|
||||
|
||||
export const pluginsEn: Record<string, string> = {
|
||||
@@ -156,7 +159,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginFailLoadSettings": "Couldn’t load plugin settings",
|
||||
"pluginFailMarketInstall": "Couldn’t install plugin from market",
|
||||
"pluginFailMarketLoad": "Couldn’t load plugin market",
|
||||
"pluginFailReadLog": "Couldn’t read plugin log",
|
||||
"pluginFailRemove": "Couldn’t remove plugin",
|
||||
"pluginFailSaveScheme": "Couldn’t save color scheme",
|
||||
"pluginFailSaveSettings": "Couldn’t save plugin settings",
|
||||
@@ -170,8 +172,8 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginInUse": "In use",
|
||||
"pluginLinkDevBtn": "Link plugin dev folder",
|
||||
"pluginLinkDevTitle": "Link local dev plugin folder",
|
||||
"pluginLogEmpty": "No log entries yet",
|
||||
"pluginLogTitle": "{id} — Log",
|
||||
"pluginMarketAlphaTag": "Alpha",
|
||||
"pluginMarketCurrentVersion": "Installed",
|
||||
"pluginMarketDownloading": "Downloading",
|
||||
"pluginMarketEmpty": "No plugins available in the market index yet. You can still import local .zip packages or configure a custom index URL.",
|
||||
"pluginMarketFeedEnd": "{count} plugins",
|
||||
@@ -187,8 +189,15 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginMarketKindTheme": "Themes",
|
||||
"pluginMarketKindTool": "Tools",
|
||||
"pluginMarketLoading": "Loading the plugin market",
|
||||
"pluginMarketPickVersionInstall": "Install version",
|
||||
"pluginMarketPickVersionTitle": "Select version",
|
||||
"pluginMarketRefresh": "Refresh index",
|
||||
"pluginMarketSearchPlaceholder": "Search market plugins, publishers, or tags",
|
||||
"pluginMarketSortComposite": "Recommended",
|
||||
"pluginMarketSortDownloads": "Most downloads",
|
||||
"pluginMarketSortLabel": "Sort by",
|
||||
"pluginMarketSortRecent": "Recently updated",
|
||||
"pluginMarketSortStars": "Most stars",
|
||||
"pluginMarketStaleBanner": "Remote market index is unreachable; showing cached or offline fallback data",
|
||||
"pluginMarketSyncing": "Syncing the plugin market",
|
||||
"pluginMarketUpdateShort": "Update",
|
||||
@@ -197,7 +206,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginMarketWithdrawnInstalledWarn": "Installed plugin {id} has been withdrawn: {reason}",
|
||||
"pluginMarketWithdrawnInstead": "Recommended replacement: {target}",
|
||||
"pluginNewScheme": "New scheme",
|
||||
"pluginPanelsSection": "Plugin panels",
|
||||
"pluginPermCount": "{count, plural, one {# permission} other {# permissions}}",
|
||||
"pluginPermissionsLabel": "Permissions: {list}",
|
||||
"pluginPublisherLicense": "Publisher / License",
|
||||
@@ -216,9 +224,7 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginScanBlockedBtn": "Blocked — cannot install",
|
||||
"pluginScanCapabilitiesSection": "Capabilities \u0026 privileges",
|
||||
"pluginScanHardSection": "Hard blockers (install refused)",
|
||||
"pluginScanInspect": "Security scan",
|
||||
"pluginScanInstallConfirm": "Proceed with install",
|
||||
"pluginScanModalTitle": "Plugin security report",
|
||||
"pluginScanMoreItems": "...and {count} more",
|
||||
"pluginSchemeDefault": "Default",
|
||||
"pluginSchemeModalTitle": "New color scheme",
|
||||
@@ -230,6 +236,7 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginStateDegraded": "Degraded",
|
||||
"pluginStateFailed": "Failed",
|
||||
"pluginStatePending": "Pending",
|
||||
"pluginSubmitBtn": "Submit plugin",
|
||||
"pluginSurfaceSeed": "Surface seed (optional)",
|
||||
"pluginTabInstalled": "Installed",
|
||||
"pluginTabMarket": "Market",
|
||||
@@ -242,7 +249,6 @@ export const pluginsEn: Record<string, string> = {
|
||||
"pluginTrustDev": "Dev",
|
||||
"pluginTrustOfficial": "Official",
|
||||
"pluginTrustVerified": "Verified",
|
||||
"pluginViewLog": "View log",
|
||||
}
|
||||
|
||||
registerBuiltinDomain(pluginsZh, pluginsEn)
|
||||
@@ -6,8 +6,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"aboutCopyDiscord": "复制邀请链接",
|
||||
"aboutCopyQQGroup": "复制群号",
|
||||
"aboutDiscord": "Discord 社区",
|
||||
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutJoinDiscord": "加入服务器",
|
||||
"aboutJoinQQGroup": "加入群聊",
|
||||
"aboutLicensesOpenGitHub": "在 GitHub 查看",
|
||||
@@ -16,14 +14,11 @@ export const settingsZh: Record<string, string> = {
|
||||
"aboutLicensesTabNotice": "第三方声明",
|
||||
"aboutLicensesTitle": "开源许可与声明",
|
||||
"aboutLicensesView": "查看",
|
||||
"aboutProjectSub": "GitHub 上的源码与发布版本",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"aboutWebsiteSub": "reims.dev 上的下载、使用文档、插件市场与兼容性列表",
|
||||
"activate": "使用",
|
||||
"affinityApplyNow": "立即应用",
|
||||
"affinityAvoidLPE": "避开 LP-E",
|
||||
@@ -61,12 +56,12 @@ export const settingsZh: Record<string, string> = {
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(Dev 滚动版)",
|
||||
"appUpdateChannelAlpha": "Alpha",
|
||||
"appUpdateChannelDev": "Dev",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(开发版)",
|
||||
"appUpdateChannelAlpha": "测试版",
|
||||
"appUpdateChannelDev": "开发版",
|
||||
"appUpdateChannelStable": "稳定版",
|
||||
"appUpdateChannelSubKeepOld": "接收 {channel} 预发布版本;启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubKeepOld": "接收{channel};启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubStable": "仅接收经过验证的正式稳定版本",
|
||||
"appUpdateChannelTitle": "更新通道",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
@@ -104,7 +99,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"bridgeUplink": "出口网卡",
|
||||
"bridgeUplinkHint": "每台虚拟机独立选择一张已连接的有线或 WLAN 网卡",
|
||||
"captureInput": "点击窗口时捕获键鼠",
|
||||
"captureInputHint": "开启后 ⌘Tab 等快捷键交给 macOS;关闭时 Win 键和 Alt+Tab 留给 Windows",
|
||||
"captureInputHint": "开启后将指针锁定在窗口内,并将 ⌘Tab 等快捷键交给 macOS;关闭后鼠标可自由移出窗口,Win 键和 Alt+Tab 留给 Windows",
|
||||
"catAdvanced": "高级",
|
||||
"catAudio": "音频",
|
||||
"catCompute": "处理器与内存",
|
||||
@@ -116,7 +111,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"catNetwork": "网络",
|
||||
"catStorage": "存储",
|
||||
"catStorageNet": "存储与网络",
|
||||
"choose": "浏览…",
|
||||
"choose": "选择…",
|
||||
"configured": "已配置",
|
||||
"coresUnit": "核",
|
||||
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
|
||||
@@ -125,6 +120,16 @@ export const settingsZh: Record<string, string> = {
|
||||
"defenderExclusionDesc": "实时扫描可能拖慢虚拟机磁盘访问。可在 Windows 安全中心为数据目录 {path} 添加排除项。",
|
||||
"defenderExclusionTitle": "Windows Defender 实时防护排除建议",
|
||||
"defenderOpenSecurity": "打开 Windows 安全中心",
|
||||
"diskCacheDescDefault": "跟随运行时默认策略(回写缓存并正常转发刷盘请求)",
|
||||
"diskCacheDescNone": "绕过宿主机页缓存直通磁盘(Direct I/O),适合裸分区直挂",
|
||||
"diskCacheDescUnsafe": "警告:忽略 Guest 刷盘指令以换取最高吞吐,宿主机断电或崩溃可能导致磁盘损坏",
|
||||
"diskCacheDescWriteback": "经宿主机页缓存回写,并安全转发 Guest 刷盘请求",
|
||||
"diskCacheOptionDefault": "默认",
|
||||
"diskCacheOptionNone": "直通",
|
||||
"diskCacheOptionUnsafe": "激进 (Unsafe)",
|
||||
"diskCacheOptionWriteback": "回写",
|
||||
"diskCacheRequiresRuntime": "当前运行时版本过旧,请更新到支持磁盘缓存策略的新版运行时",
|
||||
"diskCacheTitle": "磁盘 I/O 缓存策略",
|
||||
"diskCompactAction": "立即回收",
|
||||
"diskCompactDesc": "把 macOS 里已删除文件占用的空间还给 Windows,过程中需要与当前占用差不多的空闲空间",
|
||||
"diskCompactDone": "已回收 {reclaimed}({before} → {after})",
|
||||
@@ -149,6 +154,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"diskResizeAction": "扩容",
|
||||
"diskResizeDesc": "只能增大。扩大后在 macOS 终端运行提示的命令,新空间才能使用",
|
||||
"diskResizeDone": "已扩大到 {size}。在 macOS 终端运行:",
|
||||
"diskResizeRawDisabled": "Windows 裸分区不支持在此调整容量",
|
||||
"diskResizeTitle": "扩大磁盘",
|
||||
"diskRewriteBusy": "正在进行另一项磁盘操作。",
|
||||
"diskRewriteOverlay": "此磁盘共享基础镜像,无法直接重写。",
|
||||
@@ -362,9 +368,9 @@ export const settingsZh: Record<string, string> = {
|
||||
"kernelIrqchipLabel": "中断加速",
|
||||
"kernelIrqchipOff": "关闭",
|
||||
"kernelIrqchipOn": "开启",
|
||||
"keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时,拦截 Windows 的 Win 和 Alt 快捷键。未单独映射的 Win 和 Alt 在 macOS 中仍用作 Command 和 Option。",
|
||||
"keymapCaptureHostShortcutsTitle": "聚焦时拦截宿主机快捷键",
|
||||
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效。Ctrl+Alt+Win 保留用于释放捕获。",
|
||||
"keymapCaptureHostShortcutsDesc": "虚拟机获得焦点时拦截宿主机及第三方软件的 Win / Alt 全局热键(如截图 Alt+A、Ctrl+Alt+A),避免误触;未单独映射的 Win 和 Alt 在 macOS 中仍对应 Command 和 Option",
|
||||
"keymapCaptureHostShortcutsTitle": "拦截宿主机全局热键",
|
||||
"keymapGroupNote": "仅在此虚拟机窗口位于前台时生效;更改立即生效,无需点击保存。Ctrl+Alt+Win 保留用于释放键盘捕获",
|
||||
"keymapGroupTitle": "修饰键映射",
|
||||
"keymapGuestDefault": "默认",
|
||||
"keymapGuestDisabled": "禁用",
|
||||
@@ -386,11 +392,13 @@ export const settingsZh: Record<string, string> = {
|
||||
"keymapInputServiceRequired": "请启用宿主输入服务以使用修饰键映射",
|
||||
"keymapPending": "等待 Guest Tools 启用修饰键映射",
|
||||
"keymapPresetCustom": "自定义",
|
||||
"keymapPresetDesc": "调整修饰键映射(如将空格旁的 Alt 与 Win 互换以贴合 Mac 键位);不改键位时保持关闭即可",
|
||||
"keymapPresetOff": "关闭",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "映射预设",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "虚拟机获得焦点时生效",
|
||||
"keymapStatusTitle": "生效状态",
|
||||
"keymapStopped": "虚拟机启动后生效",
|
||||
"keymapUpgrade": "请将 Guest Tools 更新到版本 {version}",
|
||||
"keymapWaiting": "等待 Guest Tools 连接",
|
||||
@@ -496,9 +504,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"storageInstallers": "镜像",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
|
||||
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
|
||||
"targetDisplayDisconnectedOption": "已断开 · 回退至主显示器",
|
||||
"targetDisplayFallbackHint": "已保存的「{name}」当前未连接,将回退至主显示器",
|
||||
"targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)",
|
||||
@@ -550,8 +555,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"aboutCopyDiscord": "Copy invite link",
|
||||
"aboutCopyQQGroup": "Copy group ID",
|
||||
"aboutDiscord": "Discord community",
|
||||
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutJoinDiscord": "Join server",
|
||||
"aboutJoinQQGroup": "Join group",
|
||||
"aboutLicensesOpenGitHub": "View on GitHub",
|
||||
@@ -560,14 +563,11 @@ export const settingsEn: Record<string, string> = {
|
||||
"aboutLicensesTabNotice": "Third-party notices",
|
||||
"aboutLicensesTitle": "Open-source licenses",
|
||||
"aboutLicensesView": "View",
|
||||
"aboutProjectSub": "Source code and releases on GitHub",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"aboutWebsiteSub": "Downloads, docs, plugin market and compatibility list on reims.dev",
|
||||
"activate": "Use",
|
||||
"affinityApplyNow": "Apply Now",
|
||||
"affinityAvoidLPE": "Exclude LP-E",
|
||||
@@ -648,7 +648,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"bridgeUplink": "Uplink adapter",
|
||||
"bridgeUplinkHint": "Choose one connected wired or WLAN adapter independently for each VM",
|
||||
"captureInput": "Capture keyboard and mouse on click",
|
||||
"captureInputHint": "When on, shortcuts like ⌘Tab go to macOS; when off, Win and Alt+Tab stay with Windows",
|
||||
"captureInputHint": "When on, locks the pointer inside the window and sends shortcuts like ⌘Tab to macOS; when off, the mouse moves freely outside the window and Win and Alt+Tab stay with Windows",
|
||||
"catAdvanced": "Advanced",
|
||||
"catAudio": "Audio",
|
||||
"catCompute": "CPU \u0026 Memory",
|
||||
@@ -660,7 +660,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"catNetwork": "Network",
|
||||
"catStorage": "Storage",
|
||||
"catStorageNet": "Storage \u0026 Network",
|
||||
"choose": "Browse…",
|
||||
"choose": "Choose…",
|
||||
"configured": "Configured",
|
||||
"coresUnit": "cores",
|
||||
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
|
||||
@@ -669,6 +669,16 @@ export const settingsEn: Record<string, string> = {
|
||||
"defenderExclusionDesc": "Real-time scanning can slow VM disk access. You can exclude the data folder {path} in Windows Security.",
|
||||
"defenderExclusionTitle": "Windows Defender real-time protection exclusions",
|
||||
"defenderOpenSecurity": "Open Windows Security",
|
||||
"diskCacheDescDefault": "Follows the current runtime default (writeback caching, flushes forwarded to host)",
|
||||
"diskCacheDescNone": "Direct I/O bypassing host page cache; recommended for raw partition passthrough",
|
||||
"diskCacheDescUnsafe": "Warning: ignores guest flushes for peak throughput; host power loss or crash can corrupt the disk",
|
||||
"diskCacheDescWriteback": "Uses host page cache and forwards guest flushes safely to disk",
|
||||
"diskCacheOptionDefault": "Default",
|
||||
"diskCacheOptionNone": "Direct",
|
||||
"diskCacheOptionUnsafe": "Unsafe",
|
||||
"diskCacheOptionWriteback": "Writeback",
|
||||
"diskCacheRequiresRuntime": "Update to a newer runtime to configure disk I/O cache policy",
|
||||
"diskCacheTitle": "Disk I/O cache",
|
||||
"diskCompactAction": "Reclaim now",
|
||||
"diskCompactDesc": "Gives space from files deleted in macOS back to Windows. Needs about as much free space as the disk uses now",
|
||||
"diskCompactDone": "Reclaimed {reclaimed} ({before} → {after})",
|
||||
@@ -693,6 +703,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"diskResizeAction": "Expand",
|
||||
"diskResizeDesc": "Grow only. Afterwards, run the command shown in macOS Terminal to use the new space",
|
||||
"diskResizeDone": "Expanded to {size}. Run this in macOS Terminal:",
|
||||
"diskResizeRawDisabled": "Windows raw partitions cannot be resized here",
|
||||
"diskResizeTitle": "Expand disk",
|
||||
"diskRewriteBusy": "Another disk operation is in progress.",
|
||||
"diskRewriteOverlay": "This disk shares a backing image and cannot be rewritten directly.",
|
||||
@@ -906,9 +917,9 @@ export const settingsEn: Record<string, string> = {
|
||||
"kernelIrqchipLabel": "Interrupt acceleration",
|
||||
"kernelIrqchipOff": "Off",
|
||||
"kernelIrqchipOn": "On",
|
||||
"keymapCaptureHostShortcutsDesc": "Block Windows shortcuts that use Win or Alt while the VM is focused. Unmapped Win and Alt keys act as Command and Option in macOS.",
|
||||
"keymapCaptureHostShortcutsTitle": "Capture Host Shortcuts",
|
||||
"keymapGroupNote": "Applies only while this VM is focused. Ctrl+Alt+Win is reserved for releasing capture.",
|
||||
"keymapCaptureHostShortcutsDesc": "Blocks Win and Alt global hotkeys from the host and third-party apps (such as Alt+A or Ctrl+Alt+A for screenshots) while the VM is focused, preventing accidental triggers; unmapped Win and Alt keys still act as Command and Option in macOS",
|
||||
"keymapCaptureHostShortcutsTitle": "Block host global hotkeys",
|
||||
"keymapGroupNote": "Active only while this VM window is focused; changes apply immediately without clicking Save. Ctrl+Alt+Win is reserved for releasing keyboard capture",
|
||||
"keymapGroupTitle": "Modifier keys",
|
||||
"keymapGuestDefault": "Default",
|
||||
"keymapGuestDisabled": "Disabled",
|
||||
@@ -930,11 +941,13 @@ export const settingsEn: Record<string, string> = {
|
||||
"keymapInputServiceRequired": "Enable Host Input Service to use modifier mapping",
|
||||
"keymapPending": "Waiting for Guest Tools to activate modifier mapping",
|
||||
"keymapPresetCustom": "Custom",
|
||||
"keymapPresetDesc": "Remaps modifier keys (such as swapping Alt and Win next to Space to match a Mac keyboard); leave Off if no remapping is needed",
|
||||
"keymapPresetOff": "Off",
|
||||
"keymapPresetSwapAltWin": "Alt ↔ Win",
|
||||
"keymapPresetTitle": "Preset",
|
||||
"keymapPresetWinToCmd": "Win → ⌘",
|
||||
"keymapRunning": "Active while this VM is focused",
|
||||
"keymapStatusTitle": "Status",
|
||||
"keymapStopped": "Applies when this VM is running",
|
||||
"keymapUpgrade": "Update Guest Tools to version {version}",
|
||||
"keymapWaiting": "Waiting for Guest Tools to connect",
|
||||
@@ -1040,9 +1053,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"storageInstallers": "Images",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
|
||||
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
|
||||
"targetDisplayDisconnectedOption": "Disconnected · using primary",
|
||||
"targetDisplayFallbackHint": "Saved {name} is disconnected; falling back to the primary display",
|
||||
"targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)",
|
||||
|
||||
@@ -13,6 +13,8 @@ export const vmZh: Record<string, string> = {
|
||||
"connGroup": "连接",
|
||||
"copyScreenshot": "截屏并复制",
|
||||
"cores": "{n, plural, other {# 核}}",
|
||||
"creatingPreparing": "正在准备虚拟机环境与磁盘…",
|
||||
"creatingProgressTitle": "创建进度",
|
||||
"deleteConfirm": "删除",
|
||||
"deleteDesc": "配置和虚拟磁盘会被移除,无法撤销",
|
||||
"deleteDescKeep": "只移除配置,磁盘文件留在原目录",
|
||||
@@ -271,6 +273,8 @@ export const vmEn: Record<string, string> = {
|
||||
"connGroup": "Connection",
|
||||
"copyScreenshot": "Copy screenshot",
|
||||
"cores": "{n, plural, one {# core} other {# cores}}",
|
||||
"creatingPreparing": "Preparing the virtual machine and disk…",
|
||||
"creatingProgressTitle": "Creation progress",
|
||||
"deleteConfirm": "Delete",
|
||||
"deleteDesc": "Its configuration and virtual disk are removed. This can’t be undone",
|
||||
"deleteDescKeep": "Only the configuration is removed; disk files stay in place",
|
||||
|
||||
@@ -5,7 +5,7 @@ export const wizardZh: Record<string, string> = {
|
||||
"commandToggle": "等效命令",
|
||||
"commandToggleHint": "在终端运行下面这条命令效果相同",
|
||||
"createNow": "创建",
|
||||
"createStartedHint": "创建后窗口会关闭,进度在底部状态栏",
|
||||
"createStartedHint": "创建后窗口会关闭,进度会显示在侧栏与主界面",
|
||||
"issuesCount": "{n, plural, other {有 # 项需要修改}}",
|
||||
"offlineCached": "已下载",
|
||||
"offlineDownloading": "下载中",
|
||||
@@ -21,11 +21,14 @@ export const wizardZh: Record<string, string> = {
|
||||
"runtimeCurrent": "当前运行时",
|
||||
"runtimeInstall": "安装",
|
||||
"runtimeLatest": "最新:{v}",
|
||||
"runtimeLatestBadge": "最新",
|
||||
"runtimeLookupFailed": "无法读取运行时列表",
|
||||
"runtimeLookupRateLimit": "GitHub 接口限流(HTTP 403),请稍后重试或手动导入",
|
||||
"runtimeNewer": "有新版本:{v}",
|
||||
"runtimeNoneOnChannel": "这个通道还没有发布运行时",
|
||||
"runtimeNotLatest": "不是最新",
|
||||
"runtimeOnline": "在线安装",
|
||||
"runtimeRecommendLatest": "建议切换至最新运行时 {v}",
|
||||
"runtimeRetry": "重试",
|
||||
"runtimeUpToDate": "已是最新",
|
||||
"runtimeUpdate": "更新",
|
||||
@@ -93,7 +96,7 @@ export const wizardEn: Record<string, string> = {
|
||||
"commandToggle": "Equivalent command",
|
||||
"commandToggleHint": "Running this in a terminal does the same thing",
|
||||
"createNow": "Create",
|
||||
"createStartedHint": "The window closes once creation starts; progress shows in the status bar",
|
||||
"createStartedHint": "The window closes once creation starts; progress shows in the sidebar and main view",
|
||||
"issuesCount": "{n, plural, one {# issue to fix} other {# issues to fix}}",
|
||||
"offlineCached": "Downloaded",
|
||||
"offlineDownloading": "Downloading",
|
||||
@@ -109,11 +112,14 @@ export const wizardEn: Record<string, string> = {
|
||||
"runtimeCurrent": "Current runtime",
|
||||
"runtimeInstall": "Install",
|
||||
"runtimeLatest": "Latest: {v}",
|
||||
"runtimeLatestBadge": "Latest",
|
||||
"runtimeLookupFailed": "Couldn’t read the runtime list",
|
||||
"runtimeLookupRateLimit": "GitHub API rate limit reached (HTTP 403); retry later or import a local bundle",
|
||||
"runtimeNewer": "New version: {v}",
|
||||
"runtimeNoneOnChannel": "No runtime published on this channel yet",
|
||||
"runtimeNotLatest": "Not latest",
|
||||
"runtimeOnline": "Online install",
|
||||
"runtimeRecommendLatest": "Switch to latest runtime {v}",
|
||||
"runtimeRetry": "Retry",
|
||||
"runtimeUpToDate": "Up to date",
|
||||
"runtimeUpdate": "Update",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { BuiltinLocale, Locale, LocalizedText, ResolvedLocalePack } from './types'
|
||||
import { formatICU, ICUVars, pseudoLocalizeICU } from './i18n/icu'
|
||||
import type { I18nKey } from './i18n/keys.gen'
|
||||
import { builtinDict, registerBuiltinDomain } from './i18n/runtime'
|
||||
import { BuiltinLocale, Locale, LocalizedText, ResolvedLocalePack } from '../types'
|
||||
import { formatICU, ICUVars, pseudoLocalizeICU } from './icu'
|
||||
import type { I18nKey } from './keys.gen'
|
||||
import { builtinDict, registerBuiltinDomain } from './runtime'
|
||||
|
||||
export type { I18nKey }
|
||||
export { registerBuiltinDomain }
|
||||
@@ -350,10 +350,17 @@ export function joinNotices(locale: Locale, items: string[]): string {
|
||||
|
||||
export function locText(lt: LocalizedText | undefined, locale: Locale, fallback = ''): string {
|
||||
if (!lt) return fallback
|
||||
const firstExtra = () => {
|
||||
if (!lt.extra) return ''
|
||||
for (const k of Object.keys(lt.extra).sort()) {
|
||||
if (lt.extra[k]) return lt.extra[k]
|
||||
}
|
||||
return ''
|
||||
}
|
||||
const chain = buildFallbackChain(locale)
|
||||
for (const step of chain) {
|
||||
if (step === 'en-XA') {
|
||||
const base = lt['en-US'] || lt['zh-CN'] || fallback
|
||||
const base = lt['en-US'] || lt['zh-CN'] || firstExtra() || fallback
|
||||
return base ? pseudoLocalizeICU(base) : fallback
|
||||
}
|
||||
if (step === 'zh-CN' && lt['zh-CN']) return lt['zh-CN']
|
||||
@@ -361,7 +368,7 @@ export function locText(lt: LocalizedText | undefined, locale: Locale, fallback
|
||||
const hit = lt.extra?.[step]
|
||||
if (hit) return hit
|
||||
}
|
||||
return lt['en-US'] || lt['zh-CN'] || fallback
|
||||
return lt['en-US'] || lt['zh-CN'] || firstExtra() || fallback
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -5,8 +5,6 @@ export type I18nKey =
|
||||
| "aboutCopyDiscord"
|
||||
| "aboutCopyQQGroup"
|
||||
| "aboutDiscord"
|
||||
| "aboutDiscordSub"
|
||||
| "aboutIssueSub"
|
||||
| "aboutJoinDiscord"
|
||||
| "aboutJoinQQGroup"
|
||||
| "aboutLicensesOpenGitHub"
|
||||
@@ -15,14 +13,11 @@ export type I18nKey =
|
||||
| "aboutLicensesTabNotice"
|
||||
| "aboutLicensesTitle"
|
||||
| "aboutLicensesView"
|
||||
| "aboutProjectSub"
|
||||
| "aboutQQGroup"
|
||||
| "aboutQQGroupSub"
|
||||
| "aboutQQLaunchFailed"
|
||||
| "aboutQQNotInstalled"
|
||||
| "aboutQQNotInstalledSub"
|
||||
| "aboutTagline"
|
||||
| "aboutWebsiteSub"
|
||||
| "activate"
|
||||
| "affinityApplyNow"
|
||||
| "affinityAvoidLPE"
|
||||
@@ -153,6 +148,8 @@ export type I18nKey =
|
||||
| "cpuRecHint"
|
||||
| "createNow"
|
||||
| "createStartedHint"
|
||||
| "creatingPreparing"
|
||||
| "creatingProgressTitle"
|
||||
| "dataRootChooseOther"
|
||||
| "dataRootChooseTitle"
|
||||
| "dataRootReadOnlyDetail"
|
||||
@@ -182,6 +179,16 @@ export type I18nKey =
|
||||
| "discardSuspendConfirm"
|
||||
| "discardSuspendDesc"
|
||||
| "discardSuspendTitle"
|
||||
| "diskCacheDescDefault"
|
||||
| "diskCacheDescNone"
|
||||
| "diskCacheDescUnsafe"
|
||||
| "diskCacheDescWriteback"
|
||||
| "diskCacheOptionDefault"
|
||||
| "diskCacheOptionNone"
|
||||
| "diskCacheOptionUnsafe"
|
||||
| "diskCacheOptionWriteback"
|
||||
| "diskCacheRequiresRuntime"
|
||||
| "diskCacheTitle"
|
||||
| "diskCompactAction"
|
||||
| "diskCompactDesc"
|
||||
| "diskCompactDone"
|
||||
@@ -206,6 +213,7 @@ export type I18nKey =
|
||||
| "diskResizeAction"
|
||||
| "diskResizeDesc"
|
||||
| "diskResizeDone"
|
||||
| "diskResizeRawDisabled"
|
||||
| "diskResizeTitle"
|
||||
| "diskRewriteBusy"
|
||||
| "diskRewriteOverlay"
|
||||
@@ -624,11 +632,13 @@ export type I18nKey =
|
||||
| "keymapInputServiceRequired"
|
||||
| "keymapPending"
|
||||
| "keymapPresetCustom"
|
||||
| "keymapPresetDesc"
|
||||
| "keymapPresetOff"
|
||||
| "keymapPresetSwapAltWin"
|
||||
| "keymapPresetTitle"
|
||||
| "keymapPresetWinToCmd"
|
||||
| "keymapRunning"
|
||||
| "keymapStatusTitle"
|
||||
| "keymapStopped"
|
||||
| "keymapUpgrade"
|
||||
| "keymapWaiting"
|
||||
@@ -774,7 +784,6 @@ export type I18nKey =
|
||||
| "pluginFailLoadSettings"
|
||||
| "pluginFailMarketInstall"
|
||||
| "pluginFailMarketLoad"
|
||||
| "pluginFailReadLog"
|
||||
| "pluginFailRemove"
|
||||
| "pluginFailSaveScheme"
|
||||
| "pluginFailSaveSettings"
|
||||
@@ -788,8 +797,8 @@ export type I18nKey =
|
||||
| "pluginInUse"
|
||||
| "pluginLinkDevBtn"
|
||||
| "pluginLinkDevTitle"
|
||||
| "pluginLogEmpty"
|
||||
| "pluginLogTitle"
|
||||
| "pluginMarketAlphaTag"
|
||||
| "pluginMarketCurrentVersion"
|
||||
| "pluginMarketDownloading"
|
||||
| "pluginMarketEmpty"
|
||||
| "pluginMarketFeedEnd"
|
||||
@@ -805,8 +814,15 @@ export type I18nKey =
|
||||
| "pluginMarketKindTheme"
|
||||
| "pluginMarketKindTool"
|
||||
| "pluginMarketLoading"
|
||||
| "pluginMarketPickVersionInstall"
|
||||
| "pluginMarketPickVersionTitle"
|
||||
| "pluginMarketRefresh"
|
||||
| "pluginMarketSearchPlaceholder"
|
||||
| "pluginMarketSortComposite"
|
||||
| "pluginMarketSortDownloads"
|
||||
| "pluginMarketSortLabel"
|
||||
| "pluginMarketSortRecent"
|
||||
| "pluginMarketSortStars"
|
||||
| "pluginMarketStaleBanner"
|
||||
| "pluginMarketSyncing"
|
||||
| "pluginMarketUpdateShort"
|
||||
@@ -815,7 +831,6 @@ export type I18nKey =
|
||||
| "pluginMarketWithdrawnInstalledWarn"
|
||||
| "pluginMarketWithdrawnInstead"
|
||||
| "pluginNewScheme"
|
||||
| "pluginPanelsSection"
|
||||
| "pluginPermCount"
|
||||
| "pluginPermissionsLabel"
|
||||
| "pluginPublisherLicense"
|
||||
@@ -835,9 +850,7 @@ export type I18nKey =
|
||||
| "pluginScanBlockedBtn"
|
||||
| "pluginScanCapabilitiesSection"
|
||||
| "pluginScanHardSection"
|
||||
| "pluginScanInspect"
|
||||
| "pluginScanInstallConfirm"
|
||||
| "pluginScanModalTitle"
|
||||
| "pluginScanMoreItems"
|
||||
| "pluginSchemeDefault"
|
||||
| "pluginSchemeModalTitle"
|
||||
@@ -849,6 +862,7 @@ export type I18nKey =
|
||||
| "pluginStateDegraded"
|
||||
| "pluginStateFailed"
|
||||
| "pluginStatePending"
|
||||
| "pluginSubmitBtn"
|
||||
| "pluginSurfaceSeed"
|
||||
| "pluginTabInstalled"
|
||||
| "pluginTabMarket"
|
||||
@@ -861,7 +875,6 @@ export type I18nKey =
|
||||
| "pluginTrustDev"
|
||||
| "pluginTrustOfficial"
|
||||
| "pluginTrustVerified"
|
||||
| "pluginViewLog"
|
||||
| "qemuASLR"
|
||||
| "qemuASLRHint"
|
||||
| "quitFailed"
|
||||
@@ -893,11 +906,14 @@ export type I18nKey =
|
||||
| "runtimeDeleted"
|
||||
| "runtimeInstall"
|
||||
| "runtimeLatest"
|
||||
| "runtimeLatestBadge"
|
||||
| "runtimeLookupFailed"
|
||||
| "runtimeLookupRateLimit"
|
||||
| "runtimeNewer"
|
||||
| "runtimeNoneOnChannel"
|
||||
| "runtimeNotLatest"
|
||||
| "runtimeOnline"
|
||||
| "runtimeRecommendLatest"
|
||||
| "runtimeRetry"
|
||||
| "runtimeUpToDate"
|
||||
| "runtimeUpdate"
|
||||
@@ -1068,9 +1084,6 @@ export type I18nKey =
|
||||
| "suspendedNoticeDescWithTime"
|
||||
| "suspendedNoticeTitle"
|
||||
| "suspendedSettingsHint"
|
||||
| "syncHostMemorySMBIOS"
|
||||
| "syncHostMemorySMBIOSSub"
|
||||
| "syncHostMemorySMBIOSUnavailable"
|
||||
| "targetDisplayDisconnectedOption"
|
||||
| "targetDisplayFallbackHint"
|
||||
| "targetDisplayHint"
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { InstalledRuntime, RemoteRuntime } from '../types'
|
||||
|
||||
export function sameRuntimeId(a: string, b: string): boolean {
|
||||
const [baseA, revA = ''] = a.split('-', 2)
|
||||
const [baseB, revB = ''] = b.split('-', 2)
|
||||
return revA === revB && (baseA.startsWith(baseB) || baseB.startsWith(baseA))
|
||||
}
|
||||
|
||||
interface RuntimeStatus {
|
||||
active?: InstalledRuntime
|
||||
latestCommit: string
|
||||
activeIsLatest: boolean
|
||||
latestInstalled: boolean
|
||||
updatable: boolean
|
||||
switchRecommended: boolean
|
||||
}
|
||||
|
||||
export function describeRuntimeStatus(installed: InstalledRuntime[], latest?: RemoteRuntime): RuntimeStatus {
|
||||
const active = installed.find((i) => i.active) ?? installed[0]
|
||||
const latestCommit = latest?.commit ?? ''
|
||||
const activeIsLatest = !!active && !!latestCommit && sameRuntimeId(active.commit, latestCommit)
|
||||
const latestInstalled = !!latestCommit && installed.some((i) => sameRuntimeId(i.commit, latestCommit))
|
||||
const updatable = !!latestCommit && !latestInstalled
|
||||
const switchRecommended = !!active && !!latestCommit && !activeIsLatest && latestInstalled
|
||||
return { active, latestCommit, activeIsLatest, latestInstalled, updatable, switchRecommended }
|
||||
}
|
||||
@@ -33,6 +33,13 @@ export function currentTask(all: Record<string, Task>): { task: Task | null; run
|
||||
return { task: running[0] ?? null, running: running.length }
|
||||
}
|
||||
|
||||
/** Running vm-create tasks whose VM has not appeared in the VM list yet, oldest first. */
|
||||
export function creatingVMTasks(all: Record<string, Task>, existingNames: ReadonlySet<string>): Task[] {
|
||||
return Object.values(all)
|
||||
.filter((x) => x.status === 'running' && x.kind === 'vm-create' && !!x.subject && !existingNames.has(x.subject))
|
||||
.sort((a, b) => a.started_at - b.started_at || a.subject.localeCompare(b.subject))
|
||||
}
|
||||
|
||||
/** Localized title; the upstream step (English) goes in the tooltip. */
|
||||
export function taskTitle(locale: Locale, task: Task): string {
|
||||
switch (task.kind) {
|
||||
@@ -46,12 +53,12 @@ export function taskTitle(locale: Locale, task: Task): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** "8.3 / 18.4 GB · 42 MB/s" */
|
||||
/** "8.3 / 18.4 GB · 42 MB/s" or "12 / 50 MB · 512 KB/s" */
|
||||
export function taskDetail(task: Task): string {
|
||||
const parts: string[] = []
|
||||
if (task.total > 0) parts.push(`${bytes(task.done)} / ${bytes(task.total)}`)
|
||||
else if (task.done > 0) parts.push(bytes(task.done))
|
||||
if (task.rate > 0) parts.push(`${bytes(task.rate)}/s`)
|
||||
if (task.rate > 0) parts.push(rate(task.rate))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
@@ -187,3 +194,9 @@ function bytes(b: number): string {
|
||||
if (b >= 1e9) return `${(b / 1e9).toFixed(1)} GB`
|
||||
return `${Math.max(1, Math.ceil(b / 1e6))} MB`
|
||||
}
|
||||
|
||||
function rate(b: number): string {
|
||||
if (b >= 1e9) return `${(b / 1e9).toFixed(1)} GB/s`
|
||||
if (b >= 1e6) return `${(b / 1e6).toFixed(1)} MB/s`
|
||||
return `${Math.max(1, Math.round(b / 1e3))} KB/s`
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { AppUpdateInfo, Task } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
@@ -26,12 +26,18 @@ export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options)
|
||||
})
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [installing, setInstalling] = useState(false)
|
||||
const reqSeqRef = useRef(0)
|
||||
|
||||
// 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)) }
|
||||
const check = () => {
|
||||
const seq = ++reqSeqRef.current
|
||||
api.CheckAppUpdate(false)
|
||||
.then((next) => { if (reqSeqRef.current === seq) setInfo(next) })
|
||||
.catch((e) => console.warn('[app] CheckAppUpdate failed:', e))
|
||||
}
|
||||
check()
|
||||
const id = window.setInterval(check, CHECK_EVERY_MS)
|
||||
return () => window.clearInterval(id)
|
||||
@@ -55,14 +61,18 @@ export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options)
|
||||
}
|
||||
|
||||
/** Forgets a dismissed release and asks again, e.g. after the update channel changed. */
|
||||
const recheck = async () => {
|
||||
const recheck = async (force = false) => {
|
||||
const seq = ++reqSeqRef.current
|
||||
setDismissed('')
|
||||
try { localStorage.removeItem(DISMISSED_KEY) } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
|
||||
try {
|
||||
setInfo(await api.CheckAppUpdate(true))
|
||||
const next = await api.CheckAppUpdate(force)
|
||||
if (reqSeqRef.current === seq) setInfo(next)
|
||||
} catch (e) {
|
||||
setInfo(null)
|
||||
throw e
|
||||
if (reqSeqRef.current === seq) {
|
||||
setInfo(null)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,6 +8,37 @@ type KeymapAPI = {
|
||||
|
||||
export type KeymapState = { keymap: VMKeymapStatus | null; error: string; busy: boolean }
|
||||
|
||||
type KeymapStatusKey =
|
||||
| 'keymapInputServiceRequired'
|
||||
| 'keymapStopped'
|
||||
| 'keymapWaiting'
|
||||
| 'keymapUpgrade'
|
||||
| 'keymapPending'
|
||||
| 'keymapRunning'
|
||||
| 'keymapInactive'
|
||||
|
||||
type KeymapStatusHint = { key: KeymapStatusKey; vars?: { version: number } }
|
||||
|
||||
const ALL_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'win_to_cmd', 'swap_alt_win', 'custom']
|
||||
const MODERN_KEYMAP_PRESETS: readonly VMKeymapPreset[] = ['off', 'swap_alt_win', 'custom']
|
||||
|
||||
export function visibleKeymapPresets(preset: VMKeymapPreset, captureSupported: boolean): readonly VMKeymapPreset[] {
|
||||
if (!captureSupported && preset !== 'win_to_cmd') return MODERN_KEYMAP_PRESETS
|
||||
return ALL_KEYMAP_PRESETS
|
||||
}
|
||||
|
||||
export function keymapStatusHint(keymap: VMKeymapStatus): KeymapStatusHint | null {
|
||||
if (keymap.preset === 'off' && !keymap.capture_host_shortcuts) return null
|
||||
if (!keymap.input_service_available) return { key: 'keymapInputServiceRequired' }
|
||||
if (!keymap.running) return { key: 'keymapStopped' }
|
||||
if (keymap.needs_guest_tools && !keymap.guest_connected) return { key: 'keymapWaiting' }
|
||||
if (keymap.needs_guest_tools && (keymap.guest_agent_version ?? 0) < keymap.required_agent_version) {
|
||||
return { key: 'keymapUpgrade', vars: { version: keymap.required_agent_version } }
|
||||
}
|
||||
if (keymap.needs_guest_tools && !keymap.guest_keymap_active) return { key: 'keymapPending' }
|
||||
return { key: keymap.hook_active ? 'keymapRunning' : 'keymapInactive' }
|
||||
}
|
||||
|
||||
type KeymapRequest = Required<VMKeymapUpdate>
|
||||
|
||||
export function keymapUpdate(current: VMKeymapStatus, changes: Partial<KeymapRequest>): KeymapRequest {
|
||||
|
||||
@@ -911,6 +911,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
background: var(--accent); transform-origin: left center;
|
||||
transition: transform var(--dur) var(--ease-out);
|
||||
}
|
||||
.creating-row { flex-direction: column; align-items: stretch; gap: var(--sp-2); }
|
||||
.creating-head { display: flex; align-items: center; justify-content: space-between; gap: var(--sp-2); }
|
||||
.creating-progress { width: 100%; height: 6px; }
|
||||
.logs-body-wrap { position: relative; border-top: 1px solid var(--border); }
|
||||
.logs-body {
|
||||
overflow-y: auto; overscroll-behavior: contain; padding: var(--sp-2) var(--sp-4);
|
||||
@@ -977,6 +980,7 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
border: 1px solid var(--border-strong); color: var(--text);
|
||||
font-size: var(--fs-12); box-shadow: 0 8px 22px rgba(15, 23, 42, 0.16);
|
||||
display: flex; gap: var(--sp-2); align-items: center;
|
||||
max-width: min(420px, calc(100vw - 16px)); white-space: pre-line; overflow-wrap: anywhere;
|
||||
transform-origin: var(--radix-tooltip-content-transform-origin);
|
||||
}
|
||||
.tooltip kbd { font-family: var(--font-sans); color: var(--text-3); }
|
||||
@@ -1791,6 +1795,12 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.plugin-app-icon.is-md { width: 34px; height: 34px; border-radius: 9px; }
|
||||
.plugin-app-icon.is-sm { width: 30px; height: 30px; border-radius: 8px; }
|
||||
.plugin-app-icon-svg {
|
||||
display: inline-block; flex-shrink: 0; background-color: currentColor;
|
||||
-webkit-mask-repeat: no-repeat; mask-repeat: no-repeat;
|
||||
-webkit-mask-position: center; mask-position: center;
|
||||
-webkit-mask-size: contain; mask-size: contain;
|
||||
}
|
||||
.plugin-app-icon.tone-indigo { background: linear-gradient(145deg, #6e7cf0 0%, #4d5be0 100%); }
|
||||
.plugin-app-icon.tone-purple { background: linear-gradient(145deg, #bf5af2 0%, #8944ab 100%); }
|
||||
.plugin-app-icon.tone-sky { background: linear-gradient(145deg, #32a0ff 0%, #007aff 100%); }
|
||||
@@ -1830,6 +1840,9 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
/* Plugin market: cache-first feed of cards in as many columns as fit */
|
||||
.plugin-market { gap: 12px; }
|
||||
.market-toolbar { display: flex; flex-direction: column; gap: 10px; }
|
||||
.market-toolbar-top { display: flex; align-items: center; gap: 8px; }
|
||||
.market-toolbar-top > :first-child { flex: 1; min-width: 0; }
|
||||
.market-sort { flex-shrink: 0; min-width: 124px; }
|
||||
.market-kinds { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
|
||||
|
||||
.market-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; }
|
||||
@@ -1856,6 +1869,37 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
}
|
||||
.market-card-dot { flex-shrink: 0; }
|
||||
.market-card-version { flex-shrink: 0; font-variant-numeric: tabular-nums; }
|
||||
.market-card-stat {
|
||||
display: inline-flex; align-items: center; gap: 3px; flex-shrink: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.market-alpha-badge {
|
||||
display: inline-flex; align-items: center; padding: 0 5px; height: 16px;
|
||||
border-radius: 4px; font-size: 10px; font-weight: 600; flex-shrink: 0;
|
||||
color: var(--amber); background: color-mix(in srgb, var(--amber) 14%, transparent);
|
||||
}
|
||||
.market-version-list { display: flex; flex-direction: column; gap: 8px; }
|
||||
.market-version-opt {
|
||||
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px;
|
||||
border-radius: var(--r-md); border: 1px solid var(--border);
|
||||
background: var(--surface-1); cursor: pointer;
|
||||
}
|
||||
.market-version-opt.is-selected {
|
||||
border-color: var(--accent);
|
||||
background: color-mix(in srgb, var(--accent) 6%, var(--surface-1));
|
||||
}
|
||||
.market-version-opt input[type='radio'] { margin-top: 3px; flex-shrink: 0; }
|
||||
.market-version-main { display: flex; flex-direction: column; gap: 4px; min-width: 0; flex: 1; }
|
||||
.market-version-head { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; font-size: var(--fs-13); }
|
||||
.market-version-current {
|
||||
display: inline-flex; align-items: center; padding: 0 5px; height: 16px;
|
||||
border-radius: 4px; font-size: 10px; font-weight: 600;
|
||||
color: var(--accent); background: color-mix(in srgb, var(--accent) 14%, transparent);
|
||||
}
|
||||
.market-version-meta { margin-left: auto; font-size: var(--fs-12); color: var(--text-3); font-variant-numeric: tabular-nums; }
|
||||
.market-version-notes { margin: 0; font-size: var(--fs-12); color: var(--text-2); line-height: 1.45; }
|
||||
.plugin-title-link { color: inherit; text-decoration: none; }
|
||||
.plugin-title-link:hover { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
|
||||
.market-card-action { flex-shrink: 0; }
|
||||
.market-card-action .btn.market-btn { height: 28px; padding: 0 12px; font-size: var(--fs-12); }
|
||||
.market-card-desc {
|
||||
@@ -1903,10 +1947,6 @@ button.status-issue + .status-metric { margin-left: 6px; }
|
||||
|
||||
/* What a plugin can do, shown before enabling it */
|
||||
.plugin-enable-lead { margin: 0; font-size: var(--fs-13); color: var(--text-2); }
|
||||
.plugin-log-pre {
|
||||
margin: 0; font-size: var(--fs-12); line-height: 1.55;
|
||||
white-space: pre-wrap; word-break: break-word;
|
||||
}
|
||||
.plugin-risk-list {
|
||||
margin: 0; padding: 4px 0; list-style: none;
|
||||
background: var(--surface-1); border: 1px solid var(--border); border-radius: var(--r-lg);
|
||||
|
||||
@@ -106,6 +106,7 @@ export type DiskResizeResult = driver.DiskResizeResult
|
||||
export type DiskCompactResult = driver.DiskCompactResult
|
||||
export type DiskSnapshot = driver.DiskSnapshot
|
||||
export type StorageBreakdown = Model<app.StorageBreakdown>
|
||||
export type DiskCache = 'default' | 'writeback' | 'none' | 'unsafe'
|
||||
export type SetOpts = reims.SetOpts
|
||||
|
||||
export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
@@ -114,6 +115,7 @@ export type CreateOpts = Model<reims.CreateOpts> & {
|
||||
source_mode?: 'offline' | 'apple' | 'installer' | 'disk'
|
||||
disk_mode?: 'copy' | 'in-place'
|
||||
disk_controller?: 'nvme' | 'ahci' | 'virtio'
|
||||
disk_cache?: DiskCache
|
||||
graphics: 'reims-vgpu' | 'vmware-svga'
|
||||
cpus: number
|
||||
memory: string
|
||||
@@ -150,6 +152,7 @@ export type LocalizedText = plugin.LocalizedText
|
||||
export type PermissionSpec = plugin.PermissionSpec
|
||||
export type SettingProperty = plugin.SettingProperty
|
||||
export type SettingsSchema = plugin.SettingsSchema
|
||||
export type PluginIcon = plugin.PluginIcon
|
||||
export type PluginInfo = plugin.PluginInfo
|
||||
export type ScanReport = plugin.ScanReport
|
||||
export type MarketCatalogItem = plugin.MarketCatalogItem
|
||||
|
||||
@@ -169,6 +169,7 @@ export const api = {
|
||||
BrowsePluginMarket: boundGo.BrowsePluginMarket as (query: string, kind: string, includeAlpha: boolean, forceRefresh: boolean) => Promise<MarketBrowseResult>,
|
||||
PeekPluginMarket: boundGo.PeekPluginMarket as (query: string, kind: string) => Promise<MarketBrowseResult>,
|
||||
InstallMarketPlugin: boundGo.InstallMarketPlugin as (id: string, includeAlpha: boolean) => Promise<PluginInfo>,
|
||||
InstallMarketPluginVersion: boundGo.InstallMarketPluginVersion as (id: string, version: string) => Promise<PluginInfo>,
|
||||
GetPluginUIContributions: boundGo.GetPluginUIContributions as () => Promise<PluginUIContributions>,
|
||||
GetActiveTheme: boundGo.GetActiveTheme as () => Promise<ActiveThemePayload>,
|
||||
ListDrivers: boundGo.ListDrivers as () => Promise<DriverSummary[] | null>,
|
||||
|
||||
Vendored
+2
-4
@@ -152,6 +152,8 @@ export function InstallAppUpdate():Promise<void>;
|
||||
|
||||
export function InstallMarketPlugin(arg1:string,arg2:boolean):Promise<plugin.PluginInfo>;
|
||||
|
||||
export function InstallMarketPluginVersion(arg1:string,arg2:string):Promise<plugin.PluginInfo>;
|
||||
|
||||
export function InstallNpcap():Promise<void>;
|
||||
|
||||
export function InstallPluginArchive(arg1:string):Promise<plugin.PluginInfo>;
|
||||
@@ -214,8 +216,6 @@ export function PreviewCreate(arg1:reims.CreateOpts):Promise<string>;
|
||||
|
||||
export function QuitApp():Promise<void>;
|
||||
|
||||
export function ReadPluginLog(arg1:string):Promise<string>;
|
||||
|
||||
export function ReadVMLogs(arg1:string,arg2:string,arg3:boolean):Promise<string>;
|
||||
|
||||
export function RemovePlugin(arg1:string,arg2:boolean):Promise<void>;
|
||||
@@ -272,8 +272,6 @@ export function SetQEMUASLR(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
|
||||
|
||||
@@ -282,6 +282,10 @@ export function InstallMarketPlugin(arg1, arg2) {
|
||||
return window['go']['app']['App']['InstallMarketPlugin'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function InstallMarketPluginVersion(arg1, arg2) {
|
||||
return window['go']['app']['App']['InstallMarketPluginVersion'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function InstallNpcap() {
|
||||
return window['go']['app']['App']['InstallNpcap']();
|
||||
}
|
||||
@@ -406,10 +410,6 @@ export function QuitApp() {
|
||||
return window['go']['app']['App']['QuitApp']();
|
||||
}
|
||||
|
||||
export function ReadPluginLog(arg1) {
|
||||
return window['go']['app']['App']['ReadPluginLog'](arg1);
|
||||
}
|
||||
|
||||
export function ReadVMLogs(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['ReadVMLogs'](arg1, arg2, arg3);
|
||||
}
|
||||
@@ -522,10 +522,6 @@ export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1) {
|
||||
return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMAffinity(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ export namespace app {
|
||||
optimizations: host.Optimization[];
|
||||
runtimes: runtime.Installed[];
|
||||
active_runtime?: runtime.Installed;
|
||||
runtime_capture_supported: boolean;
|
||||
can_suspend: boolean;
|
||||
vms: driver.VMListItem[];
|
||||
vm_list_error?: string;
|
||||
@@ -37,6 +38,7 @@ export namespace app {
|
||||
this.optimizations = this.convertValues(source["optimizations"], host.Optimization);
|
||||
this.runtimes = this.convertValues(source["runtimes"], runtime.Installed);
|
||||
this.active_runtime = this.convertValues(source["active_runtime"], runtime.Installed);
|
||||
this.runtime_capture_supported = source["runtime_capture_supported"];
|
||||
this.can_suspend = source["can_suspend"];
|
||||
this.vms = this.convertValues(source["vms"], driver.VMListItem);
|
||||
this.vm_list_error = source["vm_list_error"];
|
||||
@@ -812,7 +814,6 @@ export namespace config {
|
||||
qemu_aslr?: boolean;
|
||||
app_update_channel?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
sync_host_memory_smbios?: boolean;
|
||||
host_dns_mode?: string;
|
||||
host_dns_doh_url?: string;
|
||||
enable_hypervisor_switch?: boolean;
|
||||
@@ -834,7 +835,6 @@ export namespace config {
|
||||
this.qemu_aslr = source["qemu_aslr"];
|
||||
this.app_update_channel = source["app_update_channel"];
|
||||
this.minimize_to_tray = source["minimize_to_tray"];
|
||||
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
|
||||
this.host_dns_mode = source["host_dns_mode"];
|
||||
this.host_dns_doh_url = source["host_dns_doh_url"];
|
||||
this.enable_hypervisor_switch = source["enable_hypervisor_switch"];
|
||||
@@ -2073,6 +2073,48 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class MarketRelease {
|
||||
version: string;
|
||||
channel?: string;
|
||||
download_url: string;
|
||||
sha256: string;
|
||||
size_bytes?: number;
|
||||
published_at?: string;
|
||||
changelog?: LocalizedText;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new MarketRelease(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.version = source["version"];
|
||||
this.channel = source["channel"];
|
||||
this.download_url = source["download_url"];
|
||||
this.sha256 = source["sha256"];
|
||||
this.size_bytes = source["size_bytes"];
|
||||
this.published_at = source["published_at"];
|
||||
this.changelog = this.convertValues(source["changelog"], LocalizedText);
|
||||
}
|
||||
|
||||
convertValues(a: any, classs: any, asMap: boolean = false): any {
|
||||
if (!a) {
|
||||
return a;
|
||||
}
|
||||
if (a.slice && a.map) {
|
||||
return (a as any[]).map(elem => this.convertValues(elem, classs));
|
||||
} else if ("object" === typeof a) {
|
||||
if (asMap) {
|
||||
for (const key of Object.keys(a)) {
|
||||
a[key] = new classs(a[key]);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
return new classs(a);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class MarketEntry {
|
||||
id: string;
|
||||
version: string;
|
||||
@@ -2084,6 +2126,7 @@ export namespace plugin {
|
||||
trust: string;
|
||||
kind?: string;
|
||||
tier?: string;
|
||||
icon?: PluginIcon;
|
||||
homepage?: string;
|
||||
readme_url?: string;
|
||||
engines: Engines;
|
||||
@@ -2094,8 +2137,11 @@ export namespace plugin {
|
||||
size_bytes?: number;
|
||||
signer?: string;
|
||||
changelog?: LocalizedText;
|
||||
releases?: MarketRelease[];
|
||||
tags?: string[];
|
||||
locales?: string[];
|
||||
stars?: number;
|
||||
downloads?: number;
|
||||
updated_at?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -2114,6 +2160,7 @@ export namespace plugin {
|
||||
this.trust = source["trust"];
|
||||
this.kind = source["kind"];
|
||||
this.tier = source["tier"];
|
||||
this.icon = this.convertValues(source["icon"], PluginIcon);
|
||||
this.homepage = source["homepage"];
|
||||
this.readme_url = source["readme_url"];
|
||||
this.engines = this.convertValues(source["engines"], Engines);
|
||||
@@ -2124,8 +2171,11 @@ export namespace plugin {
|
||||
this.size_bytes = source["size_bytes"];
|
||||
this.signer = source["signer"];
|
||||
this.changelog = this.convertValues(source["changelog"], LocalizedText);
|
||||
this.releases = this.convertValues(source["releases"], MarketRelease);
|
||||
this.tags = source["tags"];
|
||||
this.locales = source["locales"];
|
||||
this.stars = source["stars"];
|
||||
this.downloads = source["downloads"];
|
||||
this.updated_at = source["updated_at"];
|
||||
}
|
||||
|
||||
@@ -2425,6 +2475,20 @@ export namespace plugin {
|
||||
return a;
|
||||
}
|
||||
}
|
||||
export class PluginIcon {
|
||||
tone?: string;
|
||||
svg?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
return new PluginIcon(source);
|
||||
}
|
||||
|
||||
constructor(source: any = {}) {
|
||||
if ('string' === typeof source) source = JSON.parse(source);
|
||||
this.tone = source["tone"];
|
||||
this.svg = source["svg"];
|
||||
}
|
||||
}
|
||||
export class PluginInfo {
|
||||
id: string;
|
||||
version: string;
|
||||
@@ -2433,6 +2497,7 @@ export namespace plugin {
|
||||
publisher?: string;
|
||||
license?: string;
|
||||
homepage?: string;
|
||||
icon?: PluginIcon;
|
||||
source: string;
|
||||
trust: string;
|
||||
tier: string;
|
||||
@@ -2472,6 +2537,7 @@ export namespace plugin {
|
||||
this.publisher = source["publisher"];
|
||||
this.license = source["license"];
|
||||
this.homepage = source["homepage"];
|
||||
this.icon = this.convertValues(source["icon"], PluginIcon);
|
||||
this.source = source["source"];
|
||||
this.trust = source["trust"];
|
||||
this.tier = source["tier"];
|
||||
@@ -2953,6 +3019,7 @@ export namespace reims {
|
||||
disk?: string;
|
||||
disk_mode?: string;
|
||||
disk_controller?: string;
|
||||
disk_cache?: string;
|
||||
graphics?: string;
|
||||
gpu?: string;
|
||||
resolution?: string;
|
||||
@@ -2986,6 +3053,7 @@ export namespace reims {
|
||||
this.disk = source["disk"];
|
||||
this.disk_mode = source["disk_mode"];
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.disk_cache = source["disk_cache"];
|
||||
this.graphics = source["graphics"];
|
||||
this.gpu = source["gpu"];
|
||||
this.resolution = source["resolution"];
|
||||
@@ -3009,6 +3077,7 @@ export namespace reims {
|
||||
graphics?: string;
|
||||
displays?: number;
|
||||
disk_controller?: string;
|
||||
disk_cache?: string;
|
||||
resolution?: string;
|
||||
borderless?: boolean;
|
||||
capture?: boolean;
|
||||
@@ -3037,6 +3106,7 @@ export namespace reims {
|
||||
this.graphics = source["graphics"];
|
||||
this.displays = source["displays"];
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.disk_cache = source["disk_cache"];
|
||||
this.resolution = source["resolution"];
|
||||
this.borderless = source["borderless"];
|
||||
this.capture = source["capture"];
|
||||
@@ -3111,6 +3181,7 @@ export namespace reims {
|
||||
memory: string;
|
||||
disk: string;
|
||||
disk_controller: string;
|
||||
disk_cache: string;
|
||||
graphics: string;
|
||||
display: string;
|
||||
displays: number;
|
||||
@@ -3132,6 +3203,7 @@ export namespace reims {
|
||||
log_level: string;
|
||||
stop_timeout: number;
|
||||
capture: boolean;
|
||||
capture_supported: boolean;
|
||||
borderless: boolean;
|
||||
extra_args: string;
|
||||
guest_tools_attached: boolean;
|
||||
@@ -3163,6 +3235,7 @@ export namespace reims {
|
||||
this.memory = source["memory"];
|
||||
this.disk = source["disk"];
|
||||
this.disk_controller = source["disk_controller"];
|
||||
this.disk_cache = source["disk_cache"];
|
||||
this.graphics = source["graphics"];
|
||||
this.display = source["display"];
|
||||
this.displays = source["displays"];
|
||||
@@ -3184,6 +3257,7 @@ export namespace reims {
|
||||
this.log_level = source["log_level"];
|
||||
this.stop_timeout = source["stop_timeout"];
|
||||
this.capture = source["capture"];
|
||||
this.capture_supported = source["capture_supported"];
|
||||
this.borderless = source["borderless"];
|
||||
this.extra_args = source["extra_args"];
|
||||
this.guest_tools_attached = source["guest_tools_attached"];
|
||||
@@ -3475,7 +3549,7 @@ export namespace version {
|
||||
download_url?: string;
|
||||
asset_name?: string;
|
||||
asset_size?: number;
|
||||
sums_url?: string;
|
||||
asset_sha256?: string;
|
||||
published_at?: string;
|
||||
|
||||
static createFrom(source: any = {}) {
|
||||
@@ -3492,7 +3566,7 @@ export namespace version {
|
||||
this.download_url = source["download_url"];
|
||||
this.asset_name = source["asset_name"];
|
||||
this.asset_size = source["asset_size"];
|
||||
this.sums_url = source["sums_url"];
|
||||
this.asset_sha256 = source["asset_sha256"];
|
||||
this.published_at = source["published_at"];
|
||||
}
|
||||
}
|
||||
|
||||
+23
-10
@@ -74,6 +74,8 @@ type AppState struct {
|
||||
DetectedLocale string `json:"detected_locale,omitempty"`
|
||||
EffectiveLocale string `json:"effective_locale,omitempty"`
|
||||
MissingFontHint string `json:"missing_font_hint,omitempty"`
|
||||
|
||||
RuntimeCaptureSupported bool `json:"runtime_capture_supported"`
|
||||
}
|
||||
|
||||
type rebootWatcherEntry struct {
|
||||
@@ -116,8 +118,9 @@ type App struct {
|
||||
resolveFolderVolume func(string) (host.DirectoryVolume, error)
|
||||
imeBridge *host.IMEBridge
|
||||
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
launchPrevDataRoot string
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
@@ -182,10 +185,13 @@ type Lifecycle struct {
|
||||
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
i18n.SetDetailRedactor(host.RedactText)
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
launchPrevDataRoot := ""
|
||||
if launch.DataRoot != "" {
|
||||
cfg, err = config.Load(filepath.Join(launch.DataRoot, "reims-go.json"))
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
} else if cfg.DataRoot != "" && !sameDataFolder(cfg.DataRoot, launch.DataRoot) {
|
||||
launchPrevDataRoot = cfg.DataRoot
|
||||
}
|
||||
cfg.DataRoot = launch.DataRoot
|
||||
needsSetup = false
|
||||
@@ -193,9 +199,10 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
cfg = config.Default()
|
||||
}
|
||||
a := &App{
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
launchPrevDataRoot: launchPrevDataRoot,
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
@@ -445,6 +452,8 @@ func (a *App) GetState() AppState {
|
||||
DetectedLocale: string(i18n.DetectOSLocaleTag()),
|
||||
EffectiveLocale: string(i18n.EffectiveLocale(cfgCopy.Locale)),
|
||||
MissingFontHint: host.CheckMissingLocaleFontsForUI(string(i18n.EffectiveLocale(cfgCopy.Locale)), i18n.EffectiveLocale(cfgCopy.Locale)),
|
||||
|
||||
RuntimeCaptureSupported: !needsSetup && !rootStatus.ReadOnly && active != nil && runtimeAllowsCapture(*active),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -471,10 +480,6 @@ func (a *App) SetMinimizeToTray(enabled bool) error {
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
|
||||
}
|
||||
|
||||
func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.SyncHostMemorySMBIOS = enabled })
|
||||
}
|
||||
|
||||
// showMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) showMainWindow() {
|
||||
if a.ctx == nil {
|
||||
@@ -704,12 +709,18 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.LoadExisting(cfgPath)
|
||||
fresh := errors.Is(err, os.ErrNotExist)
|
||||
recordedOldRoot := ""
|
||||
if fresh {
|
||||
nextCfg = config.Default()
|
||||
nextCfg.Locale = prev.Locale
|
||||
nextCfg.QEMUASLR = prev.QEMUASLR
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
} else {
|
||||
recordedOldRoot = nextCfg.DataRoot
|
||||
}
|
||||
if recordedOldRoot == "" || sameDataFolder(recordedOldRoot, dir) {
|
||||
recordedOldRoot = prev.DataRoot
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
if changed && !setup {
|
||||
@@ -738,7 +749,6 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
nextCfg.RuntimeChannel = cur.RuntimeChannel
|
||||
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
|
||||
nextCfg.MinimizeToTray = cur.MinimizeToTray
|
||||
nextCfg.SyncHostMemorySMBIOS = cur.SyncHostMemorySMBIOS
|
||||
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
|
||||
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
|
||||
nextCfg.FullscreenHotkeyEnabled = cur.FullscreenHotkeyEnabled
|
||||
@@ -766,6 +776,9 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() {
|
||||
a.relocateRegisteredVMs(dir, recordedOldRoot)
|
||||
}
|
||||
|
||||
// Leaving a read-only folder starts the plugins and polling it held back,
|
||||
// even when the user picked the same folder again after fixing it.
|
||||
|
||||
@@ -86,8 +86,8 @@ func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, s
|
||||
VMDir: vm.Dir,
|
||||
TmpDir: tmp,
|
||||
Console: service,
|
||||
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, bool) {
|
||||
return bridge.ActiveWindow(name, maxAge)
|
||||
Window: func(maxAge time.Duration) (guesttools.ActiveWindow, time.Time, bool) {
|
||||
return bridge.ActiveWindowSample(name, maxAge)
|
||||
},
|
||||
PrepareClipboard: func(wait context.Context) (func(), error) {
|
||||
return bridge.PrepareGuestClipboardPaste(wait, name)
|
||||
@@ -108,6 +108,9 @@ func (a *App) prepareAppWindow(ctx context.Context, bridge *guesttools.Server, s
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
if errors.Is(err, appwindow.ErrNoWindow) {
|
||||
if status.AgentVersion < guesttools.StableWindowReporterAgentVersion {
|
||||
return nil, coded("E_APP_WINDOW_GUEST_TOOLS_UPDATE", "err.app_window_guest_tools_update", nil)
|
||||
}
|
||||
return nil, coded("E_APP_WINDOW_NO_WINDOW", "err.app_window_no_window", nil)
|
||||
}
|
||||
return nil, coded("E_APP_WINDOW_CAPTURE", "err.app_window_capture", err)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package app
|
||||
|
||||
// In-app update: download the new release's Windows executable as a tracked
|
||||
// task, check it against the release's SHA256SUMS.txt, then swap it in and
|
||||
// task, check it against GitHub's assets[].digest SHA-256, then swap it in and
|
||||
// restart (internal/selfupdate). Running VMs are separate processes and keep
|
||||
// running; Guest Tools reconnects once the new window is up.
|
||||
|
||||
@@ -84,7 +84,7 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
return "", a.updateErr("err.update_none")
|
||||
case info.DownloadURL == "" || info.AssetName == "":
|
||||
return "", a.updateErr("err.update_no_asset")
|
||||
case info.SumsURL == "":
|
||||
case info.AssetSHA256 == "":
|
||||
return "", a.updateErr("err.update_no_sums")
|
||||
}
|
||||
for _, t := range tasks.list() {
|
||||
@@ -122,13 +122,13 @@ func (a *App) DownloadAppUpdate() (string, error) {
|
||||
}
|
||||
|
||||
// downloadAppUpdate fetches info's executable into dir and checks it against
|
||||
// the release's SHA256SUMS.txt. It returns the file and its hash.
|
||||
// GitHub's assets[].digest SHA-256. It returns the file and its hash.
|
||||
func downloadAppUpdate(ctx context.Context, info version.UpdateInfo, dir string, onProgress fetch.Progress) (string, string, error) {
|
||||
client := netproxy.NewClient()
|
||||
want, err := fetch.ExpectedSum(ctx, client, info.SumsURL, info.AssetName)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
want := strings.ToLower(strings.TrimSpace(info.AssetSHA256))
|
||||
if len(want) != 64 {
|
||||
return "", "", errors.New("missing or invalid release asset SHA-256 digest")
|
||||
}
|
||||
client := netproxy.NewClient()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
@@ -18,16 +17,12 @@ import (
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func TestDownloadAppUpdateVerifiesAgainstSums(t *testing.T) {
|
||||
func TestDownloadAppUpdateVerifiesAgainstAssetDigest(t *testing.T) {
|
||||
body := []byte("reims-go v9.9.9 build")
|
||||
h := sha256.Sum256(body)
|
||||
good := hex.EncodeToString(h[:])
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/SHA256SUMS.txt":
|
||||
fmt.Fprintf(w, "%s reims-go-v9.9.9-windows-amd64.exe\n", good)
|
||||
case "/bad/SHA256SUMS.txt":
|
||||
fmt.Fprintf(w, "%s reims-go-v9.9.9-windows-amd64.exe\n", strings.Repeat("0", 64))
|
||||
case "/app.exe":
|
||||
_, _ = w.Write(body)
|
||||
default:
|
||||
@@ -38,7 +33,7 @@ func TestDownloadAppUpdateVerifiesAgainstSums(t *testing.T) {
|
||||
info := version.UpdateInfo{
|
||||
Latest: "v9.9.9", HasUpdate: true,
|
||||
AssetName: "reims-go-v9.9.9-windows-amd64.exe", AssetSize: int64(len(body)),
|
||||
DownloadURL: srv.URL + "/app.exe", SumsURL: srv.URL + "/SHA256SUMS.txt",
|
||||
DownloadURL: srv.URL + "/app.exe", AssetSHA256: good,
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
@@ -50,10 +45,15 @@ func TestDownloadAppUpdateVerifiesAgainstSums(t *testing.T) {
|
||||
t.Fatalf("path %s sum %s", path, sum)
|
||||
}
|
||||
|
||||
info.SumsURL = srv.URL + "/bad/SHA256SUMS.txt"
|
||||
info.AssetSHA256 = strings.Repeat("0", 64)
|
||||
if _, _, err := downloadAppUpdate(context.Background(), info, t.TempDir(), nil); err == nil || !strings.Contains(err.Error(), "SHA256 mismatch") {
|
||||
t.Fatalf("a hash mismatch must fail, got %v", err)
|
||||
}
|
||||
|
||||
info.AssetSHA256 = ""
|
||||
if _, _, err := downloadAppUpdate(context.Background(), info, t.TempDir(), nil); err == nil {
|
||||
t.Fatal("missing asset digest must fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstallAppUpdateGuards(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
|
||||
)
|
||||
|
||||
const cloneSourceSettingPlugin = "test.clone.agent"
|
||||
|
||||
// newCloneSettingsEnv builds a host whose MCP clone reads its settings from a
|
||||
// source VM. The plugin declares the same login_password/username/
|
||||
// allow_ai_access schema as reims.agent, scoped to the VM.
|
||||
func newCloneSettingsEnv(t *testing.T) (*App, *plugin.Manager, driver.Driver) {
|
||||
t.Helper()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = t.TempDir()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Close)
|
||||
if err := mgr.Registry().Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
ID: cloneSourceSettingPlugin,
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: cloneSourceSettingPlugin},
|
||||
Settings: &plugin.SettingsSchema{
|
||||
Scope: "vm",
|
||||
Properties: map[string]plugin.SettingProperty{
|
||||
"allow_ai_access": {Type: "boolean"},
|
||||
"username": {Type: "string"},
|
||||
"login_password": {Type: "string", Secret: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, _ *plugin.Scope) error {
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
h := fakedriver.NewHarness(t)
|
||||
drv := h.Add("hosted", "test.clone.driver", "test.driver.clone")
|
||||
|
||||
app := &App{
|
||||
cfg: cfg,
|
||||
pluginMgr: mgr,
|
||||
transitions: map[string]string{},
|
||||
pendingChanges: map[string][]PendingChange{},
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: map[string]cachedDiskPath{},
|
||||
procSamples: map[string]host.ProcessSample{},
|
||||
driverRouter: h.Router,
|
||||
vmStateTable: h.States,
|
||||
lifecycleSvc: lifecycle.New(h.Registry, h.Router, nil),
|
||||
}
|
||||
return app, mgr, drv
|
||||
}
|
||||
|
||||
func createVMs(t *testing.T, drv driver.Driver, names ...string) {
|
||||
t.Helper()
|
||||
for _, name := range names {
|
||||
if err := drv.Create(context.Background(), driver.CreateRequest{DriverID: drv.ID(), Name: name}, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneSecretFallsBackToAuthorizedSource(t *testing.T) {
|
||||
app, mgr, drv := newCloneSettingsEnv(t)
|
||||
createVMs(t, drv, "source", "__agent-clone")
|
||||
sourceKey := driver.NewVMRef(drv.ID(), "source").Key()
|
||||
cloneKey := driver.NewVMRef(drv.ID(), "__agent-clone").Key()
|
||||
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{
|
||||
"allow_ai_access": true,
|
||||
"username": "macuser",
|
||||
"login_password": "secret-from-source",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-clone")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneKey, sourceKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password")
|
||||
if err != nil {
|
||||
t.Fatalf("clone should borrow the source password: %v", err)
|
||||
}
|
||||
if got != "secret-from-source" {
|
||||
t.Fatalf("clone secret = %q, want the source value", got)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "macuser" {
|
||||
t.Fatalf("clone SSH user = %q, want the source user", user)
|
||||
}
|
||||
|
||||
// The clone's own value wins over the source.
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{
|
||||
"allow_ai_access": true,
|
||||
"username": "cloneuser",
|
||||
"login_password": "clone-own-password",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password")
|
||||
if err != nil || got != "clone-own-password" {
|
||||
t.Fatalf("clone own secret = %q (%v), want its own value", got, err)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" {
|
||||
t.Fatalf("clone SSH user = %q, want its own value", user)
|
||||
}
|
||||
|
||||
// Clearing the clone's own password and revoking access on the source
|
||||
// removes the fallback again.
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{"login_password": ""}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{"allow_ai_access": false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
t.Fatalf("revoked source should leave no fallback, got %v", err)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" {
|
||||
t.Fatalf("clone keeps its own SSH user after source revoke, got %q", user)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneSecretWithoutSourceStaysEmpty(t *testing.T) {
|
||||
app, mgr, drv := newCloneSettingsEnv(t)
|
||||
createVMs(t, drv, "__agent-orphan")
|
||||
cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A marker with no source (the lost-marker repair path) has no fallback.
|
||||
if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneVM.Ref().Key(), ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
t.Fatalf("clone without a source should have no fallback, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretMissingMessageLocalized(t *testing.T) {
|
||||
const key = "err.computer_use.secret_missing"
|
||||
for _, loc := range []i18n.Locale{i18n.ZhCN, i18n.EnUS} {
|
||||
msg := strings.TrimSpace(i18n.M(loc, key, nil))
|
||||
if msg == "" || msg == key {
|
||||
t.Fatalf("%s %q did not resolve", loc, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
)
|
||||
|
||||
const computerUsePreviewWidth = 1280
|
||||
const computerUseMaxImageWidth = 2560
|
||||
const computerUseMaxTextRunes = 4000
|
||||
const computerUseSecretPluginID = "reims.agent"
|
||||
|
||||
@@ -35,6 +37,11 @@ type computerUseOwnership struct {
|
||||
Version int `json:"version"`
|
||||
PluginID string `json:"plugin_id"`
|
||||
VMKey string `json:"vm_key"`
|
||||
// SourceVM is the driver-qualified key of the VM the clone was taken from.
|
||||
// A clone has no vm settings of its own (login password, SSH user), so
|
||||
// secret and username lookups fall back to the source while it is still
|
||||
// authorized. Older markers omit it and simply have no fallback.
|
||||
SourceVM string `json:"source_vm,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
@@ -50,13 +57,14 @@ func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[
|
||||
"host/vm.resume": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.resume", a.handleComputerUseVMStateChange(a.ResumeVM)),
|
||||
"host/vm.clone": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.clone", a.handleComputerUseVMClone),
|
||||
"host/vm.delete": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.delete", a.handleComputerUseVMDelete),
|
||||
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.list": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:read", "host/vm.snapshot.list", a.handleComputerUseVMSnapshotList),
|
||||
"host/vm.snapshot.create": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.create", a.handleComputerUseVMSnapshotCreate),
|
||||
"host/vm.snapshot.restore": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:control", "host/vm.snapshot.restore", a.handleComputerUseVMSnapshotRestore),
|
||||
"host/console.screenshot": a.authorizedComputerUseVMHandler(mgr, pluginID, "vm:screen", "host/console.screenshot", a.handleComputerUseScreenshot),
|
||||
"host/console.pointer": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.pointer", a.handleComputerUsePointer),
|
||||
"host/console.key": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.key", a.handleComputerUseKey),
|
||||
"host/console.type": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.type", a.handleComputerUseType),
|
||||
"host/console.release": a.authorizedComputerUseVMHandler(mgr, pluginID, "qmp:write", "host/console.release", a.handleComputerUseRelease),
|
||||
}
|
||||
// The plugin ID is supplied by the manager while wiring the sidecar, never
|
||||
// by the channel payload. Keep the handler registered for a stable method
|
||||
@@ -94,8 +102,11 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is unavailable")
|
||||
}
|
||||
secret, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), req.Setting)
|
||||
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting)
|
||||
if err != nil {
|
||||
if errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer func() { secret = "" }()
|
||||
@@ -175,14 +186,7 @@ func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID
|
||||
view["capabilities"] = append([]string(nil), vm.Capabilities...)
|
||||
}
|
||||
if accessEnabled {
|
||||
username := a.GetVMSSHUser(vm.DriverID, vm.Name)
|
||||
if mgr != nil {
|
||||
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
|
||||
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||
username = strings.TrimSpace(configured)
|
||||
}
|
||||
}
|
||||
if username != "" {
|
||||
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
|
||||
view["ssh_username"] = username
|
||||
}
|
||||
}
|
||||
@@ -208,7 +212,8 @@ func (a *App) handleComputerUseVMStart(_ context.Context, raw json.RawMessage, m
|
||||
|
||||
func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
var req struct {
|
||||
VM string `json:"vm"`
|
||||
VM string `json:"vm"`
|
||||
Force bool `json:"force"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
@@ -217,7 +222,7 @@ func (a *App) handleComputerUseVMShutdown(_ context.Context, raw json.RawMessage
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.StopVM(vm.DriverID, vm.Name, false); err != nil {
|
||||
if err := a.StopVM(vm.DriverID, vm.Name, req.Force); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
@@ -278,7 +283,7 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
return nil, err
|
||||
}
|
||||
cloneRef := cloned.Ref()
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key())
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key(), vm.Ref().Key())
|
||||
if err != nil {
|
||||
if cleanupErr := a.DeleteVM(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr))
|
||||
@@ -513,14 +518,15 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
|
||||
}
|
||||
}
|
||||
|
||||
func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error {
|
||||
func writeComputerUseOwnership(vmDir, pluginID, vmKey, sourceVM string) error {
|
||||
vmDir = strings.TrimSpace(vmDir)
|
||||
pluginID = strings.TrimSpace(pluginID)
|
||||
vmKey = strings.TrimSpace(vmKey)
|
||||
sourceVM = strings.TrimSpace(sourceVM)
|
||||
if vmDir == "" || pluginID == "" || vmKey == "" {
|
||||
return errors.New("temporary VM ownership metadata is incomplete")
|
||||
}
|
||||
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey})
|
||||
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey, SourceVM: sourceVM})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -612,15 +618,15 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
|
||||
return errors.Join(cleanupErrors...)
|
||||
}
|
||||
|
||||
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey string) error {
|
||||
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM string) error {
|
||||
if vm.Directory == "" {
|
||||
return errors.New("temporary clone directory is unavailable")
|
||||
}
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil {
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey, sourceVM); err != nil {
|
||||
return err
|
||||
}
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok || marker.PluginID != pluginID {
|
||||
if !ok || marker.PluginID != pluginID || marker.SourceVM != strings.TrimSpace(sourceVM) {
|
||||
return errors.New("temporary VM ownership marker could not be verified")
|
||||
}
|
||||
return nil
|
||||
@@ -647,7 +653,9 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
for _, pluginID := range pluginIDs {
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, key); err == nil {
|
||||
// The source VM is no longer known on this repair path (the marker
|
||||
// was lost), so write an empty source: no fallback, same as before.
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, key, ""); err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -685,6 +693,90 @@ func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) boo
|
||||
return mgr.SavedBoolSetting(pluginID, vmKey, computerUseAccessSetting)
|
||||
}
|
||||
|
||||
// computerUseSourceVM returns the driver-qualified key of the VM a temporary
|
||||
// clone was taken from, or "" when the clone records no usable source. Only
|
||||
// MCP-owned clones carry an ownership marker, so any other VM has no fallback.
|
||||
func (a *App) computerUseSourceVM(vm driver.VMInfo) string {
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
source := strings.TrimSpace(marker.SourceVM)
|
||||
if source == "" || source == vm.Ref().Key() {
|
||||
return ""
|
||||
}
|
||||
normalized, ok := driver.ParseVMRef(source)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return normalized.Key()
|
||||
}
|
||||
|
||||
// computerUseSecretSetting reads one secret for a VM. A temporary clone owns no
|
||||
// vm settings, so a value it does not have falls back to the source VM's copy
|
||||
// while that source still allows MCP access. The fallback reads the single
|
||||
// stored secret instead of copying it, so revoking access to the source also
|
||||
// revokes it for its clones and no secret is left behind when a clone is
|
||||
// disposed. A source that no longer exists resolves to nothing.
|
||||
func (a *App) computerUseSecretSetting(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, key string) (string, error) {
|
||||
value, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), key)
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
if !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
return "", err
|
||||
}
|
||||
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
|
||||
if !ok {
|
||||
return "", err
|
||||
}
|
||||
return mgr.SecretSetting(pluginID, sourceVM.Ref().Key(), key)
|
||||
}
|
||||
|
||||
// computerUseAuthorizedSource resolves a clone's source VM and confirms the
|
||||
// source still grants MCP access. It reports false when the clone has no
|
||||
// recorded source, the source is gone, or access to the source was revoked.
|
||||
func (a *App) computerUseAuthorizedSource(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) (driver.VMInfo, bool) {
|
||||
source := a.computerUseSourceVM(vm)
|
||||
if source == "" || !computerUseVMAccessEnabled(mgr, pluginID, source) {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
ref, ok := driver.ParseVMRef(source)
|
||||
if !ok {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
sourceVM, err := a.resolveVMInfo(ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
return sourceVM, true
|
||||
}
|
||||
|
||||
// computerUseSSHUser resolves the SSH login name for a VM. A temporary clone
|
||||
// has neither its own settings nor a copied .reims-go-ssh-user file, so it
|
||||
// borrows the source's user while the source still allows MCP access.
|
||||
func (a *App) computerUseSSHUser(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
|
||||
if username := a.sshUserForVM(mgr, pluginID, vm); username != "" {
|
||||
return username
|
||||
}
|
||||
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return a.sshUserForVM(mgr, pluginID, sourceVM)
|
||||
}
|
||||
|
||||
func (a *App) sshUserForVM(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
|
||||
username := a.GetVMSSHUser(vm.DriverID, vm.Name)
|
||||
if mgr != nil {
|
||||
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
|
||||
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||
username = strings.TrimSpace(configured)
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(username)
|
||||
}
|
||||
|
||||
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
|
||||
// canonical driverID:name reference returned by the VM list and resource APIs.
|
||||
func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) {
|
||||
@@ -695,18 +787,80 @@ func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) {
|
||||
return a.resolveVMInfo("", ref)
|
||||
}
|
||||
|
||||
// computerUseRegion is a rectangle in source-frame pixels.
|
||||
type computerUseRegion struct {
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
}
|
||||
|
||||
// computerUseRegionFrame cuts region from a full-resolution frame, clipped to
|
||||
// the screen, and shrinks the cut to at most maxWidth pixels wide. It returns
|
||||
// the region that was actually used.
|
||||
func computerUseRegionFrame(full image.Image, region computerUseRegion, maxWidth int) (image.Image, computerUseRegion, error) {
|
||||
area := image.Rect(region.X, region.Y, region.X+region.Width, region.Y+region.Height).Intersect(full.Bounds())
|
||||
if area.Empty() {
|
||||
return nil, computerUseRegion{}, errors.New("region does not intersect the screen")
|
||||
}
|
||||
sub, ok := full.(interface {
|
||||
SubImage(image.Rectangle) image.Image
|
||||
})
|
||||
if !ok {
|
||||
return nil, computerUseRegion{}, errors.New("screen frame cannot be cropped")
|
||||
}
|
||||
applied := computerUseRegion{X: area.Min.X, Y: area.Min.Y, Width: area.Dx(), Height: area.Dy()}
|
||||
return thumb.Scale(sub.SubImage(area), maxWidth), applied, nil
|
||||
}
|
||||
|
||||
// computerUseRegionToSource maps a region given in a refW x refH image of the
|
||||
// screen onto the source frame, widening it outward so no selected pixel is
|
||||
// lost to rounding.
|
||||
func computerUseRegionToSource(region computerUseRegion, refW, refH int, source image.Point) computerUseRegion {
|
||||
if refW <= 0 || refH <= 0 {
|
||||
return region
|
||||
}
|
||||
x0 := region.X * source.X / refW
|
||||
y0 := region.Y * source.Y / refH
|
||||
x1 := ((region.X+region.Width)*source.X + refW - 1) / refW
|
||||
y1 := ((region.Y+region.Height)*source.Y + refH - 1) / refH
|
||||
return computerUseRegion{X: x0, Y: y0, Width: x1 - x0, Height: y1 - y0}
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
var req struct {
|
||||
VM string `json:"vm"`
|
||||
VM string `json:"vm"`
|
||||
Region *computerUseRegion `json:"region"`
|
||||
MaxWidth int `json:"max_width"`
|
||||
// Width and Height name the image the region was measured in; without
|
||||
// them the region is in source pixels.
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
maxWidth := req.MaxWidth
|
||||
if maxWidth == 0 {
|
||||
maxWidth = computerUsePreviewWidth
|
||||
}
|
||||
if maxWidth < 64 || maxWidth > computerUseMaxImageWidth {
|
||||
return nil, fmt.Errorf("max_width must be between 64 and %d", computerUseMaxImageWidth)
|
||||
}
|
||||
if req.Region != nil && (req.Region.Width <= 0 || req.Region.Height <= 0) {
|
||||
return nil, errors.New("region width and height must be positive")
|
||||
}
|
||||
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
path, format, cleanup, err := a.consoleCapture(ctx, route, computerUsePreviewWidth)
|
||||
// A region is cut from the full-resolution frame, so the driver must not
|
||||
// shrink it first.
|
||||
captureEdge := maxWidth
|
||||
if req.Region != nil {
|
||||
captureEdge = 0
|
||||
}
|
||||
path, format, cleanup, err := a.consoleCapture(ctx, route, captureEdge)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -715,26 +869,43 @@ func (a *App) handleComputerUseScreenshot(ctx context.Context, raw json.RawMessa
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A blank frame is a normal screen state during boot, login and display
|
||||
// switches. Return it with a flag so pollers can keep waiting through it.
|
||||
preview, blank, err := thumb.LoadPreviewFrame(path, format, computerUsePreviewWidth)
|
||||
var (
|
||||
frame image.Image
|
||||
blank bool
|
||||
)
|
||||
result := map[string]any{"mime_type": "image/jpeg", "source_width": sourceSize.X, "source_height": sourceSize.Y}
|
||||
if req.Region == nil {
|
||||
// A blank frame is a normal screen state during boot, login and display
|
||||
// switches. Return it with a flag so pollers can keep waiting through it.
|
||||
frame, blank, err = thumb.LoadPreviewFrame(path, format, maxWidth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
full, err := thumb.Load(path, format)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var applied computerUseRegion
|
||||
region := computerUseRegionToSource(*req.Region, req.Width, req.Height, full.Bounds().Size())
|
||||
result["source_width"], result["source_height"] = full.Bounds().Dx(), full.Bounds().Dy()
|
||||
frame, applied, err = computerUseRegionFrame(full, region, maxWidth)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
blank = thumb.Blank(full)
|
||||
result["region"] = applied
|
||||
}
|
||||
encoded, err := thumb.JPEG(frame, 84)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
encoded, err := thumb.JPEG(preview, 84)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
bounds := preview.Bounds()
|
||||
return map[string]any{
|
||||
"mime_type": "image/jpeg",
|
||||
"width": bounds.Dx(),
|
||||
"height": bounds.Dy(),
|
||||
"source_width": sourceSize.X,
|
||||
"source_height": sourceSize.Y,
|
||||
"blank": blank,
|
||||
"data": base64.StdEncoding.EncodeToString(encoded),
|
||||
}, nil
|
||||
bounds := frame.Bounds()
|
||||
result["width"] = bounds.Dx()
|
||||
result["height"] = bounds.Dy()
|
||||
result["blank"] = blank
|
||||
result["data"] = base64.StdEncoding.EncodeToString(encoded)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *App) handleComputerUsePointer(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
@@ -771,6 +942,8 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
|
||||
VM string `json:"vm"`
|
||||
Key string `json:"key"`
|
||||
Modifiers []string `json:"modifiers"`
|
||||
// Down holds (true) or releases (false) one key instead of pressing it.
|
||||
Down *bool `json:"down"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
@@ -778,11 +951,40 @@ func (a *App) handleComputerUseKey(ctx context.Context, raw json.RawMessage, mgr
|
||||
if strings.TrimSpace(req.Key) == "" {
|
||||
return nil, errors.New("key is required")
|
||||
}
|
||||
if req.Down != nil && len(req.Modifiers) > 0 {
|
||||
return nil, errors.New("a held key takes no modifiers; hold each key separately")
|
||||
}
|
||||
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.consoleKey(ctx, route, req.Key, req.Modifiers); err != nil {
|
||||
if req.Down != nil {
|
||||
err = a.consoleKeyState(ctx, route, req.Key, *req.Down)
|
||||
} else {
|
||||
err = a.consoleKey(ctx, route, req.Key, req.Modifiers)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
}
|
||||
|
||||
// handleComputerUseRelease lifts the given keys and pointer buttons in one
|
||||
// report, so a client that stops mid-gesture never leaves input held.
|
||||
func (a *App) handleComputerUseRelease(ctx context.Context, raw json.RawMessage, mgr *plugin.Manager, pluginID string) (any, error) {
|
||||
var req struct {
|
||||
VM string `json:"vm"`
|
||||
Keys []string `json:"keys"`
|
||||
Buttons []string `json:"buttons"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &req); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
_, route, err := a.resolveComputerUseVM(mgr, pluginID, req.VM)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := a.consoleRelease(ctx, route, req.Keys, req.Buttons); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return map[string]any{"ok": true}, nil
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestComputerUseRegionFrameCropsSourcePixels(t *testing.T) {
|
||||
full := image.NewRGBA(image.Rect(0, 0, 400, 300))
|
||||
for y := 100; y < 150; y++ {
|
||||
for x := 200; x < 260; x++ {
|
||||
full.SetRGBA(x, y, color.RGBA{R: 255, A: 255})
|
||||
}
|
||||
}
|
||||
frame, applied, err := computerUseRegionFrame(full, computerUseRegion{X: 200, Y: 100, Width: 60, Height: 50}, 1280)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied != (computerUseRegion{X: 200, Y: 100, Width: 60, Height: 50}) {
|
||||
t.Fatalf("实际区域 = %+v", applied)
|
||||
}
|
||||
b := frame.Bounds()
|
||||
if b.Dx() != 60 || b.Dy() != 50 {
|
||||
t.Fatalf("区域未保持源分辨率:%dx%d", b.Dx(), b.Dy())
|
||||
}
|
||||
if r, _, _, _ := frame.At(b.Min.X, b.Min.Y).RGBA(); r>>8 != 255 {
|
||||
t.Fatal("裁剪结果不是所选区域的像素")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputerUseRegionFrameClipsAndShrinks(t *testing.T) {
|
||||
full := image.NewRGBA(image.Rect(0, 0, 4000, 2000))
|
||||
frame, applied, err := computerUseRegionFrame(full, computerUseRegion{X: 1000, Y: 1500, Width: 3500, Height: 1000}, 1500)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if applied != (computerUseRegion{X: 1000, Y: 1500, Width: 3000, Height: 500}) {
|
||||
t.Fatalf("越界区域未裁到屏幕内:%+v", applied)
|
||||
}
|
||||
if got := frame.Bounds().Dx(); got != 1500 {
|
||||
t.Fatalf("宽区域未缩放到 max_width:%d", got)
|
||||
}
|
||||
if _, _, err := computerUseRegionFrame(full, computerUseRegion{X: 5000, Y: 0, Width: 10, Height: 10}, 1280); err == nil {
|
||||
t.Fatal("屏幕外的区域应报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestComputerUseRegionToSourceScalesFromReferenceImage(t *testing.T) {
|
||||
got := computerUseRegionToSource(computerUseRegion{X: 100, Y: 50, Width: 33, Height: 20}, 1280, 720, image.Pt(2560, 1440))
|
||||
if got != (computerUseRegion{X: 200, Y: 100, Width: 66, Height: 40}) {
|
||||
t.Fatalf("缩放后的区域 = %+v", got)
|
||||
}
|
||||
odd := computerUseRegionToSource(computerUseRegion{X: 1, Y: 1, Width: 1, Height: 1}, 3, 3, image.Pt(4, 4))
|
||||
if odd.X != 1 || odd.Y != 1 || odd.Width < 1 || odd.Height < 1 {
|
||||
t.Fatalf("取整后丢失了所选像素:%+v", odd)
|
||||
}
|
||||
same := computerUseRegion{X: 5, Y: 6, Width: 7, Height: 8}
|
||||
if computerUseRegionToSource(same, 0, 0, image.Pt(100, 100)) != same {
|
||||
t.Fatal("未给出参考尺寸时应按源像素处理")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeReleaseButtons(t *testing.T) {
|
||||
got, err := normalizeReleaseButtons([]string{" Left", "middle"})
|
||||
if err != nil || len(got) != 2 || got[0] != "left" || got[1] != "middle" {
|
||||
t.Fatalf("got %v, %v", got, err)
|
||||
}
|
||||
if _, err := normalizeReleaseButtons([]string{"wheel-up"}); err == nil {
|
||||
t.Fatal("滚轮不是可按住的按键,应被拒绝")
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/console"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
)
|
||||
|
||||
@@ -171,6 +172,70 @@ func (a *App) consolePointer(ctx context.Context, route consoleRoute, req driver
|
||||
return fmt.Errorf("unsupported pointer action %q", req.Action)
|
||||
}
|
||||
|
||||
// consoleKeyState holds or releases one key. Only the host's QMP console can
|
||||
// hold a key; a driver console exposes presses alone.
|
||||
func (a *App) consoleKeyState(ctx context.Context, route consoleRoute, key string, down bool) error {
|
||||
if route.kind == consoleRouteDriver {
|
||||
return fmt.Errorf("computer_use_unsupported: driver %q cannot hold a key", route.vm.DriverID)
|
||||
}
|
||||
code, err := console.NormalizeHeldKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
service, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return service.SendKey(ctx, route.vm.Directory, code, down)
|
||||
}
|
||||
|
||||
// consoleRelease lifts held keys and pointer buttons on the VM's console.
|
||||
func (a *App) consoleRelease(ctx context.Context, route consoleRoute, keys, buttons []string) error {
|
||||
buttons, err := normalizeReleaseButtons(buttons)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if route.kind == consoleRouteDriver {
|
||||
// A driver console cannot hold keys, so only its buttons need lifting.
|
||||
up := false
|
||||
for _, button := range buttons {
|
||||
if err := route.console.ConsolePointer(ctx, route.vm.Name, driver.ConsolePointerRequest{Action: "button", Button: button, Down: &up}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
codes := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
code, err := console.NormalizeHeldKey(key)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
codes = append(codes, code)
|
||||
}
|
||||
if len(codes)+len(buttons) == 0 {
|
||||
return nil
|
||||
}
|
||||
service, err := a.computerUseService()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return service.ReleaseInputs(ctx, route.vm.Directory, codes, buttons)
|
||||
}
|
||||
|
||||
func normalizeReleaseButtons(buttons []string) ([]string, error) {
|
||||
out := make([]string, 0, len(buttons))
|
||||
for _, button := range buttons {
|
||||
switch name := strings.ToLower(strings.TrimSpace(button)); name {
|
||||
case "left", "right", "middle":
|
||||
out = append(out, name)
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported pointer button %q", button)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// consoleKey presses one key on the VM's console.
|
||||
func (a *App) consoleKey(ctx context.Context, route consoleRoute, key string, modifiers []string) error {
|
||||
if route.kind == consoleRouteDriver {
|
||||
|
||||
@@ -44,6 +44,15 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !active.Manifest.HasCapability("win32-native-aio") {
|
||||
loc := i18n.EffectiveLocale(cfgCopy.Locale)
|
||||
if dcache := strings.TrimSpace(opts.DiskCache); dcache != "" && !strings.EqualFold(dcache, "default") {
|
||||
return errors.New(i18n.T(loc, "validate.disk_cache_requires_runtime"))
|
||||
}
|
||||
if reims.IsWindowsRawDevicePath(opts.Disk) {
|
||||
return errors.New(i18n.T(loc, "validate.raw_disk_requires_runtime"))
|
||||
}
|
||||
}
|
||||
c := reims.NewClient(&cfgCopy, *active)
|
||||
|
||||
// Always defer starting to StartVM so commit-memory checks, Win10 cold-reboot
|
||||
@@ -186,7 +195,7 @@ func (a *App) createVMFlow(opts reims.CreateOpts) (err error) {
|
||||
finishTask(err)
|
||||
return fmt.Errorf("record VM driver ownership: %w", err)
|
||||
}
|
||||
if postSet, ok := reims.PostCreateSetOpts(opts); ok {
|
||||
if postSet, ok := reims.PostCreateSetOptsWithCapture(opts, c.AllowsSetCapture()); ok {
|
||||
var parts []string
|
||||
if postSet.DiskController != "" {
|
||||
parts = append(parts, "disk="+strings.ToUpper(postSet.DiskController))
|
||||
|
||||
@@ -35,13 +35,13 @@ func TestDataRootSwitchCarriesASLRAndCleansSource(t *testing.T) {
|
||||
if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F9"}); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.SetSyncHostMemorySMBIOS(true)
|
||||
return a.SetMinimizeToTray(false)
|
||||
})
|
||||
if err != nil || calls != 1 {
|
||||
t.Fatalf("switch: calls=%d err=%v", calls, err)
|
||||
}
|
||||
stored, err := config.LoadExisting(filepath.Join(target, "reims-go.json"))
|
||||
if err != nil || !stored.QEMUASLR || !stored.SyncHostMemorySMBIOS || a.cfg.DataRoot != target {
|
||||
if err != nil || !stored.QEMUASLR || stored.MinimizeToTray == nil || *stored.MinimizeToTray || a.cfg.DataRoot != target {
|
||||
t.Fatalf("new config: %+v, %v", stored, err)
|
||||
}
|
||||
if !stored.FullscreenHotkeyEnabled || stored.FullscreenHotkey != "F9" {
|
||||
|
||||
@@ -17,6 +17,9 @@ import (
|
||||
func (a *App) openDataRoot() dataroot.Status {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.DataRoot
|
||||
explicitLaunch := a.launch.DataRoot != ""
|
||||
prevRoot := a.launchPrevDataRoot
|
||||
a.launchPrevDataRoot = ""
|
||||
a.mu.Unlock()
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
@@ -24,6 +27,9 @@ func (a *App) openDataRoot() dataroot.Status {
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() && explicitLaunch {
|
||||
a.relocateRegisteredVMs(dir, prevRoot)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,19 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
rt "github.com/Nwflower/reims-go/internal/runtime"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -88,3 +94,127 @@ func TestReadOnlyFolderRefusesWrites(t *testing.T) {
|
||||
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
|
||||
}
|
||||
}
|
||||
|
||||
// The copied test executable acts as reims-ctl when called with set --help.
|
||||
func init() {
|
||||
marker := os.Getenv("REIMS_TEST_READ_ONLY_CAPTURE_MARKER")
|
||||
if marker == "" || len(os.Args) != 3 || os.Args[1] != "set" || os.Args[2] != "--help" {
|
||||
return
|
||||
}
|
||||
if err := os.WriteFile(marker, nil, 0o600); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
fmt.Println(" --capture <BOOL>")
|
||||
os.Exit(0)
|
||||
}
|
||||
|
||||
func TestReadOnlyFolderSkipsCaptureProbe(t *testing.T) {
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = t.TempDir()
|
||||
cfg.ActiveRuntime = "test-rt"
|
||||
installDummyRuntime(t, cfg.DataRoot)
|
||||
if err := os.WriteFile(filepath.Join(cfg.DataRoot, datamigrate.StampFile), []byte(`{"data_version": 999}`), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
active, err := rt.ResolveActive(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exe, err := os.Executable()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
binary, err := os.ReadFile(exe)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(active.ReimsCtlPath(), binary, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
marker := filepath.Join(t.TempDir(), "capture-probed")
|
||||
t.Setenv("REIMS_TEST_READ_ONLY_CAPTURE_MARKER", marker)
|
||||
output, err := exec.CommandContext(t.Context(), active.ReimsCtlPath(), "set", "--help").CombinedOutput()
|
||||
if err != nil || !strings.Contains(string(output), "--capture") {
|
||||
t.Fatalf("test runtime help = %q, err = %v", output, err)
|
||||
}
|
||||
if err := os.Remove(marker); err != nil {
|
||||
t.Fatalf("clear test runtime's probe marker: %v", err)
|
||||
}
|
||||
|
||||
a := &App{cfg: cfg, root: dataroot.Open(cfg.DataRoot, version.Version)}
|
||||
state := a.GetState()
|
||||
if !state.DataRoot.ReadOnly || state.ActiveRuntime == nil || state.RuntimeCaptureSupported {
|
||||
t.Errorf("GetState: read-only = %t, active runtime = %v, capture supported = %t", state.DataRoot.ReadOnly, state.ActiveRuntime, state.RuntimeCaptureSupported)
|
||||
}
|
||||
off := false
|
||||
opts := reims.CreateOpts{Name: "test", Capture: &off}
|
||||
preview, err := a.PreviewCreate(opts)
|
||||
if err != nil || strings.Contains(preview, "--capture") {
|
||||
t.Errorf("read-only PreviewCreate = %q, err = %v", preview, err)
|
||||
}
|
||||
for _, path := range []string{cfg.TempDir(), marker} {
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Errorf("stat %q = %v, want not exist", path, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
base := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(base, "location.json"))
|
||||
|
||||
oldRoot := filepath.Join(base, "old-root")
|
||||
newRoot := filepath.Join(base, "new-root")
|
||||
if err := (&config.Config{DataRoot: oldRoot}).EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Simulate moving the entire data folder from oldRoot to newRoot:
|
||||
// reims-go.json and vms.toml inside newRoot still reference oldRoot.
|
||||
if err := (&config.Config{DataRoot: newRoot}).EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldCfg := config.Default()
|
||||
oldCfg.DataRoot = oldRoot
|
||||
if err := config.Save(filepath.Join(newRoot, "reims-go.json"), oldCfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("disk = \"disk.qcow2\"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldVMDir := filepath.Join((&config.Config{DataRoot: oldRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(regDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
|
||||
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: oldRoot, Locale: "zh-CN"},
|
||||
root: dataroot.Open(oldRoot, version.Version),
|
||||
}
|
||||
noopASLR := func(context.Context, string, string) error { return nil }
|
||||
if err := a.setDataRoot(newRoot, noopASLR); err != nil {
|
||||
t.Fatalf("setDataRoot: %v", err)
|
||||
}
|
||||
|
||||
vms, err := reims.ListRegisteredVMs(newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 1 {
|
||||
t.Fatalf("got %d vms, want 1", len(vms))
|
||||
}
|
||||
if !strings.EqualFold(filepath.Clean(vms[0].Directory), filepath.Clean(newVMDir)) {
|
||||
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, newVMDir)
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ func TestGuestToolsBridgeFollowsPluginSwitch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClipboardFileSettingsInheritAndOverrideGlobalDefaults(t *testing.T) {
|
||||
func TestClipboardSettingsApplyGloballyFromPluginConfig(t *testing.T) {
|
||||
srv := guesttools.NewTransportServer(nil)
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = t.TempDir()
|
||||
@@ -106,33 +106,51 @@ func TestClipboardFileSettingsInheritAndOverrideGlobalDefaults(t *testing.T) {
|
||||
t.Fatal("clipboard plugin did not activate")
|
||||
}
|
||||
|
||||
info, ok := mgr.Registry().Info(builtin.IDClipboard)
|
||||
if !ok || info.Settings == nil {
|
||||
t.Fatal("clipboard plugin missing settings schema")
|
||||
}
|
||||
if info.Settings.Scope != "app" {
|
||||
t.Fatalf("clipboard schema scope = %q, want app", info.Settings.Scope)
|
||||
}
|
||||
for key, prop := range info.Settings.Properties {
|
||||
if prop.Scope != "app" {
|
||||
t.Fatalf("clipboard setting %q scope = %q, want app", key, prop.Scope)
|
||||
}
|
||||
}
|
||||
|
||||
vm := driver.NewVMRef("", "mac").Key()
|
||||
peer := driver.NewVMRef("", "peer").Key()
|
||||
set := func(vmKey string, vals map[string]any) {
|
||||
t.Helper()
|
||||
if err := a.SetPluginSettings(builtin.IDClipboard, vmKey, vals); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
set(vm, map[string]any{"sync_images": false, "direction": "host-to-guest"})
|
||||
set("", map[string]any{"sync_files": false, "max_file_mb": 64})
|
||||
policy := srv.EffectiveClipboardPolicy(vm)
|
||||
if !policy.Enabled || policy.SyncFiles || policy.MaxFileBytes != 64<<20 ||
|
||||
policy.SyncImages || policy.Direction != guesttools.ClipboardHostToGuest {
|
||||
t.Fatalf("global file defaults or existing VM policies lost: %+v", policy)
|
||||
}
|
||||
settings := a.GetVMPluginSettings(vm)[builtin.IDClipboard]
|
||||
if settings["sync_files"] != false || settings["max_file_mb"] != 64 {
|
||||
t.Fatalf("VM settings should display inherited values, got %v", settings)
|
||||
|
||||
// Stale per-VM entries saved before moving clipboard settings to plugin scope
|
||||
// must not override the plugin-level configuration.
|
||||
set(vm, map[string]any{"enabled": false, "direction": "guest-to-host", "max_file_mb": 256})
|
||||
set("", map[string]any{
|
||||
"enabled": true,
|
||||
"direction": "host-to-guest",
|
||||
"sync_images": false,
|
||||
"max_image_mb": 8,
|
||||
"sync_files": false,
|
||||
"max_file_mb": 64,
|
||||
})
|
||||
for _, target := range []string{vm, peer} {
|
||||
policy := srv.EffectiveClipboardPolicy(target)
|
||||
if !policy.Enabled || policy.Direction != guesttools.ClipboardHostToGuest ||
|
||||
policy.SyncImages || policy.MaxImageBytes != 8<<20 ||
|
||||
policy.SyncFiles || policy.MaxFileBytes != 64<<20 {
|
||||
t.Fatalf("VM %q policy did not match plugin config: %+v", target, policy)
|
||||
}
|
||||
}
|
||||
|
||||
set(vm, map[string]any{"max_file_mb": 256})
|
||||
set("", map[string]any{"sync_files": true, "max_file_mb": 32})
|
||||
policy = srv.EffectiveClipboardPolicy(vm)
|
||||
if !policy.SyncFiles || policy.MaxFileBytes != 256<<20 {
|
||||
t.Fatalf("VM must inherit the new toggle and retain its own limit, got %+v", policy)
|
||||
}
|
||||
if peer := srv.EffectiveClipboardPolicy(driver.NewVMRef("", "peer").Key()); !peer.SyncFiles || peer.MaxFileBytes != 32<<20 {
|
||||
t.Fatalf("unconfigured VM should use global defaults, got %+v", peer)
|
||||
set("", map[string]any{"enabled": false, "sync_files": true, "max_file_mb": 32})
|
||||
if policy := srv.EffectiveClipboardPolicy(vm); policy.Enabled || !policy.SyncFiles || policy.MaxFileBytes != 32<<20 {
|
||||
t.Fatalf("updated plugin config did not apply immediately: %+v", policy)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -51,6 +51,17 @@ func (a *App) client() (*reims.Client, error) {
|
||||
return reims.NewClient(&cfg, *active), nil
|
||||
}
|
||||
|
||||
func (a *App) relocateRegisteredVMs(dataRoot, previousDataRoot string) {
|
||||
updated, err := reims.RelocateRegisteredVMs(dataRoot, previousDataRoot)
|
||||
if err != nil {
|
||||
a.emitLog("app", "Relocate VM registry paths failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
if updated > 0 {
|
||||
a.emitLog("app", fmt.Sprintf("Updated %d VM registry path(s) for data folder %s", updated, dataRoot))
|
||||
}
|
||||
}
|
||||
|
||||
func enrichMacOSVMListStates(vms []driver.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
|
||||
@@ -63,7 +63,16 @@ func (a *App) ValidateCreate(opts reims.CreateOpts) []reims.ValidationIssue {
|
||||
}
|
||||
|
||||
func (a *App) PreviewCreate(opts reims.CreateOpts) (string, error) {
|
||||
return reims.PreviewCreateCommand(opts)
|
||||
if !a.dataRootUsable() {
|
||||
return reims.PreviewCreateCommandWithCapture(opts, false)
|
||||
}
|
||||
cfg := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
return reims.PreviewCreateCommandWithCapture(opts, err == nil && runtimeAllowsCapture(*active))
|
||||
}
|
||||
|
||||
func runtimeAllowsCapture(active rt.Installed) bool {
|
||||
return reims.ReimsCTLAllowsSetCapture(active.ReimsCtlPath(), nil)
|
||||
}
|
||||
|
||||
func (a *App) CreateVM(opts reims.CreateOpts) error {
|
||||
@@ -137,6 +146,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
if strings.TrimSpace(opts.DiskCache) != "" {
|
||||
cfg := a.runtimeConfig()
|
||||
active, err := rt.ResolveActive(&cfg)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s", i18n.T(cfg.Locale, "err.runtime_not_installed"))
|
||||
}
|
||||
if !active.Manifest.HasCapability("win32-native-aio") {
|
||||
return errors.New(i18n.T(i18n.EffectiveLocale(loc), "validate.disk_cache_requires_runtime"))
|
||||
}
|
||||
}
|
||||
c, err := a.client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -189,6 +208,16 @@ func (a *App) ApplyVMSettings(opts reims.SetOpts) (err error) {
|
||||
if opts.Displays > 0 && opts.Displays != cur.Displays {
|
||||
diffs = append(diffs, PendingChange{Field: "displays", From: fmt.Sprintf("%d", cur.Displays), To: fmt.Sprintf("%d", opts.Displays)})
|
||||
}
|
||||
if dc := strings.ToLower(strings.TrimSpace(opts.DiskController)); dc != "" && !strings.EqualFold(dc, cur.DiskController) {
|
||||
diffs = append(diffs, PendingChange{Field: "disk_controller", From: cur.DiskController, To: dc})
|
||||
}
|
||||
if dcache := strings.ToLower(strings.TrimSpace(opts.DiskCache)); dcache != "" && !strings.EqualFold(dcache, cur.DiskCache) {
|
||||
from := cur.DiskCache
|
||||
if from == "" {
|
||||
from = "default"
|
||||
}
|
||||
diffs = append(diffs, PendingChange{Field: "disk_cache", From: from, To: dcache})
|
||||
}
|
||||
if opts.Borderless != nil && *opts.Borderless != cur.Borderless {
|
||||
diffs = append(diffs, PendingChange{Field: "borderless", From: fmt.Sprintf("%v", cur.Borderless), To: fmt.Sprintf("%v", *opts.Borderless)})
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"errors"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/control"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
)
|
||||
|
||||
func (a *App) startPluginControlServer() {
|
||||
@@ -16,15 +17,26 @@ func (a *App) startPluginControlServer() {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
server, err := control.Listen(func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
|
||||
currentManager := func() *plugin.Manager {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
defer a.mu.Unlock()
|
||||
return a.pluginMgr
|
||||
}
|
||||
server, err := control.ListenWithOptions(control.PipeName(), func(ctx context.Context, pluginID, channel string, message json.RawMessage) (json.RawMessage, error) {
|
||||
mgr := currentManager()
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is not ready")
|
||||
}
|
||||
return mgr.ChannelMessage(ctx, pluginID, channel, message)
|
||||
})
|
||||
return mgr.ChannelMessage(ctx, pluginID, channel, control.SessionFrom(ctx), message)
|
||||
}, control.Options{OnSessionEnd: func(session string, targets []control.Target) {
|
||||
mgr := currentManager()
|
||||
if mgr == nil {
|
||||
return
|
||||
}
|
||||
for _, target := range targets {
|
||||
mgr.ChannelSessionClosed(target.PluginID, target.Channel, session)
|
||||
}
|
||||
}})
|
||||
if err != nil {
|
||||
a.emitLog("plugin", "Could not open local plugin control channel: "+err.Error())
|
||||
return
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -124,6 +123,7 @@ func (a *App) initPlugins() {
|
||||
})
|
||||
mgr.Broker().SetVMExitHandler(func(string, string) { a.wakePoll() })
|
||||
|
||||
mgr.Broker().SetLogger(a.emitLog)
|
||||
mgr.Broker().SetNotifier(func(pluginID, title, body string) {
|
||||
a.emitLog("plugin:"+pluginID, title+": "+body)
|
||||
})
|
||||
@@ -500,14 +500,6 @@ func (a *App) syncClipboardPolicies() {
|
||||
}
|
||||
globalVals := mgr.GetSettings(builtin.IDClipboard, "", false)
|
||||
gt.SetGlobalClipboardPolicy(clipboardPolicyFromMap(globalVals))
|
||||
for vmKey := range mgr.SavedVMSettingsForPlugin(builtin.IDClipboard) {
|
||||
ref, ok := driver.ParseVMRef(vmKey)
|
||||
if !ok {
|
||||
ref = driver.NewVMRef("", vmKey)
|
||||
}
|
||||
pol := clipboardPolicyFromMap(mgr.GetSettings(builtin.IDClipboard, vmKey, false))
|
||||
gt.SetVMClipboardPolicy(ref.Key(), &pol)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) onPluginSettingsChanged(pluginID, vmName string) {
|
||||
@@ -927,43 +919,6 @@ func (a *App) CreateVMWithDriver(req driver.CreateRequest) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) ReadPluginLog(pluginID string) (string, error) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
if mgr == nil {
|
||||
return "", nil
|
||||
}
|
||||
if pluginID == "" || strings.ContainsAny(pluginID, `/\`) || strings.Contains(pluginID, "..") {
|
||||
return "", errors.New("invalid plugin id")
|
||||
}
|
||||
if _, ok := mgr.Registry().Info(pluginID); !ok {
|
||||
return "", fmt.Errorf("plugin %q not found", pluginID)
|
||||
}
|
||||
logsDir := filepath.Clean(mgr.Layout().LogsDir())
|
||||
logPath := filepath.Clean(mgr.Layout().LogPath(pluginID))
|
||||
if !strings.HasPrefix(strings.ToLower(logPath), strings.ToLower(logsDir+string(os.PathSeparator))) {
|
||||
return "", errors.New("invalid plugin log path")
|
||||
}
|
||||
f, err := os.Open(logPath)
|
||||
if err != nil {
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return "", nil
|
||||
}
|
||||
return "", err
|
||||
}
|
||||
defer f.Close()
|
||||
const maxLogReadBytes = 2 << 20
|
||||
if st, statErr := f.Stat(); statErr == nil && st.Size() > maxLogReadBytes {
|
||||
_, _ = f.Seek(st.Size()-maxLogReadBytes, io.SeekStart)
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(f, maxLogReadBytes))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return host.RedactText(string(raw)), nil
|
||||
}
|
||||
|
||||
// InspectPluginArchive runs the unified static security scanner on a local .zip
|
||||
// package before installing it so the UI can display hard blockers, capabilities,
|
||||
// and L3 native execution notices.
|
||||
@@ -1051,7 +1006,7 @@ func (a *App) PeekPluginMarket(query, kind string) plugin.MarketBrowseResult {
|
||||
if mgr != nil {
|
||||
installed = mgr.Registry().List()
|
||||
}
|
||||
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind})
|
||||
return a.getPluginMarket().Peek(installed, plugin.MarketBrowseOptions{Query: query, Kind: kind, IncludeAlpha: true})
|
||||
}
|
||||
|
||||
// SuggestLanguagePack looks up the market once for a language pack matching
|
||||
@@ -1102,6 +1057,16 @@ type MarketInstallProgress struct {
|
||||
// InstallMarketPlugin downloads, verifies SHA-256, static-scans, and installs
|
||||
// a plugin from the market index.
|
||||
func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.PluginInfo, error) {
|
||||
return a.installMarketPlugin(pluginID, "", includeAlpha)
|
||||
}
|
||||
|
||||
// InstallMarketPluginVersion downloads, verifies SHA-256, static-scans, and
|
||||
// installs a specific version of a plugin from the market index.
|
||||
func (a *App) InstallMarketPluginVersion(pluginID, ver string) (*plugin.PluginInfo, error) {
|
||||
return a.installMarketPlugin(pluginID, ver, true)
|
||||
}
|
||||
|
||||
func (a *App) installMarketPlugin(pluginID, ver string, includeAlpha bool) (*plugin.PluginInfo, error) {
|
||||
a.mu.Lock()
|
||||
mgr := a.pluginMgr
|
||||
a.mu.Unlock()
|
||||
@@ -1117,6 +1082,7 @@ func (a *App) InstallMarketPlugin(pluginID string, includeAlpha bool) (*plugin.P
|
||||
a.emit("reims:plugin-install", p)
|
||||
}
|
||||
info, err := a.getPluginMarket().InstallFromMarket(context.Background(), mgr, pluginID, plugin.MarketInstallOptions{
|
||||
Version: ver,
|
||||
IncludeAlpha: includeAlpha,
|
||||
OnPhase: func(ph string) {
|
||||
progMu.Lock()
|
||||
|
||||
@@ -33,39 +33,43 @@ func (a *App) includeAlpha() bool {
|
||||
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
|
||||
}
|
||||
|
||||
// remoteCache keeps the release list for a while: GitHub allows 60
|
||||
// remoteCache keeps the release list per channel for a while: GitHub allows 60
|
||||
// unauthenticated API requests an hour, and the host page, first launch and
|
||||
// the CLI all ask for it.
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
alpha bool
|
||||
list []rt.Remote
|
||||
type remoteCacheEntry struct {
|
||||
at time.Time
|
||||
list []rt.Remote
|
||||
}
|
||||
|
||||
const remoteCacheTTL = 10 * time.Minute
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
entries map[bool]remoteCacheEntry
|
||||
}
|
||||
|
||||
const updateCacheTTL = 5 * time.Minute
|
||||
|
||||
// ListRemoteRuntimes lists published runtimes for the configured channel.
|
||||
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
|
||||
alpha := a.includeAlpha()
|
||||
remoteCache.Lock()
|
||||
defer remoteCache.Unlock()
|
||||
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
|
||||
return remoteCache.list, nil
|
||||
if entry, ok := remoteCache.entries[alpha]; ok && entry.list != nil && time.Since(entry.at) < updateCacheTTL {
|
||||
list := entry.list
|
||||
remoteCache.Unlock()
|
||||
return list, nil
|
||||
}
|
||||
remoteCache.Unlock()
|
||||
|
||||
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
|
||||
func forgetRemoteRuntimes() {
|
||||
remoteCache.Lock()
|
||||
remoteCache.list = nil
|
||||
if remoteCache.entries == nil {
|
||||
remoteCache.entries = make(map[bool]remoteCacheEntry)
|
||||
}
|
||||
remoteCache.entries[alpha] = remoteCacheEntry{at: time.Now(), list: list}
|
||||
remoteCache.Unlock()
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// SetRuntimeChannel picks "stable" or "alpha" for online installs
|
||||
@@ -77,11 +81,7 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
default:
|
||||
return fmt.Errorf("unknown channel %q", channel)
|
||||
}
|
||||
if err := a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel }); err != nil {
|
||||
return err
|
||||
}
|
||||
forgetRemoteRuntimes()
|
||||
return nil
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel })
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
@@ -179,11 +179,14 @@ func percent(done, total int64) float64 {
|
||||
return float64(done) * 100 / float64(total)
|
||||
}
|
||||
|
||||
type appUpdateCacheEntry struct {
|
||||
at time.Time
|
||||
info version.UpdateInfo
|
||||
}
|
||||
|
||||
var appUpdateCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
channel string
|
||||
info *version.UpdateInfo
|
||||
entries map[string]appUpdateCacheEntry
|
||||
}
|
||||
|
||||
// SetAppUpdateChannel picks "stable", "alpha", or "dev" for Reims-Go client
|
||||
@@ -199,10 +202,6 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
if err := a.setPreference(func(cfg *config.Config) { cfg.AppUpdateChannel = channel }); err != nil {
|
||||
return err
|
||||
}
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.info = nil
|
||||
appUpdateCache.channel = ""
|
||||
appUpdateCache.Unlock()
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = "", "", ""
|
||||
appUpdateReady.Unlock()
|
||||
@@ -210,7 +209,8 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
}
|
||||
|
||||
// CheckAppUpdate checks GitHub Releases for a newer Reims-Go version on the
|
||||
// configured app update channel. Results are cached for 10 minutes unless force is true.
|
||||
// configured app update channel. Results are cached per channel for 5 minutes
|
||||
// unless force is true.
|
||||
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
a.mu.Lock()
|
||||
ch := version.ChannelStable
|
||||
@@ -219,19 +219,26 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
appUpdateCache.Lock()
|
||||
defer appUpdateCache.Unlock()
|
||||
if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL {
|
||||
return *appUpdateCache.info, nil
|
||||
if !force {
|
||||
appUpdateCache.Lock()
|
||||
if entry, ok := appUpdateCache.entries[ch]; ok && time.Since(entry.at) < updateCacheTTL {
|
||||
info := entry.info
|
||||
appUpdateCache.Unlock()
|
||||
return info, nil
|
||||
}
|
||||
appUpdateCache.Unlock()
|
||||
}
|
||||
|
||||
info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version, ch)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
copyInfo := info
|
||||
appUpdateCache.at = time.Now()
|
||||
appUpdateCache.channel = ch
|
||||
appUpdateCache.info = ©Info
|
||||
appUpdateCache.Lock()
|
||||
if appUpdateCache.entries == nil {
|
||||
appUpdateCache.entries = make(map[string]appUpdateCacheEntry)
|
||||
}
|
||||
appUpdateCache.entries[ch] = appUpdateCacheEntry{at: time.Now(), info: info}
|
||||
appUpdateCache.Unlock()
|
||||
return info, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -66,14 +66,14 @@ func TestRuntimeConfigFollowsExternalSelection(t *testing.T) {
|
||||
if got.ActiveRuntime != "backup" || !got.QEMUASLR {
|
||||
t.Fatalf("desktop reads stale selection: %+v", got)
|
||||
}
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
|
||||
if err := a.SetMinimizeToTray(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
|
||||
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || saved.MinimizeToTray == nil || *saved.MinimizeToTray {
|
||||
t.Fatalf("saving an unrelated setting lost the selection: %+v", saved)
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func TestPreferencesDoNotOverwriteDamagedConfig(t *testing.T) {
|
||||
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err == nil {
|
||||
if err := a.SetQEMUASLR(true); err == nil {
|
||||
t.Fatal("saved preferences over an unreadable selection")
|
||||
}
|
||||
if data, err := os.ReadFile(path); err != nil || string(data) != "{" {
|
||||
@@ -100,7 +100,7 @@ func TestConfigWaitDoesNotBlockApp(t *testing.T) {
|
||||
}{
|
||||
{"ASLR", func(a *App) error { return a.SetQEMUASLR(true) }},
|
||||
{"runtime", func(a *App) error { return a.UseRuntime("backup") }},
|
||||
{"preference", func(a *App) error { return a.SetSyncHostMemorySMBIOS(true) }},
|
||||
{"preference", func(a *App) error { return a.SetMinimizeToTray(false) }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := &config.Config{DataRoot: t.TempDir()}
|
||||
@@ -129,7 +129,7 @@ func TestConfigWaitDoesNotBlockApp(t *testing.T) {
|
||||
if err := <-done; err == nil || !available {
|
||||
t.Fatalf("global lock available = %v, save error = %v", available, err)
|
||||
}
|
||||
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || a.cfg.SyncHostMemorySMBIOS {
|
||||
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || (a.cfg.MinimizeToTray != nil && !*a.cfg.MinimizeToTray) {
|
||||
t.Fatalf("failed save published %+v", a.cfg)
|
||||
}
|
||||
})
|
||||
@@ -158,7 +158,7 @@ func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
|
||||
})
|
||||
}()
|
||||
synctest.Wait()
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
|
||||
if err := a.SetMinimizeToTray(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close(resume)
|
||||
@@ -166,10 +166,10 @@ func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
|
||||
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || saved.MinimizeToTray == nil || *saved.MinimizeToTray {
|
||||
t.Fatalf("concurrent updates lost: %+v, %v", saved, err)
|
||||
}
|
||||
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || !a.cfg.SyncHostMemorySMBIOS {
|
||||
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || a.cfg.MinimizeToTray == nil || *a.cfg.MinimizeToTray {
|
||||
t.Fatalf("in-memory settings diverged: %+v", a.cfg)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -120,12 +120,17 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
_, existingCfgErr := os.Stat(cfgPath)
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
recordedOldRoot := ""
|
||||
if existingCfgErr == nil {
|
||||
recordedOldRoot = cfg.DataRoot
|
||||
}
|
||||
cfg.DataRoot = dir
|
||||
if _, statErr := os.Stat(cfgPath); statErr != nil {
|
||||
if existingCfgErr != nil {
|
||||
cfg.Locale = locale // a new folder keeps the language picked on this screen
|
||||
}
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
@@ -149,6 +154,9 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() {
|
||||
a.relocateRegisteredVMs(dir, recordedOldRoot)
|
||||
}
|
||||
// Nothing touching the data folder ran before setup (startup), so plugins
|
||||
// start now whichever folder was chosen.
|
||||
a.resetDataRootCaches()
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func TestAppUpdateCache_PerChannelFiveMinuteTTL(t *testing.T) {
|
||||
if updateCacheTTL != 5*time.Minute {
|
||||
t.Fatalf("updateCacheTTL = %v, want 5m", updateCacheTTL)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: dir, AppUpdateChannel: version.ChannelStable},
|
||||
root: dataroot.Status{Dir: dir},
|
||||
}
|
||||
|
||||
appUpdateCache.Lock()
|
||||
orig := appUpdateCache.entries
|
||||
appUpdateCache.entries = map[string]appUpdateCacheEntry{
|
||||
version.ChannelStable: {
|
||||
at: time.Now(),
|
||||
info: version.UpdateInfo{Channel: version.ChannelStable, Current: "v0.2.13", Latest: "v0.2.13", HasUpdate: false},
|
||||
},
|
||||
version.ChannelAlpha: {
|
||||
at: time.Now(),
|
||||
info: version.UpdateInfo{Channel: version.ChannelAlpha, Current: "v0.2.13", Latest: "v0.2.14-alpha.1", HasUpdate: true},
|
||||
},
|
||||
}
|
||||
appUpdateCache.Unlock()
|
||||
t.Cleanup(func() {
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.entries = orig
|
||||
appUpdateCache.Unlock()
|
||||
})
|
||||
|
||||
// Stable channel returns cached result immediately.
|
||||
got, err := a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(stable): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelStable || got.HasUpdate {
|
||||
t.Fatalf("stable got = %+v, want cached no-update", got)
|
||||
}
|
||||
|
||||
// Switching to alpha must preserve per-channel cache and return cached alpha result.
|
||||
if err := a.SetAppUpdateChannel(version.ChannelAlpha); err != nil {
|
||||
t.Fatalf("SetAppUpdateChannel(alpha): %v", err)
|
||||
}
|
||||
got, err = a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(alpha): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelAlpha || !got.HasUpdate || got.Latest != "v0.2.14-alpha.1" {
|
||||
t.Fatalf("alpha got = %+v, want cached alpha update", got)
|
||||
}
|
||||
|
||||
// Switching back to stable still hits the stable cache.
|
||||
if err := a.SetAppUpdateChannel(version.ChannelStable); err != nil {
|
||||
t.Fatalf("SetAppUpdateChannel(stable): %v", err)
|
||||
}
|
||||
got, err = a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(stable again): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelStable || got.HasUpdate {
|
||||
t.Fatalf("stable again got = %+v, want cached no-update", got)
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"image"
|
||||
"image/draw"
|
||||
"maps"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
@@ -20,6 +21,7 @@ import (
|
||||
)
|
||||
|
||||
var ErrNoWindow = errors.New("no foreground guest window reported")
|
||||
var errFrameUnconfirmed = errors.New("window geometry not confirmed after capture")
|
||||
|
||||
const (
|
||||
windowMaxAge = time.Second
|
||||
@@ -43,7 +45,7 @@ type Console interface {
|
||||
type SessionOptions struct {
|
||||
VMDir string
|
||||
TmpDir string
|
||||
Window func(time.Duration) (guesttools.ActiveWindow, bool)
|
||||
Window func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)
|
||||
Console Console
|
||||
PrepareClipboard func(context.Context) (func(), error)
|
||||
OnClipboardError func(error)
|
||||
@@ -140,6 +142,21 @@ func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
|
||||
_ = os.Remove(dir)
|
||||
}
|
||||
first, err := s.capture(ctx)
|
||||
if errors.Is(err, errFrameUnconfirmed) {
|
||||
retry, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
for errors.Is(err, errFrameUnconfirmed) {
|
||||
select {
|
||||
case <-retry.Done():
|
||||
err = ErrNoWindow
|
||||
case <-time.After(125 * time.Millisecond):
|
||||
first, err = s.capture(retry)
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
|
||||
err = ErrNoWindow
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
cleanup()
|
||||
return nil, err
|
||||
@@ -150,13 +167,13 @@ func Prepare(ctx context.Context, opts SessionOptions) (func() error, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, bool)) (guesttools.ActiveWindow, error) {
|
||||
func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.ActiveWindow, time.Time, bool)) (guesttools.ActiveWindow, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
tick := time.NewTicker(150 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if report, ok := get(windowMaxAge); ok {
|
||||
if report, _, ok := get(windowMaxAge); ok {
|
||||
return report, nil
|
||||
}
|
||||
select {
|
||||
@@ -171,14 +188,15 @@ func waitForWindow(ctx context.Context, get func(time.Duration) (guesttools.Acti
|
||||
}
|
||||
|
||||
func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
|
||||
before, ok := s.Window(windowMaxAge)
|
||||
before, _, ok := s.Window(windowMaxAge)
|
||||
if !ok || before.ID != s.id {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, frameTimeout)
|
||||
defer cancel()
|
||||
request, cancel := context.WithTimeout(ctx, frameTimeout)
|
||||
defer os.Remove(s.path)
|
||||
format, err := s.Console.ScreendumpDisplay(ctx, s.VMDir, s.path, "gfx", 0)
|
||||
format, err := s.Console.ScreendumpDisplay(request, s.VMDir, s.path, "gfx", 0)
|
||||
capturedAt := time.Now()
|
||||
cancel()
|
||||
if err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
@@ -193,14 +211,13 @@ func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
|
||||
if crop.Empty() {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
if err := s.confirmFrame(ctx, before, capturedAt); err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
frame, err := thumb.Load(s.path, format)
|
||||
if err != nil {
|
||||
return ViewerFrame{}, err
|
||||
}
|
||||
after, ok := s.Window(windowMaxAge)
|
||||
if !ok || before != after {
|
||||
return ViewerFrame{}, ErrNoWindow
|
||||
}
|
||||
img := image.NewRGBA(crop.Sub(crop.Min))
|
||||
draw.Draw(img, img.Bounds(), frame, crop.Min, draw.Src)
|
||||
s.mu.Lock()
|
||||
@@ -211,7 +228,49 @@ func (s *session) capture(ctx context.Context) (ViewerFrame, error) {
|
||||
s.mapping = mapping
|
||||
}
|
||||
s.lastFrame = time.Now()
|
||||
return ViewerFrame{Image: img, Tag: s.tag}, nil
|
||||
return ViewerFrame{Image: img, Tag: s.tag, shape: guestViewerShape(before, size, crop)}, nil
|
||||
}
|
||||
|
||||
func (s *session) confirmFrame(ctx context.Context, before guesttools.ActiveWindow, capturedAt time.Time) error {
|
||||
// Reading the same cached report twice cannot detect a window moving between polls.
|
||||
timeout := time.NewTimer(windowMaxAge)
|
||||
defer timeout.Stop()
|
||||
tick := time.NewTicker(15 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
window, receivedAt, ok := s.Window(windowMaxAge)
|
||||
if !ok || window != before {
|
||||
return errFrameUnconfirmed
|
||||
}
|
||||
if receivedAt.After(capturedAt) {
|
||||
return ctx.Err()
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timeout.C:
|
||||
return errFrameUnconfirmed
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func guestViewerShape(window guesttools.ActiveWindow, size image.Point, crop image.Rectangle) viewerShape {
|
||||
scale := func(x, y int) image.Point {
|
||||
return image.Pt(
|
||||
int(math.Round(float64(x*size.X)/float64(window.DisplayWidth))),
|
||||
int(math.Round(float64(y*size.Y)/float64(window.DisplayHeight))),
|
||||
)
|
||||
}
|
||||
point := func(x, y int) image.Point {
|
||||
return scale(window.X+x, window.Y+y).Sub(crop.Min)
|
||||
}
|
||||
return viewerShape{
|
||||
outline: image.Rectangle{Min: point(0, 0), Max: point(window.Width, window.Height)},
|
||||
// Keep the traffic lights and the outer toolbar areas available to macOS.
|
||||
caption: image.Rectangle{Min: point(80, 0), Max: point(window.Width-64, 22)},
|
||||
radius: scale(16, 16),
|
||||
}
|
||||
}
|
||||
|
||||
func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle {
|
||||
@@ -231,7 +290,7 @@ func guestCrop(window guesttools.ActiveWindow, size image.Point) image.Rectangle
|
||||
}
|
||||
|
||||
func (s *session) eventMapping(event ViewerEvent) (frameMapping, bool) {
|
||||
window, ok := s.Window(windowMaxAge)
|
||||
window, _, ok := s.Window(windowMaxAge)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.mapping, ok && event.FrameTag == s.tag && window == s.mapping.window &&
|
||||
@@ -263,7 +322,7 @@ func (s *session) run(ctx context.Context, title string, first ViewerFrame) erro
|
||||
Initial: first,
|
||||
Frame: func(ctx context.Context) (ViewerFrame, error) {
|
||||
frame, err := s.capture(ctx)
|
||||
if err == nil {
|
||||
if err == nil || errors.Is(err, errFrameUnconfirmed) {
|
||||
firstCaptureError = time.Time{}
|
||||
} else if firstCaptureError.IsZero() {
|
||||
firstCaptureError = time.Now()
|
||||
@@ -319,7 +378,7 @@ func (s *session) forwardInput(ctx context.Context, queue *inputQueue) (result e
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-checkWindow.C:
|
||||
if window, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
|
||||
if window, _, ok := s.Window(windowMaxAge); ok && window.ID == s.id {
|
||||
missingSince = time.Time{}
|
||||
} else if missingSince.IsZero() {
|
||||
missingSince = time.Now()
|
||||
|
||||
@@ -13,6 +13,18 @@ import (
|
||||
|
||||
type captureConsole struct{ Console }
|
||||
|
||||
func TestGuestViewerShapeKeepsOffscreenCornersOutsideCapture(t *testing.T) {
|
||||
window := guesttools.ActiveWindow{
|
||||
X: -35, Y: -18, Width: 300, Height: 180, DisplayWidth: 800, DisplayHeight: 600,
|
||||
}
|
||||
size := image.Pt(1600, 1200)
|
||||
shape := guestViewerShape(window, size, guestCrop(window, size))
|
||||
if shape.outline != image.Rect(-70, -36, 530, 324) ||
|
||||
shape.caption != image.Rect(90, -36, 402, 8) || shape.radius != image.Pt(32, 32) {
|
||||
t.Fatalf("unexpected shape: %+v", shape)
|
||||
}
|
||||
}
|
||||
|
||||
type pasteConsole struct {
|
||||
Console
|
||||
sent chan string
|
||||
@@ -41,7 +53,7 @@ func TestPasteWaitsForClipboardAndCancelsOnBlur(t *testing.T) {
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Console: console,
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return window, true },
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) { return window, time.Now(), true },
|
||||
PrepareClipboard: func(ctx context.Context) (func(), error) {
|
||||
close(entered)
|
||||
select {
|
||||
@@ -140,7 +152,7 @@ func TestCaptureTracksDisplayedGeometry(t *testing.T) {
|
||||
}
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, bool) { return current, true },
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) { return current, time.Now(), true },
|
||||
Console: captureConsole{},
|
||||
},
|
||||
path: filepath.Join(t.TempDir(), "test.ppm"), id: 1,
|
||||
@@ -172,3 +184,29 @@ func TestCaptureTracksDisplayedGeometry(t *testing.T) {
|
||||
t.Fatalf("capture after guest changed windows = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCaptureDiscardsFrameWhenDelayedReportShowsMovement(t *testing.T) {
|
||||
window := guesttools.ActiveWindow{
|
||||
ID: 1, AppName: "TextEdit", Width: 4, Height: 2, DisplayWidth: 4, DisplayHeight: 3,
|
||||
}
|
||||
oldReport := time.Now().Add(-time.Second)
|
||||
moved := window
|
||||
moved.X++
|
||||
samples := 0
|
||||
s := &session{
|
||||
SessionOptions: SessionOptions{
|
||||
Window: func(time.Duration) (guesttools.ActiveWindow, time.Time, bool) {
|
||||
samples++
|
||||
if samples <= 2 {
|
||||
return window, oldReport, true
|
||||
}
|
||||
return moved, time.Now(), true
|
||||
},
|
||||
Console: captureConsole{},
|
||||
},
|
||||
path: filepath.Join(t.TempDir(), "test.ppm"), id: 1,
|
||||
}
|
||||
if frame, err := s.capture(context.Background()); err != errFrameUnconfirmed || frame.Image != nil || s.tag != 0 {
|
||||
t.Fatalf("capture published a stale crop: frame=%+v, tag=%d, error=%v", frame, s.tag, err)
|
||||
}
|
||||
}
|
||||
Loaded 100 of 206 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user