Unlucky Launcher v0.0.1-alpha
CI / fmt (rustfmt --check) (push) Canceled after 0s
CI / clippy (ubuntu-latest) (push) Canceled after 0s
CI / clippy (windows-latest) (push) Canceled after 0s
CI / test (ubuntu-latest) (push) Canceled after 0s
CI / test (windows-latest) (push) Canceled after 0s
CI / build release (ubuntu-latest) (push) Canceled after 0s
CI / build release (windows-latest) (push) Canceled after 0s
Guards / core 零 UI 守门 (push) Canceled after 0s
Guards / 文件行数 ≤400 守门 (push) Canceled after 0s
Guards / 依赖许可与来源(cargo-deny) (push) Canceled after 0s

Rust 原生单文件 Minecraft 启动器:CLI 完整可用(install/launch/accounts/java/diagnose/agent),
MCP server 接入外部 Agent 工具,GUI 开发中。
This commit is contained in:
AskaEth committed 2026-10-31 21:54:10 +08:00
commit bc41dfcf7d
517 files changed
+92844

No files matched your search

+34
View File
@@ -0,0 +1,34 @@
# 换行策略:仓库内一律 LF(rustfmt 设 newline_style = "Unix",CI 在 Linux 上跑 fmt --check)。
# eol=lf 对工作区同样生效 —— Windows 克隆也不会被转换成 CRLF,避免「本地 fmt 过、CI fmt 挂」。
* text=auto eol=lf
# 明确为文本(显式列出,防止被误判成二进制)
*.rs text eol=lf
*.toml text eol=lf
*.md text eol=lf
*.slint text eol=lf
*.yml text eol=lf
*.yaml text eol=lf
*.json text eol=lf
Cargo.lock text eol=lf
# 二进制:不做换行转换、不做文本 diff
*.png binary
*.ico binary
*.icns binary
*.jpg binary
*.jpeg binary
*.gif binary
*.webp binary
*.ttf binary
*.otf binary
*.woff binary
*.woff2 binary
*.zip binary
*.7z binary
*.gz binary
*.tar binary
*.exe binary
*.dll binary
*.lib binary
*.pdb binary
+92
View File
@@ -0,0 +1,92 @@
name: CI
# 主干门禁:fmt / clippy / test / build 双平台矩阵。
# 架构守门(core 零 UI、文件 ≤400 行、依赖许可)见 guards.yml。
# 平台基线 Win10+(标准工具链产物),平台矩阵见 AGENTS.md §7。
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
RUST_BACKTRACE: 1
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true
jobs:
fmt:
name: fmt (rustfmt --check)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
components: rustfmt
- run: cargo fmt --all --check
clippy:
name: clippy (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Linux 图形栈构建依赖(winit / femtovg 编译期需要)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libfontconfig1-dev libgl1-mesa-dev libegl1-mesa-dev \
libwayland-dev libxcb1-dev
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy
- uses: Swatinem/rust-cache@v2
- run: cargo clippy --workspace --all-targets -- -D warnings
test:
name: test (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Linux 图形栈构建依赖
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libfontconfig1-dev libgl1-mesa-dev libegl1-mesa-dev \
libwayland-dev libxcb1-dev
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo test --workspace --all-targets
build:
name: build release (${{ matrix.os }})
strategy:
fail-fast: false
matrix:
os: [windows-latest, ubuntu-latest]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- name: Linux 图形栈构建依赖
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libfontconfig1-dev libgl1-mesa-dev libegl1-mesa-dev \
libwayland-dev libxcb1-dev
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- run: cargo build --workspace --release
+81
View File
@@ -0,0 +1,81 @@
name: Guards
# 架构与合规守门(与 fmt/clippy 同级,不允许 continue-on-error):
# 1. core-no-ui —— crates/core 零 UI 依赖(D3 铁律),依赖表 + cargo tree 双查
# 2. file-size —— 全仓代码/文档单文件 ≤400 行(用户硬约束)
# 3. licenses —— cargo-deny:许可证白名单 + GPL 依赖拦截 + 供应链来源校验
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
jobs:
core-no-ui:
name: core 零 UI 守门
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
- name: 依赖表直查(crates/core/Cargo.toml 不得出现 UI 框架)
run: |
set -uo pipefail
forbidden='slint|egui|eframe|iced|winit|gtk|javafx|tauri|fltk|druid|relm'
# 只看非注释行:manifest 里说明「不许出现 slint」的注释本身不该触发守门
if grep -vE '^[[:space:]]*#' crates/core/Cargo.toml | grep -nEi "$forbidden"; then
echo "::error file=crates/core/Cargo.toml::core 不得依赖 UI 框架(见 AGENTS.md 硬约束)"
exit 1
fi
echo "OK: crates/core/Cargo.toml 无 UI 依赖"
- name: 依赖树泄漏检查(cargo tree -p unlucky-core,排除自身行)
run: |
set -uo pipefail
forbidden='slint|egui|eframe|iced|winit|gtk|javafx|tauri|fltk|druid|relm'
tree=$(cargo tree -p unlucky-core --edges normal --prefix none)
echo "$tree"
if echo "$tree" | grep -vE '^unlucky-core v' | grep -qiE "$forbidden"; then
echo "::error::core 的依赖树出现 UI 框架 —— 传递依赖也不允许"
exit 1
fi
echo "OK: unlucky-core 依赖树零 UI"
file-size:
name: 文件行数 ≤400 守门
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: 检查单文件行数
run: |
set -uo pipefail
LIMIT=400
failed=0
while IFS= read -r f; do
case "$f" in
LICENSE|*/LICENSE|LICENSE-*|*/LICENSE-*) continue ;;
CHANGELOG*|*/CHANGELOG*) continue ;;
esac
n=$(wc -l < "$f")
if [ "$n" -gt "$LIMIT" ]; then
echo "::error file=$f::$f 有 $n 行,超过 $LIMIT 行上限,请按模块拆分"
failed=$((failed + 1))
fi
done < <(git ls-files '*.rs' '*.md' '*.slint' '*.yml' '*.yaml' '*.toml' '*.json')
if [ "$failed" -ne 0 ]; then
echo "共 $failed 个文件超限"
exit 1
fi
echo "OK: 全部受检文件 ≤$LIMIT 行"
licenses:
name: 依赖许可与来源(cargo-deny)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: EmbarkStudios/cargo-deny-action@v2
with:
# 只跑许可/禁用/来源三类,advisories 由后续安全轮次单独接管
command: check licenses bans sources
+24
View File
@@ -0,0 +1,24 @@
# Reference source repositories (local-only, git-ignored)
/HMCL/
/PCL/
# Local development docs
/DevDocs/
# Agent workspace (local-only)
/.tower/
# Build outputs
build/
dist/
out/
target/
# IDE
.idea/
.vscode/
*.iml
# OS
Thumbs.db
.DS_Store
+5
View File
@@ -0,0 +1,5 @@
edition = "2021"
max_width = 100
newline_style = "Unix"
use_field_init_shorthand = true
use_try_shorthand = true
Generated
+7413
View File
File diff suppressed because it is too large. Load diff
+88
View File
@@ -0,0 +1,88 @@
[workspace]
resolver = "2"
members = ["crates/core", "crates/agent", "crates/app", "crates/cli"]
[workspace.package]
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
authors = ["AskaEth <i@yeij.top>"]
repository = "https://github.com/AskaEth/Unlucky-Launcher"
rust-version = "1.92"
publish = false
[workspace.dependencies]
# 共享依赖(版本在此集中,各 crate 用 `xxx.workspace = true` 引用)
# M15(core::diagnose)首批使用者:规则正则 / 规则 YAML 解析 / 诊断结果序列化。
regex = "1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
# serde_yaml 上游已停维护(RUSTSEC-2024-0320),改用维护中的 API 兼容分支(tower 定案)
serde_yaml_ng = "0.10"
# M13(core::download):HTTP + 异步运行时 + 流 + 校验哈希。
# rustls(ring)而非 native-tls —— 免 OpenSSL/系统证书栈依赖,MinGW 与 Win7 都省事。
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "stream"] }
tokio = { version = "1", features = [
"rt-multi-thread",
"fs",
"io-util",
"time",
"sync",
"net",
"macros",
] }
futures-util = "0.3"
sha1 = "0.10"
sha2 = "0.10"
# M31(core::auth):离线账户 UUID 必须与 Minecraft 服务端/HMCL 的
# `UUID.nameUUIDFromBytes` 逐字节一致 = MD5 + v3 位改写,因此需要 MD5。
# 与 sha1/sha2 同属 RustCrypto(Apache-2.0 OR MIT),版本对齐 digest 0.10。
md-5 = "0.10"
# M29(core::launch::natives):读 natives jar(zip 容器)解压原生库。
# 只开 inflate(`deflate-flate2-zlib-rs`,纯 Rust zlib)——解压方向不需要 zopfli 压缩器。
zip = { version = "9", default-features = false, features = ["deflate-flate2-zlib-rs"] }
# M33(core::game::java):Temurin 的 Linux/macOS 产物只发 `.tar.gz`(Windows 是 `.zip`,
# 复用上面的 zip)。flate2/tar 都是纯 Rust + MIT OR Apache-2.0,白名单内。
flate2 = "1"
tar = "0.4"
# UI 层唯一入口(D2:Slint,RF 2.0 轨道)。
# 默认特性已含 backend-default + renderer-femtovg(GL)+ renderer-software(CPU 软渲染兜底,
# Win7 老机无可用 GPU 时的降级路径,见 DevDocs/PlanDoc/01c-native-gui-options.md §6)。
slint = "1.18"
# app 的 build script 用(把 ui/main.slint 编译成 Rust 代码),版本必须与 slint 主 crate 同步。
slint-build = "1.18"
# agent 层依赖(rig / rmcp)按 D4 在 M16 引入,脚手架期不引入以免版本冲突。
# 版本锁定策略见 DevDocs/PlanDoc/02-ai-agent-design.md §0:rig 锁 =0.45.x,rmcp 3.8.x。
#
# M39 的 MCP server(02 §0「传输定论」):rmcp 官方 SDK(Apache-2.0),**锁精确版本**——
# pre-1.0 且 ~6 天一个版、3.x 内已多次改 server API。只开需要的传输 feature:
# - `server`(default 带)+ `transport-io`(stdio,给 llama.cpp 内置 MCP client)
# - `transport-streamable-http-server`(主力:127.0.0.1 上的 Streamable HTTP)
# `macros` 一并留在 default 里(`#[tool]` 宏不用,但 default 拆开易漏 base64 等隐式依赖)。
rmcp = { version = "=3.8.0", features = [
"transport-io",
"transport-streamable-http-server",
] }
# rmcp 的 Streamable HTTP server 是个 tower Service,官方示例用 axum 挂监听(MIT)。
# 只吃 `nest_service` + `serve`,不引入任何 TLS/模板/DB 生态。
axum = "0.8"
[workspace.lints.rust]
unsafe_code = "deny"
missing_docs = "warn"
rust_2018_idioms = { level = "warn", priority = -1 }
[workspace.lints.clippy]
all = { level = "deny", priority = -1 }
[profile.release]
opt-level = "z"
lto = "thin"
codegen-units = 1
panic = "abort"
strip = "symbols"
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2026 AskaEth (YeiJ)
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+30
View File
@@ -0,0 +1,30 @@
Unlucky-Launcher (ULL)
Copyright 2026 AskaEth (YeiJ)
本产品采用 Apache License 2.0(见 LICENSE)。
--------------------------------------------------------------------------
第三方组件声明
--------------------------------------------------------------------------
1. Slint(https://slint.dev)
本产品的 GUI 层使用 Slint。Slint 以 Royalty-Free 2.0 许可(LicenseRef-Slint-Royalty-free-2.0)
使用,未修改 Slint 本体源码。
Slint Royalty-Free 2.0 的唯一义务:应用「关于」页显示官方 AboutSlint 部件,
或在公开下载页放置「Made with Slint」徽章。本项目的落地位置见 crates/app 的关于页(P2 排期)
与 GitHub Release 说明页;在此之前由本文件的声明承担告知义务。
Slint 的其余许可分支(GPL-3.0-only / Slint Software License 3.0)本项目不适用。
2. Rust crates 生态
cargo-deny 白名单见 deny.toml:Apache-2.0 / MIT / BSD-2-Clause / BSD-3-Clause / Zlib / BSL-1.0 / ISC /
CC0-1.0 / MIT-0 / Unlicense / Unicode-3.0 / CDLA-Permissive-2.0 / Apache-2.0 WITH LLVM-exception。
GPL 系(含 AGPL、LGPL 静态链接、SSPL)依赖不得进入主干。
3. 参考实现致谢
本项目设计参考自 HMCL(https://github.com/HMCL-dev/HMCL)与 PCL2
(https://github.com/Meloong-Git/PCL),两者均为 GPL-3.0,特此致谢。
+122
View File
@@ -0,0 +1,122 @@
# Unlucky Launcher (ULL)
**English** · [简体中文](README.zh-CN.md)
Unlucky Launcher (ULL) is a free, open-source Minecraft: Java Edition launcher written in Rust
(Apache-2.0, non-commercial), with a Slint + Metro UI. It embeds an AI agent client (chat /
configuration / crash diagnosis) and integrates with the broader agent tooling ecosystem via MCP.
Minimum baseline: Windows 10.
- Runtime: a single native Rust binary — no JVM, no WebView, no external runtime
- UI: Slint (Royalty-Free 2.0; GL preferred, CPU software-rendering fallback so older machines
without a usable GPU still get the full UI)
- License: Apache-2.0 © AskaEth (YeiJ)
## Compliance statement
Authentication uses only official Microsoft/Mojang endpoints — Microsoft OAuth 2.0 device code
flow, Xbox Live, XSTS, and api.minecraftservices.com — so players sign in with their own Microsoft
account and launch the game they already own. Account tokens are stored only on the user's local
machine and are never sent to any server operated by the project. ULL does not distribute, mirror,
proxy or modify any Minecraft game files. Online play always requires a Microsoft account with
valid entitlements. Local offline profiles never contact Microsoft or Mojang services and cannot
join online-mode servers. Not affiliated with Mojang or Microsoft.
## Status
The core engine is complete (workspace: 983+ tests passing):
- **Microsoft sign-in**: OAuth 2.0 device code flow → Xbox Live → XSTS → Minecraft Services, with
entitlement verification
- **Account credentials are stored only on the local machine** — never uploaded, and inaccessible
to the AI features
- Mod loaders: Forge / NeoForge / Fabric / Quilt, verified on real machines
- Java management: Temurin / Oracle / Microsoft / Zulu with a regional fallback chain
- Multi-source download engine; YAML rule-based crash diagnosis
- Usable as an MCP server for external agent tooling (`ull agent serve`)
- Local offline profiles: for local / isolated-network testing only; they perform no Microsoft
authentication and cannot join servers with online-mode enabled
**CLI (`ull`) is fully usable**: `install / launch / accounts / java / diagnose / agent`.
**GUI in development**: `crates/app` is currently a Slint + Metro skeleton; the theme system and
the full interface ship with subsequent versions — use the CLI until then.
## Module map
```
Unlucky-Launcher (cargo workspace)
├── crates/core # domain library, zero UI dependencies, eight modules
├── crates/agent # AI agent: ToolSpec registry + built-in client + MCP server (one shared core)
├── crates/app # Slint UI: the only crate allowed to depend on a UI framework
├── crates/cli # CLI (bin `ull`): headless, zero UI, depends on core + agent
└── packaging # single-file artifact matrix and packaging assets (planned)
```
The eight modules of `crates/core`:
| Module | Responsibility |
|--------|----------------|
| `setting` | three data-directory modes, schema-based config, atomic writes, migrations |
| `download` | multi-source health scoring, mirrors, chunked downloads, hash-while-downloading |
| `game` | version / instance repository, snapshots and inheritance resolution |
| `launch` | 10-stage launch pipeline, processes, JSONL event stream |
| `auth` | Microsoft sign-in / local offline profiles |
| `addon` | mod loader installation, modpacks, CurseForge / Modrinth |
| `diagnose` | five signal collectors, YAML rule engine, hs_err parsing |
| `platform` | OS abstraction: paths, processes, file locks, capability probing, runtime OS detection |
## Building
Prerequisites:
- Rust stable (`rust-toolchain.toml` selects the toolchain automatically; components `rustfmt` /
`clippy`)
- Windows: MSVC toolchain (used by CI) or MinGW-w64 (`x86_64-pc-windows-gnu`)
- Linux: `libxkbcommon-dev libfontconfig1-dev libgl1-mesa-dev libegl1-mesa-dev libwayland-dev libxcb1-dev`
(Slint winit backend + femtovg build dependencies)
```bash
cargo fmt --all --check # formatting
cargo clippy --workspace --all-targets -- -D warnings # lints (zero-warning gate)
cargo test --workspace # tests
cargo build --release # artifact: target/release/unlucky-launcher[.exe]
```
Software-rendering switch (machines without a usable GPU / with broken drivers):
`unlucky-launcher --software-renderer` (equivalent to `SLINT_BACKEND=winit-software`).
Dependency license check (optional locally, required in CI):
`cargo deny check licenses bans sources`.
## CI gates
| Workflow | Content |
|----------|---------|
| `.github/workflows/ci.yml` | fmt + clippy + test + build, Windows / Linux matrix |
| `.github/workflows/guards.yml` | zero-UI guard for core, 400-line-per-file guard, cargo-deny license guard |
## Platform baseline
Minimum baseline: **Windows 10**. Windows 8.1 / 8 / 7 are not supported:
- Windows 10/11 builds use the **standard toolchain** (MSVC / GNU) — no custom target specs, no
`-Zbuild-std`, no import-table allowlists
- Other platforms: macOS 12+ first class; Linux x64 with X11 preferred, Wayland as the long-term
direction; Android Termux experimental, not committed
- UI fallback: Slint software rendering (fully usable on machines without a GPU or with broken
drivers)
- Platform independence is expressed through **separate test matrices**, not separate artifact
pipelines; capability differences use feature gates with runtime probing
## License and acknowledgements
- This project: Apache License 2.0, see [LICENSE](LICENSE); third-party notices in [NOTICE](NOTICE)
- The GUI uses [Slint](https://slint.dev) (Royalty-Free 2.0 track). Per the RF 2.0 obligations an
`AboutSlint` widget will be placed on the about page (P2); until then NOTICE and this section
serve the attribution duty.
Thanks to [HMCL](https://github.com/HMCL-dev/HMCL) and
[PCL2](https://github.com/Meloong-Git/PCL) (both GPL-3.0) — these two launchers have accompanied
the vast majority of Minecraft players for many years. ULL learned a great deal about design and
implementation from them, and this project is dedicated to those two pioneers.
+97
View File
@@ -0,0 +1,97 @@
# Unlucky Launcher (ULL)
[English](README.md) · **简体中文**
Rust 原生单文件 Minecraft 启动器:**Slint + Metro 视觉**,内置 **AI Agent 客户端**(对话 / 改配置 / 崩溃诊断),
融合主流 Agent 工具(**MCP**),**最低基线 Win10+**。
- 运行时:纯 Rust 原生二进制——无 JVM、无 WebView、无外部运行时
- UI:Slint(Royalty-Free 2.0;GL 优先,CPU 软渲染兜底,无可用 GPU 的老机也有完整 UI)
- 许可:Apache-2.0 © AskaEth (YeiJ)
## 当前状态
**核心引擎已完成**(workspace 983+ 测试全绿):
- **正版登录**:Microsoft OAuth 2.0 device code flow → Xbox Live → XSTS → Minecraft Services,校验游戏拥有状态
- **账户凭据仅保存在本机**,不上传任何服务器,AI 功能无法访问
- 加载器:Forge / NeoForge / Fabric / Quilt 四家真机验证
- Java 管理:Temurin / Oracle / Microsoft / Zulu 四发行版回退链
- 多源下载引擎、崩溃诊断规则引擎
- 可作为 MCP server 接入外部 Agent 工具(`ull agent serve`)
- 本地离线档案:仅用于本地/隔离网络环境的测试,不经过 Microsoft 账户认证,无法连接启用正版验证的服务器
**CLI(`ull`)完整可用**:`install / launch / accounts / java / diagnose / agent` 等全量命令。
**图形界面(GUI)开发中**:`crates/app` 当前为 Slint + Metro 风格骨架,主题系统与完整界面
随后续版本交付——在此之前请使用 CLI。
## 模块地图
```
Unlucky-Launcher (cargo workspace)
├── crates/core # 领域库:零 UI 依赖,八模块
├── crates/agent # AI Agent:ToolSpec 注册表 + 内置客户端 + MCP server(双形态共用一个内核)
├── crates/app # Slint UI:唯一允许依赖 UI 框架的 crate
├── crates/cli # CLI(bin `ull`):headless,零 UI,只依赖 core + agent
└── packaging # 单文件产物矩阵与打包资源(规划中)
```
`crates/core` 的八个模块:
| 模块 | 职责 |
|------|------|
| `setting` | 三模式数据目录、schema 配置、原子写、迁移 |
| `download` | 多源健康度、镜像、分块下载、边下边算 |
| `game` | 版本/实例仓库、快照与继承解析 |
| `launch` | 10 阶段启动管线、进程、JSONL 事件流 |
| `auth` | Microsoft 正版登录 / 本地离线档案 |
| `addon` | 加载器安装、整合包、CurseForge / Modrinth |
| `diagnose` | 五类信号采集、YAML 规则引擎、hs_err 解析 |
| `platform` | OS 抽象:路径、进程、文件锁、能力探测、运行期 OS 检测 |
## 构建
前置:
- Rust stable(`rust-toolchain.toml` 会自动选择工具链;组件 `rustfmt` / `clippy`)
- Windows:MSVC 工具链(CI 用)或 MinGW-w64(`x86_64-pc-windows-gnu`)
- Linux:`libxkbcommon-dev libfontconfig1-dev libgl1-mesa-dev libegl1-mesa-dev libwayland-dev libxcb1-dev`
(Slint winit 后端 + femtovg 编译依赖)
```bash
cargo fmt --all --check # 格式
cargo clippy --workspace --all-targets -- -D warnings # 静态检查(零 warning 门禁)
cargo test --workspace # 测试
cargo build --release # 产物:target/release/unlucky-launcher[.exe]
```
软渲染开关(无可用 GPU / 烂驱动的老机):`unlucky-launcher --software-renderer`
(等价于 `SLINT_BACKEND=winit-software`)。
依赖许可检查(本地可选,CI 必跑):`cargo deny check licenses bans sources`。
## CI 门禁
| Workflow | 内容 |
|----------|------|
| `.github/workflows/ci.yml` | fmt + clippy + test + build,Windows / Linux 矩阵 |
| `.github/workflows/guards.yml` | core 零 UI 守门、单文件 ≤400 行守门、cargo-deny 许可守门 |
## 平台基线
最低基线 **Windows 10**。Windows 8.1 / 8 / 7 不在支持范围内:
- Windows 10/11 走**标准工具链**产物(MSVC / GNU),无自定义 target spec、无 `-Zbuild-std`、无导入表白名单
- 其他平台:macOS 12+ 一等;Linux x64 X11 优先、Wayland 为**大方向**;Android Termux 试验级不承诺
- UI 兜底:Slint 软渲染(无 GPU / 烂驱动的老机可完整使用)
- 平台独立性体现在**独立测试矩阵**,而非独立产物链;能力差异用 feature gate + 运行期探测表达
## 许可证与致谢
- 本项目:Apache License 2.0,见 [LICENSE](LICENSE);第三方声明见 [NOTICE](NOTICE)
- GUI 使用 [Slint](https://slint.dev)(Royalty-Free 2.0 轨道)。按 RF 2.0 义务,关于页将放置
`AboutSlint` 部件(P2),在此之前由 NOTICE 与本节承担告知义务
感谢 [HMCL](https://github.com/HMCL-dev/HMCL) 和 [PCL2](https://github.com/Meloong-Git/PCL)(均 GPL-3.0)这两个启动器陪伴了绝大多数 MC 玩家好多年。
ULL 的设计与实现从它们身上学到了太多,谨以此项目向两位前辈致敬。
+7
View File
@@ -0,0 +1,7 @@
# 与 Cargo.toml 的 rust-version 同步;改 MSRV 时两处一起改。
msrv = "1.92"
# core 的模块边界很薄,参数多于 8 个基本说明该拆结构体了。
too-many-arguments-threshold = 8
# 领域类型(版本号、哈希、URL)普遍是短名,不做最小名长惩罚。
min-ident-chars-threshold = 2
+44
View File
@@ -0,0 +1,44 @@
[package]
name = "unlucky-agent"
description = "Unlucky-Launcher AI Agent:工具注册表 + 内置客户端 + MCP server(双形态共用一个内核)"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
rust-version.workspace = true
publish.workspace = true
# 依赖方向:agent 依赖 core 的公共 API,core 不知道 agent 的存在(AGENTS.md §2)。
# 端口层(src/port*.rs)让 agent 能在没有 core 实现时独立编译与测试;装配层用 core 实现
# 填充 `Ports`(GUI 侧是 `crates/app`,headless 侧是 `crates/cli` 的 `ull agent serve`)。
[dependencies]
unlucky-core = { path = "../core", version = "0.1" }
# 序列化:工具 JSON Schema 是手写 serde_json::Value(不引 schemars),
# 工具结果 / 审计记录 / 事件流都用 serde derive。
serde.workspace = true
serde_json.workspace = true
# LLM Provider + agent 循环。**锁精确版本**:rig 12 周 5 个 minor、CHANGELOG 满是 breaking
# (DevDocs/PlanDoc/02-ai-agent-design.md §0 + research/02 §7 R1)。升级必须单独提交并跑回放回归。
# 依赖面收口:整个 crate 只有 src/brain/rig.rs 允许 `use rig_*`。
# feature `reqwest`:rig-core 0.45 的 default 只有 derive + rustls,HTTP 客户端要显式开;TLS 走 rustls
# (免 OpenSSL,对 Win7/MinGW 友好,见 research/02 §7 R3)。
rig-core = { version = "=0.45.0", features = ["reqwest"] }
# TODO(M16-P1): 目前**声明但未使用**——对话循环/工具编排是自研的(要在中间插确认与审计)。
# 保留是为了把版本按 02 §0 钉死;P1 接 rig 的 agent 运行时(工具服务句柄 / rig-cassette 回放 /
# rig-rmcp 让内置 agent 吃 MCP)时再真正消费。若 P1 决定彻底不用,删这一行即可。
rig-agent = "=0.45.0"
# 异步运行时(rig 的 HTTP/流式需要)与流工具(消费 rig 的 Stream)。
tokio.workspace = true
futures-util.workspace = true
# MCP server(M39):rmcp 3.8 投影 + stdio / Streamable HTTP 传输。
# 依赖面收口纪律与 rig 相同——整个 crate 只有 src/mcp/ 允许 `use rmcp::`。
rmcp.workspace = true
axum.workspace = true
[lints]
workspace = true
+283
View File
@@ -0,0 +1,283 @@
//! 审计日志:**每一次工具调用**都留痕(02 文档 §3.1 末条 / mission M16 任务 4)。
//!
//! 落盘位置由装配处给(`<data_root>/agent/audit/audit-<日期>.jsonl`,按天分文件,
//! 见 `PlanDoc/04-data-and-config.md` §2)。一行一条 JSON,只追加不修改。
//!
//! 三条纪律:
//! 1. **参数先脱敏再落盘**([`crate::redact::redact_args`])——`set_config` 能改 AI 端点,
//! 参数里会有 api_key;
//! 2. 写失败**不打断**工具执行(审计是旁路),但要把失败打到 stderr 留痕;
//! 3. YOLO 与「是否经确认」分别记录(`yolo=true, confirmed=false` 与
//! `yolo=false, confirmed=true` 是两件事,事故复盘的差别就在这)。
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::clock::{date_of_unix_ms, format_unix_ms, SharedClock};
use crate::redact::redact_args;
/// 一次工具调用的结局(审计用)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AuditOutcome {
/// 成功返回。
Ok,
/// 工具返回错误(含端口失败、未找到会话等)。
ToolError,
/// 参数没过 schema 校验(模型给错了参数)。
InvalidArgs,
/// 用户/策略拒绝。
Denied,
/// 只发出了确认请求,尚未执行(编排层在把请求交给闸门之前先记一条,
/// 这样「AI 想改 X 但被拒」和「用户点了允许」在审计里是两条独立的证据)。
AwaitingConfirmation,
/// 模型调了不存在的工具。
UnknownTool,
}
/// 一条审计记录。
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AuditRecord {
/// RFC3339 UTC。
pub ts: String,
/// 会话 id(agent 对话框的会话,不是游戏会话)。
pub agent_session_id: String,
/// 工具名。
pub tool: String,
/// 参数(已脱敏)。
pub args: Value,
/// 结局。
pub outcome: AuditOutcome,
/// 一句话结果摘要。
pub summary: String,
/// 是否运行在 YOLO 模式。
pub yolo: bool,
/// 是否经过用户确认(YOLO 下为 false——自动放行不是"确认")。
pub confirmed: bool,
/// 工具执行耗时(毫秒)。
pub duration_ms: u64,
}
/// 审计出口。
pub trait AuditSink: Send + Sync {
/// 记录一条(实现方不应阻塞工具执行链;失败自行吞掉并留痕)。
fn record(&self, record: &AuditRecord);
}
/// 按天滚动的 JSONL 审计(生产实现)。
pub struct JsonlAudit {
dir: PathBuf,
clock: SharedClock,
guard: Mutex<()>,
}
impl JsonlAudit {
/// `dir` 通常是 `<data_root>/agent/audit`;目录按需创建。
#[must_use]
pub fn new(dir: impl Into<PathBuf>, clock: SharedClock) -> Self {
Self {
dir: dir.into(),
clock,
guard: Mutex::new(()),
}
}
/// 给定时刻对应的文件路径(测试与 UI「查看审计」共用)。
#[must_use]
pub fn path_for(&self, unix_ms: u64) -> PathBuf {
self.dir
.join(format!("audit-{}.jsonl", date_of_unix_ms(unix_ms)))
}
/// 追加一行;失败返回 `std::io::Error`(由 [`AuditSink::record`] 吞掉并打日志)。
fn append(&self, record: &AuditRecord) -> std::io::Result<()> {
let path = self.path_for(self.clock.now_unix_ms());
let line = serde_json::to_string(record)
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
let _guard = self.guard.lock();
let mut file = OpenOptions::new().create(true).append(true).open(&path)?;
file.write_all(line.as_bytes())?;
file.write_all(b"\n")
}
}
impl AuditSink for JsonlAudit {
fn record(&self, record: &AuditRecord) {
if let Err(err) = self.append(record) {
// 审计是旁路:写不进去也不能让工具调用失败,但要留下痕迹。
eprintln!("[unlucky-agent] 审计写入失败: {err}");
}
}
}
/// 内存审计(测试 + 「P0 不落盘」的降级路径)。
#[derive(Debug, Default)]
pub struct MemoryAudit {
records: Mutex<Vec<AuditRecord>>,
}
impl MemoryAudit {
/// 空审计。
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// 已记录条数。
#[must_use]
pub fn len(&self) -> usize {
self.records.lock().map(|r| r.len()).unwrap_or(0)
}
/// 是否一条都没有。
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// 取快照。
#[must_use]
pub fn records(&self) -> Vec<AuditRecord> {
self.records.lock().map(|r| r.clone()).unwrap_or_default()
}
/// 按工具名筛出记录(测试断言用)。
#[must_use]
pub fn records_for(&self, tool: &str) -> Vec<AuditRecord> {
self.records()
.into_iter()
.filter(|r| r.tool == tool)
.collect()
}
}
impl AuditSink for MemoryAudit {
fn record(&self, record: &AuditRecord) {
if let Ok(mut records) = self.records.lock() {
records.push(record.clone());
}
}
}
/// 丢弃审计(不推荐,只给"连内存都不想留"的极端场景/基准测试)。
#[derive(Debug, Default, Clone, Copy)]
pub struct NullAudit;
impl AuditSink for NullAudit {
fn record(&self, _record: &AuditRecord) {}
}
/// 组装一条记录时的"其余字段"(时间戳从时钟取,参数先脱敏)。
#[derive(Debug, Clone, Copy)]
pub struct AuditDraft<'a> {
/// 工具名。
pub tool: &'a str,
/// 原始参数(内部会脱敏)。
pub args: &'a Value,
/// 结局。
pub outcome: AuditOutcome,
/// 一句话结果摘要。
pub summary: &'a str,
/// 是否 YOLO。
pub yolo: bool,
/// 是否经用户确认。
pub confirmed: bool,
/// 耗时(毫秒)。
pub duration_ms: u64,
}
/// 组装一条审计记录(时间戳从时钟取、参数脱敏,调用方不用自己拼)。
#[must_use]
pub fn make_record(
clock: &dyn crate::clock::Clock,
agent_session_id: &str,
draft: AuditDraft<'_>,
) -> AuditRecord {
AuditRecord {
ts: format_unix_ms(clock.now_unix_ms()),
agent_session_id: agent_session_id.to_string(),
tool: draft.tool.to_string(),
args: redact_args(draft.args),
outcome: draft.outcome,
summary: draft.summary.to_string(),
yolo: draft.yolo,
confirmed: draft.confirmed,
duration_ms: draft.duration_ms,
}
}
/// 便捷:给出数据根下的审计目录(`<data_root>/agent/audit`)。
#[must_use]
pub fn audit_dir(data_root: &Path) -> PathBuf {
data_root.join("agent").join("audit")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::clock::FixedClock;
use serde_json::json;
use std::sync::Arc;
#[test]
fn record_redacts_args_before_store() {
let audit = MemoryAudit::new();
let clock = FixedClock::new(1_793_304_753_123);
let args = json!({ "path": "ai.api_key", "value": "sk-x" });
let rec = make_record(
&clock,
"s1",
AuditDraft {
tool: "set_config",
args: &args,
outcome: AuditOutcome::Ok,
summary: "ok",
yolo: false,
confirmed: true,
duration_ms: 3,
},
);
audit.record(&rec);
let stored = &audit.records()[0];
assert_eq!(stored.args["value"], json!("***"), "敏感路径的值必须掩码");
assert_eq!(stored.ts, "2026-10-29T20:12:33.123Z");
}
#[test]
fn jsonl_audit_writes_one_line_per_record_per_day() {
let dir = std::env::temp_dir().join(format!("unlucky-agent-audit-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let clock: SharedClock = Arc::new(FixedClock::new(1_793_304_753_123));
let audit = JsonlAudit::new(&dir, Arc::clone(&clock));
let args = json!({});
let rec = make_record(
clock.as_ref(),
"s1",
AuditDraft {
tool: "get_config",
args: &args,
outcome: AuditOutcome::Ok,
summary: "ok",
yolo: false,
confirmed: false,
duration_ms: 1,
},
);
audit.record(&rec);
audit.record(&rec);
let path = dir.join("audit-2026-10-29.jsonl");
let content = std::fs::read_to_string(&path).expect("审计文件应存在");
assert_eq!(content.lines().count(), 2);
let first: AuditRecord = serde_json::from_str(content.lines().next().unwrap()).unwrap();
assert_eq!(first.tool, "get_config");
let _ = std::fs::remove_dir_all(&dir);
}
}
+267
View File
@@ -0,0 +1,267 @@
//! 对话协议类型 + [`ChatProvider`] trait(四态端点配置在 [`super::provider`])。
//!
//! 这里**没有协议方言**:OpenAI/Ollama/Anthropic 的报文差异全部由实现方
//! (阶段 B 的 [`super::rig`])吃掉。本模块只定义循环需要的三样东西:
//! 消息、请求/回复、流式增量回调。
//!
//! 一次工具调用的完整往返:
//! `Assistant { tool_calls }` → 编排层执行 → `Tool { call_id, name, content }` → 再次补全。
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::provider::{ProviderConfig, ProviderError};
use crate::event::{AgentEvent, AgentEventSink};
use crate::registry::ToolDefinition;
/// 一条工具调用请求(模型产出)。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolCall {
/// 调用 id(OpenAI 方言的 `tool_call_id`;Ollama 原生没有 id,由适配层生成)。
pub id: String,
/// 工具名。
pub name: String,
/// 参数(JSON 对象)。
pub arguments: Value,
}
/// 对话消息。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "role", rename_all = "snake_case")]
pub enum ChatMessage {
/// 系统提示词(每轮由 [`super::BrainConfig::system_prompt`] 重新注入,不进历史)。
System {
/// 提示词正文。
content: String,
},
/// 用户输入。
User {
/// 正文。
content: String,
},
/// 模型回复(可能带工具调用)。
Assistant {
/// 文本正文(工具调用轮可能为空)。
text: String,
/// 工具调用。
tool_calls: Vec<ToolCall>,
},
/// 工具结果回灌。
Tool {
/// 对应调用 id。
call_id: String,
/// 工具名(Ollama 原生靠 `tool_name` 配对,不是 id)。
name: String,
/// 结果 JSON 字符串。
content: String,
},
}
impl ChatMessage {
/// 便捷:系统消息。
#[must_use]
pub fn system(content: impl Into<String>) -> Self {
Self::System {
content: content.into(),
}
}
/// 便捷:用户消息。
#[must_use]
pub fn user(content: impl Into<String>) -> Self {
Self::User {
content: content.into(),
}
}
/// 便捷:工具结果消息。
#[must_use]
pub fn tool(
call_id: impl Into<String>,
name: impl Into<String>,
content: impl Into<String>,
) -> Self {
Self::Tool {
call_id: call_id.into(),
name: name.into(),
content: content.into(),
}
}
}
/// 一次补全请求。
#[derive(Debug, Clone, PartialEq)]
pub struct ChatRequest {
/// 模型名。
pub model: String,
/// 消息(system 在首位)。
pub messages: Vec<ChatMessage>,
/// 工具定义(双投影的 rig 侧载荷)。
pub tools: Vec<ToolDefinition>,
/// 采样温度。
pub temperature: Option<f32>,
/// token 上限。
pub max_tokens: Option<u32>,
}
/// token 用量(本地模型可能不报)。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Usage {
/// 输入 token。
pub prompt_tokens: Option<u32>,
/// 输出 token。
pub completion_tokens: Option<u32>,
}
/// 一次补全结果。
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ChatReply {
/// 文本正文。
pub text: String,
/// 工具调用(非空 ⇒ 循环继续)。
pub tool_calls: Vec<ToolCall>,
/// 用量。
pub usage: Option<Usage>,
}
impl ChatReply {
/// 纯文本回复。
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self {
text: text.into(),
tool_calls: Vec::new(),
usage: None,
}
}
/// 带工具调用的回复。
#[must_use]
pub fn with_tool_calls(tool_calls: Vec<ToolCall>) -> Self {
Self {
text: String::new(),
tool_calls,
usage: None,
}
}
}
/// 流式增量接收者。实现方必须**非阻塞**。
pub trait DeltaObserver: Send + Sync {
/// 收到一段文本增量。
fn on_delta(&self, text: &str);
}
/// 丢弃增量(不关心流式的调用方)。
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopObserver;
impl DeltaObserver for NoopObserver {
fn on_delta(&self, _text: &str) {}
}
/// 把增量转成 [`AgentEvent::TextDelta`](P1 聊天面板逐字渲染就靠它)。
#[derive(Clone)]
pub struct EventDeltaObserver {
sink: Arc<dyn AgentEventSink>,
}
impl EventDeltaObserver {
/// 用事件流构造。
#[must_use]
pub fn new(sink: Arc<dyn AgentEventSink>) -> Self {
Self { sink }
}
}
impl DeltaObserver for EventDeltaObserver {
fn on_delta(&self, text: &str) {
self.sink.emit(AgentEvent::TextDelta {
text: text.to_string(),
});
}
}
/// 收集增量(测试断言流式拼接)。
#[derive(Debug, Default)]
pub struct CollectingObserver {
chunks: std::sync::Mutex<Vec<String>>,
}
impl CollectingObserver {
/// 收完的内容。
#[must_use]
pub fn collected(&self) -> String {
self.chunks.lock().map(|c| c.concat()).unwrap_or_default()
}
}
impl DeltaObserver for CollectingObserver {
fn on_delta(&self, text: &str) {
if let Ok(mut chunks) = self.chunks.lock() {
chunks.push(text.to_string());
}
}
}
/// 补全未来的箱子类型。
pub type ProviderFuture<'a> =
Pin<Box<dyn Future<Output = Result<ChatReply, ProviderError>> + Send + 'a>>;
/// LLM 端点抽象:**这是 agent 唯一的异步边界**。
///
/// P0 实现 = 测试里的 mock;阶段 B 实现 = [`super::rig`] 的 rig 适配器。
/// 换实现(genai / 自写循环)只需要满足本 trait,[`super::Brain`] 不动。
pub trait ChatProvider: Send + Sync {
/// 当前配置(循环用它取 model/temperature,也用它判断是否启用)。
fn config(&self) -> &ProviderConfig;
/// 一次补全。流式增量通过 `observer` 回吐。
fn complete<'a>(
&'a self,
request: &'a ChatRequest,
observer: &'a dyn DeltaObserver,
) -> ProviderFuture<'a>;
}
/// 装配期用的 provider 工厂:按配置造实现(阶段 B 在这里接 rig,测试接 mock)。
pub type ProviderFactory =
Arc<dyn Fn(&ProviderConfig) -> Result<Arc<dyn ChatProvider>, ProviderError> + Send + Sync>;
#[cfg(test)]
mod tests {
use super::*;
use crate::event::MemoryEventSink;
#[test]
fn collecting_observer_concatenates_chunks() {
let observer = CollectingObserver::default();
observer.on_delta("正在");
observer.on_delta("读取日志");
assert_eq!(observer.collected(), "正在读取日志");
}
#[test]
fn event_observer_emits_text_delta() {
let sink = Arc::new(MemoryEventSink::new());
let observer = EventDeltaObserver::new(sink.clone());
observer.on_delta("嗨");
assert_eq!(sink.streamed_text(), "嗨");
}
#[test]
fn message_helpers_round_trip_through_json() {
let messages = vec![
ChatMessage::system("你是助手"),
ChatMessage::user("看看日志"),
ChatMessage::tool("call_1", "read_game_log", "{}"),
];
let json = serde_json::to_string(&messages).expect("可序列化");
let back: Vec<ChatMessage> = serde_json::from_str(&json).expect("可反序列化");
assert_eq!(back, messages);
assert!(json.contains("\"role\":\"tool\""));
}
}
+347
View File
@@ -0,0 +1,347 @@
//! 工具执行编排:schema 校验 → 分级确认 → 执行 → 审计 → 事件。
//!
//! **YOLO 只在这里**(mission M16 任务 3 的分工):工具自己不判断 policy,
//! 只声明「这次需要确认 + diff」;本模块按 [`ConfirmPolicy`] 决定问不问。
//!
//! 一次工具调用最多两条审计记录:
//! 1. 需要确认时先记一条 `awaiting_confirmation`(「AI 想改 X」本身必须留痕);
//! 2. 结局记一条 `ok` / `denied` / `tool_error`(带 `yolo` 与 `confirmed` 标记)。
//!
//! 这两条区分了三种在复盘里完全不同的事:用户点了拒绝、YOLO 自动放行、用户点了允许。
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use serde_json::{json, Value};
use crate::audit::{make_record, AuditDraft, AuditOutcome, AuditSink};
use crate::brain::chat::ToolCall;
use crate::clock::SharedClock;
use crate::confirm::{ConfirmDecision, ConfirmGate, ConfirmPolicy, ConfirmRequest, DenyGuidance};
use crate::event::{AgentEvent, AgentEventSink};
use crate::registry::validate::validate;
use crate::registry::{ToolCtx, ToolError, ToolRegistry};
/// 一次工具执行的结局(回灌给模型的内容 + 成败标记)。
#[derive(Debug, Clone, PartialEq)]
pub struct ToolExecOutcome {
/// 回灌内容(结构化)。
pub content: Value,
/// 是否成功(UI/事件用;模型看的是 `content`)。
pub ok: bool,
}
impl ToolExecOutcome {
/// 成功。
#[must_use]
pub fn ok(content: Value) -> Self {
Self { content, ok: true }
}
/// 失败(`code` 给模型看,帮助它改正后重试)。
#[must_use]
pub fn error(code: &str, message: impl Into<String>) -> Self {
Self {
content: json!({ "status": "error", "code": code, "message": message.into() }),
ok: false,
}
}
/// 序列化成回灌给模型的字符串(工具消息的 `content`)。
#[must_use]
pub fn to_model_content(&self) -> String {
serde_json::to_string(&self.content).unwrap_or_else(|_| {
json!({ "status": "error", "code": "internal", "message": "结果序列化失败" })
.to_string()
})
}
}
/// 工具执行器(无状态,可跨轮复用)。
pub struct ToolExecutor {
registry: Arc<ToolRegistry>,
audit: Arc<dyn AuditSink>,
gate: Arc<dyn ConfirmGate>,
policy: ConfirmPolicy,
clock: SharedClock,
sink: Arc<dyn AgentEventSink>,
guidance: DenyGuidance,
confirm_seq: AtomicU64,
}
impl ToolExecutor {
/// 装配(默认拒绝口径 = 内置对话:[`DenyGuidance::InApp`])。
pub fn new(
registry: Arc<ToolRegistry>,
audit: Arc<dyn AuditSink>,
gate: Arc<dyn ConfirmGate>,
policy: ConfirmPolicy,
clock: SharedClock,
sink: Arc<dyn AgentEventSink>,
) -> Self {
Self {
registry,
audit,
gate,
policy,
clock,
sink,
guidance: DenyGuidance::InApp,
confirm_seq: AtomicU64::new(0),
}
}
/// 换拒绝口径(外部 MCP 客户端用 [`DenyGuidance::External`]:没有弹窗可点)。
///
/// 只改**文案**:策略、闸门、审计标记一个字都不变——这正是「同一注册表、
/// 同一安全策略、同一审计」在代码上的落点。
#[must_use]
pub fn with_guidance(mut self, guidance: DenyGuidance) -> Self {
self.guidance = guidance;
self
}
/// 执行一次工具调用(含确认与审计)。
pub async fn execute(
&self,
agent_session_id: &str,
call: &ToolCall,
step: usize,
) -> ToolExecOutcome {
let started_at = self.clock.now_unix_ms();
self.sink.emit(AgentEvent::ToolCallStarted {
tool: call.name.clone(),
// 与审计同一套脱敏:事件(P1 会持久化)不能带出凭据明文。
args: crate::redact::redact_args(&call.arguments),
step,
});
let Some(spec) = self.registry.get(&call.name).cloned() else {
let message = format!(
"没有名为 `{}` 的工具。可用工具:{}",
call.name,
self.registry.names().join("、")
);
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::UnknownTool,
&message,
false,
false,
started_at,
);
self.finish_event(&call.name, false, &message, false);
return ToolExecOutcome::error("unknown_tool", message);
};
if let Err(errors) = validate(&spec.input_schema, &call.arguments) {
let message = format!("参数不合法:{}", errors.join(";"));
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::InvalidArgs,
&message,
false,
false,
started_at,
);
self.finish_event(&call.name, false, &message, false);
return ToolExecOutcome::error("invalid_args", message);
}
let ctx = ToolCtx {
agent_session_id: agent_session_id.to_string(),
confirmed: false,
};
let quoted = match (spec.handler)(&ctx, &call.arguments) {
Ok(output) => output,
Err(err) => return self.fail(agent_session_id, call, err, started_at),
};
let Some(confirmation) = quoted.confirmation.clone() else {
return self.succeed(agent_session_id, call, quoted, false, false, started_at);
};
// ── 需要确认:决定问不问(YOLO 只影响这里)──
let asked = self.policy.requires_confirmation(confirmation.sensitivity);
let yolo_auto = !asked && confirmation.sensitivity == crate::confirm::Sensitivity::High;
if asked {
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::AwaitingConfirmation,
&confirmation.summary,
false,
false,
started_at,
);
let request = ConfirmRequest {
id: format!(
"confirm-{}",
self.confirm_seq.fetch_add(1, Ordering::Relaxed) + 1
),
tool: call.name.clone(),
summary: confirmation.summary.clone(),
details: confirmation.details.clone(),
sensitivity: confirmation.sensitivity,
};
self.sink.emit(AgentEvent::ConfirmRequested {
request: Box::new(request.clone()),
});
if self.gate.request(request).await == ConfirmDecision::Denied {
let message = self.guidance.message().to_string();
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::Denied,
&message,
false,
false,
started_at,
);
self.sink.emit(AgentEvent::ToolDenied {
tool: call.name.clone(),
reason: message.clone(),
});
self.finish_event(&call.name, false, &message, true);
return ToolExecOutcome::error("denied", message);
}
}
// ── 已获授权(用户允许或 YOLO):带 confirmed 重放 ──
let confirmed_ctx = ToolCtx {
agent_session_id: agent_session_id.to_string(),
confirmed: true,
};
match (spec.handler)(&confirmed_ctx, &call.arguments) {
Ok(output) => {
if let Some(second) = output.confirmation {
// 工具在"已确认"状态下仍要确认 = 实现写错了,明确报出来而不是死循环。
let message = format!(
"工具 `{}` 在已确认状态下仍请求确认:{}",
call.name, second.summary
);
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::ToolError,
&message,
yolo_auto,
asked,
started_at,
);
self.finish_event(&call.name, false, &message, true);
return ToolExecOutcome::error("internal", message);
}
self.succeed(agent_session_id, call, output, asked, yolo_auto, started_at)
}
Err(err) => {
self.fail_after_confirm(agent_session_id, call, err, asked, yolo_auto, started_at)
}
}
}
fn succeed(
&self,
agent_session_id: &str,
call: &ToolCall,
output: crate::registry::ToolOutput,
confirmed: bool,
yolo: bool,
started_at: u64,
) -> ToolExecOutcome {
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::Ok,
&output.summary,
yolo,
confirmed,
started_at,
);
self.finish_event(
&call.name,
true,
&output.summary,
output.confirmation.is_some(),
);
ToolExecOutcome::ok(output.content)
}
fn fail(
&self,
agent_session_id: &str,
call: &ToolCall,
err: ToolError,
started_at: u64,
) -> ToolExecOutcome {
self.fail_after_confirm(agent_session_id, call, err, false, false, started_at)
}
fn fail_after_confirm(
&self,
agent_session_id: &str,
call: &ToolCall,
err: ToolError,
confirmed: bool,
yolo: bool,
started_at: u64,
) -> ToolExecOutcome {
let message = err.message().to_string();
self.record(
agent_session_id,
&call.name,
&call.arguments,
AuditOutcome::ToolError,
&message,
yolo,
confirmed,
started_at,
);
self.finish_event(&call.name, false, &message, false);
ToolExecOutcome::error(err.code(), message)
}
#[allow(clippy::too_many_arguments)]
fn record(
&self,
agent_session_id: &str,
tool: &str,
args: &Value,
outcome: AuditOutcome,
summary: &str,
yolo: bool,
confirmed: bool,
started_at: u64,
) {
let duration_ms = self.clock.now_unix_ms().saturating_sub(started_at);
let draft = AuditDraft {
tool,
args,
outcome,
summary,
yolo,
confirmed,
duration_ms,
};
self.audit
.record(&make_record(self.clock.as_ref(), agent_session_id, draft));
}
fn finish_event(&self, tool: &str, ok: bool, summary: &str, requires_confirmation: bool) {
self.sink.emit(AgentEvent::ToolCallFinished {
tool: tool.to_string(),
ok,
summary: summary.to_string(),
requires_confirmation,
});
}
}
+323
View File
@@ -0,0 +1,323 @@
//! Agent 大脑:Provider 抽象 + 对话循环 + 流式事件。
//!
//! 选型(M10 定稿):`rig-core` + `rig-agent`,**版本锁 `=0.45.x`**——上游 12 周 5 个 minor
//! 的 breaking 频率决定了必须锁死;依赖面只在本文件收口,其它模块不许直接碰 rig,
//! 以便随时换 genai / 自写循环逃生(`DevDocs/PlanDoc/02-ai-agent-design.md` §0)。
//!
//! Provider 形态(02 §2):OpenAI 兼容(默认,含本地 llama.cpp `127.0.0.1:PORT/v1`)、
//! Anthropic 原生、Ollama 原生、以及「禁用」——禁用时规则引擎仍可用。
//!
//! 统一 trait(M16 落地):`stream_chat(messages, tools) -> Stream<Event>`,含 tool_call 事件。
//! 本 crate 的落地形态是 [`chat::ChatProvider::complete`](`request + observer → ChatReply`):
//! rig 0.45 的流在 [`rig`] 适配层里展开成增量回调,循环侧只消费「文本增量 + 工具调用」两件事。
//! **rig 依赖面收口在 [`rig`] 一个文件**,本文件不 `use rig_*`。
//!
//! ## 对话循环(02 文档 §3.3)
//!
//! ```text
//! run_turn(user_input)
//! ├─ provider.complete(request) ← 流式增量经 EventDeltaObserver → UI
//! ├─ 有 tool_calls → ToolExecutor.execute(校验/确认/YOLO/审计)→ Tool 消息回灌
//! └─ 没有 tool_calls → 结束,返回最终文本
//! ```
//!
//! 三条不变量:
//! 1. **system prompt 每轮重新注入**,不进历史(改提示词立刻生效,也不会被压缩逻辑吃掉);
//! 2. 工具结果**永远回灌**(包括失败),模型才有机会改正;
//! 3. 步数上限 [`DEFAULT_MAX_STEPS`] 兜底,防止模型在两个工具间打转烧 token。
pub mod chat;
pub mod exec;
pub mod provider;
pub mod rig;
use std::fmt;
use std::sync::Arc;
use crate::audit::AuditSink;
use crate::clock::SharedClock;
use crate::confirm::{ConfirmGate, ConfirmPolicy};
use crate::event::{AgentEvent, AgentEventSink};
use crate::registry::ToolRegistry;
pub use chat::{
ChatMessage, ChatProvider, ChatReply, ChatRequest, DeltaObserver, EventDeltaObserver,
NoopObserver, ProviderFactory, ProviderFuture, ToolCall, Usage,
};
pub use exec::{ToolExecOutcome, ToolExecutor};
pub use provider::{ProviderConfig, ProviderError, ProviderKind};
/// 一轮对话最多几轮工具调用。
pub const DEFAULT_MAX_STEPS: usize = 8;
/// 内置系统提示词(P0 版本;P2 会按实例上下文按需注入)。
#[must_use]
pub fn default_system_prompt() -> String {
[
"你是 Unlucky-Launcher(ULL,Minecraft 启动器)的内置助手。",
"你能调用工具:读配置(get_config)、改配置(set_config)、列出游戏会话(list_game_sessions)、",
"读会话日志(read_game_log)、跑崩溃规则引擎(diagnose_crash)。",
"纪律:",
"1. 先查后改:改任何配置前先用 get_config 确认键名与现值。",
"2. 崩溃问题先看 diagnose_crash 的规则结论;规则未命中或需要更多信息时,才用 read_game_log",
" 取 stderr / exit / crash_found,不要拉全量日志。",
"3. 只能改 get_config 列出的可写键。敏感键会要求用户确认:被拒绝就换方案,不要重复尝试同一改动。",
"4. 用中文回答,给用户可以立即执行的下一步;不确定时直说不确定,不要编造规则或日志内容。",
]
.join("\n")
}
/// 循环参数。
#[derive(Debug, Clone)]
pub struct BrainConfig {
/// 最多几轮工具调用。
pub max_steps: usize,
/// 系统提示词。
pub system_prompt: String,
}
impl Default for BrainConfig {
fn default() -> Self {
Self {
max_steps: DEFAULT_MAX_STEPS,
system_prompt: default_system_prompt(),
}
}
}
impl BrainConfig {
/// 自定义提示词(步数用默认)。
#[must_use]
pub fn with_system_prompt(system_prompt: impl Into<String>) -> Self {
Self {
max_steps: DEFAULT_MAX_STEPS,
system_prompt: system_prompt.into(),
}
}
}
/// 循环的旁路依赖(审计/确认/时钟/事件)。
pub struct BrainDeps {
/// 审计出口。
pub audit: Arc<dyn AuditSink>,
/// 确认闸门(P0 = [`crate::confirm::NoUiGate`])。
pub gate: Arc<dyn ConfirmGate>,
/// YOLO 等策略快照。
pub policy: ConfirmPolicy,
/// 时间源。
pub clock: SharedClock,
/// 事件出口。
pub sink: Arc<dyn AgentEventSink>,
}
impl BrainDeps {
/// 装配。
pub fn new(
audit: Arc<dyn AuditSink>,
gate: Arc<dyn ConfirmGate>,
policy: ConfirmPolicy,
clock: SharedClock,
sink: Arc<dyn AgentEventSink>,
) -> Self {
Self {
audit,
gate,
policy,
clock,
sink,
}
}
}
/// 一轮对话的结局。
#[derive(Debug, Clone, PartialEq)]
pub struct TurnOutcome {
/// 最终文本(可能是空的,例如撞上步数上限且模型最后一句只有工具调用)。
pub text: String,
/// 用掉的轮次。
pub steps: usize,
/// 工具调用总次数。
pub tool_calls: usize,
/// 为什么停下来。
pub stopped_reason: StopReason,
}
/// 停止原因。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
/// 模型给出了最终回答。
Completed,
/// 撞上 [`BrainConfig::max_steps`]。
StepLimit,
}
/// 循环级错误。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum BrainError {
/// AI 被禁用(规则引擎仍可用)。
Disabled,
/// provider 报错。
Provider(ProviderError),
}
impl fmt::Display for BrainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Disabled => f.write_str(DISABLED_MESSAGE),
Self::Provider(err) => write!(f, "LLM 调用失败:{err}"),
}
}
}
impl std::error::Error for BrainError {}
/// AI 被禁用时给用户的话(装配层直接展示,不用先构造 Brain)。
pub const DISABLED_MESSAGE: &str =
"AI 已禁用:请在设置 → AI 中配置端点。规则引擎崩溃诊断不受影响。";
/// 对话循环。
pub struct Brain {
provider: Arc<dyn ChatProvider>,
registry: Arc<ToolRegistry>,
executor: ToolExecutor,
config: BrainConfig,
sink: Arc<dyn AgentEventSink>,
}
impl Brain {
/// 装配。
pub fn new(
provider: Arc<dyn ChatProvider>,
registry: Arc<ToolRegistry>,
deps: BrainDeps,
config: BrainConfig,
) -> Self {
let executor = ToolExecutor::new(
Arc::clone(&registry),
Arc::clone(&deps.audit),
Arc::clone(&deps.gate),
deps.policy,
Arc::clone(&deps.clock),
Arc::clone(&deps.sink),
);
Self {
provider,
registry,
executor,
config,
sink: deps.sink,
}
}
/// 当前 provider 配置(设置页/UI 展示用)。
#[must_use]
pub fn provider_config(&self) -> &ProviderConfig {
self.provider.config()
}
/// 跑一轮对话。`history` 由调用方持有(P1 落盘为 `agent/sessions/*.jsonl`)。
///
/// # Errors
/// AI 被禁用([`BrainError::Disabled`])或 provider 报错([`BrainError::Provider`])。
pub async fn run_turn(
&self,
agent_session_id: &str,
history: &mut Vec<ChatMessage>,
user_input: &str,
) -> Result<TurnOutcome, BrainError> {
if !self.provider.config().is_enabled() {
self.sink.emit(AgentEvent::Error {
message: DISABLED_MESSAGE.to_string(),
});
return Err(BrainError::Disabled);
}
self.sink.emit(AgentEvent::TurnStarted {
session_id: agent_session_id.to_string(),
user_text: user_input.to_string(),
});
history.push(ChatMessage::user(user_input));
let observer = EventDeltaObserver::new(Arc::clone(&self.sink));
let mut tool_calls = 0usize;
let mut last_text = String::new();
let mut used_steps = 0usize;
for step in 1..=self.config.max_steps {
used_steps = step;
let request = self.build_request(history);
let reply = match self.provider.complete(&request, &observer).await {
Ok(reply) => reply,
Err(err) => {
self.sink.emit(AgentEvent::Error {
message: err.to_string(),
});
return Err(BrainError::Provider(err));
}
};
if !reply.text.trim().is_empty() {
last_text = reply.text.clone();
self.sink.emit(AgentEvent::AssistantText {
text: reply.text.clone(),
});
}
if reply.tool_calls.is_empty() {
history.push(ChatMessage::Assistant {
text: reply.text.clone(),
tool_calls: Vec::new(),
});
self.sink.emit(AgentEvent::TurnFinished {
steps: step,
text: reply.text.clone(),
});
return Ok(TurnOutcome {
text: reply.text,
steps: step,
tool_calls,
stopped_reason: StopReason::Completed,
});
}
history.push(ChatMessage::Assistant {
text: reply.text.clone(),
tool_calls: reply.tool_calls.clone(),
});
for call in &reply.tool_calls {
let outcome = self.executor.execute(agent_session_id, call, step).await;
tool_calls += 1;
history.push(ChatMessage::tool(
call.id.clone(),
call.name.clone(),
outcome.to_model_content(),
));
}
}
self.sink.emit(AgentEvent::TurnFinished {
steps: used_steps,
text: last_text.clone(),
});
Ok(TurnOutcome {
text: last_text,
steps: used_steps,
tool_calls,
stopped_reason: StopReason::StepLimit,
})
}
fn build_request(&self, history: &[ChatMessage]) -> ChatRequest {
let config = self.provider.config();
let mut messages = Vec::with_capacity(history.len() + 1);
messages.push(ChatMessage::system(self.config.system_prompt.clone()));
messages.extend_from_slice(history);
ChatRequest {
model: config.model.clone(),
messages,
tools: self.registry.definitions(),
temperature: config.temperature,
max_tokens: config.max_tokens,
}
}
}
+340
View File
@@ -0,0 +1,340 @@
//! Provider 四态端点配置(02 文档 §2)。
//!
//! | 形态 | 端点 | 备注 |
//! |------|------|------|
//! | OpenAI 兼容(默认) | `base_url` + `api_key` + `model` | 覆盖 OpenAI/DeepSeek/Qwen/GLM/**本地 llama.cpp server**(`http://127.0.0.1:8080/v1`)/LM Studio |
//! | Anthropic 原生 | `api_key` + `model` | Claude 系列(没有可用的 Rust 单厂商 SDK,见 research/02 §3.6) |
//! | Ollama 原生 | `http://127.0.0.1:11434` | 本地另一种主流 |
//! | 禁用 | — | 完全关闭 agent,规则引擎(`diagnose_crash`)仍可用 |
//!
//! 本文件只放**配置与校验**;对话协议在 [`super::chat`]。这样 rig 的 pre-1.0 破坏面
//! (research/02 §7 R1)被关在 [`super::rig`] 一个文件里,这里连 rig 的名字都不出现。
use std::fmt;
use serde::{Deserialize, Serialize};
/// 本地 llama.cpp server 的默认 OpenAI 兼容端点(research/02 §5.1)。
pub const LLAMACPP_DEFAULT_BASE_URL: &str = "http://127.0.0.1:8080/v1";
/// Ollama 默认端点(research/02 §5.2)。
pub const OLLAMA_DEFAULT_BASE_URL: &str = "http://127.0.0.1:11434";
/// Anthropic 官方 API 端点。
pub const ANTHROPIC_DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
/// Provider 四态。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ProviderKind {
/// OpenAI 兼容(含本地 llama.cpp / LM Studio / DeepSeek / Qwen…)。
OpenAiCompatible,
/// Anthropic 原生。
Anthropic,
/// Ollama 原生。
Ollama,
/// 完全禁用 agent。
Disabled,
}
impl ProviderKind {
/// 该形态是否必须提供 API key(本地推理通常不需要)。
#[must_use]
pub fn requires_api_key(self) -> bool {
matches!(self, Self::Anthropic)
}
/// 该形态的默认端点(OpenAI 兼容没有统一默认值,必须显式填;
/// 本地 llama.cpp 走 [`ProviderConfig::llamacpp_local`] 带的显式默认)。
#[must_use]
pub fn default_base_url(self) -> &'static str {
match self {
Self::OpenAiCompatible => "",
Self::Anthropic => ANTHROPIC_DEFAULT_BASE_URL,
Self::Ollama => OLLAMA_DEFAULT_BASE_URL,
Self::Disabled => "",
}
}
/// 设置页展示名。
#[must_use]
pub fn display_name(self) -> &'static str {
match self {
Self::OpenAiCompatible => "OpenAI 兼容",
Self::Anthropic => "Anthropic 原生",
Self::Ollama => "Ollama 原生",
Self::Disabled => "已禁用",
}
}
}
/// Provider 配置(设置 → AI 的一份快照)。
///
/// `api_key` 只在进程内存在,**任何日志/审计/事件都不得带它**——
/// `Debug` 是手写的(掩码 key),要连形态一起看用 [`ProviderConfig::redacted_debug`]。
#[derive(Clone, PartialEq, Serialize, Deserialize)]
pub struct ProviderConfig {
/// 四态。
pub kind: ProviderKind,
/// 端点;空串表示用 [`ProviderKind::default_base_url`]。
pub base_url: String,
/// 模型名;`Disabled` 时可为空。
pub model: String,
/// API key(本地推理可空)。
pub api_key: Option<String>,
/// 采样温度。
pub temperature: Option<f32>,
/// 单次回复 token 上限。
pub max_tokens: Option<u32>,
}
impl Default for ProviderConfig {
fn default() -> Self {
Self::disabled()
}
}
impl ProviderConfig {
fn base(kind: ProviderKind, base_url: &str, model: &str) -> Self {
Self {
kind,
base_url: base_url.to_string(),
model: model.to_string(),
api_key: None,
temperature: None,
max_tokens: None,
}
}
/// OpenAI 兼容端点(云端或自建)。
#[must_use]
pub fn openai_compatible(base_url: &str, model: &str) -> Self {
Self::base(ProviderKind::OpenAiCompatible, base_url, model)
}
/// 本机 llama.cpp server(用户就在跑 llama-server 的默认场景)。
#[must_use]
pub fn llamacpp_local(model: &str) -> Self {
Self::base(
ProviderKind::OpenAiCompatible,
LLAMACPP_DEFAULT_BASE_URL,
model,
)
}
/// Anthropic 原生。
#[must_use]
pub fn anthropic(model: &str) -> Self {
Self::base(ProviderKind::Anthropic, ANTHROPIC_DEFAULT_BASE_URL, model)
}
/// 本机 Ollama。
#[must_use]
pub fn ollama(model: &str) -> Self {
Self::base(ProviderKind::Ollama, OLLAMA_DEFAULT_BASE_URL, model)
}
/// 禁用 agent。
#[must_use]
pub fn disabled() -> Self {
Self::base(ProviderKind::Disabled, "", "")
}
/// 带上 API key。
#[must_use]
pub fn with_api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = Some(api_key.into());
self
}
/// 带上温度。
#[must_use]
pub fn with_temperature(mut self, temperature: f32) -> Self {
self.temperature = Some(temperature);
self
}
/// agent 是否启用。
#[must_use]
pub fn is_enabled(&self) -> bool {
self.kind != ProviderKind::Disabled
}
/// 实际使用的端点(空则回落默认值)。
#[must_use]
pub fn resolved_base_url(&self) -> &str {
if self.base_url.trim().is_empty() {
self.kind.default_base_url()
} else {
self.base_url.trim()
}
}
/// 配置是否可用(装配期调用一次,错就进设置页提示而不是等到对话时炸)。
///
/// # Errors
/// 禁用、缺模型名、缺端点、缺 API key 时返回可读错误。
pub fn validate(&self) -> Result<(), ProviderError> {
if !self.is_enabled() {
return Err(ProviderError::new(
"AI 已禁用:请在设置 → AI 中选择端点(规则引擎诊断不受影响)",
));
}
if self.model.trim().is_empty() {
return Err(ProviderError::new("没有配置模型名(model)"));
}
if self.resolved_base_url().trim().is_empty() {
return Err(ProviderError::new(format!(
"{} 需要填写端点(base_url)",
self.kind.display_name()
)));
}
if self.kind.requires_api_key()
&& self
.api_key
.as_deref()
.is_none_or(|key| key.trim().is_empty())
{
return Err(ProviderError::new(format!(
"{} 需要 API key",
self.kind.display_name()
)));
}
Ok(())
}
/// 可打印的形态描述(**key 已掩码**,给日志/审计/设置页用)。
#[must_use]
pub fn redacted_debug(&self) -> String {
let key = match self.api_key.as_deref() {
None => "无".to_string(),
Some(k) if k.trim().is_empty() => "无".to_string(),
Some(_) => crate::redact::MASK.to_string(),
};
format!(
"{} base_url={} model={} api_key={key}",
self.kind.display_name(),
self.resolved_base_url(),
if self.model.is_empty() {
"(未设置)"
} else {
&self.model
},
)
}
}
impl fmt::Debug for ProviderConfig {
/// 手写 Debug:**key 掩码**(`api_key` 是唯一不能出现在日志里的字段)。
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ProviderConfig")
.field("kind", &self.kind)
.field("base_url", &self.resolved_base_url())
.field("model", &self.model)
.field(
"api_key",
&self.api_key.as_deref().map(|_| crate::redact::MASK),
)
.field("temperature", &self.temperature)
.field("max_tokens", &self.max_tokens)
.finish()
}
}
/// Provider 层错误(消息面向用户:端点连不上、key 无效、模型不存在)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProviderError {
message: String,
}
impl ProviderError {
/// 从可读文本构造。
#[must_use]
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ProviderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ProviderError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn local_defaults_match_research() {
assert_eq!(
ProviderConfig::llamacpp_local("qwen2.5").resolved_base_url(),
LLAMACPP_DEFAULT_BASE_URL
);
assert_eq!(
ProviderConfig::ollama("llama3").resolved_base_url(),
OLLAMA_DEFAULT_BASE_URL
);
assert_eq!(
ProviderConfig::anthropic("claude-sonnet-4").resolved_base_url(),
ANTHROPIC_DEFAULT_BASE_URL
);
}
#[test]
fn validate_requires_model_base_url_and_key() {
assert!(!ProviderConfig::disabled().is_enabled());
assert!(ProviderConfig::disabled().validate().is_err());
assert!(ProviderConfig::llamacpp_local("").validate().is_err());
assert!(ProviderConfig::llamacpp_local("qwen").validate().is_ok());
// OpenAI 兼容必须显式给端点
assert!(ProviderConfig::openai_compatible("", "gpt-4o-mini")
.validate()
.is_err());
assert!(
ProviderConfig::openai_compatible("https://api.deepseek.com/v1", "deepseek-chat")
.validate()
.is_ok()
);
assert!(ProviderConfig::anthropic("claude").validate().is_err());
assert!(ProviderConfig::anthropic("claude")
.with_api_key("sk-ant")
.validate()
.is_ok());
}
#[test]
fn redacted_debug_never_leaks_key() {
let config =
ProviderConfig::openai_compatible("https://api.deepseek.com/v1", "deepseek-chat")
.with_api_key("sk-super-secret");
let text = config.redacted_debug();
assert!(!text.contains("sk-super-secret"), "{text}");
assert!(text.contains(crate::redact::MASK));
// `{:?}` 也必须掩码:Debug 是 panic 消息/日志的默认出口。
let debug = format!("{config:?}");
assert!(!debug.contains("sk-super-secret"), "{debug}");
assert!(debug.contains(crate::redact::MASK), "{debug}");
}
#[test]
fn empty_base_url_falls_back_to_default() {
let mut config = ProviderConfig::ollama("llama3");
config.base_url = String::new();
assert_eq!(config.resolved_base_url(), OLLAMA_DEFAULT_BASE_URL);
}
#[test]
fn four_states_serialize_as_snake_case() {
assert_eq!(
serde_json::to_string(&ProviderKind::OpenAiCompatible).unwrap(),
"\"open_ai_compatible\""
);
assert_eq!(
serde_json::to_string(&ProviderConfig::disabled()).unwrap(),
"{\"kind\":\"disabled\",\"base_url\":\"\",\"model\":\"\",\"api_key\":null,\"temperature\":null,\"max_tokens\":null}"
);
}
}
+368
View File
@@ -0,0 +1,368 @@
//! rig 适配层:[`ChatProvider`] 的**唯一**实现,也是整个 crate 唯一允许 `use rig_*` 的文件。
//!
//! 依赖面收窄纪律(`DevDocs/PlanDoc/02-ai-agent-design.md` §0 + research/02 §7 R1):
//! rig 是 pre-1.0、12 周 5 个 minor、CHANGELOG 满是 `[**breaking**]`(0.43 把 MCP 拆出 rig-agent、
//! 0.45 升 rmcp 3.5 并改 owned connection)。所以把它关在这一个文件里:它变了,只有这里编译失败,
//! [`super::ChatProvider`] 以上的循环/编排/审计一行不用动。
//!
//! ## 0.45 的接线(实读源码,非照文档猜)
//!
//! ```text
//! ProviderConfig ─┬─ OpenAiCompatible → OpenAIConfig::new(key).with_base_url(url).client().chat(model)
//! ├─ Anthropic → AnthropicConfig::new(key).with_base_url(url).client().completion(model)
//! ├─ Ollama → OllamaConfig::new().with_base_url(url).client().completion(model)
//! └─ Disabled → 不构造(Brain::run_turn 已提前返回)
//! ↓ Model<W>.erase()
//! DynModel<Completion>(wire + transport 擦除,本文件只持有这一个类型)
//! ```
//!
//! 循环侧只要两件事:流式文本增量、以及折好的 [`ChatReply`](文本 + 工具调用)。
//! 所以这里用 `model.stream(request)` 边转发 [`StreamEvent::Text`] 增量给 [`DeltaObserver`],
//! 最后 `Streamed::finish()` 拿到完整 [`CompletionResponse`]——工具调用从响应里取,
//! 不自己拼分片 JSON(拼分片是 rig 的 `ReplyFold` 已经做过的事)。
//!
//! ## 三个已确认的坑
//!
//! 1. **llama.cpp 默认端点就是 `http://localhost:8080/v1`**(`providers/llamacpp/mod.rs`),
//! 与 [`LLAMACPP_DEFAULT_BASE_URL`] 一致。这里统一走 OpenAI 方言 + 显式 base_url:
//! llama.cpp / LM Studio / DeepSeek 都是 OpenAI 兼容面,方言差异主要在默认端点与特有位
//! (`chat_template_kwargs`、`num_ctx`)——真要下发这些,再换成 `providers::llamacpp` 方言或
//! Ollama 的 `native_completion`。
//! 2. **Ollama 原生方言的工具结果用 `tool_name` 配对(没有 id)**,OpenAI 方言用 `tool_call_id`。
//! 这里走 rig 的 `Ollama::completion`(OpenAI 兼容 `/v1/chat/completions`),由 rig 负责回灌形状;
//! 要下发 `num_ctx`(崩溃日志几千行,上下文必须可配)才需要 `native_completion`,留作 P1。
//! 3. **取消**:`Streamed` 是普通 future/stream,丢弃即断开——P0 用「丢弃 future」实现停止生成,
//! P1 接 UI 的「停止」按钮时按 rig 的取消语义(drop stream)对齐即可,不需要 unsafe。
//!
//! ## 逃生口(保留但不是 Plan A)
//!
//! rig 的破坏变更真伤到(或 Rust 1.92 MSRV 追不上 rig 的 1.97.1)时:换 `genai`
//! (provider + function calling,无 agent 循环)或自己写 OpenAI 方言(约 300~500 行)。
//! **代价只是实现一个新的 [`ChatProvider`]**——这正是把它关在一个文件里的意义。
//!
//! [`LLAMACPP_DEFAULT_BASE_URL`]: super::provider::LLAMACPP_DEFAULT_BASE_URL
//! [`StreamEvent::Text`]: rig_core::streaming::StreamEvent::Text
use std::sync::Arc;
use futures_util::StreamExt;
use rig_core::completion::{CompletionRequest, ToolDefinition as RigToolDefinition};
use rig_core::error::ProviderError as RigError;
use rig_core::message::{
AssistantContent as RigAssistantContent, AssistantMessage as RigAssistantMessage, CallId,
Message as RigMessage, Text as RigText, ToolCall as RigToolCall, ToolFunction,
ToolName as RigToolName, ToolResult, ToolResultContent, UserContent,
};
use rig_core::operation::Completion;
use rig_core::providers::anthropic::AnthropicConfig;
use rig_core::providers::ollama::OllamaConfig;
use rig_core::providers::openai::OpenAIConfig;
use rig_core::streaming::{Item, StreamEvent};
use rig_core::DynModel;
use super::chat::{
ChatMessage, ChatProvider, ChatReply, ChatRequest, DeltaObserver, ProviderFactory,
ProviderFuture,
};
use super::provider::{ProviderConfig, ProviderError, ProviderKind};
/// 锁定的 rig 版本(与 `Cargo.toml` 的唯一记录点,避免两处不一致)。
pub const RIG_VERSION_PIN: &str = "=0.45.0";
/// 擦掉 wire / transport 之后的补全模型——本文件对外只暴露这一个 rig 类型之外的东西。
type ErasedModel = DynModel<Completion>;
/// rig 实现的 [`ChatProvider`]:四态配置 + 一个擦除后的模型。
pub struct RigProvider {
config: ProviderConfig,
model: ErasedModel,
}
impl RigProvider {
/// 按配置造 provider。`Disabled`、缺模型名、缺 key 都在这里被拒(fail-fast)。
///
/// # Errors
/// AI 被禁用、配置不完整、或 rig 端点构造失败时返回可读错误。
pub fn new(config: ProviderConfig) -> Result<Self, ProviderError> {
config.validate()?;
let model = build_model(&config)?;
Ok(Self { config, model })
}
/// 装配层用的工厂:`ProviderFactory` 直接塞给 `crates/app`。
#[must_use]
pub fn factory() -> ProviderFactory {
Arc::new(|config: &ProviderConfig| {
Ok(Arc::new(Self::new(config.clone())?) as Arc<dyn ChatProvider>)
})
}
}
impl ChatProvider for RigProvider {
fn config(&self) -> &ProviderConfig {
&self.config
}
fn complete<'a>(
&'a self,
request: &'a ChatRequest,
observer: &'a dyn DeltaObserver,
) -> ProviderFuture<'a> {
Box::pin(async move {
let rig_request = build_request(request)?;
let mut stream = self.model.stream(rig_request).map_err(map_error)?;
// 先转发增量,再拿折好的完整响应(工具调用只从响应取,不拼分片)。
let mut text = String::new();
while let Some(item) = stream.next().await {
match item.map_err(map_error)? {
Item::Event(StreamEvent::Text { text: fragment, .. }) => {
text.push_str(&fragment);
observer.on_delta(&fragment);
}
Item::Event(_) | Item::Unknown(_) => {}
}
}
let response = stream.finish().await.map_err(map_error)?;
to_reply(&response, text)
})
}
}
/// 四态 → rig 模型。
fn build_model(config: &ProviderConfig) -> Result<ErasedModel, ProviderError> {
let model = config.model.trim().to_string();
let base_url = config.resolved_base_url().to_string();
let api_key = config.api_key.clone().unwrap_or_default();
let erased = match config.kind {
ProviderKind::OpenAiCompatible => OpenAIConfig::new(api_key)
.with_base_url(base_url)
.client()
.chat(model)
.erase(),
ProviderKind::Anthropic => AnthropicConfig::new(api_key)
.with_base_url(base_url)
.client()
.completion(model)
.erase(),
ProviderKind::Ollama => OllamaConfig::new()
.with_base_url(base_url)
.client()
.completion(model)
.erase(),
ProviderKind::Disabled => {
return Err(ProviderError::new(
"AI 已禁用:请在设置 → AI 中选择端点(规则引擎诊断不受影响)",
))
}
};
Ok(erased)
}
/// 本方消息 → rig 补全请求。
fn build_request(request: &ChatRequest) -> Result<CompletionRequest, ProviderError> {
let mut history = to_rig_messages(&request.messages)?;
// rig 把历史最后一条当 prompt,其余是上下文;空历史没有可发的 prompt。
let prompt = history
.pop()
.ok_or_else(|| ProviderError::new("对话历史为空:至少需要一条用户消息"))?;
let prompt = Arc::unwrap_or_clone(prompt);
let tools = request
.tools
.iter()
.map(to_rig_tool)
.collect::<Result<Vec<_>, _>>()?;
Ok(CompletionRequest::new(prompt)
.messages(history)
.tools(tools)
.temperature(request.temperature.map(f64::from))
.max_tokens(request.max_tokens.map(u64::from)))
}
/// 本方工具定义 → rig 工具定义(入参都是裸 JSON Schema,这正是双投影的支点)。
fn to_rig_tool(tool: &crate::registry::ToolDefinition) -> Result<RigToolDefinition, ProviderError> {
let name = tool_name(&tool.name)?;
Ok(RigToolDefinition::new(
name,
tool.description.clone(),
tool.input_schema.clone(),
))
}
/// 本方消息 → rig 消息。
fn to_rig_messages(messages: &[ChatMessage]) -> Result<Vec<Arc<RigMessage>>, ProviderError> {
let mut out = Vec::with_capacity(messages.len());
for message in messages {
let rig = match message {
ChatMessage::System { content } => RigMessage::system(content.clone()),
ChatMessage::User { content } => RigMessage::user(content.clone()),
ChatMessage::Assistant { text, tool_calls } => {
let mut parts = Vec::with_capacity(tool_calls.len() + 1);
if !text.trim().is_empty() {
parts.push(RigAssistantContent::Text(RigText::new(text.clone())));
}
for call in tool_calls {
parts.push(RigAssistantContent::ToolCall(RigToolCall::new(
CallId::from_wire(call.id.clone()),
ToolFunction::new(tool_name(&call.name)?, call.arguments.clone()),
)));
}
RigMessage::Assistant(RigAssistantMessage::new(parts))
}
ChatMessage::Tool {
call_id,
name,
content,
} => RigMessage::User {
content: vec![UserContent::ToolResult(ToolResult {
call: CallId::from_wire(call_id.clone()),
name: tool_name(name)?,
content: vec![ToolResultContent::text(content.clone())],
is_error: false,
})],
},
};
out.push(Arc::new(rig));
}
Ok(out)
}
/// rig 响应 → 本方回复(文本 + 工具调用 + 用量)。
fn to_reply(
response: &rig_core::completion::CompletionResponse,
streamed: String,
) -> Result<ChatReply, ProviderError> {
let mut text = streamed;
let mut tool_calls = Vec::new();
for part in &response.choice {
match part {
RigAssistantContent::Text(chunk) => {
if text.is_empty() {
text.push_str(&chunk.text);
}
}
RigAssistantContent::ToolCall(call) => {
if let Some(raw) = call.function.invalid_arguments.as_deref() {
return Err(ProviderError::new(format!(
"模型返回的工具调用参数不是 JSON 对象(工具 `{}`):{raw}",
call.function.name.as_str()
)));
}
tool_calls.push(super::chat::ToolCall {
id: call.id.to_string(),
name: call.function.name.as_str().to_string(),
arguments: serde_json::Value::Object(call.function.arguments.clone()),
});
}
// 推理链/图片/未知块不进对话循环(P0 只消费文本 + 工具调用)。
_ => {}
}
}
Ok(ChatReply {
text,
tool_calls,
usage: Some(super::chat::Usage {
prompt_tokens: response
.usage
.input_tokens
.and_then(|v| u32::try_from(v).ok()),
completion_tokens: response
.usage
.output_tokens
.and_then(|v| u32::try_from(v).ok()),
}),
})
}
/// rig 错误 → 本方错误(文案面向用户)。
fn map_error(error: RigError) -> ProviderError {
ProviderError::new(error.to_string())
}
/// 工具名 → rig 的 [`RigToolName`](空名是唯一的非法输入)。
fn tool_name(name: &str) -> Result<RigToolName, ProviderError> {
RigToolName::new(name)
.map_err(|_| ProviderError::new("工具名不能为空(ToolSpec 注册阶段应已拦截)"))
}
#[cfg(test)]
mod tests {
use super::*;
fn tool(id: &str, name: &str) -> super::super::chat::ToolCall {
super::super::chat::ToolCall {
id: id.to_string(),
name: name.to_string(),
arguments: serde_json::json!({ "path": "appearance.theme_mode" }),
}
}
#[test]
fn disabled_config_is_rejected_before_touching_the_network() {
let Err(err) = RigProvider::new(ProviderConfig::disabled()) else {
panic!("禁用态应在构造阶段被拒");
};
assert!(err.to_string().contains("禁用"));
}
#[test]
fn anthropic_without_key_is_rejected() {
assert!(RigProvider::new(ProviderConfig::anthropic("claude-sonnet-4")).is_err());
assert!(RigProvider::new(
ProviderConfig::anthropic("claude-sonnet-4").with_api_key("sk-ant")
)
.is_ok());
}
#[test]
fn local_states_build_offline() {
assert!(RigProvider::new(ProviderConfig::llamacpp_local("qwen2.5-7b")).is_ok());
assert!(RigProvider::new(ProviderConfig::ollama("llama3.1")).is_ok());
}
#[test]
fn request_maps_messages_and_tools() {
let request = ChatRequest {
model: "mock".to_string(),
messages: vec![
ChatMessage::system("你是助手"),
ChatMessage::user("把主题换成浅色"),
ChatMessage::Assistant {
text: String::new(),
tool_calls: vec![tool("call_1", "set_config")],
},
ChatMessage::tool("call_1", "set_config", "{\"status\":\"written\"}"),
],
tools: vec![crate::registry::ToolDefinition {
name: "set_config".to_string(),
description: "改配置".to_string(),
input_schema: serde_json::json!({ "type": "object" }),
}],
temperature: Some(0.5),
max_tokens: Some(512),
};
let built = build_request(&request).expect("应能构造");
assert_eq!(built.chat_history.len(), 4);
assert_eq!(built.tools.len(), 1);
assert_eq!(built.tools[0].name.as_str(), "set_config");
assert_eq!(built.temperature, Some(0.5));
assert_eq!(built.max_tokens, Some(512));
// 工具结果在 rig 0.45 里是 user 角色的 ToolResult 内容块
let json = serde_json::to_string(&built.chat_history[3]).expect("可序列化");
assert!(json.contains("toolresult"), "{json}");
}
#[test]
fn empty_history_is_a_readable_error() {
let request = ChatRequest {
model: "m".to_string(),
messages: Vec::new(),
tools: Vec::new(),
temperature: None,
max_tokens: None,
};
let err = build_request(&request).unwrap_err();
assert!(err.to_string().contains("对话历史为空"));
}
}
+139
View File
@@ -0,0 +1,139 @@
//! 时间源:审计日志、事件流、工具耗时都要时间戳,但**测试不能依赖真实时钟**
//! (否则断言不稳定)。所以照既有做法注入 [`Clock`]。
//!
//! 时间戳格式化自己实现([`format_unix_ms`]),不引 `chrono`:agent 的依赖面按
//! `DevDocs/PlanDoc/02-ai-agent-design.md` §0 越窄越好,RFC3339 UTC 只需要一个
//! 民用历换算(Howard Hinnant 的 `civil_from_days`)。
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
/// 时间源。生产用 [`SystemClock`],测试用 [`FixedClock`]。
pub trait Clock: Send + Sync {
/// 当前 Unix 毫秒时间戳。
fn now_unix_ms(&self) -> u64;
}
/// 真实系统时钟(单调性不保证,审计只要"大致有序")。
#[derive(Debug, Default, Clone, Copy)]
pub struct SystemClock;
impl Clock for SystemClock {
fn now_unix_ms(&self) -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as u64)
}
}
/// 可控时钟:测试里固定起点、必要时手动推进。
#[derive(Debug)]
pub struct FixedClock {
ms: AtomicU64,
step_ms: u64,
}
impl FixedClock {
/// 从固定时间戳开始,每次读走一步 `step_ms`(0 = 不自动推进)。
#[must_use]
pub fn new(start_ms: u64) -> Self {
Self {
ms: AtomicU64::new(start_ms),
step_ms: 0,
}
}
/// 每次读取自动前进 `step_ms`,用来断言工具耗时字段。
#[must_use]
pub fn with_step(start_ms: u64, step_ms: u64) -> Self {
Self {
ms: AtomicU64::new(start_ms),
step_ms,
}
}
/// 手动推进。
pub fn advance(&self, ms: u64) {
self.ms.fetch_add(ms, Ordering::Relaxed);
}
}
impl Clock for FixedClock {
fn now_unix_ms(&self) -> u64 {
if self.step_ms == 0 {
return self.ms.load(Ordering::Relaxed);
}
self.ms.fetch_add(self.step_ms, Ordering::Relaxed) + self.step_ms
}
}
/// `Arc<dyn Clock>` 的简写。
pub type SharedClock = Arc<dyn Clock>;
/// Unix 毫秒 → `YYYY-MM-DDTHH:MM:SS.mmmZ`(UTC)。
#[must_use]
pub fn format_unix_ms(ms: u64) -> String {
let secs = (ms / 1000) as i64;
let millis = ms % 1000;
let days = secs.div_euclid(86_400);
let sod = secs.rem_euclid(86_400);
let (y, m, d) = civil_from_days(days);
let (h, mi, s) = (sod / 3600, (sod % 3600) / 60, sod % 60);
format!("{y:04}-{m:02}-{d:02}T{h:02}:{mi:02}:{s:02}.{millis:03}Z")
}
/// Unix 毫秒 → `YYYY-MM-DD`(UTC),审计落盘按天分文件用。
#[must_use]
pub fn date_of_unix_ms(ms: u64) -> String {
let (y, m, d) = civil_from_days(((ms / 1000) as i64).div_euclid(86_400));
format!("{y:04}-{m:02}-{d:02}")
}
/// 1970-01-01 起的天数 → (年, 月, 日)。
fn civil_from_days(days: i64) -> (i64, u32, u32) {
let z = days + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = (z - era * 146_097) as u64; // [0, 146096]
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
let y = yoe as i64 + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
let mp = (5 * doy + 2) / 153; // [0, 11]
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats_epoch_and_known_instants() {
assert_eq!(format_unix_ms(0), "1970-01-01T00:00:00.000Z");
// 2026-10-29T20:12:33.123Z
assert_eq!(
format_unix_ms(1_793_304_753_123),
"2026-10-29T20:12:33.123Z"
);
assert_eq!(date_of_unix_ms(1_793_304_753_123), "2026-10-29");
}
#[test]
fn handles_leap_day() {
// 2024-02-29T00:00:00Z
assert_eq!(
format_unix_ms(1_709_164_800_000),
"2024-02-29T00:00:00.000Z"
);
}
#[test]
fn fixed_clock_can_step() {
let clock = FixedClock::with_step(1_000, 5);
assert_eq!(clock.now_unix_ms(), 1_005);
assert_eq!(clock.now_unix_ms(), 1_010);
clock.advance(10);
assert_eq!(clock.now_unix_ms(), 1_025);
}
}
+235
View File
@@ -0,0 +1,235 @@
//! 分级确认协议(02 文档 §3.1「分级确认」+ §4b「YOLO」)。
//!
//! 分工:
//! - **工具**只声明「这次调用需要确认」并给出 diff([`ConfirmRequest`]),不自己做决定;
//! - **编排层**([`crate::brain::exec`])拿 [`ConfirmPolicy`] 决定是问人、还是走 YOLO;
//! - **UI** 在 P1 通过 [`ConfirmGate`] 接进来(P0 只有事件 + fail-closed 的默认实现)。
//!
//! fail-closed 是刻意的:P0 没有确认弹窗,敏感键的写入**一律拒绝**而不是静默放行
//! (research/02 §7 R9「写操作的破坏半径」)。
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// 敏感等级。**与 M12 `setting::spec::Sensitivity` 逐字一致**
/// (`DevDocs/SubAgentsTalk/setting-接口约定.md` §8):
///
/// | 等级 | 语义 |
/// |------|------|
/// | `Low` | 静默生效 |
/// | `Medium` | 静默生效,审计里能查到(每次调用本来都审计,这里只是标记用途) |
/// | `High` | 必须用户确认(YOLO 可跳过确认,但**仍受白名单约束**) |
///
/// 「AI 完全不能写」的键(`ai.api_key` 等凭据)由 M12 的 `writable=false` 表达,
/// 它们**不进白名单**,agent 侧走「不在白名单」的拒绝分支,不需要第四级。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Sensitivity {
/// 静默生效。
#[default]
Low,
/// 静默生效但审计标记(下载源、语言、日志级别)。
Medium,
/// 必须用户确认(数据目录、Java 路径、代理、AI 端点/YOLO 开关)。
High,
}
/// 一个待确认的操作:给用户看的措辞 + 结构化细节(UI 画 diff 用)。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct ConfirmRequest {
/// 请求 id(编排层生成,UI 回填决定时原样带回)。
pub id: String,
/// 工具名。
pub tool: String,
/// 一句话请求(「AI 请求把 `instance.java.path` 改为 `D:\jdk17`」)。
pub summary: String,
/// 结构化细节(`{"path":…, "old":…, "new":…}`)。
pub details: Value,
/// 敏感等级。
pub sensitivity: Sensitivity,
}
/// 用户决定。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ConfirmDecision {
/// 允许这一次。
Approved,
/// 拒绝(工具调用返回「用户拒绝」给模型)。
Denied,
/// 允许,且本会话后续不再询问(UI 的「全部允许」)。
///
/// 编排层当前**只当普通放行**处理(`brain/exec.rs` 不区分两者);「据此临时开 YOLO」
/// 是 P1 的行为,落地前不要按已实现来看。
ApprovedAll,
}
impl ConfirmDecision {
/// 是否放行(`Approved` 与 `ApprovedAll` 都放行)。
#[must_use]
pub fn is_approved(self) -> bool {
matches!(self, Self::Approved | Self::ApprovedAll)
}
}
/// 确认闸门:P1 由 app 的 Slint 弹窗实现;测试用 [`ScriptedGate`]。
pub trait ConfirmGate: Send + Sync {
/// 发起确认并等待决定(UI 未接时由实现方立即给出 fail-closed 结果)。
fn request(&self, request: ConfirmRequest) -> ConfirmFuture;
}
/// 确认未来的箱子类型。
pub type ConfirmFuture = Pin<Box<dyn Future<Output = ConfirmDecision> + Send + 'static>>;
/// 一律放行(YOLO 单测 / 未来"用户已信任该工具"场景)。
#[derive(Debug, Default, Clone, Copy)]
pub struct AutoApproveGate;
impl ConfirmGate for AutoApproveGate {
fn request(&self, _request: ConfirmRequest) -> ConfirmFuture {
Box::pin(async { ConfirmDecision::Approved })
}
}
/// 一律拒绝(fail-closed 的极简形态)。
#[derive(Debug, Default, Clone, Copy)]
pub struct AutoDenyGate;
impl ConfirmGate for AutoDenyGate {
fn request(&self, _request: ConfirmRequest) -> ConfirmFuture {
Box::pin(async { ConfirmDecision::Denied })
}
}
/// P0 默认闸门:**没有确认 UI** → 一律拒绝(fail-closed)。
///
/// 请求本身已经由编排层作为 [`crate::event::AgentEvent::ConfirmRequested`] 发出去了,
/// 所以 P0 的行为是「敏感操作既不静默执行,也不卡住对话」:事件流里留下了
/// 「AI 想改 X」的完整记录,P1 接上弹窗后同一个事件直接变成可点的确认框。
#[derive(Debug, Default, Clone, Copy)]
pub struct NoUiGate;
impl ConfirmGate for NoUiGate {
fn request(&self, _request: ConfirmRequest) -> ConfirmFuture {
Box::pin(async { ConfirmDecision::Denied })
}
}
/// 脚本化闸门:按顺序返回预设决定,用完之后走 `default`(测试用)。
pub struct ScriptedGate {
decisions: Mutex<VecDeque<ConfirmDecision>>,
default: ConfirmDecision,
}
impl ScriptedGate {
/// 依次给出 `decisions`,耗尽后返回 `default`。
#[must_use]
pub fn new(
decisions: impl IntoIterator<Item = ConfirmDecision>,
default: ConfirmDecision,
) -> Self {
Self {
decisions: Mutex::new(decisions.into_iter().collect()),
default,
}
}
}
impl ConfirmGate for ScriptedGate {
fn request(&self, _request: ConfirmRequest) -> ConfirmFuture {
let decision = self
.decisions
.lock()
.ok()
.and_then(|mut q| q.pop_front())
.unwrap_or(self.default);
Box::pin(async move { decision })
}
}
/// 确认策略(编排层用)。YOLO 的真实开关在设置里,这里只是当次运行的快照。
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ConfirmPolicy {
/// 自动批准全部工具调用(设置 → AI → YOLO,默认关)。
pub yolo: bool,
}
/// 拒绝时的引导口径:**内置对话**有弹窗可点,**外部 MCP** 没有 UI——这条差别只在
/// 「拒绝文案」上,策略本身完全相同(同一条 `ConfirmPolicy`、同一份审计)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DenyGuidance {
/// 内置对话:弹窗拒绝(或 P0 的 fail-closed)。
InApp,
/// 外部 MCP 客户端:引导用户去设置页确认,或打开 YOLO。
External,
}
impl DenyGuidance {
/// 拒绝后回给模型/用户的一句话(区分「谁拒的」与「下一步怎么办」)。
#[must_use]
pub fn message(self) -> &'static str {
match self {
Self::InApp => "用户拒绝了这次操作,未做任何修改",
Self::External => {
"这次操作需要用户确认,但当前是外部 MCP 客户端(没有确认弹窗),已按默认策略拒绝。\
请让用户在启动器设置页手动修改,或在设置 → AI 里打开 YOLO 模式后重试(审计照记)。"
}
}
}
}
impl ConfirmPolicy {
/// 该等级是否需要**询问**用户:只有 `High` 会问;YOLO 下连 `High` 也不问
/// (02 文档 §4b:YOLO 跳过分级确认,但**仍受白名单约束**——能改的键没变少)。
#[must_use]
pub fn requires_confirmation(self, sensitivity: Sensitivity) -> bool {
!self.yolo && sensitivity == Sensitivity::High
}
/// 该等级是否可以直接执行(不需要询问)。
#[must_use]
pub fn auto_approves(self, sensitivity: Sensitivity) -> bool {
!self.requires_confirmation(sensitivity)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn low_and_medium_keys_never_ask() {
let policy = ConfirmPolicy { yolo: false };
assert!(!policy.requires_confirmation(Sensitivity::Low));
assert!(!policy.requires_confirmation(Sensitivity::Medium));
assert!(policy.auto_approves(Sensitivity::Low));
assert!(policy.auto_approves(Sensitivity::Medium));
}
#[test]
fn high_keys_ask_unless_yolo() {
assert!(ConfirmPolicy { yolo: false }.requires_confirmation(Sensitivity::High));
assert!(!ConfirmPolicy { yolo: false }.auto_approves(Sensitivity::High));
assert!(!ConfirmPolicy { yolo: true }.requires_confirmation(Sensitivity::High));
assert!(ConfirmPolicy { yolo: true }.auto_approves(Sensitivity::High));
}
#[test]
fn sensitivity_matches_m12_levels() {
// 序列化名必须与 M12 `setting::spec::Sensitivity` 一致
assert_eq!(serde_json::to_string(&Sensitivity::Low).unwrap(), "\"low\"");
assert_eq!(
serde_json::to_string(&Sensitivity::Medium).unwrap(),
"\"medium\""
);
assert_eq!(
serde_json::to_string(&Sensitivity::High).unwrap(),
"\"high\""
);
}
}
+197
View File
@@ -0,0 +1,197 @@
//! agent 事件流:**UI 与审计之外的观察者**都从这里接(02 文档 §1 的「event channel」)。
//!
//! P0 只做输出([`AgentEventSink`]),P1 的 Slint 聊天面板订阅同一路事件把
//! 「正在读取日志…」「请求修改设置:下载并发 64→16」画出来,确认弹窗直接复用
//! [`AgentEvent::ConfirmRequested`]。
//!
//! 实现方必须**非阻塞**:`emit` 在对话循环的同步路径上被调用。
use std::sync::mpsc::Sender;
use std::sync::Mutex;
use serde::Serialize;
use serde_json::Value;
use crate::confirm::ConfirmRequest;
/// 一条 agent 事件(全部可序列化:P1 走 IPC 给 app 时不写两套类型)。
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AgentEvent {
/// 一轮对话开始。
TurnStarted {
/// agent 会话 id。
session_id: String,
/// 用户输入。
user_text: String,
},
/// 流式文本增量(P1 聊天面板逐字渲染)。
TextDelta {
/// 增量文本。
text: String,
},
/// 模型这一轮的非流式完整文本(流式之外的兜底,也是审计用的正文)。
AssistantText {
/// 文本。
text: String,
},
/// 开始执行一个工具调用。
ToolCallStarted {
/// 工具名。
tool: String,
/// 模型给的参数。
args: Value,
/// 第几轮工具循环(从 1 开始)。
step: usize,
},
/// 一个工具调用结束。
ToolCallFinished {
/// 工具名。
tool: String,
/// 是否成功。
ok: bool,
/// 一句话结果摘要(UI 直接显示)。
summary: String,
/// 这次是否触发了确认请求。
requires_confirmation: bool,
},
/// 需要用户确认(P0 只发事件,P1 变成可点的弹窗)。
ConfirmRequested {
/// 待确认请求。
request: Box<ConfirmRequest>,
},
/// 工具调用被拒绝(策略或用户)。
ToolDenied {
/// 工具名。
tool: String,
/// 拒绝原因。
reason: String,
},
/// 一轮对话结束。
TurnFinished {
/// 实际用掉的最大工具轮次。
steps: usize,
/// 最终给用户看的文本。
text: String,
},
/// 循环级错误(provider 挂了、AI 被禁用…)。
Error {
/// 人类可读原因。
message: String,
},
}
/// 事件出口。
pub trait AgentEventSink: Send + Sync {
/// 发一条事件。实现方不得阻塞。
fn emit(&self, event: AgentEvent);
}
/// 丢弃事件。
#[derive(Debug, Default, Clone, Copy)]
pub struct NoopSink;
impl AgentEventSink for NoopSink {
fn emit(&self, _event: AgentEvent) {}
}
/// 内存事件流(测试断言 + P0 的「暂不接 UI」)。
#[derive(Debug, Default)]
pub struct MemoryEventSink {
events: Mutex<Vec<AgentEvent>>,
}
impl MemoryEventSink {
/// 空 sink。
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// 取快照。
#[must_use]
pub fn events(&self) -> Vec<AgentEvent> {
self.events.lock().map(|e| e.clone()).unwrap_or_default()
}
/// 已发条数。
#[must_use]
pub fn len(&self) -> usize {
self.events.lock().map(|e| e.len()).unwrap_or(0)
}
/// 是否还没发过事件。
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// 拼接所有文本增量(测试断言「流式内容拼起来等于完整文本」)。
#[must_use]
pub fn streamed_text(&self) -> String {
self.events()
.into_iter()
.filter_map(|e| match e {
AgentEvent::TextDelta { text } => Some(text),
_ => None,
})
.collect()
}
}
impl AgentEventSink for MemoryEventSink {
fn emit(&self, event: AgentEvent) {
if let Ok(mut events) = self.events.lock() {
events.push(event);
}
}
}
/// 标准库 channel 出口(P1 的 app 用一个线程收、喂给 Slint 的事件循环)。
#[derive(Debug, Clone)]
pub struct MpscSink {
tx: Sender<AgentEvent>,
}
impl MpscSink {
/// 包一个 `std::sync::mpsc::Sender`。
#[must_use]
pub fn new(tx: Sender<AgentEvent>) -> Self {
Self { tx }
}
}
impl AgentEventSink for MpscSink {
fn emit(&self, event: AgentEvent) {
// 接收端已关闭说明 UI 没了,事件直接丢弃(不能拖累对话)。
let _ = self.tx.send(event);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn memory_sink_collects_and_concatenates_deltas() {
let sink = MemoryEventSink::new();
sink.emit(AgentEvent::TextDelta {
text: "正在".into(),
});
sink.emit(AgentEvent::TextDelta {
text: "读取日志".into(),
});
assert_eq!(sink.streamed_text(), "正在读取日志");
assert_eq!(sink.len(), 2);
}
#[test]
fn mpsc_sink_forwards() {
let (tx, rx) = std::sync::mpsc::channel();
let sink = MpscSink::new(tx);
sink.emit(AgentEvent::Error {
message: "boom".into(),
});
assert!(matches!(rx.recv(), Ok(AgentEvent::Error { .. })));
}
}
+45
View File
@@ -0,0 +1,45 @@
//! Unlucky-Launcher AI Agent(`unlucky_agent`)。
//!
//! 形态定案(决策 D4):**内置 Agent 客户端 + 对外的 MCP server 双形态,共享同一个工具内核**。
//! 设计定稿:`DevDocs/PlanDoc/02-ai-agent-design.md`。
//!
//! 三条不能破的边界:
//! 1. 工具只定义一次([`registry`]),内置客户端与 MCP server 都把同一个 `ToolSpec` 投影出去;
//! 2. AI 是 Port 不是 Service——LLM 不可用时规则引擎仍能诊断;
//! 3. AI 永不接触账户凭据;写配置受 schema 白名单约束并留审计。
//!
//! 与 core 的关系:agent 依赖 core 的公共 API,core 不知道 agent 的存在。
//! 落地方式是把需要 core 的能力收成[`port`]里的五个 trait(配置读写 / 会话日志 / 崩溃诊断 /
//! 实例与 Java / 账户),由装配层用 core 的实现填充——这样 M12/M14/M15/M18/M31/M33 未合并时
//! agent 也能独立编译、独立测试。装配处有两条:`crates/app`(GUI)与 `ull agent serve`(headless)。
//!
//! 当前状态:工具内核 + 对话循环 + 审计(P0 定稿)+ **对外 MCP server**(M39)已落地。
//! 两个外部依赖都收口在单文件:[`brain::rig`] 对 rig、[`mcp`] 对 rmcp(3.8.x)——
//! 它们升 breaking 时只有那两个模块编译失败,上层的循环/编排/审计一行不用动。
//!
//! 模块分工:
//! - [`registry`] 工具注册表(唯一真相源 + 双投影载荷);
//! - [`tools`] 工具 v1 实现(配置读写 / 会话日志 / 崩溃诊断);
//! - [`brain`] Provider 抽象 + 对话循环 + 工具编排;
//! - [`mcp`] 对外 MCP server(rmcp 双投影 + stdio / Streamable HTTP 传输);
//! - [`confirm`] 分级确认协议与 YOLO 策略;
//! - [`audit`] 每次工具调用的审计留痕;
//! - [`event`] 面向 UI 的事件流;
//! - [`port`] 与 core 的接触面(依赖倒置);
//! - [`redact`] 密钥/主目录脱敏;
//! - [`clock`] 可注入时间源(审计/事件用);
//! - [`testing`] 五个端口的 mock 实现(供本 crate、app 与 MCP 契约测试复用)。
#![forbid(unsafe_code)]
pub mod audit;
pub mod brain;
pub mod clock;
pub mod confirm;
pub mod event;
pub mod mcp;
pub mod port;
pub mod redact;
pub mod registry;
pub mod testing;
pub mod tools;
+159
View File
@@ -0,0 +1,159 @@
//! 对外 MCP server(02 文档 §1「双形态共享一个工具内核」的第二形态)。
//!
//! 传输定论(§0):**Streamable HTTP on 127.0.0.1 是主力**(外部 agent 起 stdio 会变成
//! 双实例抢数据目录锁),**stdio 形态保留**给 llama.cpp server 的内置 MCP client。
//!
//! 与内置客户端的关系:两侧都只吃 [`crate::registry::ToolRegistry`] 的 `(name, description,
//! input_schema)`,并且**都必须走** [`crate::brain::exec::ToolExecutor`]——schema 校验、
//! 分级确认、YOLO、审计一个字都不少。所以「用户在聊天里让 AI 改配置」与「Claude Code
//! 通过 MCP 改配置」是同一条路径(02 §1 的铁律)。
//!
//! 安全边界(MCP 场景的差别只有一条):
//! - 敏感键(`Sensitivity::High`)默认**拒绝**而不是弹窗——外部客户端没有我们的 UI;
//! 拒绝文案引导用户去设置页确认,或在设置里打开 `ai.yolo`(YOLO 下照记 `yolo=true` 审计);
//! - 写工具默认不暴露(`agent.mcp.allow_write=false`):只读子集注册进注册表,
//! 调写工具会得到「没有这个工具 + 可用工具清单」(并留一条 `unknown_tool` 审计)。
//!
//! 依赖面纪律:整个 crate 只有本模块允许 `use rmcp::`(与 `brain::rig` 对 rig 的规则同形)。
pub mod projection;
pub mod sample;
pub mod serve;
pub mod server;
use std::fmt;
pub use sample::{config_samples, ConfigSamples};
pub use serve::{bind, serve_http, serve_http_on, serve_stdio};
pub use server::RegistryServer;
/// 一次 MCP server 运行的配置(由设置键 `agent.mcp.*` + 命令行覆盖合成)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpConfig {
/// 监听地址。**只允许回环地址**(默认 `127.0.0.1`):MCP 工具能改配置,不能对外开。
pub host: String,
/// Streamable HTTP 端口(默认 47823,设置键 `agent.mcp.port`)。
pub port: u16,
/// 访问令牌(`Authorization: Bearer <token>`);`None` = 不校验(仅限回环监听时允许)。
pub token: Option<String>,
/// 是否只暴露只读工具(默认 **true**;`agent.mcp.allow_write=true` 才放开写侧)。
pub read_only: bool,
}
impl Default for McpConfig {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 47823,
token: None,
read_only: true,
}
}
}
impl McpConfig {
/// `host:port` 形态的监听地址(IPv6 字面量自动加方括号,`::1` 不会拼成 `::1:47823`)。
#[must_use]
pub fn socket_addr(&self) -> String {
if self.host.contains(':') {
format!("[{}]:{}", self.host, self.port)
} else {
format!("{}:{}", self.host, self.port)
}
}
/// MCP 端点 URL(客户端配置样例里用的那串)。
#[must_use]
pub fn url(&self) -> String {
format!("http://{}/mcp", self.socket_addr())
}
/// 拒绝非回环监听——这是安全铁律的**代码化**,不是文档里的建议。
///
/// # Errors
/// `host` 不是回环地址时返回 [`McpServeError::NotLoopback`]。
pub fn ensure_loopback(&self) -> Result<(), McpServeError> {
let host = self.host.trim();
if host == "127.0.0.1" || host == "localhost" || host == "::1" {
return Ok(());
}
Err(McpServeError::NotLoopback(host.to_string()))
}
}
/// MCP server 启动/运行期错误(文案面向用户,可直接进 CLI 输出)。
#[derive(Debug)]
pub enum McpServeError {
/// 监听地址不是回环地址。
NotLoopback(String),
/// 端口被占用(最常见:另一个 `ull agent serve` 已经在跑)。
PortInUse {
/// 监听地址(`127.0.0.1:47823`)。
addr: String,
},
/// 其他 IO 失败(权限、端口不足、传输中断)。
Io(String),
}
impl fmt::Display for McpServeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotLoopback(host) => write!(
f,
"拒绝在 `{host}` 上监听:MCP server 只允许回环地址(127.0.0.1 / localhost / ::1)"
),
Self::PortInUse { addr } => write!(
f,
"端口已被占用:{addr}。可能另一个 `ull agent serve` 正在运行;\
用 `--port <端口>` 或设置键 `agent.mcp.port` 换一个"
),
Self::Io(message) => write!(f, "MCP server 传输失败:{message}"),
}
}
}
impl std::error::Error for McpServeError {}
impl From<std::io::Error> for McpServeError {
fn from(error: std::io::Error) -> Self {
Self::Io(error.to_string())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_loopback_hosts_are_accepted() {
let mut cfg = McpConfig::default();
assert!(cfg.ensure_loopback().is_ok());
cfg.host = "localhost".to_string();
assert!(cfg.ensure_loopback().is_ok());
cfg.host = "::1".to_string();
assert_eq!(cfg.url(), "http://[::1]:47823/mcp");
assert!(cfg.ensure_loopback().is_ok());
cfg.host = "0.0.0.0".to_string();
let err = cfg.ensure_loopback().unwrap_err();
assert!(matches!(err, McpServeError::NotLoopback(_)));
assert!(err.to_string().contains("回环地址"));
}
#[test]
fn default_is_read_only_on_the_documented_port() {
let cfg = McpConfig::default();
assert!(cfg.read_only);
assert_eq!(cfg.port, 47823);
assert_eq!(cfg.url(), "http://127.0.0.1:47823/mcp");
}
#[test]
fn port_in_use_message_is_actionable() {
let err = McpServeError::PortInUse {
addr: "127.0.0.1:47823".to_string(),
};
let text = err.to_string();
assert!(text.contains("--port"), "{text}");
assert!(text.contains("agent.mcp.port"), "{text}");
}
}
+106
View File
@@ -0,0 +1,106 @@
//! 双投影的 **MCP 侧**:`ToolDefinition` → rmcp `Tool`(`ToolRoute::new_dyn` 的属性入参)。
//!
//! rig 侧在 [`crate::brain::rig`](`ToolDefinition → RigToolDefinition`)。两侧都只吃裸
//! `serde_json::Value` schema,所以「一致性」是可断言的:`tests/mcp_contract.rs` 遍历注册表,
//! 断言 MCP 侧的 `(name, description, input_schema)` 与注册表逐项相等——这就是
//! research/02 §6.2 建议进 CI 的那条契约。
//!
//! 额外一位信息:`annotations.read_only_hint`。MCP 客户端拿它决定「这个工具能不能
//! 静默调用」,我们用它把 [`Access`] 语义透出去(只读提示,不是权限——权限在编排层)。
use std::sync::Arc;
use rmcp::model::{JsonObject, Tool, ToolAnnotations};
use serde_json::Value;
use crate::registry::{Access, ToolDefinition, ToolRegistry};
/// 一个 `ToolDefinition` → rmcp `Tool`。
///
/// 注册表在注册阶段已保证 `input_schema` 根是 `object`,所以这里的兜底分支
/// (非对象 → 空 schema)只是为了不 panic:真走到它说明注册校验被绕过了。
#[must_use]
pub fn tool_attr(definition: &ToolDefinition, access: Access) -> Tool {
let schema: JsonObject = match &definition.input_schema {
Value::Object(map) => map.clone(),
_ => JsonObject::new(),
};
let mut attr = Tool::new(
definition.name.clone(),
definition.description.clone(),
Arc::new(schema),
);
let mut annotations = ToolAnnotations::default();
annotations.read_only_hint = Some(access == Access::ReadOnly);
annotations.destructive_hint = Some(access == Access::Mutating);
attr.annotations = Some(annotations);
attr
}
/// 注册表 → rmcp `Tool` 列表(顺序同注册顺序,便于两侧比对)。
#[must_use]
pub fn tool_attrs(registry: &ToolRegistry) -> Vec<Tool> {
registry
.specs()
.iter()
.map(|spec| tool_attr(&spec.definition(), spec.access))
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::mock_ports;
use crate::tools::build_v1_registry;
use serde_json::json;
fn registry() -> ToolRegistry {
let (ports, _settings) = mock_ports();
build_v1_registry(&ports).expect("注册表应装配成功")
}
#[test]
fn projection_keeps_name_description_and_schema() {
let registry = registry();
let attrs = tool_attrs(&registry);
assert_eq!(attrs.len(), registry.len());
for (attr, spec) in attrs.iter().zip(registry.specs()) {
let definition = spec.definition();
assert_eq!(attr.name.as_ref(), definition.name);
assert_eq!(
attr.description.as_deref(),
Some(definition.description.as_str()),
"{} 的说明必须逐字相等",
definition.name
);
let projected = Value::Object((*attr.input_schema).clone());
assert_eq!(
projected, definition.input_schema,
"{} 的 JSON Schema 必须逐字相等",
definition.name
);
}
}
#[test]
fn read_only_hint_matches_access() {
let registry = registry();
for (attr, spec) in tool_attrs(&registry).iter().zip(registry.specs()) {
let hint = attr
.annotations
.as_ref()
.and_then(|a| a.read_only_hint)
.unwrap_or(false);
assert_eq!(hint, spec.access == Access::ReadOnly, "{}", attr.name);
}
}
#[test]
fn schema_root_stays_an_object_on_the_wire() {
for attr in tool_attrs(&registry()) {
let value = Value::Object((*attr.input_schema).clone());
assert_eq!(value["type"], json!("object"), "{}", attr.name);
}
}
}
+80
View File
@@ -0,0 +1,80 @@
//! 对外客户端配置样例(用户把它们粘进 Claude Code / Cursor 就能连上)。
//!
//! 为什么要生成而不是写在文档里:端口与令牌是**用户本机**的值,手抄必错。
//! 两个客户端的形状不同(02 §0):
//! - **Claude Code**:`{"type":"http","url":…}`(`type` 必填,缺了会被当成 stdio)
//! - **Cursor**:`{"url":…}`(`mcp.json` 里只认 url;多写 type 会被忽略但不报错)
//!
//! 令牌只在设置里非空时出现——回环 + 无令牌是允许的(研究里“至少一个 token”是建议不是铁律,
//! 而我们用 `McpConfig::ensure_loopback` 硬性禁掉对外监听)。
use serde_json::{json, Value};
/// 客户端配置样例(三件套:端点 URL + 两份可直接粘的 JSON)。
#[derive(Debug, Clone, PartialEq)]
pub struct ConfigSamples {
/// `http://127.0.0.1:<port>/mcp`。
pub url: String,
/// Claude Code(`claude mcp add` / `~/.claude.json` 的 `mcpServers` 片段)。
pub claude_code: Value,
/// Cursor(`.cursor/mcp.json` 的 `mcpServers` 片段)。
pub cursor: Value,
}
/// 生成样例。`token` 非空时补 `headers.Authorization`。
#[must_use]
pub fn config_samples(url: &str, token: Option<&str>) -> ConfigSamples {
let headers = token
.filter(|t| !t.trim().is_empty())
.map(|t| json!({ "Authorization": format!("Bearer {t}") }));
let mut claude_entry = json!({ "type": "http", "url": url });
let mut cursor_entry = json!({ "url": url });
if let Some(headers) = &headers {
claude_entry["headers"] = headers.clone();
cursor_entry["headers"] = headers.clone();
}
ConfigSamples {
url: url.to_string(),
claude_code: json!({ "mcpServers": { "unlucky-launcher": claude_entry } }),
cursor: json!({ "mcpServers": { "unlucky-launcher": cursor_entry } }),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn claude_code_needs_type_http_and_cursor_does_not() {
let samples = config_samples("http://127.0.0.1:47823/mcp", None);
assert_eq!(
samples.claude_code["mcpServers"]["unlucky-launcher"]["type"],
json!("http")
);
assert_eq!(
samples.claude_code["mcpServers"]["unlucky-launcher"]["url"],
json!("http://127.0.0.1:47823/mcp")
);
assert!(samples.cursor["mcpServers"]["unlucky-launcher"]
.get("type")
.is_none());
assert_eq!(
samples.cursor["mcpServers"]["unlucky-launcher"]["url"],
json!("http://127.0.0.1:47823/mcp")
);
}
#[test]
fn token_becomes_bearer_header_and_empty_token_is_skipped() {
let with = config_samples("http://127.0.0.1:1/mcp", Some("s3cret"));
let header = &with.cursor["mcpServers"]["unlucky-launcher"]["headers"]["Authorization"];
assert_eq!(header, &json!("Bearer s3cret"));
let without = config_samples("http://127.0.0.1:1/mcp", Some(" "));
assert!(without.claude_code["mcpServers"]["unlucky-launcher"]
.get("headers")
.is_none());
}
}
+144
View File
@@ -0,0 +1,144 @@
//! 两种传输:stdio(llama.cpp 内置 MCP client 用)与 Streamable HTTP(主力)。
//!
//! 传输定论(02 §0):**外部 MCP 主力是 127.0.0.1 上的 Streamable HTTP**,
//! 因为 stdio 形态要被外部 agent 拉起 = 同一份数据目录出现第二个实例,
//! 迟早撞上单写者锁(M18 的会话 jsonl、M12 的 launcher.json 都是单写者)。
//! stdio 保留给**已经常驻的**本地模型服务(llama.cpp server 的 MCP client 由它自己拉子进程)。
//!
//! 令牌:`Authorization: Bearer <agent.mcp.token>`。设置里为空 = 不校验(只允许回环监听,
//! `McpConfig::ensure_loopback` 已经拦掉对外监听)。research/02 §4.4 的原话是
//! 「至少要有 headers 里的一枚随机 token」——我们做成可配、默认留空但样例里带。
use std::net::SocketAddr;
use axum::extract::Request;
use axum::http::header::AUTHORIZATION;
use axum::http::StatusCode;
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use rmcp::ServiceExt;
use tokio::net::TcpListener;
use crate::mcp::server::RegistryServer;
use crate::mcp::{McpConfig, McpServeError};
/// stdio 形态:读 stdin 写 stdout,直到对端关闭。
///
/// 注意:**stdout 只能有 JSON-RPC**。任何日志都要走 stderr(否则客户端解析失败)。
///
/// # Errors
/// 传输中断或初始化失败时返回 [`McpServeError`]。
pub async fn serve_stdio(server: RegistryServer) -> Result<(), McpServeError> {
let service = server
.serve(rmcp::transport::stdio())
.await
.map_err(|error| McpServeError::Io(format!("stdio 初始化失败:{error}")))?;
service
.waiting()
.await
.map_err(|error| McpServeError::Io(format!("stdio 传输中断:{error}")))?;
Ok(())
}
/// 绑定 Streamable HTTP 监听(**只绑回环**),返回实际地址。
///
/// 拆出来是为了让调用方在进入 `axum::serve` 之前就能打印「监听在哪」——
/// 端口被占用时也能拿到一条可操作的错误(tower 的提醒:撞端口要给出换端口的指引)。
///
/// # Errors
/// 非回环地址、端口被占用、或绑定失败时返回 [`McpServeError`]。
pub async fn bind(cfg: &McpConfig) -> Result<(SocketAddr, TcpListener), McpServeError> {
cfg.ensure_loopback()?;
let addr = cfg.socket_addr();
let listener = TcpListener::bind(&addr).await.map_err(|error| {
if error.kind() == std::io::ErrorKind::AddrInUse {
McpServeError::PortInUse { addr: addr.clone() }
} else {
McpServeError::Io(format!("绑定 {addr} 失败:{error}"))
}
})?;
let local = listener
.local_addr()
.map_err(|error| McpServeError::Io(error.to_string()))?;
Ok((local, listener))
}
/// Streamable HTTP 形态:`POST /mcp` 一条 JSON-RPC 请求 / 一条响应。
///
/// `json_response = true`:简单请求直接回 `application/json`(脚本与裸 JSON-RPC
/// 客户端最省事;需要服务端推送时 rmcp 会自动回落到 SSE)。
///
/// # Errors
/// 绑定失败(见 [`bind`])或服务运行期致命错误时返回 [`McpServeError`]。
pub async fn serve_http(server: RegistryServer, cfg: McpConfig) -> Result<(), McpServeError> {
let (local, listener) = bind(&cfg).await?;
serve_http_on(server, cfg, local, listener).await
}
/// 在已绑定的监听上跑(测试用临时端口,避免抢 47823)。
///
/// # Errors
/// 服务运行期致命错误时返回 [`McpServeError`]。
pub async fn serve_http_on(
server: RegistryServer,
cfg: McpConfig,
local: SocketAddr,
listener: TcpListener,
) -> Result<(), McpServeError> {
let http_config = StreamableHttpServerConfig::default()
.with_json_response(true)
.with_legacy_session_mode(false);
let factory_server = server.clone();
let service: StreamableHttpService<RegistryServer, LocalSessionManager> =
StreamableHttpService::new(
move || Ok(factory_server.clone()),
std::sync::Arc::new(LocalSessionManager::default()),
http_config,
);
let token = cfg.token.clone();
let app = axum::Router::new()
.nest_service("/mcp", service)
.layer(axum::middleware::from_fn(
move |request: Request, next: Next| {
let token = token.clone();
async move { authorize(token, request, next).await }
},
));
eprintln!(
"[unlucky-agent] MCP server 监听 http://{local}/mcp({} 个工具;令牌:{})",
server.tool_count(),
if cfg.token.is_some() {
"已启用"
} else {
"未设置(仅回环监听)"
}
);
axum::serve(listener, app)
.await
.map_err(|error| McpServeError::Io(error.to_string()))
}
/// Bearer 令牌闸门:未配置 = 放行;配置了则严格比对。
async fn authorize(token: Option<String>, request: Request, next: Next) -> Response {
let Some(expected) = token else {
return next.run(request).await;
};
let presented = request
.headers()
.get(AUTHORIZATION)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
if presented == format!("Bearer {expected}") {
return next.run(request).await;
}
(
StatusCode::UNAUTHORIZED,
"缺少或错误的 Authorization: Bearer <agent.mcp.token>",
)
.into_response()
}
+243
View File
@@ -0,0 +1,243 @@
//! rmcp `ServerHandler`:把同一份注册表挂成 MCP 工具路由。
//!
//! 每次 `tools/call` 都走 [`ToolExecutor`]——schema 校验、确认闸门、YOLO、审计、
//! 事件**与内置客户端完全同一条路径**(02 §1 铁律)。工具级失败返回
//! `CallToolResult::error`(客户端能看到文案),协议级错误只留给「路由不到」的情况
//! (research/02 §3.2:`Err(McpError)` 会被大多数客户端吞成 "internal error")。
use std::sync::Arc;
use rmcp::handler::server::tool::{ToolCallContext, ToolRoute, ToolRouter};
use rmcp::model::{
CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,
ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
};
use rmcp::service::RequestContext;
use rmcp::{ErrorData as McpError, RoleServer, ServerHandler};
use serde_json::Value;
use crate::brain::chat::ToolCall;
use crate::brain::exec::ToolExecutor;
use crate::mcp::projection::tool_attr;
use crate::registry::{Access, ToolRegistry};
/// MCP server 的 `ServerHandler` 实现。
///
/// `Clone` 是 Streamable HTTP 要的:每个会话/请求由工厂造一份(共享同一批 `Arc`,
/// 因此审计与策略仍是同一份)。
#[derive(Clone)]
pub struct RegistryServer {
router: ToolRouter<RegistryServer>,
visible: Arc<Vec<Tool>>,
session_id: String,
}
impl std::fmt::Debug for RegistryServer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegistryServer")
.field("session_id", &self.session_id)
.field("tools", &self.visible.len())
.finish()
}
}
impl RegistryServer {
/// 用注册表 + 执行器装配。
///
/// **`router_registry` 必须是完整注册表**(含写工具),`executor` 才决定「哪些工具真能跑」:
/// - 只读模式:`-executor` 用 `read_only_subset()` 装配,`tools/list` 只列只读项,
/// 硬调写工具会路由到执行器 → `unknown_tool`(**tool-level 错误 + 审计**),
/// 而不是 rmcp 的协议级 `-32602 tool not found`(那个客户端只会显示 "internal error")。
/// - 写模式:两者都是完整注册表。
///
/// `session_id` 进审计的 `agent_session_id` 字段(`mcp-http` / `mcp-stdio`),
/// 让复盘时能区分「内置对话改的」和「外部 MCP 改的」。
#[must_use]
pub fn new(
router_registry: Arc<ToolRegistry>,
executor: Arc<ToolExecutor>,
session_id: impl Into<String>,
read_only: bool,
) -> Self {
let mut router = ToolRouter::new();
for spec in router_registry.specs() {
let attr = tool_attr(&spec.definition(), spec.access);
router.add_route(route(attr, Arc::clone(&executor)));
}
let visible: Vec<Tool> = router_registry
.specs()
.iter()
.filter(|spec| !read_only || spec.access == Access::ReadOnly)
.map(|spec| tool_attr(&spec.definition(), spec.access))
.collect();
Self {
router,
visible: Arc::new(visible),
session_id: session_id.into(),
}
}
/// 本 server **对外可见**的工具(`tools/list` 的内容)。
#[must_use]
pub fn tools(&self) -> Vec<Tool> {
(*self.visible).clone()
}
/// 审计用的会话标签。
#[must_use]
pub fn session_id(&self) -> &str {
&self.session_id
}
/// 对外可见的工具数(启动日志/断言用)。
#[must_use]
pub fn tool_count(&self) -> usize {
self.visible.len()
}
}
fn route(attr: Tool, executor: Arc<ToolExecutor>) -> ToolRoute<RegistryServer> {
ToolRoute::new_dyn(attr, move |context: ToolCallContext<'_, RegistryServer>| {
let executor = Arc::clone(&executor);
let session_id = context.service.session_id().to_string();
let name = context.name().to_string();
let arguments = context
.arguments
.clone()
.map_or_else(|| Value::Object(serde_json::Map::new()), Value::Object);
Box::pin(async move {
let call = ToolCall {
id: format!("mcp-{name}"),
name,
arguments,
};
let outcome = executor.execute(&session_id, &call, 0).await;
let text = outcome.to_model_content();
let content = vec![ContentBlock::text(text)];
let result = if outcome.ok {
CallToolResult::structured(outcome.content)
} else {
CallToolResult::error(content)
};
Ok(result.into())
})
})
}
impl ServerHandler for RegistryServer {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_server_info(Implementation::new(
"unlucky-launcher",
env!("CARGO_PKG_VERSION"),
))
.with_instructions(
"Unlucky-Launcher 的工具服务:读写启动器配置、看实例/版本/Java、读游戏日志、跑崩溃诊断。\
账户凭据永不经由本服务出口;写配置受 schema 白名单与敏感键确认约束。",
)
}
async fn list_tools(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListToolsResult, McpError> {
Ok(ListToolsResult::with_all_items(self.tools()))
}
async fn call_tool(
&self,
request: CallToolRequestParams,
context: RequestContext<RoleServer>,
) -> Result<CallToolResponse, McpError> {
let call_context = ToolCallContext::new(self, request, context);
self.router.call(call_context).await
}
fn get_tool(&self, name: &str) -> Option<Tool> {
self.router.get(name).cloned()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::audit::MemoryAudit;
use crate::clock::{FixedClock, SharedClock};
use crate::confirm::{AutoDenyGate, ConfirmPolicy};
use crate::event::NoopSink;
use crate::testing::mock_ports;
use crate::tools::build_v1_registry;
use serde_json::json;
fn server(registry: Arc<ToolRegistry>, read_only: bool) -> (RegistryServer, Arc<MemoryAudit>) {
let audit = Arc::new(MemoryAudit::new());
let clock: SharedClock = Arc::new(FixedClock::new(1_793_304_753_123));
let exposed = if read_only {
Arc::new(registry.read_only_subset())
} else {
Arc::clone(&registry)
};
let executor = Arc::new(ToolExecutor::new(
exposed,
audit.clone(),
Arc::new(AutoDenyGate),
ConfirmPolicy::default(),
clock,
Arc::new(NoopSink),
));
(
RegistryServer::new(registry, executor, "mcp-test", read_only),
audit,
)
}
fn registry() -> Arc<ToolRegistry> {
let (ports, _settings) = mock_ports();
Arc::new(build_v1_registry(&ports).expect("注册表应装配成功"))
}
#[test]
fn lists_every_registered_tool_in_write_mode() {
let registry = registry();
let (server, _audit) = server(Arc::clone(&registry), false);
let tools = server.tools();
assert_eq!(tools.len(), registry.len());
assert_eq!(server.tool_count(), registry.len());
assert_eq!(server.session_id(), "mcp-test");
assert!(tools.iter().any(|tool| tool.name == "set_config"));
}
#[test]
fn read_only_mode_hides_the_writing_tool_but_keeps_it_routable() {
let (server, _audit) = server(registry(), true);
let names: Vec<String> = server.tools().iter().map(|t| t.name.to_string()).collect();
assert!(!names.iter().any(|n| n == "set_config"), "{names:?}");
assert!(names.iter().any(|n| n == "get_config"));
assert_eq!(names.len(), 9);
// 路由仍然存在(否则 rmcp 会回协议级 -32602,客户端看到的是 "internal error"),
// 真正拦下来的是只读子集执行器 → tool-level 错误 + 审计。
assert!(server.router.get("set_config").is_some());
}
#[test]
fn info_advertises_tools_and_a_stable_identity() {
let (server, _audit) = server(registry(), false);
let info = server.get_info();
assert!(info.capabilities.tools.is_some());
assert_eq!(info.server_info.name, "unlucky-launcher");
}
#[test]
fn get_tool_returns_the_projected_attr() {
let (server, _audit) = server(registry(), false);
let attr = server.get_tool("get_config").expect("工具存在");
assert_eq!(attr.name, "get_config");
assert_eq!(
Value::Object((*attr.input_schema).clone())["type"],
json!("object")
);
assert!(server.get_tool("nope").is_none());
}
}
+315
View File
@@ -0,0 +1,315 @@
//! 端口层(port):agent 与 `ull-core` 各模块之间**唯一**的接触面。
//!
//! 为什么不直接 `use ull_core::*`:M12(setting)/ M14(game)/ M15(diagnose)/ M18(launch)
//! 与本 crate 并行开发,直接依赖会把 agent 的编译期绑死在别人的 API 日期上。这里用
//! **依赖倒置**——agent 只声明自己需要的形状(本文件的 trait + 结构体),由 `crates/app`
//! 在装配处用 `ull-core` 的实现去满足(`#![forbid(unsafe_code)]` 的纯适配层)。
//!
//! | 端口 | 提供的工具 | 对方模块 / 数据源 |
//! |------|-----------|------------------|
//! | [`SettingPort`] | `get_config` / `set_config` | M12 · `config/*.json` schema |
//! | [`GameSessionPort`] | `list_game_sessions` / `read_game_log` | M18 · `agent/sessions/game/{index,<id>}.jsonl` |
//! | [`DiagnosePort`] | `diagnose_crash` | M15 · 规则引擎 |
//!
//! 形状依据(以对方文件为准,改字段先改对方文件):
//! - `DevDocs/SubAgentsTalk/launch-接口约定.md` §2/§5(事件行 + 索引行)
//! - `DevDocs/SubAgentsTalk/agent-ToolSpec约定.md`(本 crate 对外的对齐说明)
//!
//! 错误一律用 `Result<T, String>`:错误文本会**原样进工具结果**给模型与用户看
//! (rmcp 的 `CallToolResult::error` 同理——协议级错误不给模型看,见 research/02 §3.2)。
//! 因此端口实现写中文、面向用户、可执行(「配置键 `x` 不存在」而不是 `ENOENT`)。
use std::collections::BTreeMap;
use std::sync::Arc;
use serde::Serialize;
use serde_json::Value;
use crate::confirm::Sensitivity;
pub mod game;
pub use game::{
AccountPort, AccountSummary, GamePort, InstanceSummary, JavaRuntimeSummary, JavaStatus,
VersionSummary,
};
/// 端口调用结果的错误文本(面向用户可读,直接进工具结果)。
pub type PortResult<T> = Result<T, String>;
/// agent 需要的全部端口。装配处(`crates/app` / `ull agent serve`)用它一次性注入。
#[derive(Clone)]
pub struct Ports {
/// 配置读写(M12)。
pub setting: Arc<dyn SettingPort>,
/// 游戏会话与日志(M18)。
pub sessions: Arc<dyn GameSessionPort>,
/// 崩溃规则引擎(M15)。
pub diagnose: Arc<dyn DiagnosePort>,
/// 实例 / 版本 / Java(M14 + M33)。
pub game: Arc<dyn GamePort>,
/// 账户元数据(M31,**只有公开字段**,凭据永不出口)。
pub accounts: Arc<dyn AccountPort>,
}
// ───────────────────────────── 配置(M12) ─────────────────────────────
/// AI 可写白名单里的一个键,带**敏感分级**(02 文档 §3.1 的「分级确认」依据)。
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct SettingKey {
/// 点分路径,如 `download.concurrency`、`java.selected_path`(键名以 M12 的 schema 为准)。
pub path: String,
/// 敏感等级(M12 `Low/Medium/High`):只有 `High` 需要用户确认。
pub sensitivity: Sensitivity,
/// 值类型(`string` / `integer` / `boolean` / `enum` / `json`),用于错误提示。
pub value_type: String,
/// 一句话说明,同时进 `get_config` 概要与模型上下文。
pub description: String,
}
/// 一次成功的写入,带旧值即「diff」(research/02 §6.4 的 dry-run 落点)。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct SettingChange {
/// 被修改的键路径。
pub path: String,
/// 修改前的值;键此前不存在时为 `None`。
pub old: Option<Value>,
/// 写入后的值。
pub new: Value,
}
/// 配置端口(M12 实现,`ull-core::setting` 的 schema API 直译)。
///
/// agent 侧只做**白名单 + 敏感分级 + 确认编排**,值本身的范围/类型校验归 setting 模块所有
/// (单一真相源:配置 schema 在 M12,agent 不复制一份)。
pub trait SettingPort: Send + Sync {
/// 全量概要(`get_config()` 无参时返回):键 → 当前值的扁平表,敏感键已脱敏。
fn summary(&self) -> Value;
/// 读单个键。键不存在时返回人类可读错误。
///
/// **凭据契约**:`writable=false` 的凭据类键(`ai.api_key` 等)必须**拒绝或掩码**,
/// 不得返回明文——agent 侧还有一道 `redact::is_sensitive_key` 守卫,但端口是数据的
/// 第一道闸(模型上下文与对话历史都会带上这里的返回值)。
fn get(&self, path: &str) -> PortResult<Value>;
/// 写单个键(值校验由实现方负责),返回 diff。
fn set(&self, path: &str, value: &Value) -> PortResult<SettingChange>;
/// **AI 可写白名单**(含敏感分级)。不在表里的键 agent 一律拒绝。
fn writable_keys(&self) -> Vec<SettingKey>;
/// 配置 schema 的给 AI 版本(`get_config_schema` 工具):只含 AI 可写键与
/// `x-ai-sensitivity` 标注,凭据类键天然不在其中(M12 `SettingSchema::to_json_schema`)。
fn schema(&self) -> Value;
}
// ──────────────────────── 游戏会话与日志(M18) ────────────────────────
/// `index.jsonl` 一行 → 一个会话摘要(同 id 多行由实现方取最后一行)。
///
/// 字段对齐 `launch-接口约定.md` §5;对方新增字段时这里补 `Option`,不破坏旧实现。
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct GameSessionSummary {
/// 会话 id,格式 `YYYYMMDDTHHMMSS-<6 位 hex>`(UTC)。
pub session_id: String,
/// 实例 id。
pub instance_id: Option<String>,
/// 实例显示名。
pub instance_name: Option<String>,
/// MC 版本。
pub game_version: Option<String>,
/// 启动时间(RFC3339 UTC)。
pub started_at: Option<String>,
/// 结束时间;会话未结束时为 `None`。
pub ended_at: Option<String>,
/// 时长毫秒。
pub duration_ms: u64,
/// 退出码;未正常结束时可能缺失。
pub exit_code: Option<i32>,
/// `exit_type`:`normal|application_error|jvm_error|sigkill|sigterm|killed|interrupted`。
pub exit_type: Option<String>,
/// exit 0 但疑似静默失败(D8 升级 1)。
pub silent_failure: bool,
/// 是否检测到游戏窗口。
pub window_detected: bool,
/// 事件条数。
pub event_count: u64,
/// 是否发现 crash-report / hs_err。
pub crash_found: bool,
/// 规则引擎首选结论 id(`diagnosis` 事件的 top candidate)。
pub diagnosis_top: Option<String>,
}
/// `read_game_log` 的查询条件:**按事件 seq 切片**,不是按行号
/// (stdout/stderr 是一行一事件,但同一条日志行可能被切成多块,见 launch §1)。
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LogQuery {
/// 起始 `seq`(含)。
pub from_seq: Option<u64>,
/// 结束 `seq`(含)。
pub to_seq: Option<u64>,
/// 只要这些 `kind`(空 = 全部)。未知 kind 由实现方忽略而不是报错(前向兼容)。
pub kinds: Vec<String>,
/// 最多返回多少条事件(工具层已钳到 [`crate::tools::session::MAX_LOG_EVENTS`])。
pub max_events: usize,
}
/// 一条事件行(`{v,seq,ts,t_ms,kind,session_id,payload}`),落盘时已脱敏。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct LogEvent {
/// 会话内单调递增序号。
pub seq: u64,
/// RFC3339 UTC。
pub ts: String,
/// 距会话开始的毫秒数。
pub t_ms: u64,
/// 事件类型(`stdout|stderr|exit|crash_found|diagnosis|…`)。
pub kind: String,
/// 事件负载,原样透传(已脱敏)。
pub payload: Value,
}
/// 一页日志事件 + 全量统计(模型拿到摘要就不会盲目翻页,防 token 爆炸)。
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct LogPage {
/// 会话 id。
pub session_id: String,
/// 文件内事件总数。
pub total_events: u64,
/// 命中过滤条件的事件数。
pub matched_events: u64,
/// 是否因 `max_events` 截断。
pub truncated: bool,
/// 全量 kind 计数(不受过滤影响)。
pub kind_counts: BTreeMap<String, u64>,
/// 首事件时间。
pub first_ts: Option<String>,
/// 末事件时间。
pub last_ts: Option<String>,
/// 本次返回的事件(已按 seq 升序)。
pub events: Vec<LogEvent>,
}
/// 会话端口(M18 实现,`ull-core::launch::session_index` + `session` 的读侧)。
///
/// 读取**必须容忍最后一行不完整**(会话被 kill 时 jsonl 尾部可能截断)——这是实现方义务,
/// 由 `launch-接口约定.md` §1 规定,agent 只消费结果。
pub trait GameSessionPort: Send + Sync {
/// 按 `started_at` 倒序、按 `session_id` 去重后的会话列表;`instance_id` 非空时过滤。
fn list_sessions(
&self,
limit: usize,
instance_id: Option<&str>,
) -> PortResult<Vec<GameSessionSummary>>;
/// 按 [`LogQuery`] 切片读取一个会话的事件流。
fn read_log(&self, session_id: &str, query: &LogQuery) -> PortResult<LogPage>;
}
// ───────────────────────── 崩溃诊断(M15) ─────────────────────────
/// 六维修复动作(M15 `diagnose::rules::FixActionKind`,internally-tagged enum,
/// YAML 里写 `kind:`)。序列化名与 M15 逐字相同:`change_java|adjust_memory|
/// change_graphics|remove_mod|reinstall|seek_help`。
#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum FixActionKind {
/// 换 Java(大版本上下界/指定实现)。
ChangeJava,
/// 调 Xmx/Xms、64 位 Java、系统虚拟内存。
AdjustMemory,
/// 驱动/渲染器/分辨率/覆盖层。
ChangeGraphics,
/// 删/禁/换 mod。
RemoveMod,
/// 重装/修组件(java|game_jar|loader|natives|libraries|assets|mods…)。
Reinstall,
/// 导出诊断包 / 需要更多信息。
SeekHelp,
}
/// 一条修复建议(M15 的 `MaterializedFixAction { kind, tool, args }` + 一句人话)。
///
/// `tool` 是 M15 给的**语义动作 id**(`java.set` / `memory.set` / …)。P0 没有这些细分工具,
/// 所以 agent 侧按 [`FixActionKind`] 桥接到现有工具(见 [`crate::tools::diagnose`]),
/// `tool` 只原样透传给模型与审计,不用于分发。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct FixAction {
/// 六维动作类别。
pub kind: FixActionKind,
/// 语义动作 id(如 `memory.set`);P1 落对应工具后可直接当工具名。
pub tool: String,
/// 一句话建议(可为空,agent 会按 `kind` 补兜底文案)。
pub label: String,
/// 已做模板替换与单位换算的参数(M15 `materialize()` 的产物)。
pub args: std::collections::BTreeMap<String, String>,
}
/// 一条诊断候选(M15 `DiagnosisRecord::candidates[]`)。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct DiagnosisCandidate {
/// 规则 id(如 `jvm.32bit`)。
pub id: String,
/// `critical|error|warn|info`。
pub severity: String,
/// 分组(`jvm|memory|graphics|integrity|mod|…`)。
pub category: String,
/// 置信度 0.0~1.0。
pub confidence: f32,
/// i18n key(如 `diagnose.cause.jvm.32bit`)。
pub message_key: String,
/// **渲染后**的人类可读结论(M15 保证非空;agent 侧只在极旧数据上回落 `message_key`)。
pub message: String,
/// 更细的处理建议(M15 `detail`,可能为空)。
pub detail: String,
/// 证据行(已脱敏)。
pub evidence: Vec<String>,
/// 该候选的修复动作。
pub fix_actions: Vec<FixAction>,
}
/// 退出摘要(M15 `DiagnosisRecord::exit`,与 launch 的 `exit` 事件同源)。
#[derive(Debug, Clone, Default, Serialize, PartialEq)]
pub struct ExitSummary {
/// 退出码。
pub code: Option<i32>,
/// `normal|application_error|jvm_error|sigkill|sigterm|killed|interrupted`。
pub exit_type: Option<String>,
/// exit 0 但疑似静默失败。
pub silent_failure: bool,
}
/// 规则引擎结论:**这就是给 LLM 的全部输入**(不是裸日志)。
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct CrashDiagnosis {
/// 会话 id。
pub session_id: String,
/// `rules|ai`(谁产出的)。
pub source: String,
/// 规则拿不准、需要更多信息时置 true(此时才值得让 LLM 深挖)。
pub needs_more_info: bool,
/// 主因候选,`candidates[0]` 即首因(M15 已按 priority→confidence 排序)。
pub candidates: Vec<DiagnosisCandidate>,
/// 被抑制的次要候选。
pub secondary: Vec<DiagnosisCandidate>,
/// 会话级关键片段(`crash_found.excerpt` / `hs_err` 摘要,已脱敏)。
pub evidence: Vec<String>,
/// 退出摘要。
pub exit: ExitSummary,
}
impl CrashDiagnosis {
/// 首选候选(主因)。
#[must_use]
pub fn top(&self) -> Option<&DiagnosisCandidate> {
self.candidates.first()
}
/// 最高置信度(没有候选时为 0)。
#[must_use]
pub fn top_confidence(&self) -> f32 {
self.top().map_or(0.0, |c| c.confidence)
}
}
/// 诊断端口(M15 实现)。agent 只做「调规则引擎 → 把结论 + 片段交给 LLM」。
pub trait DiagnosePort: Send + Sync {
/// 对一个会话跑规则引擎。会话不存在/没有日志时返回人类可读错误。
fn diagnose(&self, session_id: &str) -> PortResult<CrashDiagnosis>;
}
+152
View File
@@ -0,0 +1,152 @@
//! 实例 / 版本 / Java / 账户四个读侧端口(M39 的只读工具集用)。
//!
//! 与 [`super`] 的既有三个端口同形:trait 由 agent 声明,实现在装配层用 `unlucky-core` 填充。
//! 拆分出来的原因是 `port.rs` 挨着 400 行硬上限(`guards.yml` 的 file-size 门禁)——
//! 「会话与日志」「崩溃诊断」留在父模块,「游戏与账户」在这里,语义上也是一刀干净的分界。
//!
//! **凭据红线**(D9 / 02 文档 §3.1):账户端口只露 [`AccountSummary`] 的公开字段。
//! `Credentials`(access token / 刷新令牌 / authlib 密码)在 core 的 Secret 体系里,
//! 根本不出现在本文件的类型里,因此不可能被工具结果带出去。
use serde::Serialize;
use super::PortResult;
// ───────────────────────── 实例 / 版本(M14) ─────────────────────────
/// 一个实例(`profiles.json` 一行)的摘要:模型只需要「能定位、能判断载荷在不在」。
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct InstanceSummary {
/// 实例 id。
pub id: String,
/// 显示名。
pub name: String,
/// 版本 id(如 `1.21.1` / `fabric-loader-0.16.9-1.21.1`)。
pub version_id: String,
/// 该版本的载荷是否真的在 `versions/` 下(`false` = 装了档案但载荷缺失)。
pub version_present: bool,
/// 独立游戏目录(未覆盖时为 `None`)。
pub game_dir: Option<String>,
/// 实例级 Java 覆盖路径(未覆盖时为 `None`)。
pub java_path: Option<String>,
/// 上次启动时刻(Unix 毫秒;从未启动为 `None`)。
pub last_played_at: Option<u64>,
}
/// 已安装版本的摘要(`versions/<id>/` 的存在性 + 可读的元信息)。
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct VersionSummary {
/// 版本 id。
pub id: String,
/// 版本 JSON 里声明的 `type`(`release` / `snapshot` / 加载器自报),读不到为 `None`。
pub kind: Option<String>,
/// 被几个实例引用。
pub instance_count: usize,
}
// ──────────────────────────── Java(M33) ────────────────────────────
/// 一个探测到的 Java 运行时。
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct JavaRuntimeSummary {
/// `java` 可执行文件路径。
pub binary: String,
/// 完整版本串(`21.0.2` / `1.8.0_402`)。
pub version: Option<String>,
/// 主版本号(8 / 17 / 21)。
pub major: Option<u32>,
/// 发行方(temurin / oracle / microsoft / zulu …)。
pub vendor: Option<String>,
/// 来源类别(`instance` / `managed` / `env` / `system`)。
pub origin: String,
}
/// Java 现状(`get_java_status`)。
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct JavaStatus {
/// 默认堆内存(MB,`java.default_memory_mb`)。
pub default_memory_mb: Option<u64>,
/// 托管 JDK 的扫描根。
pub managed_roots: Vec<String>,
/// 探测到的候选(已去重,优先级从高到低)。
pub candidates: Vec<JavaRuntimeSummary>,
}
// ──────────────────────────── 账户(M31) ────────────────────────────
/// 账户的**公开字段**摘要。凭据类字段刻意不存在(凭据红线)。
#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
pub struct AccountSummary {
/// 条目 id。
pub id: String,
/// 轨道:`offline` / `microsoft` / `authlib`。
pub kind: String,
/// Minecraft 档案 UUID(32 位无连字符)。
pub profile_id: String,
/// 玩家名(可能为空串 = 有档案但名字待刷新)。
pub profile_name: String,
/// 登录名(仅 authlib 轨有值)。
pub login_name: Option<String>,
/// 创建时刻(Unix 毫秒)。
pub created_at_ms: u64,
}
/// 游戏资产端口(M14 实例/版本 + M33 Java 探测)。
pub trait GamePort: Send + Sync {
/// 全部实例(按上次启动时间倒序)。
fn list_instances(&self) -> PortResult<Vec<InstanceSummary>>;
/// 已安装版本清单。
fn list_versions(&self) -> PortResult<Vec<VersionSummary>>;
/// Java 现状(候选 + 托管根 + 默认内存)。
fn java_status(&self) -> PortResult<JavaStatus>;
}
/// 账户端口(M31)。实现方只允许读 `AccountStore::accounts()`(`AccountMeta`),
/// **不得**调用 `credentials()`——那是凭据出口,agent 侧没有对应字段可以承接。
pub trait AccountPort: Send + Sync {
/// 账户清单(公开字段)。
fn list_accounts(&self) -> PortResult<Vec<AccountSummary>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn account_summary_has_no_credential_fields() {
// 把摘要序列化成 JSON:任何 token / password / secret 形态的键都不许出现。
// 这是凭据红线的**可执行断言**——将来有人往结构体里加字段,这条测试先炸。
let summary = AccountSummary {
id: "a1".to_string(),
kind: "offline".to_string(),
profile_id: "0123456789abcdef0123456789abcdef".to_string(),
profile_name: "Steve".to_string(),
login_name: Some("steve@example.com".to_string()),
created_at_ms: 1_793_304_753_123,
};
let json = serde_json::to_string(&summary).expect("可序列化");
for forbidden in ["token", "password", "secret", "credential", "refresh"] {
assert!(
!json.to_lowercase().contains(forbidden),
"账户摘要不得包含 `{forbidden}`:{json}"
);
}
}
#[test]
fn java_status_round_trips() {
let status = JavaStatus {
default_memory_mb: Some(2048),
managed_roots: vec!["/data/java-managed".to_string()],
candidates: vec![JavaRuntimeSummary {
binary: "/jdk/bin/java".to_string(),
version: Some("21.0.2".to_string()),
major: Some(21),
vendor: Some("temurin".to_string()),
origin: "managed".to_string(),
}],
};
assert_eq!(status.candidates.len(), 1);
assert_eq!(status.candidates[0].major, Some(21));
}
}
+217
View File
@@ -0,0 +1,217 @@
//! 脱敏:审计日志的参数、以及日志工具返回文本的**第二道**防线。
//!
//! 第一道在 launch 落盘时(`launch-接口约定.md` §4:`<redacted:token>` / `<home>` /
//! `<redacted:opaque>`),所以这里不重复实现那套;本模块只兜两件事:
//! 1. 审计日志里的参数可能含 API key(`set_config` 能改 AI 端点)→ 按键名掩码;
//! 2. 日志正文万一含用户主目录绝对路径(旧会话、第三方 mod 输出)→ 掩码用户名段。
//!
//! 幂等:对已脱敏文本再跑一遍结果不变(`<home>` / `***` 原样保留)。
use serde_json::{Map, Value};
/// 掩码占位。
pub const MASK: &str = "***";
/// 键名是否敏感(不区分大小写,含子串即算)。
///
/// 覆盖:`api_key` / `apikey` / `accessToken` / `session_token` / `password` /
/// `secret` / `authorization` / `credential`。
#[must_use]
pub fn is_sensitive_key(key: &str) -> bool {
const NEEDLES: [&str; 8] = [
"api_key",
"apikey",
"token",
"password",
"passwd",
"secret",
"authorization",
"credential",
];
let lower = key.to_ascii_lowercase();
NEEDLES.iter().any(|n| lower.contains(n))
}
/// 审计用:递归把敏感键的值换成 [`MASK`](保留结构,读审计的人仍能看出改的是哪个键)。
///
/// 除了「键名本身敏感」之外,还认 `set_config {path, value}` 这种**值随路径敏感**的形状:
/// 当同级的 `path` 是敏感键名(`ai.api_key`)时,`value`/`old`/`new` 一律掩码——
/// 否则审计日志会把 API key 原文写进磁盘。
#[must_use]
pub fn redact_args(value: &Value) -> Value {
match value {
Value::Object(map) => {
let sensitive_path = map
.get("path")
.and_then(Value::as_str)
.is_some_and(is_sensitive_key);
let mut out = Map::with_capacity(map.len());
for (k, v) in map {
let mask = is_sensitive_key(k)
|| (sensitive_path && matches!(k.as_str(), "value" | "old" | "new"));
let masked = if mask {
Value::String(MASK.to_string())
} else {
redact_args(v)
};
out.insert(k.clone(), masked);
}
Value::Object(out)
}
Value::Array(items) => Value::Array(items.iter().map(redact_args).collect()),
other => other.clone(),
}
}
/// 文本脱敏:用户主目录段 + `Bearer` 令牌。已脱敏文本原样返回(幂等)。
#[must_use]
pub fn redact_text(text: &str) -> String {
let masked = mask_user_dirs(text);
mask_bearer(&masked)
}
/// 任意 JSON 的每个字符串都过 [`redact_text`](工具结果出口的第二道防线)。
///
/// 与 [`redact_args`] 的分工:那个按键名掩码(审计参数),这个按**内容**掩码
/// (日志正文、账户展示名之类可能夹带主目录/Bearer 的字符串)。
#[must_use]
pub fn redact_texts(value: &Value) -> Value {
match value {
Value::String(text) => Value::String(redact_text(text)),
Value::Array(items) => Value::Array(items.iter().map(redact_texts).collect()),
Value::Object(map) => Value::Object(
map.iter()
.map(|(key, child)| (key.clone(), redact_texts(child)))
.collect(),
),
other => other.clone(),
}
}
/// `C:\Users\<名>` / `/home/<名>` / `/Users/<名>` → 用户名段替换为 [`MASK`]。
fn mask_user_dirs(text: &str) -> String {
let lower = text.to_ascii_lowercase();
let mut out = String::with_capacity(text.len());
let mut cursor = 0usize;
while cursor < text.len() {
let Some((start, marker_len)) = find_marker(&lower, cursor) else {
out.push_str(&text[cursor..]);
break;
};
out.push_str(&text[cursor..start + marker_len]);
let name_start = start + marker_len;
let name_end = segment_end(text, name_start);
let segment = &text[name_start..name_end];
if segment.is_empty() || segment == MASK || segment.eq_ignore_ascii_case("<home>") {
out.push_str(segment);
} else {
out.push_str(MASK);
}
cursor = name_end;
}
out
}
/// 找最靠前的用户目录标记,返回 `(字节位置, 标记长度)`。标记须与 `lower` 同源。
fn find_marker(lower: &str, from: usize) -> Option<(usize, usize)> {
const MARKERS: [&str; 3] = ["c:\\users\\", "/home/", "/users/"];
MARKERS
.iter()
.filter_map(|m| lower[from..].find(m).map(|p| (from + p, m.len())))
.min_by_key(|(start, _)| *start)
}
/// 从 `from` 起取到下一个路径分隔符/空白/引号为止。
fn segment_end(text: &str, from: usize) -> usize {
const STOPS: [char; 9] = ['\\', '/', '"', '\'', ' ', '\t', '\n', '\r', ','];
text[from..]
.find(STOPS)
.map_or(text.len(), |offset| from + offset)
}
/// `Bearer <token>` → `Bearer ***`。
fn mask_bearer(text: &str) -> String {
let mut out = String::with_capacity(text.len());
let mut cursor = 0usize;
while let Some(pos) = text[cursor..].find("Bearer ") {
let token_start = cursor + pos + "Bearer ".len();
let token_end = segment_end(text, token_start);
out.push_str(&text[cursor..token_start]);
if token_end > token_start {
out.push_str(MASK);
}
cursor = token_end;
}
out.push_str(&text[cursor..]);
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn masks_sensitive_arg_keys_only() {
let args = json!({
"path": "launcher.theme",
"value": "light",
"nested": { "accessToken": "abc", "keep": 1 },
"list": [{ "password": "p" }]
});
let red = redact_args(&args);
// 非敏感路径:值原样保留(审计要能看出改成了什么)
assert_eq!(red["value"], json!("light"));
assert_eq!(red["path"], json!("launcher.theme"));
// 键名敏感:值掩码
assert_eq!(red["nested"]["accessToken"], json!(MASK));
assert_eq!(red["nested"]["keep"], json!(1));
assert_eq!(red["list"][0]["password"], json!(MASK));
}
#[test]
fn masks_value_when_path_itself_is_sensitive() {
// `set_config {path: "ai.api_key", value: "sk-…"}` 是最容易漏的泄漏点
let args = json!({ "path": "ai.api_key", "value": "sk-super-secret" });
let red = redact_args(&args);
assert_eq!(red["value"], json!(MASK));
let rendered = red.to_string();
assert!(!rendered.contains("sk-super-secret"), "{rendered}");
}
#[test]
fn masks_windows_and_posix_home() {
assert_eq!(
redact_text(r"C:\Users\aska\.minecraft\logs\latest.log"),
r"C:\Users\***\.minecraft\logs\latest.log"
);
assert_eq!(
redact_text("/home/aska/.minecraft/logs"),
"/home/***/.minecraft/logs"
);
}
#[test]
fn keeps_already_redacted_and_is_idempotent() {
let once = redact_text(r"C:\Users\aska\game\log.txt");
assert_eq!(once, r"C:\Users\***\game\log.txt");
assert_eq!(redact_text(&once), once);
assert_eq!(redact_text("<home>/.minecraft"), "<home>/.minecraft");
}
#[test]
fn masks_bearer_token() {
assert_eq!(
redact_text("Authorization: Bearer eyJhbGciOi.payload.sig"),
"Authorization: Bearer ***"
);
}
#[test]
fn detects_sensitive_key_names() {
assert!(is_sensitive_key("ai.api_key"));
assert!(is_sensitive_key("AccessToken"));
assert!(is_sensitive_key("proxy.password"));
assert!(!is_sensitive_key("download.concurrency"));
}
}
+260
View File
@@ -0,0 +1,260 @@
//! 工具注册表:整个 agent 的**唯一真相源**。
//!
//! 一个 `ToolSpec`(名称 + 描述 + serde JSON Schema)投影两份:
//! - 内置客户端的 rig `DynamicTool` 视图;
//! - 对外 MCP server 的 rmcp `ToolRouter` 视图。
//!
//! 两份投影必须一致,用契约测试固定(同 name / 同 description / 同 schema)。
//! 设计依据:`DevDocs/PlanDoc/02-ai-agent-design.md` §1。
//!
//! 工具 v1 清单(M16 起,M39 扩到十个):`get_config` / `set_config` / `get_config_schema` /
//! `list_instances` / `list_versions` / `get_java_status` / `list_accounts` /
//! `list_game_sessions` / `read_game_log` / `diagnose_crash`。
//!
//! 安全策略随工具走:敏感键分级确认、YOLO 模式标记、审计留痕(02 §3.1 / §4b)。
//!
//! ## 落地形态
//!
//! ```text
//! registry(Vec<ToolSpec>)
//! ├─ definitions() → rig `DynamicTool::new` (内置 agent,`brain::rig`)
//! └─ definitions() → rmcp `ToolRoute::new_dyn` (外部 MCP,`mcp::projection`)
//! ```
//!
//! 防漂移的关键一招(research/02 §6.2 建议进 CI):**契约测试**遍历注册表,断言两侧
//! 投影拿到的 `(name, description, schema)` 逐字节相等。因为两侧都只吃
//! [`ToolDefinition`],这条约束在本 crate 里天然成立——测试只需要锁住
//! 「definition 是纯投影」+「schema 根必须是 object」+「名字不重复」。
//!
//! 注册表**不持有任何端口**:工具闭包在构造时就捕获了 `Arc<dyn …Port>`,注册表只是索引。
pub mod schema;
pub mod spec;
pub mod validate;
use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::sync::Arc;
pub use spec::{
Access, Confirmation, ToolCtx, ToolDefinition, ToolError, ToolFn, ToolOutput, ToolSpec,
};
/// 注册失败原因。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RegistryError {
/// 工具名为空或重复。
DuplicateName(String),
/// schema 不合法(根必须是 `type: object`,否则 MCP 侧直接拒收)。
InvalidSchema {
/// 工具名。
tool: String,
/// 原因。
reason: String,
},
/// 说明为空(模型靠 description 选工具,空说明等于没有这个工具)。
EmptyDescription(String),
}
impl fmt::Display for RegistryError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::DuplicateName(name) => write!(f, "工具名重复或为空:`{name}`"),
Self::InvalidSchema { tool, reason } => {
write!(f, "工具 `{tool}` 的 schema 不合法:{reason}")
}
Self::EmptyDescription(name) => write!(f, "工具 `{name}` 缺少说明"),
}
}
}
impl std::error::Error for RegistryError {}
/// 工具注册表。
#[derive(Debug, Default, Clone)]
pub struct ToolRegistry {
specs: Vec<Arc<ToolSpec>>,
index: BTreeMap<String, usize>,
}
impl ToolRegistry {
/// 空注册表。
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// 注册一个工具。注册即校验名/schema/说明,**运行时不再做二次判断**。
///
/// # Errors
/// 名字重复或为空、schema 根不是 object、说明为空时返回 [`RegistryError`]。
pub fn register(&mut self, spec: ToolSpec) -> Result<(), RegistryError> {
let name = spec.name.trim();
if name.is_empty() || self.index.contains_key(name) {
return Err(RegistryError::DuplicateName(name.to_string()));
}
if spec.description.trim().is_empty() {
return Err(RegistryError::EmptyDescription(name.to_string()));
}
if spec.input_schema.get("type").and_then(|t| t.as_str()) != Some("object") {
return Err(RegistryError::InvalidSchema {
tool: name.to_string(),
reason: "根类型必须是 object(rig 与 rmcp 的入参都是对象 schema)".to_string(),
});
}
self.index.insert(name.to_string(), self.specs.len());
self.specs.push(Arc::new(spec));
Ok(())
}
/// 按名查找。
#[must_use]
pub fn get(&self, name: &str) -> Option<&Arc<ToolSpec>> {
self.index.get(name).and_then(|i| self.specs.get(*i))
}
/// 全部工具(按注册顺序,模型看到的顺序稳定)。
#[must_use]
pub fn specs(&self) -> &[Arc<ToolSpec>] {
&self.specs
}
/// 工具名列表(错误提示/审计用)。
#[must_use]
pub fn names(&self) -> Vec<&str> {
self.specs.iter().map(|s| s.name).collect()
}
/// 工具数量。
#[must_use]
pub fn len(&self) -> usize {
self.specs.len()
}
/// 是否没有工具。
#[must_use]
pub fn is_empty(&self) -> bool {
self.specs.is_empty()
}
/// **投影 1/2 的公共载荷**:`(name, description, input_schema)`。
#[must_use]
pub fn definitions(&self) -> Vec<ToolDefinition> {
self.specs.iter().map(|s| s.definition()).collect()
}
/// 只读子集(P1 的 `--readonly` 外部 MCP 模式用)。
#[must_use]
pub fn read_only_definitions(&self) -> Vec<ToolDefinition> {
self.specs
.iter()
.filter(|s| s.access == Access::ReadOnly)
.map(|s| s.definition())
.collect()
}
/// **只读模式**的注册表副本(外部 MCP 默认形态)。
///
/// 返回的是「物理上不含写工具」的新注册表:`tools/list` 里看不到 `set_config`,
/// 硬调它也会在编排层得到 `unknown_tool`(并留一条审计),而不是静默执行。
/// 这比「列表过滤 + 调用拦截」两套逻辑更不容易漏——只有一份子集,两侧天然一致。
#[must_use]
pub fn read_only_subset(&self) -> Self {
let mut subset = Self::new();
for spec in self.specs.iter().filter(|s| s.access == Access::ReadOnly) {
let name = spec.name.to_string();
if subset.index.insert(name, subset.specs.len()).is_none() {
subset.specs.push(Arc::clone(spec));
}
}
subset
}
/// 名 → access(装配处检查白名单/只读模式)。
#[must_use]
pub fn access_of(&self, name: &str) -> Option<Access> {
self.get(name).map(|s| s.access)
}
/// 去重后的名字集合(契约测试用)。
#[must_use]
pub fn unique_names(&self) -> BTreeSet<&str> {
self.specs.iter().map(|s| s.name).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registry::schema::{non_empty_string, object};
use serde_json::{json, Value};
fn echo(name: &'static str) -> ToolSpec {
ToolSpec::read_only(
name,
"回显",
object(&[("text", non_empty_string("文本"))], &["text"]),
Arc::new(|_ctx: &ToolCtx, args: &Value| Ok(ToolOutput::ok(args.clone(), "echo"))),
)
}
#[test]
fn register_and_lookup() {
let mut reg = ToolRegistry::new();
reg.register(echo("echo")).unwrap();
assert_eq!(reg.len(), 1);
assert_eq!(reg.names(), vec!["echo"]);
assert!(reg.get("echo").is_some());
assert!(reg.get("nope").is_none());
assert_eq!(reg.access_of("echo"), Some(Access::ReadOnly));
}
#[test]
fn rejects_duplicate_empty_and_non_object_schema() {
let mut reg = ToolRegistry::new();
reg.register(echo("echo")).unwrap();
assert_eq!(
reg.register(echo("echo")),
Err(RegistryError::DuplicateName("echo".into()))
);
let bad = ToolSpec::read_only(
"bad",
"x",
json!({ "type": "array" }),
Arc::new(|_, _| Ok(ToolOutput::ok(Value::Null, "x"))),
);
assert!(matches!(
reg.register(bad),
Err(RegistryError::InvalidSchema { .. })
));
let no_desc = ToolSpec::read_only(
"nodesc",
" ",
json!({ "type": "object" }),
Arc::new(|_, _| Ok(ToolOutput::ok(Value::Null, "x"))),
);
assert!(matches!(
reg.register(no_desc),
Err(RegistryError::EmptyDescription(_))
));
}
#[test]
fn definitions_are_stable_and_filterable() {
let mut reg = ToolRegistry::new();
reg.register(echo("a")).unwrap();
reg.register(ToolSpec::mutating(
"b",
"写",
json!({ "type": "object" }),
Arc::new(|_, _| Ok(ToolOutput::ok(Value::Null, "b"))),
))
.unwrap();
assert_eq!(reg.definitions().len(), 2);
assert_eq!(reg.read_only_definitions().len(), 1);
assert_eq!(reg.definitions()[0].name, "a");
assert_eq!(reg.unique_names().len(), 2);
}
}
+116
View File
@@ -0,0 +1,116 @@
//! JSON Schema 构造helper。
//!
//! 工具参数 schema 一律**手写 JSON**(research/02 §6.2:`rig` 的 `DynamicTool::new` 与
//! rmcp 的 `ToolRoute::new_dyn` 吃的都是裸 `serde_json::Value`),所以不需要 schemars 派生。
//! 手写的好处是同一份 schema 直接喂两方,坏处是啰嗦——这个模块把啰嗦收敛到几个函数。
//!
//! 生成的 schema 一律按 **JSON Schema 2020-12** 的写法(rmcp 支持该版本;
//! `additionalProperties: false` 让模型少给野参数,[`super::validate`] 会执行它)。
use serde_json::{json, Map, Value};
/// 对象 schema。`properties` 按给定顺序写入(JSON 对象保序,UI 展示稳定)。
#[must_use]
pub fn object(properties: &[(&str, Value)], required: &[&str]) -> Value {
let mut props = Map::new();
for (name, schema) in properties {
props.insert((*name).to_string(), schema.clone());
}
json!({
"type": "object",
"properties": Value::Object(props),
"required": required,
"additionalProperties": false,
})
}
/// 任意 JSON 值(不校验类型)。
#[must_use]
pub fn any() -> Value {
json!({})
}
/// 字符串。
#[must_use]
pub fn string(description: &str) -> Value {
json!({ "type": "string", "description": description })
}
/// 非空字符串(`minLength: 1`,省掉一堆「路径不能为空」的运行时判断)。
#[must_use]
pub fn non_empty_string(description: &str) -> Value {
json!({ "type": "string", "description": description, "minLength": 1 })
}
/// 枚举字符串。
#[must_use]
pub fn string_enum(values: &[&str], description: &str) -> Value {
json!({ "type": "string", "description": description, "enum": values })
}
/// 布尔。
#[must_use]
pub fn boolean(description: &str) -> Value {
json!({ "type": "boolean", "description": description })
}
/// 带范围约束的整数。
#[must_use]
pub fn integer(description: &str, minimum: i64, maximum: i64) -> Value {
json!({
"type": "integer",
"description": description,
"minimum": minimum,
"maximum": maximum,
})
}
/// 字符串数组(可选条数上限)。
#[must_use]
pub fn string_array(description: &str, max_items: u64) -> Value {
json!({
"type": "array",
"description": description,
"items": { "type": "string" },
"maxItems": max_items,
})
}
/// 枚举字符串数组(如 `kinds: ["stderr","exit"]`)。
#[must_use]
pub fn enum_string_array(values: &[&str], description: &str, max_items: u64) -> Value {
json!({
"type": "array",
"description": description,
"items": { "type": "string", "enum": values },
"maxItems": max_items,
"uniqueItems": true,
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registry::validate::validate;
#[test]
fn object_records_required_and_forbids_extras() {
let schema = object(
&[("path", non_empty_string("键路径")), ("value", any())],
&["path", "value"],
);
assert_eq!(schema["type"], json!("object"));
assert_eq!(schema["additionalProperties"], json!(false));
assert_eq!(schema["required"], json!(["path", "value"]));
assert!(validate(&schema, &json!({ "path": "a", "value": 1 })).is_ok());
}
#[test]
fn integer_builder_carries_bounds() {
let schema = integer("条数", 1, 500);
assert_eq!(schema["minimum"], json!(1));
assert_eq!(schema["maximum"], json!(500));
assert!(validate(&schema, &json!(0)).is_err());
assert!(validate(&schema, &json!(500)).is_ok());
}
}
+262
View File
@@ -0,0 +1,262 @@
//! 工具的**唯一定义类型**([`ToolSpec`])与它的两份投影载荷([`ToolDefinition`])。
//!
//! 双投影的支点在 research/02 §6.2:`rig::tool::DynamicTool::new(name, description,
//! parameters: serde_json::Value, ..)` 与 `rmcp::ToolRoute::new_dyn(name, description,
//! schema, handler)` 的入参**都是裸 JSON Schema**。所以本 crate 只维护一份
//! [`ToolSpec`],由 [`ToolSpec::definition`] 生成两侧共用的 `(name, description, schema)`。
//!
//! 工具实现是**同步**的:端口调用全是本地文件/内存,没有网络 IO;异步只存在于
//! provider 边界([`crate::brain::provider::ChatProvider`])。P1 若出现网络类工具
//! (mod 搜索/版本安装)再升成 `Fn -> BoxFuture`,不影响调用方语义。
use std::fmt;
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::confirm::Sensitivity;
/// 工具的副作用等级(外部 MCP 只读模式、P1 的 `--readonly` 都按它筛)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum Access {
/// 只读:可以给外部 agent、可以在无确认的情况下调用。
ReadOnly,
/// 会改用户数据(写配置),受白名单 + 分级确认约束。
Mutating,
}
/// 工具定义的三元组:**双投影就投这个**。
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolDefinition {
/// 工具名(模型可见,`snake_case`)。
pub name: String,
/// 一句话说明(模型可见)。
pub description: String,
/// 参数 JSON Schema(2020-12,根类型必须 `object`)。
pub input_schema: Value,
}
/// 工具调用上下文:编排层注入,工具只读。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolCtx {
/// agent 对话会话 id(审计用;与游戏 session_id 不是一回事)。
pub agent_session_id: String,
/// 是否已获确认。**只有编排层能置 true**(YOLO 或用户点了允许),
/// 工具据此决定「先报价再执行」还是「直接执行」。
pub confirmed: bool,
}
/// 工具的返回。
#[derive(Debug, Clone, PartialEq)]
pub struct ToolOutput {
/// 给模型/审计的结构化结果(编排层序列化成 JSON 字符串回灌)。
pub content: Value,
/// 一句话摘要(UI 展示 + 审计 summary)。
pub summary: String,
/// 非空表示「这次没执行,先要确认」([`crate::confirm::ConfirmRequest`] 的原料)。
pub confirmation: Option<Confirmation>,
}
/// 待确认的操作详情(dry-run 的产物)。
#[derive(Debug, Clone, PartialEq)]
pub struct Confirmation {
/// 一句话请求(「AI 请求把 X 从 A 改为 B」)。
pub summary: String,
/// 结构化 diff(`{"path":…,"old":…,"new":…}`)。
pub details: Value,
/// 敏感等级(决定 YOLO 能不能跳过)。
pub sensitivity: Sensitivity,
}
impl ToolOutput {
/// 成功返回。
#[must_use]
pub fn ok(content: Value, summary: impl Into<String>) -> Self {
Self {
content,
summary: summary.into(),
confirmation: None,
}
}
/// 需要确认(本次**没有**产生副作用)。
#[must_use]
pub fn needs_confirmation(
summary: impl Into<String>,
details: Value,
sensitivity: Sensitivity,
) -> Self {
let summary = summary.into();
Self {
content: serde_json::json!({
"status": "needs_confirmation",
"summary": summary,
}),
confirmation: Some(Confirmation {
summary: summary.clone(),
details,
sensitivity,
}),
summary,
}
}
}
/// 工具错误。**全部面向用户可读**——它们会作为工具结果回到模型,
/// 由模型决定重试还是换方案(rmcp 的 `Ok(CallToolResult::error(..))` 同义,
/// 见 research/02 §3.2:协议级 `Err` 会被客户端吞掉,不能用来报业务错误)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToolError {
/// 参数语义不合法(schema 校验之外的规则,如路径不在白名单)。
NotAllowed(String),
/// 找不到对象(会话/键/文件)。
NotFound(String),
/// 端口(M12/M15/M18)报错,文本原样透传。
Port(String),
/// 工具自身内部错误(不该发生)。
Internal(String),
}
impl ToolError {
/// 一句话文案(写日志/审计用)。
#[must_use]
pub fn message(&self) -> &str {
match self {
Self::NotAllowed(m) | Self::NotFound(m) | Self::Port(m) | Self::Internal(m) => m,
}
}
/// 错误码(审计与 UI 分类用)。
#[must_use]
pub fn code(&self) -> &'static str {
match self {
Self::NotAllowed(_) => "not_allowed",
Self::NotFound(_) => "not_found",
Self::Port(_) => "port_error",
Self::Internal(_) => "internal",
}
}
}
impl fmt::Display for ToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for ToolError {}
/// 工具处理函数。
pub type ToolFn = Arc<dyn Fn(&ToolCtx, &Value) -> Result<ToolOutput, ToolError> + Send + Sync>;
/// 一个工具的完整定义 + 实现。
#[derive(Clone)]
pub struct ToolSpec {
/// 工具名(`snake_case`,同时是 MCP 侧的工具名)。
pub name: &'static str,
/// 说明。
pub description: &'static str,
/// 参数 schema(根必须 object)。
pub input_schema: Value,
/// 副作用等级。
pub access: Access,
/// 实现。
pub handler: ToolFn,
}
impl fmt::Debug for ToolSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ToolSpec")
.field("name", &self.name)
.field("access", &self.access)
.finish_non_exhaustive()
}
}
impl ToolSpec {
/// 建一个只读工具。
#[must_use]
pub fn read_only(
name: &'static str,
description: &'static str,
input_schema: Value,
handler: ToolFn,
) -> Self {
Self {
name,
description,
input_schema,
access: Access::ReadOnly,
handler,
}
}
/// 建一个会改数据的工具。
#[must_use]
pub fn mutating(
name: &'static str,
description: &'static str,
input_schema: Value,
handler: ToolFn,
) -> Self {
Self {
name,
description,
input_schema,
access: Access::Mutating,
handler,
}
}
/// 投影成两侧共用的 `(name, description, schema)`。
#[must_use]
pub fn definition(&self) -> ToolDefinition {
ToolDefinition {
name: self.name.to_string(),
description: self.description.to_string(),
input_schema: self.input_schema.clone(),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registry::schema::{non_empty_string, object};
use serde_json::json;
fn echo_handler() -> ToolFn {
Arc::new(|_ctx: &ToolCtx, args: &Value| Ok(ToolOutput::ok(args.clone(), "echo")))
}
#[test]
fn definition_is_a_pure_projection() {
let spec = ToolSpec::read_only(
"echo",
"回显",
object(&[("text", non_empty_string("文本"))], &["text"]),
echo_handler(),
);
let def = spec.definition();
assert_eq!(def.name, "echo");
assert_eq!(def.description, "回显");
assert_eq!(def.input_schema, spec.input_schema);
assert_eq!(spec.access, Access::ReadOnly);
}
#[test]
fn confirmation_carries_details() {
let out = ToolOutput::needs_confirmation(
"AI 请求修改 x",
json!({ "path": "x" }),
Sensitivity::High,
);
assert_eq!(out.content["status"], json!("needs_confirmation"));
let confirmation = out.confirmation.expect("必须有待确认详情");
assert_eq!(confirmation.sensitivity, Sensitivity::High);
assert_eq!(confirmation.summary, out.summary);
assert_eq!(confirmation.details, json!({ "path": "x" }));
}
}
+332
View File
@@ -0,0 +1,332 @@
//! 参数校验:JSON Schema 2020-12 的**最小子集**实现。
//!
//! 为什么不引 `jsonschema` crate:agent 的 schema 全是自己手写的([`super::schema`]),
//! 用到的关键字只有 `type/required/properties/additionalProperties/enum/minimum/maximum/
//! minLength/minItems/maxItems/uniqueItems/items`。三百行的校验器换掉一棵依赖树,
//! 对 Win7 单文件形态(D12)值得。
//!
//! 校验失败的文案是给**模型**看的(它会据此改正参数重试),所以要具体:
//! 「参数 `limit` 必须是 1~500 的整数,实际是 2000」,不是 `schema validation failed`。
use serde_json::Value;
/// 校验入口。返回全部错误(一次给全,省模型来回试错)。
///
/// # Errors
/// 参数不符合 schema 时返回人类可读的错误列表。
pub fn validate(schema: &Value, args: &Value) -> Result<(), Vec<String>> {
let mut errors = Vec::new();
validate_at(schema, args, "", &mut errors);
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// 只取第一条错误(日志/审计摘要用)。
#[must_use]
pub fn first_error(schema: &Value, args: &Value) -> Option<String> {
validate(schema, args)
.err()
.and_then(|errors| errors.into_iter().next())
}
fn validate_at(schema: &Value, value: &Value, path: &str, errors: &mut Vec<String>) {
let Some(schema) = schema.as_object() else {
return; // `{}` = 任意值
};
if let Some(expected) = schema.get("type").and_then(Value::as_str) {
if !type_matches(expected, value) {
errors.push(format!(
"参数 {} 应为 {},实际是 {}",
label(path),
expected,
type_name(value)
));
return; // 类型都不对,后面的范围检查没有意义
}
}
if let Some(allowed) = schema.get("enum").and_then(Value::as_array) {
if !allowed.iter().any(|v| v == value) {
let list: Vec<String> = allowed.iter().map(render).collect();
errors.push(format!(
"参数 {} 只能取 [{}],实际是 {}",
label(path),
list.join(", "),
render(value)
));
}
}
check_bounds(schema, value, path, errors);
match value {
Value::Object(map) => {
let required = schema.get("required").and_then(Value::as_array);
for name in required.into_iter().flatten().filter_map(Value::as_str) {
if !map.contains_key(name) {
errors.push(format!("缺少必填参数 {}", label(&join(path, name))));
}
}
let properties = schema.get("properties").and_then(Value::as_object);
for (key, entry) in map {
match properties.and_then(|p| p.get(key)) {
Some(sub) => validate_at(sub, entry, &join(path, key), errors),
None => {
if schema.get("additionalProperties").and_then(Value::as_bool)
== Some(false)
{
let known: Vec<&str> = properties
.map(|p| p.keys().map(String::as_str).collect())
.unwrap_or_default();
errors.push(format!(
"参数 {} 不是可接受的参数名(可用:{})",
label(&join(path, key)),
if known.is_empty() {
"无".to_string()
} else {
known.join(", ")
}
));
}
}
}
}
}
Value::Array(items) => {
if let Some(sub) = schema.get("items") {
for (i, item) in items.iter().enumerate() {
validate_at(sub, item, &format!("{path}[{i}]"), errors);
}
}
}
_ => {}
}
}
fn check_bounds(
schema: &serde_json::Map<String, Value>,
value: &Value,
path: &str,
errors: &mut Vec<String>,
) {
let number = value.as_f64();
let minimum = schema.get("minimum").and_then(Value::as_f64);
let maximum = schema.get("maximum").and_then(Value::as_f64);
if let (Some(n), Some(min), Some(max)) = (number, minimum, maximum) {
if n < min || n > max {
errors.push(format!(
"参数 {} 必须在 {}~{} 之间,实际是 {}",
label(path),
render_number(min),
render_number(max),
render_number(n)
));
return;
}
} else if let (Some(n), Some(min)) = (number, minimum) {
if n < min {
errors.push(format!(
"参数 {} 不能小于 {},实际是 {}",
label(path),
render_number(min),
render_number(n)
));
}
} else if let (Some(n), Some(max)) = (number, maximum) {
if n > max {
errors.push(format!(
"参数 {} 不能大于 {},实际是 {}",
label(path),
render_number(max),
render_number(n)
));
}
}
if let Some(text) = value.as_str() {
if let Some(min_len) = schema.get("minLength").and_then(Value::as_u64) {
if (text.chars().count() as u64) < min_len {
errors.push(format!(
"参数 {} 不能为空(最少 {} 个字符)",
label(path),
min_len
));
}
}
}
if let Some(items) = value.as_array() {
if let Some(max_items) = schema.get("maxItems").and_then(Value::as_u64) {
if items.len() as u64 > max_items {
errors.push(format!(
"参数 {} 最多 {} 项,实际 {} 项",
label(path),
max_items,
items.len()
));
}
}
if let Some(min_items) = schema.get("minItems").and_then(Value::as_u64) {
if (items.len() as u64) < min_items {
errors.push(format!(
"参数 {} 至少 {} 项,实际 {} 项",
label(path),
min_items,
items.len()
));
}
}
if schema.get("uniqueItems").and_then(Value::as_bool) == Some(true) {
if let Some(duplicate) = first_duplicate(items) {
errors.push(format!(
"参数 {} 不能有重复项({} 出现了多次)",
label(path),
render(duplicate)
));
}
}
}
}
/// 数组里第一个重复出现的元素(`uniqueItems` 用;`null` 也算一个值)。
fn first_duplicate(items: &[Value]) -> Option<&Value> {
items
.iter()
.enumerate()
.find(|(index, item)| items.iter().take(*index).any(|prev| prev == *item))
.map(|(_, item)| item)
}
fn type_matches(expected: &str, value: &Value) -> bool {
match expected {
"object" => value.is_object(),
"array" => value.is_array(),
"string" => value.is_string(),
"boolean" => value.is_boolean(),
"null" => value.is_null(),
"integer" => value.as_f64().is_some_and(|n| n.fract() == 0.0),
"number" => value.is_number(),
_ => true, // 未知关键字不拦(前向兼容)
}
}
fn type_name(value: &Value) -> &'static str {
match value {
Value::Null => "null",
Value::Bool(_) => "boolean",
Value::Number(n) if n.as_f64().is_some_and(|f| f.fract() == 0.0) => "integer",
Value::Number(_) => "number",
Value::String(_) => "string",
Value::Array(_) => "array",
Value::Object(_) => "object",
}
}
fn label(path: &str) -> String {
if path.is_empty() {
"(根)".to_string()
} else {
format!("`{path}`")
}
}
fn join(path: &str, key: &str) -> String {
if path.is_empty() {
key.to_string()
} else {
format!("{path}.{key}")
}
}
fn render(value: &Value) -> String {
match value {
Value::String(s) => format!("\"{s}\""),
other => other.to_string(),
}
}
fn render_number(n: f64) -> String {
if n.fract() == 0.0 {
format!("{}", n as i64)
} else {
n.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::registry::schema::{
enum_string_array, integer, non_empty_string, object, string_array, string_enum,
};
use serde_json::json;
fn errors(schema: &Value, args: &Value) -> Vec<String> {
validate(schema, args).unwrap_err()
}
#[test]
fn accepts_valid_and_reports_missing_required() {
let schema = object(
&[("session_id", non_empty_string("会话 id"))],
&["session_id"],
);
assert!(validate(&schema, &json!({ "session_id": "20261029T124501-9f3c2a" })).is_ok());
let errs = errors(&schema, &json!({}));
assert_eq!(errs.len(), 1);
assert!(errs[0].contains("缺少必填参数 `session_id`"), "{errs:?}");
}
#[test]
fn rejects_empty_string_and_wrong_type() {
let schema = object(
&[("session_id", non_empty_string("会话 id"))],
&["session_id"],
);
assert!(errors(&schema, &json!({ "session_id": "" }))[0].contains("不能为空"));
assert!(errors(&schema, &json!({ "session_id": 1 }))[0].contains("应为 string"));
}
#[test]
fn rejects_out_of_range_and_unknown_keys() {
let schema = object(
&[
("limit", integer("条数", 1, 500)),
("kinds", string_array("类型", 8)),
],
&[],
);
let errs = errors(&schema, &json!({ "limit": 2000 }));
assert!(errs[0].contains("1~500"), "{errs:?}");
let errs = errors(&schema, &json!({ "limit": 1, "evil": true }));
assert!(errs[0].contains("不是可接受的参数名"), "{errs:?}");
}
#[test]
fn checks_enum_and_nested_objects() {
let schema = object(&[("level", string_enum(&["error", "warn"], "级别"))], &[]);
assert!(validate(&schema, &json!({ "level": "error" })).is_ok());
assert!(errors(&schema, &json!({ "level": "fatal" }))[0].contains("只能取"));
}
#[test]
fn rejects_duplicate_items_when_unique() {
let schema = object(
&[("kinds", enum_string_array(&["stderr", "exit"], "类型", 4))],
&[],
);
let errs = errors(&schema, &json!({ "kinds": ["stderr", "exit", "stderr"] }));
assert!(errs[0].contains("不能有重复项"), "{errs:?}");
assert!(validate(&schema, &json!({ "kinds": ["stderr", "exit"] })).is_ok());
}
#[test]
fn integer_type_rejects_fraction() {
assert!(validate(&json!({ "type": "integer" }), &json!(1.5)).is_err());
assert!(validate(&json!({ "type": "integer" }), &json!(2.0)).is_ok());
}
}
+190
View File
@@ -0,0 +1,190 @@
//! 测试替身:五个端口的 **mock 实现**(无盘、无网络、无时间依赖)。
//!
//! 放在库内(而不是只在 `#[cfg(test)]`)是刻意的:`crates/app` 装配时也要能给
//! 自己的单测造一套「无盘」环境,且 P1/M39 的 MCP 契约测试要复用同一批假数据。
//!
//! 按端口拆文件(`port.rs` 挨 400 行上限的同款理由):`settings` 配置、`sessions`
//! 会话日志在下面,`game` 实例/Java/账户与 `diagnose` 诊断各一个子模块。
//! 对外名字不变,`unlucky_agent::testing::MockSettings` 之类照旧可用(走 re-export)。
pub mod diagnose;
pub mod game;
pub mod settings;
use std::collections::{BTreeMap, BTreeSet};
use serde_json::{json, Value};
use crate::port::{GameSessionPort, GameSessionSummary, LogEvent, LogPage, LogQuery, PortResult};
pub use diagnose::MockDiagnose;
pub use game::{MockAccounts, MockGame};
pub use settings::MockSettings;
/// 内存会话端口。
#[derive(Debug, Default)]
pub struct MockSessions {
sessions: Vec<GameSessionSummary>,
events: BTreeMap<String, Vec<LogEvent>>,
}
impl MockSessions {
/// 空数据。
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// 加一个会话及其事件流。
pub fn add(&mut self, summary: GameSessionSummary, events: Vec<LogEvent>) {
self.events.insert(summary.session_id.clone(), events);
self.sessions.push(summary);
}
/// 便捷:造一个崩溃会话(`exit_code=1` + stderr + crash_found)。
#[must_use]
pub fn crashing_session(session_id: &str) -> (GameSessionSummary, Vec<LogEvent>) {
let summary = GameSessionSummary {
session_id: session_id.to_string(),
instance_id: Some("inst-1".to_string()),
instance_name: Some("1.20.1 Forge".to_string()),
game_version: Some("1.20.1".to_string()),
started_at: Some("2026-10-29T12:45:01.123Z".to_string()),
ended_at: Some("2026-10-29T12:46:31.123Z".to_string()),
duration_ms: 90_000,
exit_code: Some(1),
exit_type: Some("application_error".to_string()),
silent_failure: false,
window_detected: true,
event_count: 5,
crash_found: true,
diagnosis_top: Some("forge_missing_library".to_string()),
};
let events = vec![
event(
0,
"stdout",
json!({ "line": "Starting Minecraft 1.20.1", "level": "info" }),
),
event(
1,
"stderr",
json!({ "line": "java.lang.NoClassDefFoundError: cpw/mods/bootstraplauncher/BootstrapLauncher", "level": "error" }),
),
event(
2,
"crash_found",
json!({ "source": "crash_report", "path": r"C:\Users\aska\.minecraft\crash-reports\crash-1.txt", "excerpt": "Description: Mod loading failure" }),
),
event(
3,
"exit",
json!({ "code": 1, "exit_type": "application_error", "silent_failure": false }),
),
event(
4,
"session_end",
json!({ "reason": "exit", "duration_ms": 90000 }),
),
];
(summary, events)
}
}
fn event(seq: u64, kind: &str, payload: Value) -> LogEvent {
LogEvent {
seq,
ts: format!("2026-10-29T12:45:0{seq}.000Z"),
t_ms: seq * 1_000,
kind: kind.to_string(),
payload,
}
}
impl GameSessionPort for MockSessions {
fn list_sessions(
&self,
limit: usize,
instance_id: Option<&str>,
) -> PortResult<Vec<GameSessionSummary>> {
let mut out: Vec<GameSessionSummary> = self
.sessions
.iter()
.filter(|s| instance_id.is_none_or(|id| s.instance_id.as_deref() == Some(id)))
.cloned()
.collect();
out.sort_by(|a, b| b.started_at.cmp(&a.started_at));
out.truncate(limit);
Ok(out)
}
fn read_log(&self, session_id: &str, query: &LogQuery) -> PortResult<LogPage> {
let events = self
.events
.get(session_id)
.ok_or_else(|| format!("会话 `{session_id}` 不存在"))?;
let mut kind_counts = BTreeMap::new();
for event in events {
*kind_counts.entry(event.kind.clone()).or_insert(0u64) += 1;
}
let matched: Vec<&LogEvent> = events
.iter()
.filter(|e| query.from_seq.is_none_or(|from| e.seq >= from))
.filter(|e| query.to_seq.is_none_or(|to| e.seq <= to))
.filter(|e| query.kinds.is_empty() || query.kinds.contains(&e.kind))
.collect();
let max = if query.max_events == 0 {
matched.len()
} else {
query.max_events
};
let truncated = matched.len() > max;
Ok(LogPage {
session_id: session_id.to_string(),
total_events: events.len() as u64,
matched_events: matched.len() as u64,
truncated,
kind_counts,
first_ts: events.first().map(|e| e.ts.clone()),
last_ts: events.last().map(|e| e.ts.clone()),
events: matched.into_iter().take(max).cloned().collect(),
})
}
}
/// 一次性造好全部端口的 [`crate::port::Ports`](含一个崩溃会话,够跑通对话与日志工具)。
#[must_use]
pub fn mock_ports() -> (crate::port::Ports, std::sync::Arc<MockSettings>) {
use std::sync::Arc;
let settings = Arc::new(MockSettings::new());
let (summary, events) = MockSessions::crashing_session("20261029T124501-9f3c2a");
let mut sessions = MockSessions::new();
sessions.add(summary, events);
let ports = crate::port::Ports {
setting: settings.clone(),
sessions: Arc::new(sessions),
diagnose: Arc::new(MockDiagnose::new()),
game: Arc::new(MockGame::new()),
accounts: Arc::new(MockAccounts::new()),
};
(ports, settings)
}
/// 测试里常用的「全部工具名」集合(契约测试与 MCP 投影比对用)。
#[must_use]
pub fn expected_v1_tool_names() -> BTreeSet<&'static str> {
[
"get_config",
"get_config_schema",
"set_config",
"list_game_sessions",
"read_game_log",
"diagnose_crash",
"list_instances",
"list_versions",
"get_java_status",
"list_accounts",
]
.into_iter()
.collect()
}
+87
View File
@@ -0,0 +1,87 @@
//! 内存诊断端口(`DiagnosePort` 的测试替身)。
use crate::port::{
CrashDiagnosis, DiagnosePort, DiagnosisCandidate, ExitSummary, FixAction, FixActionKind,
PortResult,
};
/// 内存诊断端口(固定返回一份规则结论)。
#[derive(Debug, Clone)]
pub struct MockDiagnose {
report: Option<CrashDiagnosis>,
}
impl Default for MockDiagnose {
fn default() -> Self {
Self {
report: Some(Self::forge_missing_library()),
}
}
}
impl MockDiagnose {
/// 构造使用默认结论的端口。
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// 让端口对所有会话返回「会话不存在」。
#[must_use]
pub fn unavailable() -> Self {
Self { report: None }
}
/// 默认结论:Forge 缺库(对应 analyse/02 的高发场景)。
#[must_use]
pub fn forge_missing_library() -> CrashDiagnosis {
CrashDiagnosis {
session_id: String::new(),
source: "rules".to_string(),
needs_more_info: false,
candidates: vec![DiagnosisCandidate {
id: "integrity.forge_missing_library".to_string(),
severity: "error".to_string(),
category: "integrity".to_string(),
confidence: 0.86,
message_key: "diagnose.cause.integrity.forge_missing_library".to_string(),
message: "Forge 启动缺少 bootstraplauncher 库,通常是版本组件未下载完整"
.to_string(),
detail: "在实例上重装 Forge 组件(或先用官方启动器补全一次再回来)".to_string(),
evidence: vec![
"java.lang.NoClassDefFoundError: cpw/mods/bootstraplauncher/BootstrapLauncher"
.to_string(),
],
fix_actions: vec![FixAction {
kind: FixActionKind::Reinstall,
tool: "component.reinstall".to_string(),
label: "重装该版本的 Forge 组件".to_string(),
args: [("component".to_string(), "forge".to_string())]
.into_iter()
.collect(),
}],
}],
secondary: Vec::new(),
evidence: vec!["Description: Mod loading failure".to_string()],
exit: ExitSummary {
code: Some(1),
exit_type: Some("application_error".to_string()),
silent_failure: false,
},
}
}
}
impl DiagnosePort for MockDiagnose {
fn diagnose(&self, session_id: &str) -> PortResult<CrashDiagnosis> {
self.report.clone().map_or_else(
|| Err(format!("会话 `{session_id}` 不存在")),
|report| {
Ok(CrashDiagnosis {
session_id: session_id.to_string(),
..report
})
},
)
}
}
+158
View File
@@ -0,0 +1,158 @@
//! 实例 / 版本 / Java / 账户四个只读端口的测试替身。
use crate::port::game::{
AccountPort, AccountSummary, GamePort, InstanceSummary, JavaRuntimeSummary, JavaStatus,
VersionSummary,
};
use crate::port::PortResult;
/// 内存游戏端口:一个 1.20.1 Forge 实例 + 两个已安装版本 + 两个 Java 候选。
#[derive(Debug, Clone)]
pub struct MockGame {
instances: Vec<InstanceSummary>,
versions: Vec<VersionSummary>,
java: JavaStatus,
fail: Option<String>,
}
impl Default for MockGame {
fn default() -> Self {
Self::new()
}
}
impl MockGame {
/// 默认假数据(够跑通 `list_instances` / `list_versions` / `get_java_status`)。
#[must_use]
pub fn new() -> Self {
Self {
instances: vec![InstanceSummary {
id: "inst-1".to_string(),
name: "1.20.1 Forge".to_string(),
version_id: "1.20.1-forge-47.2.20".to_string(),
version_present: true,
game_dir: None,
java_path: Some(r"D:\jdk17\bin\java.exe".to_string()),
last_played_at: Some(1_793_304_753_123),
}],
versions: vec![
VersionSummary {
id: "1.20.1-forge-47.2.20".to_string(),
kind: Some("release".to_string()),
instance_count: 1,
},
VersionSummary {
id: "1.21.1".to_string(),
kind: Some("release".to_string()),
instance_count: 0,
},
],
java: JavaStatus {
default_memory_mb: Some(2048),
managed_roots: vec![r"D:\ULL\.ULL\data\java-managed".to_string()],
candidates: vec![
JavaRuntimeSummary {
binary: r"D:\ULL\.ULL\data\java-managed\jdk-17-temurin\bin\java.exe"
.to_string(),
version: Some("17.0.13".to_string()),
major: Some(17),
vendor: Some("temurin".to_string()),
origin: "managed".to_string(),
},
JavaRuntimeSummary {
binary: "/usr/bin/java".to_string(),
version: Some("21.0.2".to_string()),
major: Some(21),
vendor: None,
origin: "PATH".to_string(),
},
],
},
fail: None,
}
}
/// 让三个查询全部返回同一个错误(测端口错误透传)。
#[must_use]
pub fn failing(message: &str) -> Self {
Self {
fail: Some(message.to_string()),
..Self::new()
}
}
fn fail(&self) -> Option<String> {
self.fail.clone()
}
}
impl GamePort for MockGame {
fn list_instances(&self) -> PortResult<Vec<InstanceSummary>> {
self.fail().map_or_else(|| Ok(self.instances.clone()), Err)
}
fn list_versions(&self) -> PortResult<Vec<VersionSummary>> {
self.fail().map_or_else(|| Ok(self.versions.clone()), Err)
}
fn java_status(&self) -> PortResult<JavaStatus> {
self.fail().map_or_else(|| Ok(self.java.clone()), Err)
}
}
/// 内存账户端口:一个离线账户。**只有公开字段**,凭据无处可放。
#[derive(Debug, Clone)]
pub struct MockAccounts {
accounts: Vec<AccountSummary>,
fail: Option<String>,
}
impl Default for MockAccounts {
fn default() -> Self {
Self::new()
}
}
impl MockAccounts {
/// 一个离线账户(Steve)。
#[must_use]
pub fn new() -> Self {
Self {
accounts: vec![AccountSummary {
id: "acc-1".to_string(),
kind: "offline".to_string(),
profile_id: "8667ba71b85a4004af54457a9734eed7".to_string(),
profile_name: "Steve".to_string(),
login_name: None,
created_at_ms: 1_793_304_753_123,
}],
fail: None,
}
}
/// 空账户列表(测「没有账户」的提示文案)。
#[must_use]
pub fn empty() -> Self {
Self {
accounts: Vec::new(),
fail: None,
}
}
/// 让查询失败(测端口错误透传)。
#[must_use]
pub fn failing(message: &str) -> Self {
Self {
fail: Some(message.to_string()),
..Self::new()
}
}
}
impl AccountPort for MockAccounts {
fn list_accounts(&self) -> PortResult<Vec<AccountSummary>> {
self.fail
.clone()
.map_or_else(|| Ok(self.accounts.clone()), Err)
}
}
+201
View File
@@ -0,0 +1,201 @@
//! 内存配置端口(`SettingPort` 的测试替身)。
use std::collections::BTreeMap;
use std::sync::Mutex;
use serde_json::{json, Map, Value};
use crate::confirm::Sensitivity;
use crate::port::{PortResult, SettingChange, SettingKey, SettingPort};
/// 内存配置端口。
#[derive(Debug, Default)]
pub struct MockSettings {
keys: Vec<SettingKey>,
values: Mutex<BTreeMap<String, Value>>,
fail_set: Mutex<Option<String>>,
set_calls: Mutex<usize>,
}
/// 与 `PlanDoc/04` §3 / M12 `setting-接口约定.md` §8 的键表一致的默认白名单
/// (覆盖三档敏感度;`ai.api_key` 这类凭据是 `writable=false`,**故意不在这里**)。
fn default_keys() -> Vec<SettingKey> {
fn key(
path: &str,
sensitivity: Sensitivity,
value_type: &str,
description: &str,
) -> SettingKey {
SettingKey {
path: path.to_string(),
sensitivity,
value_type: value_type.to_string(),
description: description.to_string(),
}
}
vec![
key(
"appearance.theme_mode",
Sensitivity::Low,
"enum",
"界面主题",
),
key(
"download.concurrency",
Sensitivity::Low,
"integer",
"下载并发(1~256)",
),
key(
"java.default_memory_mb",
Sensitivity::Low,
"integer",
"最大内存(512~65536 MB)",
),
key("download.region", Sensitivity::Medium, "enum", "下载源区域"),
key("ai.model", Sensitivity::Medium, "text", "AI 模型名"),
key(
"java.selected_path",
Sensitivity::High,
"path",
"Java 可执行文件路径",
),
key("download.proxy_url", Sensitivity::High, "text", "HTTP 代理"),
key("ai.base_url", Sensitivity::High, "text", "AI 端点"),
key(
"core.data_mode",
Sensitivity::High,
"enum",
"数据目录模式(portable/standard/custom)",
),
]
}
impl MockSettings {
/// 用默认白名单 + 一批初值造一个。
#[must_use]
pub fn new() -> Self {
let mut values = BTreeMap::new();
values.insert("appearance.theme_mode".to_string(), json!("metro_dark"));
values.insert("download.concurrency".to_string(), json!(8));
values.insert("java.default_memory_mb".to_string(), json!(2048));
Self {
keys: default_keys(),
values: Mutex::new(values),
fail_set: Mutex::new(None),
set_calls: Mutex::new(0),
}
}
/// 让接下来的 `set` 全部失败(测错误透传)。
pub fn fail_set_with(&self, message: &str) {
if let Ok(mut slot) = self.fail_set.lock() {
*slot = Some(message.to_string());
}
}
/// 当前值(断言「未确认时没有写进去」)。
#[must_use]
pub fn value_of(&self, path: &str) -> Option<Value> {
self.values.lock().ok().and_then(|v| v.get(path).cloned())
}
/// 直接塞一个值,模拟 M12 真实实现里存在的**任意键**(含凭据键)。
///
/// 白名单以外的键也能塞——测「`get_config` 不把凭据读给模型」需要它
/// (`ai.api_key` 是 `writable=false`,故意不在白名单里)。
pub fn seed_value(&self, path: &str, value: Value) {
if let Ok(mut values) = self.values.lock() {
values.insert(path.to_string(), value);
}
}
/// 成功写入次数。
#[must_use]
pub fn set_calls(&self) -> usize {
self.set_calls.lock().map(|n| *n).unwrap_or(0)
}
}
impl SettingPort for MockSettings {
fn summary(&self) -> Value {
let values = self.values.lock().map(|v| v.clone()).unwrap_or_default();
let mut map = serde_json::Map::new();
for key in &self.keys {
let value = values.get(&key.path).cloned().unwrap_or(Value::Null);
map.insert(key.path.clone(), value);
}
Value::Object(map)
}
fn get(&self, path: &str) -> PortResult<Value> {
self.values
.lock()
.ok()
.and_then(|v| v.get(path).cloned())
.ok_or_else(|| format!("配置键 `{path}` 没有值"))
}
fn set(&self, path: &str, value: &Value) -> PortResult<SettingChange> {
if let Ok(slot) = self.fail_set.lock() {
if let Some(message) = slot.as_ref() {
return Err(message.clone());
}
}
let old = self.get(path).ok();
if let Ok(mut values) = self.values.lock() {
values.insert(path.to_string(), value.clone());
}
if let Ok(mut calls) = self.set_calls.lock() {
*calls += 1;
}
Ok(SettingChange {
path: path.to_string(),
old,
new: value.clone(),
})
}
fn writable_keys(&self) -> Vec<SettingKey> {
self.keys.clone()
}
fn schema(&self) -> Value {
// 与 `core::setting::catalog::SettingSchema::to_json_schema` 同形:
// 只含白名单键 + `x-ai-sensitivity`,凭据键天然缺席。
let mut properties = Map::new();
for key in &self.keys {
properties.insert(
key.path.clone(),
json!({
"type": key.value_type,
"description": key.description,
"x-ai-sensitivity": key.sensitivity,
}),
);
}
json!({
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "ull.launcher",
"type": "object",
"additionalProperties": false,
"properties": properties,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn schema_excludes_credential_keys() {
let schema = MockSettings::new().schema();
let json = schema.to_string();
assert!(
!json.contains("ai.api_key"),
"schema 不得包含凭据键:{json}"
);
assert!(json.contains("download.concurrency"));
}
}
+110
View File
@@ -0,0 +1,110 @@
//! `list_accounts`:账户清单(**凭据永不出口**)。
//!
//! 这个工具存在的理由很具体:用户常问「我有哪几个号 / 这局用的是哪个号」。
//! 但 D4/D9 的凭据红线是硬的——工具结果会回灌模型、也可能被发往远端 LLM,
//! 所以:
//! 1. 端口只回 [`crate::port::AccountSummary`](`AccountMeta` 的公开字段);
//! 2. 本文件里**没有任何**能表达 token / 密码的类型(连字段名都不出现);
//! 3. 工具结果再过一遍 [`crate::redact`],兜住实现方把凭据塞进 `profile_name` 的意外。
use std::sync::Arc;
use serde_json::{json, Value};
use crate::port::AccountPort;
use crate::registry::schema::object;
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 工具名。
pub const LIST_ACCOUNTS: &str = "list_accounts";
/// 注册 `list_accounts`。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(
registry: &mut ToolRegistry,
port: Arc<dyn AccountPort>,
) -> Result<(), RegistryError> {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, _args: &Value| {
let accounts = port.list_accounts().map_err(ToolError::Port)?;
let count = accounts.len();
let display: Vec<String> = accounts
.iter()
.map(|a| {
if a.profile_name.trim().is_empty() {
format!("{}({})", a.id, a.kind)
} else {
format!("{}({})", a.profile_name, a.kind)
}
})
.collect();
let mut content = json!({
"count": count,
"accounts": accounts,
"credential_policy": "账户凭据(access token / 刷新令牌 / authlib 密码)永不经由 AI 工具出口",
});
// 兜底脱敏:端口实现若把敏感串塞进了公开字段,这里也不会带出去。
content = crate::redact::redact_texts(&content);
Ok(ToolOutput::ok(
content,
if count == 0 {
"还没有任何账户".to_string()
} else {
format!("账户 {count} 个:{}", display.join("、"))
},
))
});
registry.register(ToolSpec::read_only(
LIST_ACCOUNTS,
"列出启动器里已登录的账户(展示名 / 轨道 offline|microsoft|authlib / 档案 UUID / 创建时间)。**永不返回任何凭据**:令牌与密码不在工具结果的类型里,需要登录态请让用户在启动器界面查看。",
object(&[], &[]),
handler,
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockAccounts;
fn registry(port: Arc<dyn AccountPort>) -> ToolRegistry {
let mut registry = ToolRegistry::new();
register(&mut registry, port).expect("注册应成功");
registry
}
fn call(registry: &ToolRegistry) -> Value {
let spec = registry.get(LIST_ACCOUNTS).expect("工具存在").clone();
let ctx = ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
};
(spec.handler)(&ctx, &json!({})).expect("应成功").content
}
#[test]
fn lists_accounts_without_credentials() {
let content = call(&registry(Arc::new(MockAccounts::new())));
assert_eq!(content["count"], json!(1));
assert_eq!(content["accounts"][0]["profile_name"], json!("Steve"));
// 只扫账户数据本身:`credential_policy` 那句说明文字里本来就写着 "token"。
let fields = content["accounts"].to_string().to_lowercase();
for forbidden in ["token", "password", "refresh", "secret"] {
assert!(
!fields.contains(forbidden),
"账户字段含 `{forbidden}`:{fields}"
);
}
}
#[test]
fn empty_list_is_not_an_error() {
let content = call(&registry(Arc::new(MockAccounts::empty())));
assert_eq!(content["count"], json!(0));
assert_eq!(content["accounts"], json!([]));
}
}
+345
View File
@@ -0,0 +1,345 @@
//! `get_config` / `set_config`(02 文档 §3.1「有权限修改 ULL 各项配置」)。
//!
//! 安全边界都落在这里,但**分级确认的"要不要问"不在这里**:
//! 工具只负责「白名单过滤 → 生成 diff → 需要确认时只报价不执行」,
//! 问不问由编排层按 [`crate::confirm::ConfirmPolicy`] 决定(YOLO 也只改那一处)。
//!
//! 值校验(类型/范围/schema)归 M12 的配置 schema 所有:agent 不复制一份,
//! 否则两处规则迟早漂移(02 文档 §3.1「schema 强校验」)。
use std::sync::Arc;
use serde_json::{json, Value};
use crate::confirm::Sensitivity;
use crate::port::{SettingKey, SettingPort};
use crate::registry::schema::{any, non_empty_string, object, string};
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 读配置。
pub const GET_CONFIG: &str = "get_config";
/// 写配置。
pub const SET_CONFIG: &str = "set_config";
/// 错误提示里最多列多少个可写键(防"把白名单灌给模型")。
pub const MAX_LISTED_KEYS: usize = 16;
/// 摘要里值的最大展示长度。
const BRIEF_CHARS: usize = 60;
/// 注册两个配置工具。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(
registry: &mut ToolRegistry,
port: Arc<dyn SettingPort>,
) -> Result<(), RegistryError> {
registry.register(get_config_spec(Arc::clone(&port)))?;
registry.register(set_config_spec(port))
}
fn get_config_spec(port: Arc<dyn SettingPort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let path = args
.get("path")
.and_then(Value::as_str)
.map(str::trim)
.filter(|p| !p.is_empty());
match path {
None => {
let summary = port.summary();
let writable = port.writable_keys();
Ok(ToolOutput::ok(
json!({
"scope": "all",
"values": summary,
"writable_keys": writable.iter().map(describe_key).collect::<Vec<_>>(),
}),
format!(
"读取全部配置概要({} 个键,其中 {} 个 AI 可写)",
summary.as_object().map_or(0, serde_json::Map::len),
writable.len()
),
))
}
Some(path) => {
// 凭据类键一律不读:值会进 ToolOutput.content → 回灌模型 → 发往远端 LLM,
// 违反本 crate 的硬边界(AI 永不接触账户凭据,见 `lib.rs`)。
// 这是 agent 侧的第二道防线:第一道是 M12 不把凭据放白名单/概要。
if crate::redact::is_sensitive_key(path) {
return Err(ToolError::NotAllowed(format!(
"`{path}` 是凭据类配置,AI 不可读取也不可写入;请让用户自己在设置页查看。"
)));
}
let value = port.get(path).map_err(ToolError::Port)?;
Ok(ToolOutput::ok(
json!({ "scope": "key", "path": path, "value": value }),
format!("读取配置 `{path}` = {}", brief(&value)),
))
}
}
});
ToolSpec::read_only(
GET_CONFIG,
"读取启动器配置。不带 path 返回全部配置概要(含 AI 可写键及其敏感等级);带 path 返回单个键的值。",
object(
&[(
"path",
string("配置键点分路径,如 `download.concurrency`;省略则返回全部概要"),
)],
&[],
),
handler,
)
}
fn set_config_spec(port: Arc<dyn SettingPort>) -> ToolSpec {
let handler: ToolFn =
Arc::new(move |ctx: &ToolCtx, args: &Value| apply_set_config(port.as_ref(), ctx, args));
ToolSpec::mutating(
SET_CONFIG,
"修改启动器配置(仅限白名单内的键)。普通键立即生效;敏感键(Java 路径/数据目录/代理/AI 端点)会先返回 needs_confirmation,等用户确认后才会真正写入。值必须符合该键的类型与范围。",
object(
&[
("path", non_empty_string("配置键点分路径,必须是 get_config 列出的可写键")),
("value", any()),
],
&["path", "value"],
),
handler,
)
}
/// `set_config` 的实现(独立成函数便于单测直接调用)。
///
/// # Errors
/// 键不在白名单、值缺失、端口写入失败时返回 [`ToolError`]。
pub fn apply_set_config(
port: &dyn SettingPort,
ctx: &ToolCtx,
args: &Value,
) -> Result<ToolOutput, ToolError> {
let path = args
.get("path")
.and_then(Value::as_str)
.map(str::trim)
.filter(|p| !p.is_empty())
.ok_or_else(|| ToolError::NotAllowed("缺少参数 `path`".to_string()))?
.to_string();
let value = args
.get("value")
.cloned()
.ok_or_else(|| ToolError::NotAllowed("缺少参数 `value`".to_string()))?;
let keys = port.writable_keys();
let key = keys
.iter()
.find(|k| k.path == path)
.ok_or_else(|| ToolError::NotAllowed(not_writable_message(&keys, &path)))?;
// 旧值读不到不影响写(首次设置),只是 diff 少一半。
let old = port.get(&path).ok();
if !ctx.confirmed && key.sensitivity == Sensitivity::High {
let diff = json!({
"path": path,
"old": old,
"new": value,
"sensitivity": key.sensitivity,
"description": key.description,
});
return Ok(ToolOutput::needs_confirmation(
format!(
"AI 请求把 `{path}` 从 {} 改为 {}({})",
brief_opt(&old),
brief(&value),
sensitivity_label(key.sensitivity)
),
diff,
key.sensitivity,
));
}
let change = port.set(&path, &value).map_err(ToolError::Port)?;
Ok(ToolOutput::ok(
json!({
"status": "written",
"path": change.path,
"old": change.old,
"new": change.new,
"sensitivity": key.sensitivity,
}),
format!(
"已把 `{}` 从 {} 改为 {}",
change.path,
brief_opt(&change.old),
brief(&change.new)
),
))
}
/// 白名单拒绝的文案:说清"不能写"并给出可写键(模型会据此改用正确路径)。
fn not_writable_message(keys: &[SettingKey], path: &str) -> String {
let listed: Vec<&str> = keys
.iter()
.take(MAX_LISTED_KEYS)
.map(|k| k.path.as_str())
.collect();
let rest = keys.len().saturating_sub(listed.len());
let tail = if rest > 0 {
format!(",另有 {rest} 个键见 get_config 概要")
} else {
String::new()
};
format!(
"配置键 `{path}` 不在 AI 可写白名单内。可写键({} 个):{}{tail}",
keys.len(),
listed.join("、")
)
}
fn describe_key(key: &SettingKey) -> Value {
json!({
"path": key.path,
"sensitivity": key.sensitivity,
"value_type": key.value_type,
"description": key.description,
})
}
fn sensitivity_label(sensitivity: Sensitivity) -> &'static str {
match sensitivity {
Sensitivity::Low => "普通",
Sensitivity::Medium => "中等(静默但审计)",
Sensitivity::High => "敏感,需确认",
}
}
fn brief(value: &Value) -> String {
let rendered = match value {
Value::String(s) => s.clone(),
other => other.to_string(),
};
truncate(&rendered)
}
fn brief_opt(value: &Option<Value>) -> String {
value
.as_ref()
.map_or_else(|| "(未设置)".to_string(), brief)
}
fn truncate(text: &str) -> String {
if text.chars().count() <= BRIEF_CHARS {
return text.to_string();
}
let head: String = text.chars().take(BRIEF_CHARS).collect();
format!("{head}…")
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockSettings;
fn ctx(confirmed: bool) -> ToolCtx {
ToolCtx {
agent_session_id: "s1".to_string(),
confirmed,
}
}
#[test]
fn rejects_keys_outside_whitelist() {
let port = MockSettings::new();
let err = apply_set_config(
&port,
&ctx(true),
&json!({ "path": "java.random.thing", "value": 1 }),
)
.unwrap_err();
assert!(matches!(err, ToolError::NotAllowed(_)));
assert!(err.message().contains("不在 AI 可写白名单内"));
assert!(err.message().contains("download.concurrency"));
assert_eq!(port.set_calls(), 0);
}
#[test]
fn normal_key_writes_without_confirmation() {
let port = MockSettings::new();
let out = apply_set_config(
&port,
&ctx(false),
&json!({ "path": "download.concurrency", "value": 16 }),
)
.unwrap();
assert!(out.confirmation.is_none());
assert_eq!(out.content["status"], json!("written"));
assert_eq!(port.value_of("download.concurrency"), Some(json!(16)));
}
#[test]
fn medium_key_writes_silently_too() {
// M12:Medium = 静默生效但审计标记,不弹窗
let port = MockSettings::new();
let out = apply_set_config(
&port,
&ctx(false),
&json!({ "path": "download.region", "value": "cn" }),
)
.unwrap();
assert!(out.confirmation.is_none());
assert_eq!(port.set_calls(), 1);
}
#[test]
fn high_key_quotes_first_then_writes_after_confirm() {
let port = MockSettings::new();
let args = json!({ "path": "java.selected_path", "value": "D:/jdk17/bin/java.exe" });
let quoted = apply_set_config(&port, &ctx(false), &args).unwrap();
let confirmation = quoted.confirmation.expect("High 键应要求确认");
assert_eq!(confirmation.sensitivity, Sensitivity::High);
assert_eq!(confirmation.details["new"], json!("D:/jdk17/bin/java.exe"));
assert_eq!(port.set_calls(), 0, "未确认前不得写入");
let written = apply_set_config(&port, &ctx(true), &args).unwrap();
assert!(written.confirmation.is_none());
assert_eq!(port.set_calls(), 1);
assert_eq!(
port.value_of("java.selected_path"),
Some(json!("D:/jdk17/bin/java.exe"))
);
}
#[test]
fn locked_credential_key_is_not_writable() {
// M12:ai.api_key 是 writable=false,不在白名单里 → 任何情况下都拒绝
let port = MockSettings::new();
let err = apply_set_config(
&port,
&ctx(true),
&json!({ "path": "ai.api_key", "value": "sk-x" }),
)
.unwrap_err();
assert!(matches!(err, ToolError::NotAllowed(_)));
assert_eq!(port.set_calls(), 0);
}
#[test]
fn port_error_is_passed_through() {
let port = MockSettings::new();
port.fail_set_with("磁盘只读");
let err = apply_set_config(
&port,
&ctx(true),
&json!({ "path": "appearance.theme_mode", "value": "metro_light" }),
)
.unwrap_err();
assert_eq!(err.code(), "port_error");
assert!(err.message().contains("磁盘只读"));
}
}
+335
View File
@@ -0,0 +1,335 @@
//! `diagnose_crash`(02 文档 §3.2 第三条)。
//!
//! 流水线是「**规则在前、模型补位**」(analyse/02 §8.3):本工具只跑 M15 的规则引擎,
//! 把**结构化结论 + 关键片段**交给模型,绝不让模型读裸日志。规则未命中
//! (`candidates` 空 / `needs_more_info`)时,模型再去用 `read_game_log` 自己找证据。
//!
//! P0 与 M15 的桥:M15 的修复动作指向 `java.set` / `memory.set` 这些 **P1 才有的**语义工具 id。
//! P0 只有 `set_config`,所以这里按 [`FixActionKind`] 生成 `p0_next_steps`
//! (`adjust_memory` → `set_config {"path":"java.default_memory_mb"}`,`change_java` →
//! `set_config {"path":"java.selected_path"}`,见 [`MEMORY_KEY`] / [`JAVA_KEY`]),
//! 剩下的动作明确标成「P0 无工具,解释给用户」。
use std::sync::Arc;
use serde_json::{json, Value};
use crate::port::{CrashDiagnosis, DiagnosePort, DiagnosisCandidate, FixAction, FixActionKind};
use crate::redact::redact_text;
use crate::registry::schema::{integer, non_empty_string, object};
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 诊断工具名。
pub const DIAGNOSE_CRASH: &str = "diagnose_crash";
/// 单次返回的证据行上限(防 token 爆炸)。
pub const MAX_EVIDENCE_LINES: usize = 40;
/// 证据行默认条数。
pub const DEFAULT_EVIDENCE_LINES: usize = 20;
/// 单条证据最大字符数。
pub const MAX_EVIDENCE_CHARS: usize = 400;
/// 内存建议的配置键(M12 白名单里的键名,见 `setting-接口约定.md` §8)。
pub const MEMORY_KEY: &str = "java.default_memory_mb";
/// Java 路径的配置键。
pub const JAVA_KEY: &str = "java.selected_path";
/// 注册诊断工具。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(
registry: &mut ToolRegistry,
port: Arc<dyn DiagnosePort>,
) -> Result<(), RegistryError> {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let session_id = args
.get("session_id")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| ToolError::NotAllowed("缺少参数 `session_id`".to_string()))?;
let max_lines = args
.get("max_evidence_lines")
.and_then(Value::as_u64)
.map_or(DEFAULT_EVIDENCE_LINES, |n| n as usize)
.clamp(1, MAX_EVIDENCE_LINES);
let report = port.diagnose(session_id).map_err(ToolError::Port)?;
Ok(render(&report, max_lines))
});
registry.register(ToolSpec::read_only(
DIAGNOSE_CRASH,
"对某次游戏会话跑规则引擎(59 条崩溃规则)并返回结构化结论:主因、置信度、证据行、修复动作。规则未命中时会提示需要更多信息——此时再用 read_game_log 取 stderr/exit 片段。",
object(
&[
("session_id", non_empty_string("会话 id,来自 list_game_sessions")),
(
"max_evidence_lines",
integer("返回多少条证据行", 1, MAX_EVIDENCE_LINES as i64),
),
],
&["session_id"],
),
handler,
))
}
/// 把规则引擎结论压成工具结果。
fn render(report: &CrashDiagnosis, max_evidence_lines: usize) -> ToolOutput {
let candidates: Vec<Value> = report
.candidates
.iter()
.map(|c| render_candidate(c, max_evidence_lines))
.collect();
let secondary: Vec<Value> = report
.secondary
.iter()
.take(5)
.map(|c| {
json!({
"id": c.id,
"severity": c.severity,
"category": c.category,
"confidence": c.confidence,
"message": message_of(c),
})
})
.collect();
let next_steps: Vec<Value> = report
.candidates
.iter()
.flat_map(|c| c.fix_actions.iter())
.map(bridge_to_p0)
.collect();
let content = json!({
"session_id": report.session_id,
"source": report.source,
"needs_more_info": report.needs_more_info,
"exit": report.exit,
"top_confidence": report.top_confidence(),
"candidates": candidates,
"secondary": secondary,
"evidence": cap_lines(&report.evidence, max_evidence_lines),
"p0_next_steps": next_steps,
});
ToolOutput::ok(content, summarize(report))
}
fn render_candidate(candidate: &DiagnosisCandidate, max_evidence_lines: usize) -> Value {
json!({
"id": candidate.id,
"severity": candidate.severity,
"category": candidate.category,
"confidence": candidate.confidence,
"message": message_of(candidate),
"detail": candidate.detail,
"evidence": cap_lines(&candidate.evidence, max_evidence_lines),
"fix_actions": candidate.fix_actions,
})
}
/// `message` 为空时回落显示 i18n key(装配层没渲染时至少不丢信息)。
fn message_of(candidate: &DiagnosisCandidate) -> String {
let text = candidate.message.trim();
if text.is_empty() {
candidate.message_key.clone()
} else {
text.to_string()
}
}
fn summarize(report: &CrashDiagnosis) -> String {
match report.top() {
Some(top) => {
let label = top
.fix_actions
.first()
.map(action_label)
.unwrap_or_else(|| "没有可执行的修复动作".to_string());
format!(
"规则引擎命中 {} 条候选,主因 `{}`(置信度 {:.2});建议:{label}",
report.candidates.len(),
top.id,
top.confidence
)
}
None if report.needs_more_info => {
"规则引擎未命中,且需要更多信息(用 read_game_log 取 stderr/exit 片段后再判断)"
.to_string()
}
None => "规则引擎未命中(59 条规则都不匹配),需要结合日志片段人工/AI 判断".to_string(),
}
}
/// M15 的语义动作 → P0 现有工具。返回给模型看的"下一步"。
fn bridge_to_p0(action: &FixAction) -> Value {
let label = action_label(action);
match action.kind {
FixActionKind::AdjustMemory => {
let value = pick_memory_mb(action).map_or(Value::Null, |mb| json!(mb));
json!({
"action": action.tool,
"kind": action.kind,
"label": label,
"suggested_tool": "set_config",
"suggested_args": { "path": MEMORY_KEY, "value": value },
})
}
FixActionKind::ChangeJava => {
let value = pick_arg(action, &["path", "java_path", "binary", "value"])
.map_or(Value::Null, |p| json!(p));
json!({
"action": action.tool,
"kind": action.kind,
"label": label,
"suggested_tool": "set_config",
"suggested_args": { "path": JAVA_KEY, "value": value },
})
}
other => json!({
"action": action.tool,
"kind": other,
"label": label,
"suggested_tool": Value::Null,
"unavailable_reason": "P0 没有对应工具(P1 落地),请把这个建议解释给用户",
}),
}
}
/// 动作的人话:优先 M15 给的 `label`,否则按 kind 兜底。
fn action_label(action: &FixAction) -> String {
let label = action.label.trim();
if !label.is_empty() {
return label.to_string();
}
match action.kind {
FixActionKind::ChangeJava => "换一个匹配的 Java 版本".to_string(),
FixActionKind::AdjustMemory => "调整最大内存".to_string(),
FixActionKind::ChangeGraphics => "调整图形设置/驱动".to_string(),
FixActionKind::RemoveMod => "移除或替换冲突的 Mod".to_string(),
FixActionKind::Reinstall => "重装/修复对应组件".to_string(),
FixActionKind::SeekHelp => "导出诊断包并反馈".to_string(),
}
}
/// 从动作参数里挑内存上限:先看常见键,再退化成"第一个带数字的值"。
fn pick_memory_mb(action: &FixAction) -> Option<i64> {
if let Some(value) = pick_arg(
action,
&["value", "suggest", "mb", "max_mb", "xmx", "xmx_mb"],
) {
if let Some(mb) = parse_mb(&value) {
return Some(mb);
}
}
action.args.values().find_map(|v| parse_mb(v))
}
fn pick_arg(action: &FixAction, keys: &[&str]) -> Option<String> {
keys.iter()
.find_map(|key| action.args.get(*key).cloned())
.filter(|v| !v.trim().is_empty())
}
/// `"4096"` / `"4G"` / `"6144M"` → MB。
fn parse_mb(raw: &str) -> Option<i64> {
let text = raw.trim().to_ascii_lowercase();
let (number, scale) = if let Some(rest) = text.strip_suffix('g') {
(rest, 1024)
} else if let Some(rest) = text.strip_suffix("gb") {
(rest, 1024)
} else if let Some(rest) = text.strip_suffix('m') {
(rest, 1)
} else if let Some(rest) = text.strip_suffix("mb") {
(rest, 1)
} else {
(text.as_str(), 1)
};
number.trim().parse::<i64>().ok().map(|n| n * scale)
}
fn cap_lines(lines: &[String], max_lines: usize) -> Vec<String> {
lines
.iter()
.take(max_lines)
.map(|line| {
let masked = redact_text(line);
if masked.chars().count() <= MAX_EVIDENCE_CHARS {
masked
} else {
let head: String = masked.chars().take(MAX_EVIDENCE_CHARS).collect();
format!("{head}…")
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockDiagnose;
fn call(port: &MockDiagnose, session_id: &str) -> ToolOutput {
let report = port.diagnose(session_id).expect("mock 应返回结论");
render(&report, DEFAULT_EVIDENCE_LINES)
}
#[test]
fn renders_candidates_with_p0_bridge_for_reinstall() {
let out = call(&MockDiagnose::new(), "s-1");
assert_eq!(out.content["candidates"].as_array().unwrap().len(), 1);
let confidence = out.content["top_confidence"].as_f64().unwrap();
assert!((confidence - 0.86).abs() < 1e-6, "{confidence}");
let steps = out.content["p0_next_steps"].as_array().unwrap();
assert_eq!(steps[0]["kind"], json!("reinstall"));
assert_eq!(steps[0]["suggested_tool"], Value::Null);
assert!(out.summary.contains("建议:重装该版本的 Forge 组件"));
}
#[test]
fn bridges_memory_action_to_set_config() {
let mut report = MockDiagnose::forge_missing_library();
if let Some(candidate) = report.candidates.first_mut() {
candidate.fix_actions = vec![FixAction {
kind: FixActionKind::AdjustMemory,
tool: "memory.set".to_string(),
label: String::new(),
args: [("suggest".to_string(), "4G".to_string())]
.into_iter()
.collect(),
}];
}
let out = render(&report, 5);
let steps = out.content["p0_next_steps"].as_array().unwrap();
assert_eq!(steps[0]["suggested_tool"], json!("set_config"));
assert_eq!(steps[0]["suggested_args"]["path"], json!(MEMORY_KEY));
assert_eq!(steps[0]["suggested_args"]["value"], json!(4096));
assert_eq!(steps[0]["label"], json!("调整最大内存"));
}
#[test]
fn parses_memory_units() {
assert_eq!(parse_mb("4096"), Some(4096));
assert_eq!(parse_mb("4G"), Some(4096));
assert_eq!(parse_mb("6144mb"), Some(6144));
assert_eq!(parse_mb("abc"), None);
}
#[test]
fn empty_candidates_says_need_more_info() {
let report = CrashDiagnosis {
session_id: "s-2".into(),
source: "rules".into(),
needs_more_info: true,
candidates: vec![],
secondary: vec![],
evidence: vec![],
exit: crate::port::ExitSummary::default(),
};
let out = render(&report, 5);
assert!(out.summary.contains("需要更多信息"));
}
}
+199
View File
@@ -0,0 +1,199 @@
//! 实例 / 版本 / Java 三个只读工具(M39 任务 3 的读侧)。
//!
//! 全部只读、全部走 [`crate::port::GamePort`]:agent 不自己去翻 `versions/` 目录,
//! 也不自己扫 JDK——那两件事的真相源在 M14(game)与 M33(java),重复一份必然漂。
//!
//! 输出形状刻意做成「摘要 + 上限」:实例可能几十个、Java 候选可能十几个,
//! 一次全塞给模型等于烧 token(02 §3.2 的「单次返回上限防 token 爆炸」同理)。
use std::sync::Arc;
use serde_json::{json, Value};
use crate::port::GamePort;
use crate::registry::schema::{integer, object};
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 实例列表工具名。
pub const LIST_INSTANCES: &str = "list_instances";
/// 版本列表工具名。
pub const LIST_VERSIONS: &str = "list_versions";
/// Java 现状工具名。
pub const GET_JAVA_STATUS: &str = "get_java_status";
/// 单次最多返回多少个实例/版本。
pub const MAX_ROWS: usize = 50;
/// 注册三个只读工具。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(registry: &mut ToolRegistry, port: Arc<dyn GamePort>) -> Result<(), RegistryError> {
registry.register(list_instances_spec(Arc::clone(&port)))?;
registry.register(list_versions_spec(Arc::clone(&port)))?;
registry.register(java_status_spec(port))
}
fn limit_arg(args: &Value) -> usize {
args.get("limit")
.and_then(Value::as_u64)
.map_or(MAX_ROWS, |n| usize::try_from(n).unwrap_or(MAX_ROWS))
.clamp(1, MAX_ROWS)
}
fn limit_schema() -> Value {
integer(
&format!("最多返回多少条(1~{MAX_ROWS},默认 {MAX_ROWS})"),
1,
MAX_ROWS as i64,
)
}
fn list_instances_spec(port: Arc<dyn GamePort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let limit = limit_arg(args);
let mut instances = port.list_instances().map_err(ToolError::Port)?;
let total = instances.len();
instances.truncate(limit);
Ok(ToolOutput::ok(
json!({
"total": total,
"shown": instances.len(),
"truncated": total > instances.len(),
"instances": instances,
}),
format!("列出 {}/{} 个实例", instances.len(), total),
))
});
ToolSpec::read_only(
LIST_INSTANCES,
"列出启动器里的游戏实例(id / 名称 / 版本 id / 载荷是否已安装 / 独立游戏目录 / 实例级 Java)。要看某个实例的日志先用 list_game_sessions。",
object(&[("limit", limit_schema())], &[]),
handler,
)
}
fn list_versions_spec(port: Arc<dyn GamePort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let limit = limit_arg(args);
let mut versions = port.list_versions().map_err(ToolError::Port)?;
let total = versions.len();
versions.truncate(limit);
Ok(ToolOutput::ok(
json!({
"total": total,
"shown": versions.len(),
"truncated": total > versions.len(),
"versions": versions,
}),
format!("列出 {}/{} 个已安装版本", versions.len(), total),
))
});
ToolSpec::read_only(
LIST_VERSIONS,
"列出已安装的游戏版本(`versions/<id>/` 下真实存在的载荷),带类型与被几个实例引用。判断「实例的载荷缺没缺」时配合 list_instances 的 version_present 一起看。",
object(&[("limit", limit_schema())], &[]),
handler,
)
}
fn java_status_spec(port: Arc<dyn GamePort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, _args: &Value| {
let status = port.java_status().map_err(ToolError::Port)?;
let majors: Vec<String> = status
.candidates
.iter()
.filter_map(|c| c.major.map(|m| m.to_string()))
.collect();
Ok(ToolOutput::ok(
json!({
"default_memory_mb": status.default_memory_mb,
"managed_roots": status.managed_roots,
"candidate_count": status.candidates.len(),
"majors": majors,
"candidates": status.candidates,
}),
format!(
"Java 候选 {} 个(主版本 {})",
status.candidates.len(),
if majors.is_empty() {
"无".to_string()
} else {
majors.join("/")
}
),
))
});
ToolSpec::read_only(
GET_JAVA_STATUS,
"读取 Java 现状:托管扫描根、默认堆内存、探测到的全部运行时(路径 / 版本 / 主版本 / 发行方 / 来源)。启动报「不支持的 class 版本」「找不到 Java」时先看这里。",
object(&[], &[]),
handler,
)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockGame;
fn registry() -> ToolRegistry {
let mut registry = ToolRegistry::new();
register(&mut registry, Arc::new(MockGame::new())).expect("注册应成功");
registry
}
fn call(registry: &ToolRegistry, name: &str, args: Value) -> Value {
let spec = registry.get(name).expect("工具存在").clone();
let ctx = ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
};
(spec.handler)(&ctx, &args).expect("应成功").content
}
#[test]
fn lists_instances_with_limit() {
let content = call(&registry(), LIST_INSTANCES, json!({ "limit": 1 }));
assert_eq!(content["total"], json!(1));
assert_eq!(content["instances"][0]["id"], json!("inst-1"));
assert_eq!(content["truncated"], json!(false));
}
#[test]
fn lists_versions() {
let content = call(&registry(), LIST_VERSIONS, json!({}));
assert_eq!(content["total"], json!(2));
assert_eq!(content["versions"][0]["id"], json!("1.20.1-forge-47.2.20"));
}
#[test]
fn java_status_summarises_majors() {
let content = call(&registry(), GET_JAVA_STATUS, json!({}));
assert_eq!(content["candidate_count"], json!(2));
assert_eq!(content["majors"], json!(["17", "21"]));
assert_eq!(content["default_memory_mb"], json!(2048));
}
#[test]
fn port_errors_are_passed_through() {
let mut registry = ToolRegistry::new();
register(
&mut registry,
Arc::new(MockGame::failing("versions 目录不可读")),
)
.expect("注册应成功");
let spec = registry.get(LIST_VERSIONS).expect("工具存在").clone();
let ctx = ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
};
let err = (spec.handler)(&ctx, &json!({})).unwrap_err();
assert_eq!(err.code(), "port_error");
assert!(err.message().contains("versions 目录不可读"));
}
}
+39
View File
@@ -0,0 +1,39 @@
//! 工具集 v1(02 文档 §3):配置读写 / 会话与日志 / 崩溃诊断 / 实例与 Java / 账户。
//!
//! 分工边界(重要,评审时按这条看):
//! - **工具**:参数语义 → 端口调用 → 结构化结果;需要确认时**只报价不执行**。
//! - **编排层**([`crate::brain::exec`]):schema 校验、确认闸门、YOLO 判定、审计、事件。
//! - **端口**([`crate::port`]):真正的 IO 与领域校验(M12/M14/M15/M18/M31/M33 拥有)。
//!
//! 这样「YOLO」只在一个地方(编排层),工具的测试不需要关心 policy。
//!
//! 双投影:这里的注册表是**唯一真相源**,内置客户端投成 rig `DynamicTool`,
//! 对外 MCP server 投成 rmcp `ToolRoute`([`crate::mcp`])。工具数量与顺序对外一致。
pub mod accounts;
pub mod config;
pub mod diagnose;
pub mod game;
pub mod schema_tool;
pub mod session;
use crate::port::Ports;
use crate::registry::{RegistryError, ToolRegistry};
/// 组装 v1 的全部工具。注册顺序 = 模型看到的顺序(只读在前,写在后)。
///
/// 顺序不是随便排的:模型在长工具表里更容易选中靠前的项,所以「先看再改」
/// (`get_config*` 在 `set_config` 之前)是刻意的提示。
///
/// # Errors
/// 工具名重复 / schema 非法时返回 [`RegistryError`](属于编码错误,装配期就该炸)。
pub fn build_v1_registry(ports: &Ports) -> Result<ToolRegistry, RegistryError> {
let mut registry = ToolRegistry::new();
config::register(&mut registry, ports.setting.clone())?;
schema_tool::register(&mut registry, ports.setting.clone())?;
game::register(&mut registry, ports.game.clone())?;
accounts::register(&mut registry, ports.accounts.clone())?;
session::register(&mut registry, ports.sessions.clone())?;
diagnose::register(&mut registry, ports.diagnose.clone())?;
Ok(registry)
}
+84
View File
@@ -0,0 +1,84 @@
//! `get_config_schema`:把 M12 的配置 schema(**只含 AI 可写键**)投给模型。
//!
//! 为什么单独一个工具而不是塞进 `get_config`:模型要能「先看有哪些键、类型是什么、
//! 哪些是敏感键」,再决定要不要写——这是一次性的静态信息,和读当前值不是同一件事。
//! 拆开还能让 token 预算更可控(schema 比概要大一个量级)。
//!
//! 凭据边界:schema 由 M12 的 `SettingSchema::to_json_schema()` 生成,只遍历
//! `ai.writable && !deprecated` 的键,`ai.api_key`(`locked`)天然不在其中。
use std::sync::Arc;
use serde_json::{json, Value};
use crate::port::SettingPort;
use crate::registry::schema::object;
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 工具名。
pub const GET_CONFIG_SCHEMA: &str = "get_config_schema";
/// 注册 `get_config_schema`。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(
registry: &mut ToolRegistry,
port: Arc<dyn SettingPort>,
) -> Result<(), RegistryError> {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, _args: &Value| {
let schema = port.schema();
if schema.get("properties").is_none() {
return Err(ToolError::Port(
"配置 schema 不可用:装配层没有提供 SettingPort::schema()".to_string(),
));
}
let writable = schema
.get("properties")
.and_then(Value::as_object)
.map_or(0, serde_json::Map::len);
Ok(ToolOutput::ok(
json!({
"scope": "ai_writable_schema",
"writable_key_count": writable,
"schema": schema,
}),
format!("读取配置 schema({writable} 个 AI 可写键)"),
))
});
registry.register(ToolSpec::read_only(
GET_CONFIG_SCHEMA,
"读取启动器配置的 JSON Schema(只含 AI 可写键)。每个键带类型、取值范围、说明与 `x-ai-sensitivity` 敏感等级;凭据类键不会出现。写配置前先看它。",
object(&[], &[]),
handler,
))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockSettings;
fn ctx() -> ToolCtx {
ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
}
}
#[test]
fn returns_schema_without_credentials() {
let port: Arc<dyn SettingPort> = Arc::new(MockSettings::new());
let mut registry = ToolRegistry::new();
register(&mut registry, port).expect("注册应成功");
let spec = registry.get(GET_CONFIG_SCHEMA).expect("工具存在").clone();
let out = (spec.handler)(&ctx(), &json!({})).expect("应返回 schema");
let text = out.content.to_string();
assert!(out.content["writable_key_count"].as_u64().unwrap_or(0) > 0);
assert!(text.contains("x-ai-sensitivity"));
assert!(!text.contains("ai.api_key"), "凭据键不得进 schema:{text}");
}
}
+388
View File
@@ -0,0 +1,388 @@
//! `list_game_sessions` / `read_game_log`(02 文档 §3.2「能读取某次游戏崩溃日志」)。
//!
//! 数据源是 M18 的会话事件流(`DevDocs/SubAgentsTalk/launch-接口约定.md`):
//! - 列表读 `index.jsonl`(每会话一行摘要,同 id 取最后一行);
//! - 日志读 `<session-id>.jsonl`,**按 `seq` 切片 + 按 `kind` 过滤**,不是按行号。
//!
//! 两条防 token 爆炸的硬约束:
//! 1. 单次最多 [`MAX_LOG_EVENTS`] 条事件(默认 [`DEFAULT_LOG_EVENTS`]);
//! 2. 单条 payload 里的字符串超过 [`MAX_PAYLOAD_CHARS`] 截断。
//!
//! 脱敏:launch 落盘前已经做过一遍(`<home>` / `<redacted:token>`),本工具再跑一遍
//! [`crate::redact::redact_text`] 作为第二道防线(幂等,旧会话/第三方 mod 输出可能漏网)。
use std::sync::Arc;
use serde_json::{json, Map, Value};
use crate::port::{GameSessionPort, LogEvent, LogPage, LogQuery};
use crate::redact::redact_text;
use crate::registry::schema::{enum_string_array, integer, non_empty_string, object, string};
use crate::registry::{
RegistryError, ToolCtx, ToolError, ToolFn, ToolOutput, ToolRegistry, ToolSpec,
};
/// 列出游戏会话。
pub const LIST_GAME_SESSIONS: &str = "list_game_sessions";
/// 读一个会话的日志。
pub const READ_GAME_LOG: &str = "read_game_log";
/// 单次返回的事件上限(防 token 爆炸的硬闸)。
pub const MAX_LOG_EVENTS: usize = 500;
/// 默认返回条数。
pub const DEFAULT_LOG_EVENTS: usize = 100;
/// 单条 payload 字符串的展示上限(字符)。
pub const MAX_PAYLOAD_CHARS: usize = 800;
/// 列表默认/最大条数。
pub const DEFAULT_SESSION_LIMIT: usize = 10;
/// 列表最大条数。
pub const MAX_SESSION_LIMIT: usize = 50;
/// `launch-接口约定.md` §3 的事件类型(schema 里给模型做枚举;未知 kind 仍可透传)。
pub const KNOWN_KINDS: [&str; 13] = [
"session_start",
"java_selected",
"cmd_built",
"natives_extracted",
"proc_start",
"stdout",
"stderr",
"window_detected",
"exit",
"crash_found",
"diagnosis",
"killed",
"session_end",
];
/// 注册两个日志工具。
///
/// # Errors
/// 工具名重复/schema 非法时返回 [`RegistryError`]。
pub fn register(
registry: &mut ToolRegistry,
port: Arc<dyn GameSessionPort>,
) -> Result<(), RegistryError> {
registry.register(list_sessions_spec(Arc::clone(&port)))?;
registry.register(read_log_spec(port))
}
fn list_sessions_spec(port: Arc<dyn GameSessionPort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let limit = args
.get("limit")
.and_then(Value::as_u64)
.map_or(DEFAULT_SESSION_LIMIT, |n| n as usize)
.clamp(1, MAX_SESSION_LIMIT);
let instance_id = args.get("instance_id").and_then(Value::as_str);
let sessions = port
.list_sessions(limit, instance_id)
.map_err(ToolError::Port)?;
if sessions.is_empty() {
return Ok(ToolOutput::ok(
json!({ "sessions": [], "count": 0 }),
"没有游戏会话记录(还没启动过游戏,或数据目录不对)".to_string(),
));
}
let crashed = sessions
.iter()
.filter(|s| s.crash_found || s.silent_failure || s.exit_code.is_some_and(|c| c != 0))
.count();
let summary = format!(
"最近 {} 个游戏会话,其中 {crashed} 个崩溃/异常退出;最近一次 {}({})",
sessions.len(),
sessions[0].session_id,
sessions[0].started_at.as_deref().unwrap_or("启动时间未知")
);
Ok(ToolOutput::ok(
json!({ "sessions": sessions, "count": sessions.len(), "problem_count": crashed }),
summary,
))
});
ToolSpec::read_only(
LIST_GAME_SESSIONS,
"列出最近的游戏会话(启动时间、退出码、是否崩溃、规则引擎首选结论)。用于定位要读哪一次会话的日志。",
object(
&[
("limit", integer("返回条数", 1, MAX_SESSION_LIMIT as i64)),
("instance_id", string("只看某个实例的会话;省略则全部实例")),
],
&[],
),
handler,
)
}
fn read_log_spec(port: Arc<dyn GameSessionPort>) -> ToolSpec {
let handler: ToolFn = Arc::new(move |_ctx: &ToolCtx, args: &Value| {
let session_id = args
.get("session_id")
.and_then(Value::as_str)
.map(str::trim)
.filter(|s| !s.is_empty())
.ok_or_else(|| ToolError::NotAllowed("缺少参数 `session_id`".to_string()))?
.to_string();
let kinds: Vec<String> = args
.get("kinds")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.map(str::to_string)
.collect()
})
.unwrap_or_default();
let max_events = args
.get("max_events")
.and_then(Value::as_u64)
.map_or(DEFAULT_LOG_EVENTS, |n| n as usize)
.clamp(1, MAX_LOG_EVENTS);
let query = LogQuery {
from_seq: args.get("from_seq").and_then(Value::as_u64),
to_seq: args.get("to_seq").and_then(Value::as_u64),
kinds,
max_events,
};
let page = port
.read_log(&session_id, &query)
.map_err(ToolError::Port)?;
Ok(render_page(&page))
});
ToolSpec::read_only(
READ_GAME_LOG,
"读取某次游戏会话的事件流(stdout/stderr 按行、退出事件、crash-report 摘录)。可按 seq 区间和事件类型过滤;单次最多 500 条、单条最长 800 字符,优先用 kinds 过滤 stderr/exit/crash_found 而不是拉全量。",
object(
&[
("session_id", non_empty_string("会话 id,来自 list_game_sessions")),
("from_seq", integer("起始 seq(含)", 0, 9_007_199_254_740_991)),
("to_seq", integer("结束 seq(含)", 0, 9_007_199_254_740_991)),
(
"kinds",
enum_string_array(&KNOWN_KINDS, "只要这些事件类型;省略则全部", 13),
),
("max_events", integer("最多返回多少条", 1, MAX_LOG_EVENTS as i64)),
],
&["session_id"],
),
handler,
)
}
/// 把端口返回的一页日志压成工具结果(含摘要,模型据此决定要不要继续翻页)。
fn render_page(page: &LogPage) -> ToolOutput {
let events: Vec<Value> = page.events.iter().map(render_event).collect();
let kind_summary = page
.kind_counts
.iter()
.map(|(kind, count)| format!("{kind}×{count}"))
.collect::<Vec<_>>()
.join(", ");
let (content, summary) = if events.is_empty() {
(
json!({
"session_id": page.session_id,
"total_events": page.total_events,
"matched_events": 0,
"truncated": false,
"kind_counts": page.kind_counts,
"first_ts": page.first_ts,
"last_ts": page.last_ts,
"events": [],
"hint": "没有符合过滤条件的事件;把 kinds/from_seq/to_seq 放宽再试",
}),
format!(
"会话 {} 没有匹配的事件(共 {} 条)",
page.session_id, page.total_events
),
)
} else {
let truncated_note = if page.truncated {
"(已截断)"
} else {
""
};
(
json!({
"session_id": page.session_id,
"total_events": page.total_events,
"matched_events": page.matched_events,
"truncated": page.truncated,
"kind_counts": page.kind_counts,
"first_ts": page.first_ts,
"last_ts": page.last_ts,
"events": events,
}),
format!(
"会话 {}:共 {} 条事件,返回 {} 条{truncated_note};类型分布 {kind_summary}",
page.session_id,
page.total_events,
events.len(),
),
)
};
ToolOutput::ok(content, summary)
}
fn render_event(event: &LogEvent) -> Value {
json!({
"seq": event.seq,
"ts": event.ts,
"t_ms": event.t_ms,
"kind": event.kind,
"payload": shrink(&event.payload),
})
}
/// 递归脱敏 + 截断(第二道脱敏防线)。
fn shrink(value: &Value) -> Value {
match value {
Value::String(text) => Value::String(cap(&redact_text(text))),
Value::Array(items) => Value::Array(items.iter().map(shrink).collect()),
Value::Object(map) => {
let mut out = Map::with_capacity(map.len());
for (key, item) in map {
out.insert(key.clone(), shrink(item));
}
Value::Object(out)
}
other => other.clone(),
}
}
fn cap(text: &str) -> String {
let length = text.chars().count();
if length <= MAX_PAYLOAD_CHARS {
return text.to_string();
}
let head: String = text.chars().take(MAX_PAYLOAD_CHARS).collect();
format!("{head}…(已截断 {} 字符)", length - MAX_PAYLOAD_CHARS)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::MockSessions;
use serde_json::json;
const SESSION: &str = "20261029T124501-9f3c2a";
fn mock() -> MockSessions {
let (summary, events) = MockSessions::crashing_session(SESSION);
let (older, older_events) = MockSessions::crashing_session("20261028T100000-aaaaaa");
let mut sessions = MockSessions::new();
sessions.add(summary, events);
sessions.add(older, older_events);
sessions
}
fn registry() -> ToolRegistry {
let mut registry = ToolRegistry::new();
register(&mut registry, Arc::new(mock())).expect("注册应成功");
registry
}
/// 走**真实注册表 → 真实 handler**,不复制实现(否则测的是复制品)。
fn call(tool: &str, args: Value) -> ToolOutput {
let registry = registry();
let spec = registry.get(tool).expect("工具应存在").clone();
(spec.handler)(
&ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
},
&args,
)
.expect("工具应成功")
}
#[test]
fn lists_sessions_newest_first() {
let out = call(LIST_GAME_SESSIONS, json!({ "limit": 5 }));
assert_eq!(out.content["count"], json!(2));
assert_eq!(out.content["sessions"][0]["session_id"], json!(SESSION));
assert_eq!(out.content["problem_count"], json!(2));
assert!(out.summary.contains("2 个崩溃/异常退出"));
}
#[test]
fn list_respects_limit() {
let out = call(LIST_GAME_SESSIONS, json!({ "limit": 1 }));
assert_eq!(out.content["count"], json!(1));
}
#[test]
fn filters_by_kind_and_keeps_summary() {
let out = call(
READ_GAME_LOG,
json!({ "session_id": SESSION, "kinds": ["stderr"] }),
);
assert_eq!(out.content["events"].as_array().unwrap().len(), 1);
assert_eq!(out.content["kind_counts"]["stdout"], json!(1));
assert!(out.summary.contains("共 5 条事件"));
}
#[test]
fn truncates_when_more_events_than_cap() {
let out = call(
READ_GAME_LOG,
json!({ "session_id": SESSION, "max_events": 2 }),
);
assert_eq!(out.content["events"].as_array().unwrap().len(), 2);
assert_eq!(out.content["truncated"], json!(true));
assert_eq!(out.content["matched_events"], json!(5));
}
#[test]
fn masks_user_dir_in_payload() {
let out = call(
READ_GAME_LOG,
json!({ "session_id": SESSION, "kinds": ["crash_found"] }),
);
let payload = &out.content["events"][0]["payload"];
assert_eq!(
payload["path"],
json!(r"C:\Users\***\.minecraft\crash-reports\crash-1.txt")
);
}
#[test]
fn reports_empty_result_with_hint() {
let out = call(
READ_GAME_LOG,
json!({ "session_id": SESSION, "kinds": ["window_detected"] }),
);
assert_eq!(out.content["events"], json!([]));
assert!(out.content["hint"].is_string());
}
#[test]
fn caps_long_payload_text() {
let long = "x".repeat(MAX_PAYLOAD_CHARS + 10);
assert!(cap(&long).contains("已截断 10 字符"));
}
#[test]
fn unknown_session_is_a_port_error() {
let registry = registry();
let spec = registry.get(READ_GAME_LOG).expect("工具应存在").clone();
let err = (spec.handler)(
&ToolCtx {
agent_session_id: "s1".to_string(),
confirmed: false,
},
&json!({ "session_id": "nope" }),
)
.unwrap_err();
assert_eq!(err.code(), "port_error");
assert!(err.message().contains("不存在"));
}
}
+248
View File
@@ -0,0 +1,248 @@
//! 对话循环集成测试:mock provider 驱动**完整链路**(provider → 工具编排 → 审计 → 事件)。
//!
//! 这里测"循环的骨架":多轮工具调用、步数上限、流式增量、禁用态、provider 失败。
//! 安全边界(白名单/确认/YOLO/审计标记)在 `tools_security.rs`。
mod support;
use std::sync::Arc;
use serde_json::json;
use support::{
block_on, list_args, tool_call_reply, Harness, MockProvider, AGENT_SESSION, SESSION,
};
use unlucky_agent::audit::AuditOutcome;
use unlucky_agent::brain::{BrainError, ChatMessage, ChatReply, StopReason, ToolCall};
use unlucky_agent::event::AgentEvent;
#[test]
fn single_turn_without_tools_returns_text() {
let harness = Harness::new(vec![ChatReply::text("你好,需要我看看最近的崩溃吗?")]);
let mut history = Vec::new();
let outcome = block_on(harness.brain.run_turn(AGENT_SESSION, &mut history, "你好")).unwrap();
assert_eq!(outcome.text, "你好,需要我看看最近的崩溃吗?");
assert_eq!(outcome.steps, 1);
assert_eq!(outcome.tool_calls, 0);
assert_eq!(outcome.stopped_reason, StopReason::Completed);
assert_eq!(history.len(), 2, "应只有 user + assistant");
assert!(harness.audit.is_empty(), "没调工具就不该有审计记录");
}
#[test]
fn system_prompt_leads_every_request_and_tools_are_projected() {
let harness = Harness::new(vec![ChatReply::text("好的")]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "看看配置"),
)
.unwrap();
let requests = harness.provider.requests();
assert_eq!(requests.len(), 1);
let request = &requests[0];
assert!(
matches!(&request.messages[0], ChatMessage::System { content } if content.contains("Unlucky-Launcher")),
"system prompt 必须在首位"
);
assert_eq!(request.model, "mock-model");
let names: Vec<&str> = request.tools.iter().map(|t| t.name.as_str()).collect();
assert_eq!(
names,
vec![
"get_config",
"set_config",
"get_config_schema",
"list_instances",
"list_versions",
"get_java_status",
"list_accounts",
"list_game_sessions",
"read_game_log",
"diagnose_crash",
],
"注册表的双投影载荷必须原样交给 provider"
);
// 双投影契约:provider 收到的 schema 与注册表定义逐字节相等。
assert_eq!(request.tools, harness.registry.definitions());
}
#[test]
fn tool_call_round_trip_feeds_result_back_and_finishes() {
let harness = Harness::new(vec![
tool_call_reply("call_1", "list_game_sessions", list_args()),
ChatReply::text("最近一次会话崩溃了,要不要跑诊断?"),
]);
let mut history = Vec::new();
let outcome = block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "最近崩了吗"),
)
.unwrap();
assert_eq!(outcome.tool_calls, 1);
assert_eq!(outcome.steps, 2);
assert_eq!(outcome.stopped_reason, StopReason::Completed);
let requests = harness.provider.requests();
assert_eq!(requests.len(), 2);
let tool_message = requests[1]
.messages
.iter()
.find_map(|m| match m {
ChatMessage::Tool {
call_id,
name,
content,
} => Some((call_id.clone(), name.clone(), content.clone())),
_ => None,
})
.expect("必须有工具结果消息");
assert_eq!(tool_message.0, "call_1");
assert_eq!(tool_message.1, "list_game_sessions");
assert!(
tool_message.2.contains(SESSION),
"工具结果应包含会话 id:{}",
tool_message.2
);
let audits = harness.audit.records();
assert_eq!(audits.len(), 1);
assert_eq!(audits[0].tool, "list_game_sessions");
assert_eq!(audits[0].outcome, AuditOutcome::Ok);
assert!(!audits[0].yolo);
assert!(!audits[0].confirmed);
}
#[test]
fn multiple_tool_calls_in_one_step_all_execute() {
let reply = ChatReply::with_tool_calls(vec![
ToolCall {
id: "c1".to_string(),
name: "list_game_sessions".to_string(),
arguments: list_args(),
},
ToolCall {
id: "c2".to_string(),
name: "diagnose_crash".to_string(),
arguments: json!({ "session_id": SESSION }),
},
]);
let harness = Harness::new(vec![reply, ChatReply::text("诊断完成")]);
let mut history = Vec::new();
let outcome = block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "查一下"),
)
.unwrap();
assert_eq!(outcome.tool_calls, 2);
assert_eq!(harness.audit.len(), 2);
assert_eq!(
harness
.audit
.records()
.iter()
.map(|r| r.tool.as_str())
.collect::<Vec<_>>(),
vec!["list_game_sessions", "diagnose_crash"]
);
}
#[test]
fn step_limit_stops_runaway_loop() {
// 每一步都要求调工具,永远不会给最终回答。
let script: Vec<ChatReply> = (0..16)
.map(|i| tool_call_reply(&format!("c{i}"), "get_config", json!({})))
.collect();
let harness = Harness::new(script);
let mut history = Vec::new();
let outcome = block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "死循环"),
)
.unwrap();
assert_eq!(outcome.stopped_reason, StopReason::StepLimit);
assert_eq!(outcome.steps, unlucky_agent::brain::DEFAULT_MAX_STEPS);
assert_eq!(outcome.tool_calls, unlucky_agent::brain::DEFAULT_MAX_STEPS);
}
#[test]
fn streaming_deltas_are_forwarded_as_events() {
let harness = Harness::new(vec![ChatReply::text("日志里是 NoClassDefFoundError")]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "什么错误"),
)
.unwrap();
assert_eq!(
harness.events.streamed_text(),
"日志里是 NoClassDefFoundError"
);
let events = harness.events.events();
assert!(events
.iter()
.any(|e| matches!(e, AgentEvent::TurnStarted { .. })));
assert!(events
.iter()
.any(|e| matches!(e, AgentEvent::AssistantText { .. })));
assert!(events
.iter()
.any(|e| matches!(e, AgentEvent::TurnFinished { .. })));
}
#[test]
fn disabled_provider_fails_fast() {
let harness = Harness::from_provider(Arc::new(MockProvider::disabled()));
let mut history = Vec::new();
let err = block_on(harness.brain.run_turn(AGENT_SESSION, &mut history, "你好")).unwrap_err();
assert_eq!(err, BrainError::Disabled);
assert!(err.to_string().contains("规则引擎"), "要提示降级能力");
assert!(
harness.provider.requests().is_empty(),
"禁用态不该发起任何请求"
);
assert!(history.is_empty(), "禁用态不该改动历史");
}
#[test]
fn provider_error_surfaces_as_brain_error_and_event() {
let harness = Harness::from_provider(Arc::new(MockProvider::failing(
"连接 http://127.0.0.1:8080 失败",
)));
let mut history = Vec::new();
let err = block_on(harness.brain.run_turn(AGENT_SESSION, &mut history, "你好")).unwrap_err();
assert_eq!(
err,
BrainError::Provider(unlucky_agent::brain::ProviderError::new(
"连接 http://127.0.0.1:8080 失败"
))
);
assert!(harness
.events
.events()
.iter()
.any(|e| matches!(e, AgentEvent::Error { message } if message.contains("8080"))));
}
#[test]
fn empty_script_yields_empty_completion_turn() {
let harness = Harness::new(vec![]);
let mut history = Vec::new();
let outcome = block_on(harness.brain.run_turn(AGENT_SESSION, &mut history, "你好")).unwrap();
assert_eq!(outcome.text, "");
assert_eq!(outcome.stopped_reason, StopReason::Completed);
}
+132
View File
@@ -0,0 +1,132 @@
//! **双投影契约测试(MCP 侧)**:注册表 → rmcp `Tool` 必须与 rig 侧逐项相等。
//!
//! research/02 §6.2 建议进 CI 的那条断言,M16 落的是「注册表自身是纯投影」+「rig 适配层
//! 只做直投」,M39 补上 rmcp 侧:
//!
//! 1. `mcp::projection::tool_attrs(&registry)` 的 `(name, description, input_schema)`
//! 与 `registry.definitions()` **逐项相等**(JSON 层面,不是"看起来差不多");
//! 2. `tools/list` 的顺序与注册顺序一致,数量等于注册表长度;
//! 3. 每个 schema 根是 `object`(rig 与 rmcp 的共同前提);
//! 4. `read_only_hint` 与 `Access` 一致(外部客户端据此决定能不能静默调用);
//! 5. 只读子集不会漏出写工具(`agent.mcp.allow_write=false` 的默认形态)。
use serde_json::{json, Value};
use unlucky_agent::mcp::projection::{tool_attr, tool_attrs};
use unlucky_agent::port::Ports;
use unlucky_agent::registry::{Access, ToolDefinition, ToolRegistry};
use unlucky_agent::testing::mock_ports;
use unlucky_agent::tools::build_v1_registry;
fn registry() -> ToolRegistry {
let (ports, _settings) = mock_ports();
build_v1_registry(&ports).expect("注册表应装配成功")
}
fn ports() -> Ports {
mock_ports().0
}
#[test]
fn mcp_projection_equals_registry_definition_item_by_item() {
let registry = registry();
let definitions = registry.definitions();
let attrs = tool_attrs(&registry);
assert_eq!(attrs.len(), definitions.len());
for (attr, definition) in attrs.iter().zip(definitions.iter()) {
assert_eq!(attr.name.as_ref(), definition.name, "工具名必须相等");
assert_eq!(
attr.description.as_deref(),
Some(definition.description.as_str()),
"{} 的 description 必须逐字相等",
definition.name
);
assert_eq!(
Value::Object((*attr.input_schema).clone()),
definition.input_schema,
"{} 的 JSON Schema 必须逐项相等",
definition.name
);
}
}
#[test]
fn projection_order_matches_registration_order() {
let registry = registry();
let projected: Vec<String> = tool_attrs(&registry)
.iter()
.map(|attr| attr.name.to_string())
.collect();
assert_eq!(projected, registry.names(), "两侧顺序必须一致");
}
#[test]
fn every_projected_schema_is_an_object_and_round_trips() {
for attr in tool_attrs(&registry()) {
let schema = Value::Object((*attr.input_schema).clone());
assert_eq!(
schema["type"],
json!("object"),
"{} 的 schema 根必须是 object",
attr.name
);
// rmcp 会把 Tool 序列化进 tools/list 的响应体:必须能反序列化回来。
let json = serde_json::to_string(&attr).expect("Tool 可序列化");
let back: rmcp::model::Tool = serde_json::from_str(&json).expect("Tool 可反序列化");
assert_eq!(back, attr);
}
}
#[test]
fn read_only_hint_tracks_access() {
let registry = registry();
for (attr, spec) in tool_attrs(&registry).iter().zip(registry.specs()) {
let hint = attr
.annotations
.as_ref()
.and_then(|annotations| annotations.read_only_hint)
.expect("每个工具都应有 read_only_hint");
assert_eq!(hint, spec.access == Access::ReadOnly, "{}", attr.name);
}
}
#[test]
fn read_only_subset_projects_without_the_writing_tool() {
let subset = registry().read_only_subset();
assert_eq!(subset.len(), 9);
let names: Vec<String> = tool_attrs(&subset)
.iter()
.map(|attr| attr.name.to_string())
.collect();
assert!(!names.iter().any(|name| name == "set_config"), "{names:?}");
assert!(subset.access_of("set_config").is_none());
}
#[test]
fn projected_attrs_are_pure_functions_of_the_definition() {
let definition = ToolDefinition {
name: "demo".to_string(),
description: "演示".to_string(),
input_schema: json!({ "type": "object", "properties": {}, "required": [] }),
};
let first = tool_attr(&definition, Access::ReadOnly);
let second = tool_attr(&definition, Access::ReadOnly);
assert_eq!(first, second);
// 副作用等级换一下,只有 annotations 变,name/description/schema 不变。
let mutating = tool_attr(&definition, Access::Mutating);
assert_eq!(first.name, mutating.name);
assert_eq!(first.input_schema, mutating.input_schema);
assert_ne!(first.annotations, mutating.annotations);
}
#[test]
fn mock_ports_cover_every_port_the_registry_needs() {
// 装配完整性:五个端口都在,注册表才有这十个工具(少一个端口 = 少工具)。
let ports = ports();
let registry = build_v1_registry(&ports).expect("注册表应装配成功");
assert_eq!(registry.len(), 10);
assert!(unlucky_agent::testing::expected_v1_tool_names()
.iter()
.all(|name| registry.get(name).is_some()));
}
+336
View File
@@ -0,0 +1,336 @@
//! MCP over Streamable HTTP 的端到端测试:真起监听、打裸 JSON-RPC,断言工具返回与审计。
//!
//! 为什么不用 MCP 客户端 crate:客户端依赖会再拖一棵 reqwest 树(且 3.8 的客户端 feature
//! 与我们的服务端 feature 不是一组)。裸 HTTP 反而更贴近「用户用 Claude Code 连上来」
//! 的实际形状——握手、会话头、`tools/list`、`tools/call` 一个都不省。
//!
//! 覆盖的安全语义(02 §3.1 / §4b):
//! - 只读模式下 `set_config` 根本不在工具表里,硬调 → tool-level 错误 + `unknown_tool` 审计;
//! - 普通键(`download.concurrency`,Low)直接写入,审计 `outcome=ok`;
//! - 敏感键(`java.selected_path`,High)在**没有弹窗**的外部场景被拒,文案引导去设置页/YOLO;
//! - 打开 YOLO 后同一个写入成功,审计 `yolo=true`。
use std::net::SocketAddr;
use std::sync::Arc;
use serde_json::{json, Value};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use unlucky_agent::audit::{AuditOutcome, AuditRecord, JsonlAudit};
use unlucky_agent::brain::exec::ToolExecutor;
use unlucky_agent::clock::{FixedClock, SharedClock};
use unlucky_agent::confirm::{ConfirmPolicy, DenyGuidance, NoUiGate};
use unlucky_agent::event::NoopSink;
use unlucky_agent::mcp::{bind, serve_http_on, McpConfig, RegistryServer};
use unlucky_agent::testing::mock_ports;
use unlucky_agent::tools::build_v1_registry;
const INITIALIZE: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"ull-test","version":"0.1"}}}"#;
struct Harness {
addr: SocketAddr,
audit_dir: std::path::PathBuf,
}
fn audit_dir(tag: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("ull-mcp-http-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
dir
}
fn server(read_only: bool, yolo: bool, audit: Arc<JsonlAudit>) -> RegistryServer {
let (ports, _settings) = mock_ports();
let registry = Arc::new(build_v1_registry(&ports).expect("注册表应装配成功"));
let exposed = if read_only {
Arc::new(registry.read_only_subset())
} else {
Arc::clone(&registry)
};
let clock: SharedClock = Arc::new(FixedClock::new(1_793_304_753_123));
let executor = Arc::new(
ToolExecutor::new(
exposed,
audit,
Arc::new(NoUiGate),
ConfirmPolicy { yolo },
clock,
Arc::new(NoopSink),
)
.with_guidance(DenyGuidance::External),
);
RegistryServer::new(registry, executor, "mcp-http", read_only)
}
async fn spawn(tag: &str, read_only: bool, yolo: bool) -> Harness {
let dir = audit_dir(tag);
let clock: SharedClock = Arc::new(FixedClock::new(1_793_304_753_123));
let audit = Arc::new(JsonlAudit::new(&dir, clock));
let server = server(read_only, yolo, audit);
let cfg = McpConfig {
port: 0,
..McpConfig::default()
};
let (addr, listener) = bind(&cfg).await.expect("应能绑定临时端口");
tokio::spawn(async move {
let _ = serve_http_on(server, cfg, addr, listener).await;
});
Harness {
addr,
audit_dir: dir,
}
}
/// 发一条 HTTP POST(`Connection: close` 让读取变成 read_to_end)。
async fn post(
addr: SocketAddr,
body: &str,
session: Option<&str>,
token: Option<&str>,
) -> (u16, Option<String>, String) {
let mut stream = TcpStream::connect(addr).await.expect("连接失败");
let mut head = format!(
"POST /mcp HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\n\
Accept: application/json, text/event-stream\r\nConnection: close\r\n\
Content-Length: {}\r\n",
body.len()
);
if let Some(session) = session {
head.push_str(&format!("Mcp-Session-Id: {session}\r\n"));
}
if let Some(token) = token {
head.push_str(&format!("Authorization: Bearer {token}\r\n"));
}
head.push_str("\r\n");
stream
.write_all(format!("{head}{body}").as_bytes())
.await
.expect("写请求失败");
stream.flush().await.expect("刷新失败");
let mut raw = Vec::new();
stream.read_to_end(&mut raw).await.expect("读响应失败");
let text = String::from_utf8_lossy(&raw).to_string();
let (head, body) = text.split_once("\r\n\r\n").unwrap_or((text.as_str(), ""));
let status = head
.lines()
.next()
.and_then(|line| line.split_whitespace().nth(1))
.and_then(|code| code.parse::<u16>().ok())
.unwrap_or(0);
let session = head.lines().find_map(|line| {
let (name, value) = line.split_once(':')?;
name.eq_ignore_ascii_case("mcp-session-id")
.then(|| value.trim().to_string())
});
(status, session, body.to_string())
}
/// 响应体可能是裸 JSON,也可能是 SSE(`data: {...}`);两种都解出第一条 JSON-RPC 响应。
fn parse_rpc(body: &str) -> Value {
if let Ok(value) = serde_json::from_str::<Value>(body.trim()) {
return value;
}
for line in body.lines() {
let Some(data) = line.strip_prefix("data: ") else {
continue;
};
if let Ok(value) = serde_json::from_str::<Value>(data.trim()) {
return value;
}
}
panic!("响应体既不是 JSON 也不是 SSE:{body}");
}
async fn initialize(addr: SocketAddr) -> Option<String> {
let (status, session, body) = post(addr, INITIALIZE, None, None).await;
assert_eq!(status, 200, "initialize 应成功:{body}");
let response = parse_rpc(&body);
assert_eq!(
response["result"]["serverInfo"]["name"],
json!("unlucky-launcher")
);
// 按 MCP 规范补一条 initialized 通知(无 id、无响应体)。
let _ = post(
addr,
r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
session.as_deref(),
None,
)
.await;
session
}
async fn rpc(
addr: SocketAddr,
session: Option<&str>,
id: u32,
method: &str,
params: Value,
) -> Value {
let body =
json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }).to_string();
let (status, _session, text) = post(addr, &body, session, None).await;
assert_eq!(status, 200, "{method} 应成功:{text}");
parse_rpc(&text)
}
fn audit_records(dir: &std::path::Path) -> Vec<AuditRecord> {
let mut out = Vec::new();
if let Ok(entries) = std::fs::read_dir(dir) {
for entry in entries.flatten() {
let text = std::fs::read_to_string(entry.path()).unwrap_or_default();
for line in text.lines() {
if let Ok(record) = serde_json::from_str::<AuditRecord>(line) {
out.push(record);
}
}
}
}
out
}
#[tokio::test(flavor = "multi_thread")]
async fn readonly_server_lists_and_serves_only_read_tools() {
let harness = spawn("readonly", true, false).await;
let session = initialize(harness.addr).await;
let list = rpc(harness.addr, session.as_deref(), 2, "tools/list", json!({})).await;
let tools = list["result"]["tools"].as_array().expect("应有 tools 数组");
let names: Vec<&str> = tools
.iter()
.filter_map(|tool| tool["name"].as_str())
.collect();
assert_eq!(names.len(), 9, "{names:?}");
assert!(!names.contains(&"set_config"), "只读模式不得暴露写工具");
assert!(names.contains(&"get_config"));
// 真调一个只读工具:返回真实配置概要(mock 端口)。
let call = rpc(
harness.addr,
session.as_deref(),
3,
"tools/call",
json!({ "name": "get_config", "arguments": {} }),
)
.await;
assert_ne!(call["result"]["isError"], json!(true), "{call}");
let text = call["result"]["content"][0]["text"]
.as_str()
.unwrap_or_default();
assert!(text.contains("download.concurrency"), "{text}");
// 硬调写工具:tool-level 错误(客户端能看见文案)+ unknown_tool 审计。
let denied = rpc(
harness.addr,
session.as_deref(),
4,
"tools/call",
json!({ "name": "set_config", "arguments": { "path": "download.concurrency", "value": 16 } }),
)
.await;
assert_eq!(denied["result"]["isError"], json!(true), "{denied}");
let records = audit_records(&harness.audit_dir);
assert!(records.iter().any(|r| r.tool == "get_config"
&& r.outcome == AuditOutcome::Ok
&& r.agent_session_id == "mcp-http"));
assert!(records
.iter()
.any(|r| r.tool == "set_config" && r.outcome == AuditOutcome::UnknownTool));
let _ = std::fs::remove_dir_all(&harness.audit_dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn write_server_enforces_sensitive_key_confirmation() {
let harness = spawn("write", false, false).await;
let session = initialize(harness.addr).await;
// 普通键:直接写。
let ok = rpc(
harness.addr,
session.as_deref(),
2,
"tools/call",
json!({ "name": "set_config", "arguments": { "path": "download.concurrency", "value": 16 } }),
)
.await;
assert_ne!(ok["result"]["isError"], json!(true), "{ok}");
// 敏感键:外部客户端没有弹窗 → 拒绝,文案要能指导用户下一步。
let denied = rpc(
harness.addr,
session.as_deref(),
3,
"tools/call",
json!({ "name": "set_config", "arguments": { "path": "java.selected_path", "value": "D:/jdk17/bin/java.exe" } }),
)
.await;
assert_eq!(denied["result"]["isError"], json!(true), "{denied}");
let text = denied["result"]["content"][0]["text"]
.as_str()
.unwrap_or_default();
assert!(
text.contains("YOLO"),
"拒绝文案应引导到 YOLO/设置页:{text}"
);
assert!(text.contains("设置页"), "{text}");
let records = audit_records(&harness.audit_dir);
assert!(records
.iter()
.any(|r| r.tool == "set_config" && r.outcome == AuditOutcome::AwaitingConfirmation));
assert!(records
.iter()
.any(|r| r.tool == "set_config" && r.outcome == AuditOutcome::Denied && !r.yolo));
let _ = std::fs::remove_dir_all(&harness.audit_dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn yolo_lets_the_same_write_through_and_audits_the_flag() {
let harness = spawn("yolo", false, true).await;
let session = initialize(harness.addr).await;
let written = rpc(
harness.addr,
session.as_deref(),
2,
"tools/call",
json!({ "name": "set_config", "arguments": { "path": "java.selected_path", "value": "D:/jdk17/bin/java.exe" } }),
)
.await;
assert_ne!(written["result"]["isError"], json!(true), "{written}");
let records = audit_records(&harness.audit_dir);
let yolo_ok = records
.iter()
.find(|r| r.tool == "set_config" && r.outcome == AuditOutcome::Ok);
let record = yolo_ok.expect("应有一条 ok 审计");
assert!(record.yolo, "YOLO 放行必须标记 yolo=true");
assert!(!record.confirmed, "YOLO 自动放行不算用户确认");
let _ = std::fs::remove_dir_all(&harness.audit_dir);
}
#[tokio::test(flavor = "multi_thread")]
async fn bearer_token_is_enforced_when_configured() {
let dir = audit_dir("token");
let clock: SharedClock = Arc::new(FixedClock::new(1_793_304_753_123));
let audit = Arc::new(JsonlAudit::new(&dir, clock));
let server = server(true, false, audit);
let cfg = McpConfig {
port: 0,
token: Some("s3cret".to_string()),
..McpConfig::default()
};
let (addr, listener) = bind(&cfg).await.expect("应能绑定");
tokio::spawn(async move {
let _ = serve_http_on(server, cfg, addr, listener).await;
});
let (status, _, _) = post(addr, INITIALIZE, None, None).await;
assert_eq!(status, 401, "没带令牌必须 401");
let (status, _, body) = post(addr, INITIALIZE, None, Some("s3cret")).await;
assert_eq!(status, 200, "带对令牌应通过:{body}");
let _ = std::fs::remove_dir_all(&dir);
}
+163
View File
@@ -0,0 +1,163 @@
//! **双投影契约测试**(research/02 §6.2 建议进 CI 的那一条)。
//!
//! rig 侧(`DynamicTool::new`)与 rmcp 侧(`ToolRoute::new_dyn`)吃的都是
//! `(name, description, serde_json::Value schema)`。本 crate 只维护一份 `ToolSpec`,
//! 所以「两侧相等」在这里等价于三条可断言的性质:
//! 1. [`unlucky_agent::registry::ToolRegistry::definitions`] 是纯投影(多次调用逐字节相等);
//! 2. 每个 schema 根是 `type: object`(两侧都要求对象入参)且拒绝多余参数;
//! 3. 名字唯一,`required` 真的被执行(缺参能被校验器抓到)。
//!
//! 本文件只锁**投影载荷本身**;两侧的一致性各有专测:
//! - rig 侧:`tests/brain_loop.rs` 断言 `provider` 收到的 `request.tools` 与
//! `registry.definitions()` 逐字节相等(`brain/rig.rs` 只做直投);
//! - MCP 侧:`tests/mcp_contract.rs` 断言 rmcp `Tool` 的 `(name, description, schema)` 与
//! 注册表逐项相等(M39 补的那条)。
use serde_json::json;
use unlucky_agent::registry::validate::validate;
use unlucky_agent::registry::{Access, ToolDefinition};
use unlucky_agent::testing::mock_ports;
fn registry() -> unlucky_agent::registry::ToolRegistry {
let (ports, _settings) = mock_ports();
unlucky_agent::tools::build_v1_registry(&ports).expect("注册表应装配成功")
}
#[test]
fn ships_exactly_the_v1_tools() {
let registry = registry();
assert_eq!(
registry.names(),
vec![
"get_config",
"set_config",
"get_config_schema",
"list_instances",
"list_versions",
"get_java_status",
"list_accounts",
"list_game_sessions",
"read_game_log",
"diagnose_crash",
]
);
assert_eq!(registry.len(), 10);
}
#[test]
fn definitions_are_pure_projections() {
let registry = registry();
let first = registry.definitions();
let second = registry.definitions();
assert_eq!(first, second, "投影必须是纯函数");
for definition in &first {
// 序列化后再反序列化必须完全一样(rig 与 rmcp 都走 JSON)。
let json = serde_json::to_string(definition).expect("可序列化");
let round_trip: ToolDefinition = serde_json::from_str(&json).expect("可反序列化");
assert_eq!(&round_trip, definition);
assert!(!definition.description.trim().is_empty());
assert_eq!(
definition.input_schema["type"],
json!("object"),
"{} 的 schema 根必须是 object",
definition.name
);
}
}
#[test]
fn only_set_config_is_mutating() {
let registry = registry();
for name in registry.names() {
let expected = if name == "set_config" {
Access::Mutating
} else {
Access::ReadOnly
};
assert_eq!(registry.access_of(name), Some(expected), "{name}");
}
let read_only: Vec<String> = registry
.read_only_definitions()
.into_iter()
.map(|d| d.name)
.collect();
assert_eq!(
read_only,
vec![
"get_config",
"get_config_schema",
"list_instances",
"list_versions",
"get_java_status",
"list_accounts",
"list_game_sessions",
"read_game_log",
"diagnose_crash",
],
"只读 MCP 模式只暴露这九个(写侧只有 set_config)"
);
}
#[test]
fn every_schema_rejects_unknown_arguments() {
for definition in registry().definitions() {
let err = validate(&definition.input_schema, &json!({ "__unexpected": 1 }))
.expect_err(&format!("{} 应拒绝野参数", definition.name));
assert!(
err.iter().any(|e| e.contains("不是可接受的参数名")),
"{}: {err:?}",
definition.name
);
}
}
#[test]
fn required_fields_are_actually_enforced() {
for definition in registry().definitions() {
let required = definition
.input_schema
.get("required")
.and_then(|r| r.as_array())
.cloned()
.unwrap_or_default();
if required.is_empty() {
continue;
}
let err = validate(&definition.input_schema, &json!({}))
.expect_err(&format!("{} 应有必填参数", definition.name));
for field in required {
let name = field.as_str().unwrap_or_default();
assert!(
err.iter().any(|e| e.contains(name)),
"{} 的必填 `{name}` 没被校验:{err:?}",
definition.name
);
}
}
}
#[test]
fn integer_bounds_are_declared_and_enforced() {
let registry = registry();
let read_log = registry.get("read_game_log").expect("工具存在");
let max_events = &read_log.input_schema["properties"]["max_events"];
assert_eq!(max_events["minimum"], json!(1));
assert_eq!(max_events["maximum"], json!(500));
assert!(validate(
&read_log.input_schema,
&json!({ "session_id": "s", "max_events": 0 })
)
.is_err());
assert!(validate(
&read_log.input_schema,
&json!({ "session_id": "s", "max_events": 501 })
)
.is_err());
assert!(validate(
&read_log.input_schema,
&json!({ "session_id": "s", "max_events": 500 })
)
.is_ok());
}
+225
View File
@@ -0,0 +1,225 @@
//! 集成测试的公共脚手架:**mock provider** + 迷你 `block_on` + 装配好的 harness。
//!
//! `block_on` 是手写的 20 行:mock provider 的 future 永远立刻 Ready,所以不需要运行时。
//! 这样 agent 的循环测试**零 tokio 依赖**,阶段 B 换成 rig 后才需要真运行时。
#![allow(dead_code)]
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll, Waker};
use serde_json::{json, Value};
use unlucky_agent::audit::{AuditSink, MemoryAudit};
use unlucky_agent::brain::{Brain, BrainConfig, BrainDeps};
use unlucky_agent::brain::{
ChatProvider, ChatReply, ChatRequest, DeltaObserver, ProviderConfig, ProviderError,
ProviderFuture, ToolCall,
};
use unlucky_agent::clock::{FixedClock, SharedClock};
use unlucky_agent::confirm::{AutoApproveGate, ConfirmGate, ConfirmPolicy, NoUiGate};
use unlucky_agent::event::{AgentEventSink, MemoryEventSink};
use unlucky_agent::registry::ToolRegistry;
use unlucky_agent::testing::{mock_ports, MockSettings};
/// 立刻完成的 future 直接 poll;挂起就是测试写错了。
pub fn block_on<F: Future>(future: F) -> F::Output {
let mut future: Pin<Box<F>> = Box::pin(future);
let waker = Waker::noop();
let mut context = Context::from_waker(waker);
match future.as_mut().poll(&mut context) {
Poll::Ready(value) => value,
Poll::Pending => panic!("mock provider 不应挂起:测试里没有执行器"),
}
}
/// 脚本化 provider:按顺序回放 [`ChatReply`],并记录收到的请求。
pub struct MockProvider {
config: ProviderConfig,
script: Mutex<VecDeque<ChatReply>>,
requests: Mutex<Vec<ChatRequest>>,
fail_with: Option<String>,
}
impl MockProvider {
/// 用默认模型名(本地 llama.cpp 形态)回放脚本。
#[must_use]
pub fn new(script: Vec<ChatReply>) -> Self {
Self {
config: ProviderConfig::llamacpp_local("mock-model"),
script: Mutex::new(script.into()),
requests: Mutex::new(Vec::new()),
fail_with: None,
}
}
/// 禁用态(测 `BrainError::Disabled`)。
#[must_use]
pub fn disabled() -> Self {
Self {
config: ProviderConfig::disabled(),
script: Mutex::new(VecDeque::new()),
requests: Mutex::new(Vec::new()),
fail_with: None,
}
}
/// 每次补全都失败(测 provider 错误透传)。
#[must_use]
pub fn failing(message: &str) -> Self {
Self {
fail_with: Some(message.to_string()),
..Self::new(Vec::new())
}
}
/// 收到的请求(断言 system prompt / 工具定义 / 回灌的工具消息)。
#[must_use]
pub fn requests(&self) -> Vec<ChatRequest> {
self.requests.lock().map(|r| r.clone()).unwrap_or_default()
}
}
impl ChatProvider for MockProvider {
fn config(&self) -> &ProviderConfig {
&self.config
}
fn complete<'a>(
&'a self,
request: &'a ChatRequest,
observer: &'a dyn DeltaObserver,
) -> ProviderFuture<'a> {
Box::pin(async move {
if let Ok(mut requests) = self.requests.lock() {
requests.push(request.clone());
}
if let Some(message) = &self.fail_with {
return Err(ProviderError::new(message.clone()));
}
let reply = self
.script
.lock()
.ok()
.and_then(|mut script| script.pop_front())
.unwrap_or_default();
// 按 4 字符切块吐增量,模拟流式。
if !reply.text.is_empty() {
for chunk in reply.text.chars().collect::<Vec<_>>().chunks(4) {
observer.on_delta(&chunk.iter().collect::<String>());
}
}
Ok(reply)
})
}
}
/// 装配好的测试环境。
pub struct Harness {
/// 对话循环。
pub brain: Brain,
/// 审计出口(内存)。
pub audit: Arc<MemoryAudit>,
/// 事件出口(内存)。
pub events: Arc<MemoryEventSink>,
/// mock provider(查请求)。
pub provider: Arc<MockProvider>,
/// mock 配置端口(查是否真的写入)。
pub settings: Arc<MockSettings>,
/// 工具注册表。
pub registry: Arc<ToolRegistry>,
}
impl Harness {
/// P0 默认形态:无确认 UI(`NoUiGate`,敏感操作 fail-closed)+ 非 YOLO。
/// 确认请求本身仍会作为 [`unlucky_agent::event::AgentEvent::ConfirmRequested`] 发出。
#[must_use]
pub fn new(script: Vec<ChatReply>) -> Self {
Self::with_gate(script, ConfirmPolicy::default(), |_sink| Arc::new(NoUiGate))
}
/// YOLO:自动放行全部(除破坏性)。
#[must_use]
pub fn yolo(script: Vec<ChatReply>) -> Self {
Self::with_gate(script, ConfirmPolicy { yolo: true }, |_sink| {
Arc::new(AutoApproveGate)
})
}
/// 用指定的(可能失效/禁用的)provider 装配,其余同 [`Harness::new`]。
#[must_use]
pub fn from_provider(provider: Arc<MockProvider>) -> Self {
Self::build(provider, ConfirmPolicy::default(), |_sink| {
Arc::new(NoUiGate)
})
}
/// 自定义闸门 + 策略。
#[must_use]
pub fn with_gate(
script: Vec<ChatReply>,
policy: ConfirmPolicy,
make_gate: impl FnOnce(Arc<dyn AgentEventSink>) -> Arc<dyn ConfirmGate>,
) -> Self {
Self::build(Arc::new(MockProvider::new(script)), policy, make_gate)
}
fn build(
provider: Arc<MockProvider>,
policy: ConfirmPolicy,
make_gate: impl FnOnce(Arc<dyn AgentEventSink>) -> Arc<dyn ConfirmGate>,
) -> Self {
let (ports, settings) = mock_ports();
let registry =
Arc::new(unlucky_agent::tools::build_v1_registry(&ports).expect("注册表应装配成功"));
let audit = Arc::new(MemoryAudit::new());
let events = Arc::new(MemoryEventSink::new());
let clock: SharedClock = Arc::new(FixedClock::with_step(1_793_314_353_123, 3));
let gate = make_gate(events.clone());
let deps = BrainDeps::new(
audit.clone() as Arc<dyn AuditSink>,
gate,
policy,
clock,
events.clone() as Arc<dyn AgentEventSink>,
);
let brain = Brain::new(
provider.clone(),
Arc::clone(&registry),
deps,
BrainConfig::default(),
);
Self {
brain,
audit,
events,
provider,
settings,
registry,
}
}
}
/// 构造一条工具调用回复。
#[must_use]
pub fn tool_call_reply(id: &str, name: &str, arguments: Value) -> ChatReply {
ChatReply::with_tool_calls(vec![ToolCall {
id: id.to_string(),
name: name.to_string(),
arguments,
}])
}
/// 便捷:游戏会话 id(与 `MockSessions::crashing_session` 一致)。
pub const SESSION: &str = "20261029T124501-9f3c2a";
/// 便捷:agent 对话会话 id。
pub const AGENT_SESSION: &str = "chat-1";
/// 便捷:`list_game_sessions` 的最小参数。
#[must_use]
pub fn list_args() -> Value {
json!({ "limit": 5 })
}
+365
View File
@@ -0,0 +1,365 @@
//! 安全边界集成测试:白名单拦截、分级确认、YOLO、审计标记。
//!
//! 这些是 02 文档 §3.1「安全边界」+ §4b「YOLO」与 M12 `setting-接口约定.md` §8
//! (`Low/Medium/High` 三档 + `writable=false` 凭据)的可执行版本;
//! 判断口径对照 research/02 §7 R9(写操作的破坏半径)。
mod support;
use std::sync::Arc;
use serde_json::{json, Value};
use support::{block_on, tool_call_reply, Harness, AGENT_SESSION};
use unlucky_agent::audit::AuditOutcome;
use unlucky_agent::brain::ChatReply;
use unlucky_agent::confirm::{ConfirmDecision, ConfirmPolicy, ScriptedGate};
use unlucky_agent::event::AgentEvent;
fn set_config_reply(path: &str, value: Value) -> ChatReply {
tool_call_reply("c1", "set_config", json!({ "path": path, "value": value }))
}
fn tool_results(harness: &Harness) -> Vec<String> {
harness
.provider
.requests()
.last()
.map(|request| {
request
.messages
.iter()
.filter_map(|m| match m {
unlucky_agent::brain::ChatMessage::Tool { content, .. } => {
Some(content.clone())
}
_ => None,
})
.collect()
})
.unwrap_or_default()
}
fn confirm_events(harness: &Harness) -> usize {
harness
.events
.events()
.iter()
.filter(|e| matches!(e, AgentEvent::ConfirmRequested { .. }))
.count()
}
#[test]
fn low_key_writes_silently_without_confirmation() {
let harness = Harness::new(vec![
set_config_reply("appearance.theme_mode", json!("metro_light")),
ChatReply::text("已切换主题"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换成浅色"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 1);
assert_eq!(
harness.settings.value_of("appearance.theme_mode"),
Some(json!("metro_light"))
);
assert_eq!(confirm_events(&harness), 0, "Low 键不该打扰用户");
let records = harness.audit.records_for("set_config");
assert_eq!(records.len(), 1);
assert_eq!(records[0].outcome, AuditOutcome::Ok);
assert!(!records[0].confirmed, "静默生效不是「用户确认」");
assert!(!records[0].yolo);
}
#[test]
fn medium_key_also_writes_silently() {
// M12:Medium = 静默生效但审计标记(不弹窗)
let harness = Harness::new(vec![
set_config_reply("download.region", json!("cn")),
ChatReply::text("已切到国内源"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换下载源"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 1);
assert_eq!(confirm_events(&harness), 0);
assert_eq!(
harness.audit.records_for("set_config")[0].outcome,
AuditOutcome::Ok
);
}
#[test]
fn high_key_is_fail_closed_without_ui() {
let harness = Harness::new(vec![
set_config_reply("java.selected_path", json!("D:/jdk17/bin/java.exe")),
ChatReply::text("需要你确认"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换 Java"),
)
.unwrap();
assert_eq!(
harness.settings.set_calls(),
0,
"P0 无 UI 时必须 fail-closed"
);
assert_eq!(harness.settings.value_of("java.selected_path"), None);
assert_eq!(confirm_events(&harness), 1, "确认请求必须作为事件发出");
let outcomes: Vec<AuditOutcome> = harness
.audit
.records_for("set_config")
.iter()
.map(|r| r.outcome)
.collect();
assert_eq!(
outcomes,
vec![AuditOutcome::AwaitingConfirmation, AuditOutcome::Denied],
"先记「AI 想改」,再记「被拒绝」"
);
assert!(tool_results(&harness)
.iter()
.any(|content| content.contains("denied")));
assert!(harness
.events
.events()
.iter()
.any(|e| matches!(e, AgentEvent::ToolDenied { .. })));
}
#[test]
fn user_approval_writes_and_marks_confirmed() {
let harness = Harness::with_gate(
vec![
set_config_reply("java.selected_path", json!("D:/jdk17/bin/java.exe")),
ChatReply::text("已更新"),
],
ConfirmPolicy::default(),
|_sink| {
Arc::new(ScriptedGate::new(
[ConfirmDecision::Approved],
ConfirmDecision::Denied,
))
},
);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换 Java"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 1, "确认后只写一次");
let records = harness.audit.records_for("set_config");
let last = records.last().expect("必须有审计记录");
assert_eq!(last.outcome, AuditOutcome::Ok);
assert!(last.confirmed, "用户点了允许");
assert!(!last.yolo);
}
#[test]
fn yolo_skips_confirm_but_audits_flag() {
let harness = Harness::yolo(vec![
set_config_reply("java.selected_path", json!("D:/jdk17/bin/java.exe")),
ChatReply::text("已更新"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换 Java"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 1);
assert_eq!(confirm_events(&harness), 0, "YOLO 不打扰用户");
let records = harness.audit.records_for("set_config");
assert_eq!(records.len(), 1, "YOLO 只留结局记录");
assert!(records[0].yolo, "审计必须标记 yolo");
assert!(!records[0].confirmed, "自动放行不是用户确认");
assert_eq!(records[0].outcome, AuditOutcome::Ok);
}
#[test]
fn whitelist_violation_is_rejected_and_audited() {
let harness = Harness::new(vec![
set_config_reply("java.home.mystery", json!("x")),
ChatReply::text("换个方案"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "改个不存在的键"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 0);
let records = harness.audit.records_for("set_config");
assert_eq!(records.len(), 1);
assert_eq!(records[0].outcome, AuditOutcome::ToolError);
let results = tool_results(&harness);
assert!(
results.iter().any(|c| c.contains("白名单")),
"模型需要知道为什么被拒:{results:?}"
);
}
#[test]
fn invalid_args_are_rejected_before_any_side_effect() {
// 缺 value(schema required)
let harness = Harness::new(vec![
tool_call_reply(
"c1",
"set_config",
json!({ "path": "appearance.theme_mode" }),
),
ChatReply::text("参数补上"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "改主题"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 0);
let records = harness.audit.records_for("set_config");
assert_eq!(records[0].outcome, AuditOutcome::InvalidArgs);
assert!(tool_results(&harness)
.iter()
.any(|c| c.contains("缺少必填参数")));
// 多余参数(additionalProperties: false)
let harness = Harness::new(vec![
tool_call_reply(
"c2",
"read_game_log",
json!({ "session_id": "x", "path": "evil" }),
),
ChatReply::text("好"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "读日志"),
)
.unwrap();
let records = harness.audit.records_for("read_game_log");
assert_eq!(records[0].outcome, AuditOutcome::InvalidArgs);
}
#[test]
fn unknown_tool_lists_available_names() {
let harness = Harness::new(vec![
tool_call_reply("c1", "delete_everything", json!({})),
ChatReply::text("抱歉"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "删库跑路"),
)
.unwrap();
let records = harness.audit.records_for("delete_everything");
assert_eq!(records[0].outcome, AuditOutcome::UnknownTool);
let results = tool_results(&harness);
assert!(
results.iter().any(|c| c.contains("get_config")),
"{results:?}"
);
}
#[test]
fn locked_credential_key_is_refused_even_under_yolo() {
// M12:ai.api_key 是 writable=false(不在白名单)→ YOLO 也不能放宽可写范围
let harness = Harness::yolo(vec![
set_config_reply("ai.api_key", json!("sk-super-secret-value")),
ChatReply::text("换不了"),
]);
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "换 key"),
)
.unwrap();
assert_eq!(harness.settings.set_calls(), 0);
let records = harness.audit.records_for("set_config");
assert_eq!(records[0].outcome, AuditOutcome::ToolError);
let args = serde_json::to_string(&records[0].args).unwrap();
assert!(
!args.contains("sk-super-secret-value"),
"审计绝不能落明文密钥:{args}"
);
assert!(args.contains("***"), "{args}");
}
#[test]
fn get_config_refuses_credential_keys() {
// F1:模型可自由给 path,凭据键必须读不到 —— 否则值会进模型上下文发往远端 LLM。
let harness = Harness::new(vec![
tool_call_reply("c1", "get_config", json!({ "path": "ai.api_key" })),
ChatReply::text("读不到"),
]);
// 模拟 M12 真实实现:凭据键在文件里确实有值(writable=false,不在白名单也要能防住读)
harness
.settings
.seed_value("ai.api_key", json!("sk-live-credential-value"));
let mut history = Vec::new();
block_on(
harness
.brain
.run_turn(AGENT_SESSION, &mut history, "看看我的 key"),
)
.unwrap();
// 1) 工具报错并被审计
let records = harness.audit.records_for("get_config");
assert_eq!(records[0].outcome, AuditOutcome::ToolError);
// 2) 模型拿到的是拒绝文案,不是值
let results = tool_results(&harness);
assert!(
results.iter().any(|c| c.contains("凭据")),
"应给出可读拒绝:{results:?}"
);
assert!(
!results
.iter()
.any(|c| c.contains("sk-live-credential-value")),
"工具结果绝不能带凭据:{results:?}"
);
// 3) 事件流与对话历史里也不能出现(P1 事件会落盘 / 历史会持久化)
let leaked_in_events = harness
.events
.events()
.iter()
.any(|e| format!("{e:?}").contains("sk-live-credential-value"));
assert!(!leaked_in_events, "事件流不能带凭据明文");
let leaked_in_history = history
.iter()
.any(|m| format!("{m:?}").contains("sk-live-credential-value"));
assert!(!leaked_in_history, "对话历史不能带凭据明文");
}
+29
View File
@@ -0,0 +1,29 @@
[package]
name = "unlucky-app"
description = "Unlucky-Launcher 桌面壳:Slint + Metro 视觉(唯一允许依赖 UI 框架的 crate)"
version.workspace = true
edition.workspace = true
license.workspace = true
authors.workspace = true
repository.workspace = true
rust-version.workspace = true
publish.workspace = true
[[bin]]
name = "unlucky-launcher"
path = "src/main.rs"
[dependencies]
slint.workspace = true
# 边界(01c §5 / D3):app 只经 DTO 消费 core/agent,**不 import 内部类型**。
# P0 的 host 是 src/mock.rs 的假后端;这两个依赖在这里登记,是为了后续把真实 host
# (core 的快照/事件流翻译成 src/dto 的类型)落位时不必再动 workspace 契约。
unlucky-core = { path = "../core", version = "0.1" }
unlucky-agent = { path = "../agent", version = "0.1" }
[build-dependencies]
slint-build.workspace = true
[lints]
workspace = true
+7
View File
@@ -0,0 +1,7 @@
//! Slint 编译入口:把 ui/main.slint 编译成 Rust 代码,供 src/main.rs 的 `slint::include_modules!()` 引入。
//! 保持极简——UI 结构演进(多文件拆分、主题文件)在 M17 阶段 B 里扩展本脚本。
/// 编译 `ui/main.slint`;失败时让构建直接报错(UI 语法错误不该被静默忽略)。
fn main() {
slint_build::compile("ui/main.slint").expect("Slint UI 编译失败(ui/main.slint)");
}
+124
View File
@@ -0,0 +1,124 @@
//! 「外观(高级)」四件的回调接线(从 `callbacks.rs` 拆出,守住单文件 ≤400 行)。
//!
//! 与 `wire_settings` 的分工:这个文件只负责 09 §101-104 的四个高级特性
//! (背景图 / 面板半透明度 / 玻璃拟态 / 强调色)+ 主题三态。
//! 每个回调都是同一套动作:改 `state.prefs` → 下发到 Slint(`apply_*`)→ 落盘(`persist_settings`)→
//! `sync()`。出厂全部关闭,所以「不碰设置页」时这里一次都不会触发。
use std::rc::Weak;
use crate::conv;
use crate::ui_bind::Inner;
/// 接主题三态与外观四件的回调。
pub(crate) fn wire(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_theme_changed(move |mode| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.theme = conv::theme_mode_from(mode);
this.apply_theme();
this.persist_settings();
this.sync();
});
}
// ── 09 §101-104「外观(高级)」四件(出厂全关,改动即刻落盘)────────
{
let weak = weak.clone();
ui.on_bg_image_enabled_changed(move |enabled| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.bg_image_enabled = enabled;
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_bg_image_changed(move |path| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.bg_image = path.to_string();
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_bg_fill_changed(move |fill| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.bg_fill = conv::bg_fill_from(fill);
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_bg_dim_changed(move |value| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.bg_dim = value;
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_panel_alpha_changed(move |value| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.panel_alpha = value;
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_glass_changed(move |enabled| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.appearance.glass = enabled;
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_accent_color_changed(move |text| {
let Some(this) = weak.upgrade() else { return };
let accepted = this.state.borrow_mut().prefs.appearance.set_accent(&text);
// 非法输入:只亮设置页的 warn 行,不改现状、不落盘
this.ui.set_accent_invalid(!accepted);
if accepted {
this.apply_appearance();
this.persist_settings();
}
this.sync();
});
}
{
let weak = weak.clone();
ui.on_accent_swatch_picked(move |index| {
let Some(this) = weak.upgrade() else { return };
let Ok(index) = usize::try_from(index) else {
return;
};
let accepted = this
.state
.borrow_mut()
.prefs
.appearance
.set_accent_preset(index);
if !accepted {
return;
}
let hex = this.state.borrow().prefs.appearance.accent_color.clone();
this.ui.set_accent_color(conv::accent_color(&hex));
this.ui.set_accent_invalid(false);
this.apply_appearance();
this.persist_settings();
this.sync();
});
}
}
+370
View File
@@ -0,0 +1,370 @@
//! 背景图与玻璃拟态模糊层的准备(09 §101/§103 的「预生成」手法,纯 Rust、无新依赖)。
//!
//! 为什么要自己算:Slint 没有 `backdrop-filter`,也无法在渲染管线里做高斯模糊。可用的只有
//! `Image::load_from_path` + 像素缓冲(`to_rgba8` / `from_rgba8`)。于是:
//!
//! - **模糊层** = 把原图按面积平均降到极小的尺寸(默认宽 48px),渲染时被平滑放大 → 天然模糊
//! (面积平均本身就是低通滤波,比在满分辨率上跑 box blur 快几个数量级,且一次只在设置变更时算);
//! - **tile 模式** = Slint 的 `image-fit` 没有 `repeat`,所以在 Rust 侧按窗口尺寸平铺成一张画布,
//! 交给 `image-fit: cover`(画布与窗口同尺寸,等价于 1:1 铺设)。
//!
//! 解码格式:Slint 默认只编译 PNG 解码器(`image-default-formats` 特性未开),因此这里只保证 PNG;
//! 其它格式 `load_from_path` 直接失败,UI 侧给出提示而不是静默无效果。
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
use crate::prefs::BgFill;
/// 模糊层目标宽度(像素)。越小越糊;96 在 1180px 宽窗口上 ≈ 24px 半径高斯的效果。
const BLUR_WIDTH: u32 = 96;
/// 小图上再跑几轮 box blur(3×3):把降采样的块状边缘抹平。
const BLUR_PASSES: usize = 3;
/// tile 画布上限(防超大窗口吃爆内存:4096×2560×4 ≈ 40MB)。
const TILE_MAX_WIDTH: u32 = 4096;
const TILE_MAX_HEIGHT: u32 = 2560;
/// 一次准备出来的两张图:原图(按填充模式处理)+ 模糊层。
#[derive(Debug, Clone, Default)]
pub struct BackgroundLayers {
/// 铺在窗口底的图(tile 模式下已平铺成整窗画布)
pub image: Image,
/// 玻璃拟态用的模糊层
pub blur: Image,
}
/// 载入并加工背景图。
///
/// `viewport` 是窗口的**物理像素**尺寸(tile 模式平铺用;拿不到时传 `(0, 0)` 退回只载入)。
/// 返回 `None` 表示路径无效 / 解码失败 / 读了像素但为空——调用方据此提示用户。
#[must_use]
pub fn prepare(path: &str, fill: BgFill, viewport: (u32, u32)) -> Option<BackgroundLayers> {
let path = path.trim();
if path.is_empty() {
return None;
}
let loaded = Image::load_from_path(std::path::Path::new(path)).ok()?;
let source = loaded.to_rgba8()?;
if source.width() == 0 || source.height() == 0 {
return None;
}
let image = match fill {
BgFill::Tile => {
let (width, height) = tile_canvas_size(source.width(), source.height(), viewport);
Image::from_rgba8(tile(&source, width, height))
}
// cover / contain 交给 Slint 的 image-fit,这里保留原图
BgFill::Cover | BgFill::Contain => loaded,
};
let blurred = box_blur(&downscale(&source, BLUR_WIDTH), BLUR_PASSES);
// 放大回窗口物理尺寸再做 1:1 贴图:软件渲染器对图片缩放不做平滑插值(最近邻),
// 直接把 96px 的小图丢给它会出现明显方块;这里自己双线性放大,观感才是「磨砂」。
let blur = match viewport {
(0, 0) => Image::from_rgba8(blurred),
(width, height) => Image::from_rgba8(upscale(&blurred, width, height)),
};
Some(BackgroundLayers { image, blur })
}
/// 3×3 均值模糊,`passes` 轮(小图上跑,代价可忽略)。
fn box_blur(
source: &SharedPixelBuffer<Rgba8Pixel>,
passes: usize,
) -> SharedPixelBuffer<Rgba8Pixel> {
let width = source.width() as usize;
let height = source.height() as usize;
if width < 3 || height < 3 || passes == 0 {
return source.clone();
}
let mut current: Vec<Rgba8Pixel> = source.as_slice().to_vec();
let mut next = current.clone();
for _ in 0..passes {
for y in 0..height {
for x in 0..width {
let mut sum = [0u32; 4];
let mut count = 0u32;
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let sy = (y as i32 + dy).clamp(0, height as i32 - 1) as usize;
let sx = (x as i32 + dx).clamp(0, width as i32 - 1) as usize;
let pixel = current[sy * width + sx];
sum[0] += u32::from(pixel.r);
sum[1] += u32::from(pixel.g);
sum[2] += u32::from(pixel.b);
sum[3] += u32::from(pixel.a);
count += 1;
}
}
next[y * width + x] = Rgba8Pixel {
r: (sum[0] / count) as u8,
g: (sum[1] / count) as u8,
b: (sum[2] / count) as u8,
a: (sum[3] / count) as u8,
};
}
}
std::mem::swap(&mut current, &mut next);
}
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(source.width(), source.height());
out.make_mut_slice().copy_from_slice(&current);
out
}
/// 双线性放大到目标尺寸。
fn upscale(
source: &SharedPixelBuffer<Rgba8Pixel>,
width: u32,
height: u32,
) -> SharedPixelBuffer<Rgba8Pixel> {
let src_w = source.width();
let src_h = source.height();
if src_w == 0 || src_h == 0 || width == 0 || height == 0 {
return SharedPixelBuffer::new(width.max(1), height.max(1));
}
let pixels = source.as_slice();
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
let dst = out.make_mut_slice();
let sample = |fx: f32, fy: f32| -> Rgba8Pixel {
let x = (fx * (src_w - 1) as f32).clamp(0.0, (src_w - 1) as f32);
let y = (fy * (src_h - 1) as f32).clamp(0.0, (src_h - 1) as f32);
let x0 = x.floor() as usize;
let y0 = y.floor() as usize;
let x1 = (x0 + 1).min(src_w as usize - 1);
let y1 = (y0 + 1).min(src_h as usize - 1);
let tx = x - x0 as f32;
let ty = y - y0 as f32;
let at = |px: usize, py: usize| pixels[py * src_w as usize + px];
let blend = |a: u8, b: u8, c: u8, d: u8| -> u8 {
let top = f32::from(a) * (1.0 - tx) + f32::from(b) * tx;
let bottom = f32::from(c) * (1.0 - tx) + f32::from(d) * tx;
(top * (1.0 - ty) + bottom * ty).round().clamp(0.0, 255.0) as u8
};
let (p00, p10, p01, p11) = (at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1));
Rgba8Pixel {
r: blend(p00.r, p10.r, p01.r, p11.r),
g: blend(p00.g, p10.g, p01.g, p11.g),
b: blend(p00.b, p10.b, p01.b, p11.b),
a: blend(p00.a, p10.a, p01.a, p11.a),
}
};
for y in 0..height as usize {
let fy = y as f32 / height as f32;
for x in 0..width as usize {
dst[y * width as usize + x] = sample(x as f32 / width as f32, fy);
}
}
out
}
/// 平铺画布尺寸:覆盖整个视口、且是原图尺寸的整数倍(超上限就截断)。
fn tile_canvas_size(source_width: u32, source_height: u32, viewport: (u32, u32)) -> (u32, u32) {
if viewport.0 == 0 || viewport.1 == 0 {
return (source_width, source_height);
}
let repeat_x = viewport.0.div_ceil(source_width).max(1);
let repeat_y = viewport.1.div_ceil(source_height).max(1);
let width = (repeat_x * source_width).min(TILE_MAX_WIDTH);
let height = (repeat_y * source_height).min(TILE_MAX_HEIGHT);
(width.max(source_width), height.max(source_height))
}
/// 按整数格平铺(源图超出画布的部分裁掉)。
fn tile(
source: &SharedPixelBuffer<Rgba8Pixel>,
width: u32,
height: u32,
) -> SharedPixelBuffer<Rgba8Pixel> {
let mut canvas = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
let src_w = source.width() as usize;
let src_h = source.height() as usize;
let src = source.as_slice();
let dst = canvas.make_mut_slice();
for y in 0..height as usize {
let src_row = (y % src_h) * src_w;
let dst_row = y * width as usize;
for x in 0..width as usize {
dst[dst_row + x] = src[src_row + (x % src_w)];
}
}
canvas
}
/// 面积平均降采样(保留宽高比,最窄 1px)。
fn downscale(
source: &SharedPixelBuffer<Rgba8Pixel>,
target_width: u32,
) -> SharedPixelBuffer<Rgba8Pixel> {
let src_w = source.width();
let src_h = source.height();
let target_width = target_width.clamp(1, src_w);
let target_height = ((src_h as u64 * target_width as u64) / src_w as u64).max(1) as u32;
let mut out = SharedPixelBuffer::<Rgba8Pixel>::new(target_width, target_height);
let src = source.as_slice();
let dst = out.make_mut_slice();
for ty in 0..target_height as usize {
// 每个目标像素覆盖的源矩形(按比例分块,块内取平均)
let y0 = ty * src_h as usize / target_height as usize;
let y1 = ((ty + 1) * src_h as usize / target_height as usize).max(y0 + 1);
for tx in 0..target_width as usize {
let x0 = tx * src_w as usize / target_width as usize;
let x1 = ((tx + 1) * src_w as usize / target_width as usize).max(x0 + 1);
let mut sum = [0u32; 4];
let mut count = 0u32;
for y in y0..y1.min(src_h as usize) {
for x in x0..x1.min(src_w as usize) {
let pixel = src[y * src_w as usize + x];
sum[0] += u32::from(pixel.r);
sum[1] += u32::from(pixel.g);
sum[2] += u32::from(pixel.b);
sum[3] += u32::from(pixel.a);
count += 1;
}
}
let count = count.max(1);
dst[ty * target_width as usize + tx] = Rgba8Pixel {
r: (sum[0] / count) as u8,
g: (sum[1] / count) as u8,
b: (sum[2] / count) as u8,
a: (sum[3] / count) as u8,
};
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn solid(width: u32, height: u32, pixel: Rgba8Pixel) -> SharedPixelBuffer<Rgba8Pixel> {
let mut buffer = SharedPixelBuffer::<Rgba8Pixel>::new(width, height);
buffer.make_mut_slice().fill(pixel);
buffer
}
#[test]
fn downscale_keeps_aspect_and_averages_area() {
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(96, 48);
// 左半黑、右半白:降采样后左右两侧应各自保持纯色
for y in 0..48 {
for x in 0..96 {
let value = if x < 48 { 0 } else { 255 };
source.make_mut_slice()[y * 96 + x] = Rgba8Pixel {
r: value,
g: value,
b: value,
a: 255,
};
}
}
let small = downscale(&source, 24);
assert_eq!(small.width(), 24);
assert_eq!(small.height(), 12, "宽高比保持 2:1");
let pixels = small.as_slice();
assert_eq!(pixels[0].r, 0, "左侧仍是黑");
assert_eq!(pixels[23].r, 255, "右侧仍是白");
}
#[test]
fn downscale_never_produces_zero_height() {
let source = solid(
400,
3,
Rgba8Pixel {
r: 1,
g: 2,
b: 3,
a: 255,
},
);
let small = downscale(&source, 2);
assert_eq!(small.width(), 2);
assert!(small.height() >= 1);
}
#[test]
fn tile_canvas_covers_viewport_in_whole_repeats() {
assert_eq!(tile_canvas_size(120, 100, (1180, 760)), (1200, 800));
// 视口未知(取不到窗口尺寸)时退回单块
assert_eq!(tile_canvas_size(120, 100, (0, 0)), (120, 100));
// 超大视口被上限截断
let (width, height) = tile_canvas_size(64, 64, (9000, 9000));
assert!(width <= TILE_MAX_WIDTH && height <= TILE_MAX_HEIGHT);
}
#[test]
fn tile_repeats_source_pixels() {
let source = solid(
2,
2,
Rgba8Pixel {
r: 9,
g: 9,
b: 9,
a: 255,
},
);
let canvas = tile(&source, 5, 3);
assert_eq!(canvas.width(), 5);
assert_eq!(canvas.height(), 3);
assert!(canvas.as_slice().iter().all(|pixel| pixel.r == 9));
}
#[test]
fn prepare_rejects_bad_input() {
assert!(prepare("", BgFill::Cover, (100, 100)).is_none());
assert!(prepare("D:/definitely/not/here.png", BgFill::Cover, (100, 100)).is_none());
}
#[test]
fn box_blur_smooths_a_hard_edge() {
// 左黑右白:模糊后交界处应出现中间灰(硬边被抹平)
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(9, 3);
for y in 0..3 {
for x in 0..9 {
let value = if x < 4 { 0 } else { 255 };
source.make_mut_slice()[y * 9 + x] = Rgba8Pixel {
r: value,
g: value,
b: value,
a: 255,
};
}
}
let blurred = box_blur(&source, 2);
let middle = blurred.as_slice()[9 + 4]; // 第 1 行(共 9 列)的第 4 个像素
assert!(
middle.r > 20 && middle.r < 235,
"交界处应被抹成中间灰,实际 {}",
middle.r
);
}
#[test]
fn upscale_matches_requested_size_and_interpolates() {
let mut source = SharedPixelBuffer::<Rgba8Pixel>::new(2, 1);
let pixels = source.make_mut_slice();
pixels[0] = Rgba8Pixel {
r: 0,
g: 0,
b: 0,
a: 255,
};
pixels[1] = Rgba8Pixel {
r: 255,
g: 255,
b: 255,
a: 255,
};
let big = upscale(&source, 8, 2);
assert_eq!(big.width(), 8);
assert_eq!(big.height(), 2);
let row = big.as_slice();
// 双线性:中间像素应是灰阶过渡而不是 0/255 二值
assert!(row[3].r > 60 && row[3].r < 200, "实际 {}", row[3].r);
}
}
+354
View File
@@ -0,0 +1,354 @@
//! 回调接线:把 `ui/main.slint` 暴露的每个回调翻译成「状态变更 + AppCommand + 同步」。
//!
//! 逐条列出而不做通用转发,是为了让「用户能做的每一件事」在这里一目了然;
//! 新增交互时只改这一处 + `.slint` 的 callback 声明。
use std::rc::Weak;
use slint::ComponentHandle;
use crate::conv;
use crate::dto::AppCommand;
use crate::router::Route;
use crate::toast::ToastKind;
use crate::ui_bind::Inner;
/// 接全部回调;闭包持弱引用,避免 `MainWindow` 与闭包互相持有导致窗口永不释放。
pub(crate) fn wire(weak: Weak<Inner>) {
let Some(inner) = weak.upgrade() else { return };
// 只在注册期间持有强引用;闭包内一律持弱引用(否则窗口与闭包互相持有、永不释放)。
let ui = &inner.ui;
wire_window(ui, &weak);
wire_navigation(ui, &weak);
wire_instances(ui, &weak);
wire_download(ui, &weak);
wire_logs(ui, &weak);
wire_settings(ui, &weak);
wire_overlays(ui, &weak);
}
fn wire_window(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_toggle_maximize(move || {
let Some(this) = weak.upgrade() else { return };
let window = this.ui.window();
window.set_maximized(!window.is_maximized());
});
}
{
let weak = weak.clone();
ui.on_minimize(move || {
if let Some(this) = weak.upgrade() {
this.ui.window().set_minimized(true);
}
});
}
{
let weak = weak.clone();
ui.on_request_close(move || {
if let Some(this) = weak.upgrade() {
let _ = this.ui.hide();
}
let _ = slint::quit_event_loop();
});
}
}
fn wire_navigation(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_navigate(move |route| {
let Some(this) = weak.upgrade() else { return };
if let Some(route) = conv::route_from(route) {
this.state.borrow_mut().navigate(route);
this.sync();
}
});
}
{
let weak = weak.clone();
ui.on_toggle_nav(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().toggle_nav();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_toggle_ai(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().toggle_ai();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_expand_ai(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().navigate(Route::Agent);
this.sync();
});
}
{
let weak = weak.clone();
ui.on_dock_ai(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().back();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_toggle_yolo(move || {
let Some(this) = weak.upgrade() else { return };
let enabled = {
let mut state = this.state.borrow_mut();
state.ai.yolo = !state.ai.yolo;
state.ai.yolo
};
this.dispatch(AppCommand::SetYolo(enabled));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_ai_send(move |text| {
let Some(this) = weak.upgrade() else { return };
let text = text.to_string();
if text.trim().is_empty() {
return;
}
// 不做本地回显:user 消息由 host 的 MessageAppended 事件带回(契约 §3)
this.state.borrow_mut().ai.draft.clear();
this.ui.set_ai_draft("".into());
this.ask_agent(&text);
this.sync();
});
}
{
let weak = weak.clone();
ui.on_ai_stop(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().ai.finish_stream();
this.dispatch(AppCommand::StopAgent);
this.sync();
});
}
}
fn wire_instances(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_instance_launch(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::LaunchInstance(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_instance_configure(move |id| {
let Some(this) = weak.upgrade() else { return };
// 齿轮键进实例详情(G4 占位页),实例级设置后续挂在该页 tab 上
this.state
.borrow_mut()
.navigate(Route::Detail(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_instance_stop(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::StopInstance(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_instance_open(move |id| {
let Some(this) = weak.upgrade() else { return };
this.state
.borrow_mut()
.navigate(Route::Detail(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_new_instance(move || {
let Some(this) = weak.upgrade() else { return };
this.state
.borrow_mut()
.toasts
.push(ToastKind::Info, "新建实例向导(G5)在 P1 落地");
this.sync();
});
}
{
let weak = weak.clone();
ui.on_instance_view_changed(move |view| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.instance_view = conv::instance_view_from(view);
this.sync();
});
}
{
let weak = weak.clone();
ui.on_tile_size_changed(move |size| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().prefs.tile_size = conv::tile_size_from(size);
this.sync();
});
}
{
let weak = weak.clone();
ui.on_instance_query_changed(move |query| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().instance_query = query.to_string();
this.sync();
});
}
}
fn wire_download(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_download_category_changed(move |category| {
let Some(this) = weak.upgrade() else { return };
let category = conv::version_category(category);
this.state.borrow_mut().prefs.download_category = category;
this.dispatch(AppCommand::ListVersions(category));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_download_install(move |id| {
let Some(this) = weak.upgrade() else { return };
this.dispatch(AppCommand::InstallVersion(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_installed_only_changed(move |only| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().installed_only = only;
this.sync();
});
}
{
let weak = weak.clone();
ui.on_download_query_changed(move |query| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().download_query = query.to_string();
this.sync();
});
}
{
let weak = weak.clone();
ui.on_ancient_help(move || {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().toasts.push(
ToastKind::Info,
"远古版(classic/alpha/beta)需旧版 Java 与旧启动参数;完整说明页 P1 接入",
);
this.sync();
});
}
}
fn wire_logs(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_log_select(move |id| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().selected_session = Some(id.to_string());
this.dispatch(AppCommand::OpenLogSession(id.to_string()));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_log_ask_ai(move |id| {
let Some(this) = weak.upgrade() else { return };
let question = format!("帮我看下会话 {id} 为什么崩溃");
this.state.borrow_mut().navigate(Route::Agent);
this.ask_agent(&question);
this.sync();
});
}
{
let weak = weak.clone();
ui.on_log_apply_fix(move || {
let Some(this) = weak.upgrade() else { return };
this.state
.borrow_mut()
.toasts
.push(ToastKind::Warn, "一键修复在 P1 接 diagnose 的 fix_action");
this.sync();
});
}
}
fn wire_settings(ui: &crate::MainWindow, weak: &Weak<Inner>) {
// 主题三态 + 外观四件在 appearance_bind.rs(拆文件守 400 行)
crate::appearance_bind::wire(ui, weak);
{
let weak = weak.clone();
ui.on_yolo_changed(move |enabled| {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().ai.yolo = enabled;
this.dispatch(AppCommand::SetYolo(enabled));
this.sync();
});
}
{
let weak = weak.clone();
ui.on_mcp_changed(move |_enabled| {
let Some(this) = weak.upgrade() else { return };
this.state
.borrow_mut()
.toasts
.push(ToastKind::Info, "MCP server 开关在 P1 接 agent");
this.sync();
});
}
// P0 只保留入口:设置分组与 AI 端点暂不落状态(P1 接 setting schema)。
ui.on_settings_section_changed(|_section| {});
ui.on_ai_endpoint_changed(|_index| {});
}
fn wire_overlays(ui: &crate::MainWindow, weak: &Weak<Inner>) {
{
let weak = weak.clone();
ui.on_dialog_primary(move || close_current_dialog(&weak));
}
{
let weak = weak.clone();
ui.on_dialog_secondary(move || close_current_dialog(&weak));
}
{
let weak = weak.clone();
ui.on_dialog_dismissed(move || close_current_dialog(&weak));
}
{
let weak = weak.clone();
ui.on_toast_dismissed(move |id| {
let Some(this) = weak.upgrade() else { return };
if let Ok(id) = id.parse::<u64>() {
this.state.borrow_mut().toasts.dismiss(id);
this.sync();
}
});
}
}
fn close_current_dialog(weak: &Weak<Inner>) {
let Some(this) = weak.upgrade() else { return };
this.state.borrow_mut().dialogs.close_current();
this.sync();
}
+103
View File
@@ -0,0 +1,103 @@
//! AI 页与覆盖层:会话消息、对话框(一次一条)、Toast。
use crate::dialogs as dlg;
use crate::dto::ChatRole as DtoChatRole;
use crate::state::AppState;
use crate::toast as toast_mod;
use crate::{ChatRole, DialogKind, UiChatMessage, UiDialog, UiToast};
/// AI 会话消息。
pub fn chat(state: &AppState) -> Vec<UiChatMessage> {
state
.ai
.messages
.iter()
.map(|message| UiChatMessage {
role: match message.role {
DtoChatRole::User => ChatRole::User,
DtoChatRole::Assistant => ChatRole::Assistant,
DtoChatRole::Tool => ChatRole::Tool,
DtoChatRole::System => ChatRole::System,
},
text: message.text.clone().into(),
tool_name: message
.tool
.as_ref()
.map(|tool| tool.name.clone())
.unwrap_or_default()
.into(),
tool_ok: message.tool.as_ref().is_none_or(|tool| tool.ok),
streaming: message.streaming,
})
.collect()
}
/// 当前对话框(一次一条)+ 是否显示 + 队列剩余条数。
pub fn dialog(state: &AppState) -> (UiDialog, bool, i32) {
let queued = i32::try_from(state.dialogs.pending_len()).unwrap_or(0);
match state.dialogs.current() {
None => (UiDialog::default(), false, queued),
Some(request) => {
let (kind, primary, secondary) = match &request.kind {
dlg::DialogKind::Confirm { primary, secondary } => {
(DialogKind::Confirm, primary.clone(), secondary.clone())
}
dlg::DialogKind::Input { primary, .. } => {
(DialogKind::Input, primary.clone(), String::new())
}
dlg::DialogKind::Progress { .. } => {
(DialogKind::Progress, "取消".to_string(), String::new())
}
dlg::DialogKind::Error { primary, .. } => {
(DialogKind::Error, primary.clone(), "忽略".to_string())
}
};
let progress = match &request.kind {
dlg::DialogKind::Progress { progress, .. } => *progress,
_ => 0.0,
};
let input_label = match &request.kind {
dlg::DialogKind::Input { label, .. } => label.clone(),
_ => String::new(),
};
let input_value = match &request.kind {
dlg::DialogKind::Input { value, .. } => value.clone(),
_ => String::new(),
};
(
UiDialog {
id: request.id.to_string().into(),
kind,
title: request.title.clone().into(),
body: request.body.clone().into(),
primary: primary.into(),
secondary: secondary.into(),
progress,
input_label: input_label.into(),
input_value: input_value.into(),
},
true,
queued,
)
}
}
}
/// Toast 列表。
pub fn toasts(state: &AppState) -> Vec<UiToast> {
state
.toasts
.items()
.iter()
.map(|toast| UiToast {
id: toast.id.to_string().into(),
kind: match toast.kind {
toast_mod::ToastKind::Info => crate::ToastKind::Info,
toast_mod::ToastKind::Success => crate::ToastKind::Success,
toast_mod::ToastKind::Warn => crate::ToastKind::Warn,
toast_mod::ToastKind::Error => crate::ToastKind::Error,
},
text: toast.text.clone().into(),
})
.collect()
}
+162
View File
@@ -0,0 +1,162 @@
//! 实例相关:磁贴外观(相位/进度/徽标/占位色)、运行中列表。
use slint::Color;
use crate::dto::{self, InstanceRuntime};
use crate::state::{AppState, TileCell};
use crate::{LoaderKind, RuntimePhase, UiTile};
/// 头像/图标占位的底色池(Metro 强调色系,按 id 哈希稳定取色)。
const HUES: [u32; 8] = [
0x0078D4, 0x8764B0, 0xD13438, 0xCA5010, 0x498205, 0x038387, 0x5C2D91, 0x0050EF,
];
/// 加载器枚举。
pub fn loader(kind: dto::LoaderKind) -> LoaderKind {
match kind {
dto::LoaderKind::Vanilla => LoaderKind::Vanilla,
dto::LoaderKind::Fabric => LoaderKind::Fabric,
dto::LoaderKind::Quilt => LoaderKind::Quilt,
dto::LoaderKind::Forge => LoaderKind::Forge,
dto::LoaderKind::NeoForge => LoaderKind::Neoforge,
dto::LoaderKind::OptiFine => LoaderKind::Optifine,
dto::LoaderKind::LiteLoader => LoaderKind::Liteloader,
}
}
/// 运行时状态 → (磁贴外观相位, 进度 0~1, 阶段文案)。
pub fn phase(runtime: &InstanceRuntime) -> (RuntimePhase, f32, String) {
match runtime {
InstanceRuntime::Idle => (RuntimePhase::Idle, 0.0, String::new()),
InstanceRuntime::Busy { stage, progress } => {
let phase = match stage {
dto::LaunchStage::Download => RuntimePhase::Downloading,
dto::LaunchStage::Verify => RuntimePhase::Verifying,
dto::LaunchStage::Launch => RuntimePhase::Launching,
};
(phase, progress.ratio(), stage.label().to_string())
}
InstanceRuntime::Running { .. } => (RuntimePhase::Running, 1.0, "运行中".to_string()),
InstanceRuntime::Failed { reason } => (RuntimePhase::Failed, 0.0, reason.clone()),
}
}
/// 名字首字(无图标时的占位字母)。
pub fn initial_of(name: &str) -> String {
name.chars()
.next()
.map(|c| c.to_string())
.unwrap_or_else(|| "?".to_string())
}
/// id → 稳定底色(同一实例每次启动同色)。
pub fn hue_of(id: &str) -> Color {
let hash = id.bytes().fold(0u32, |acc, byte| {
acc.wrapping_mul(31).wrapping_add(u32::from(byte))
});
Color::from_argb_encoded(0xFF00_0000 | HUES[(hash as usize) % HUES.len()])
}
/// ISO-8601 UTC → 逗号少的本地展示串(`2026-10-29 19:22`);None/空 → 从未启动。
pub fn last_played(raw: &Option<String>) -> String {
match raw {
None => "从未启动".to_string(),
Some(value) if value.is_empty() => "从未启动".to_string(),
Some(value) => {
let trimmed = value.trim_end_matches('Z');
let mut out = String::with_capacity(trimmed.len());
let mut seen_time = false;
for ch in trimmed.chars() {
match ch {
'T' => {
seen_time = true;
out.push(' ');
}
':' if seen_time && out.ends_with(|c: char| c.is_ascii_digit()) => {
// 只保留到分钟:秒(第三段冒号之后)直接截断
if out.matches(':').count() >= 1 {
break;
}
out.push(ch);
}
_ => out.push(ch),
}
}
out
}
}
}
/// 单个磁贴。
pub fn tile(cell: &TileCell<'_>) -> UiTile {
let instance = cell.instance;
let (phase, progress, label) = phase(&instance.runtime);
UiTile {
id: instance.id.clone().into(),
name: instance.name.clone().into(),
mc_version: instance.mc_version.clone().into(),
loader: loader(instance.loader.kind),
loader_version: instance.loader.version.clone().into(),
loader_label: instance.loader.badge().into(),
last_played: last_played(&instance.last_played).into(),
phase,
phase_label: label.into(),
progress,
icon: slint::Image::default(),
hue: hue_of(&instance.id),
initial: initial_of(&instance.name).into(),
row: i32::try_from(cell.row).unwrap_or(0),
col: i32::try_from(cell.col).unwrap_or(0),
}
}
/// 磁贴网格(已按当前尺寸算好 row/col)。
pub fn tiles(state: &AppState) -> Vec<UiTile> {
state.tiles().iter().map(tile).collect()
}
/// 运行中实例(顶部迷你状态条)。
pub fn running_tiles(state: &AppState) -> Vec<UiTile> {
state
.running()
.iter()
.enumerate()
.map(|(index, instance)| {
let cell = TileCell {
instance,
row: 0,
col: index,
};
tile(&cell)
})
.collect()
}
#[cfg(test)]
mod tests {
use super::{hue_of, initial_of, last_played};
#[test]
fn initial_is_first_grapheme_or_question_mark() {
assert_eq!(initial_of("生存整合包"), "生");
assert_eq!(initial_of("Vanilla"), "V");
assert_eq!(initial_of(""), "?");
}
#[test]
fn hue_is_stable_per_id() {
assert_eq!(hue_of("survival"), hue_of("survival"));
// 不同 id 大体不同色(哈希池 8 色,这里只验证确定性 + 不 panic)
let _ = hue_of("another-instance");
}
#[test]
fn last_played_formats_iso_to_minutes() {
assert_eq!(
last_played(&Some("2026-10-29T19:22:45Z".to_string())),
"2026-10-29 19:22"
);
assert_eq!(last_played(&None), "从未启动");
assert_eq!(last_played(&Some(String::new())), "从未启动");
}
}
+84
View File
@@ -0,0 +1,84 @@
//! 日志页:会话列表、日志行、D8 诊断卡片。
use crate::dto::{LogLevel as DtoLogLevel, LogOutcome as DtoLogOutcome};
use crate::state::AppState;
use crate::{LogLevel, LogOutcome, UiDiagnosis, UiLogLine, UiLogSession};
/// 日志会话列表。
pub fn log_sessions(state: &AppState) -> Vec<UiLogSession> {
state
.log_sessions
.iter()
.map(|session| UiLogSession {
id: session.id.clone().into(),
when: session.when.clone().into(),
instance: session.instance.clone().into(),
outcome: match session.outcome {
DtoLogOutcome::Ok => LogOutcome::Ok,
DtoLogOutcome::Crashed => LogOutcome::Crashed,
DtoLogOutcome::SilentFail => LogOutcome::SilentFail,
},
duration: duration(session.duration_secs).into(),
})
.collect()
}
/// 秒 → `1h03m` / `62s`。
pub fn duration(secs: u64) -> String {
if secs >= 3_600 {
format!("{}h{:02}m", secs / 3_600, (secs % 3_600) / 60)
} else if secs >= 60 {
format!("{}m{:02}s", secs / 60, secs % 60)
} else {
format!("{secs}s")
}
}
/// 当前会话日志行。
pub fn log_lines(state: &AppState) -> Vec<UiLogLine> {
state
.log_lines
.iter()
.map(|line| UiLogLine {
text: line.text.clone().into(),
level: match line.level {
DtoLogLevel::Debug => LogLevel::Debug,
DtoLogLevel::Info => LogLevel::Info,
DtoLogLevel::Warn => LogLevel::Warn,
DtoLogLevel::Error => LogLevel::Error,
},
})
.collect()
}
/// 诊断卡片内容(无结论时返回默认值 + has=false)。
pub fn diagnosis(state: &AppState) -> (UiDiagnosis, bool) {
match &state.diagnosis {
None => (UiDiagnosis::default(), false),
Some(report) => {
let diagnosis = &report.diagnosis;
(
UiDiagnosis {
rule: diagnosis.rule.clone().into(),
title: diagnosis.title.clone().into(),
confidence: i32::from(diagnosis.confidence),
hint: diagnosis.hint.clone().into(),
has_fix: diagnosis.fix.is_some(),
},
true,
)
}
}
}
#[cfg(test)]
mod tests {
use super::duration;
#[test]
fn duration_is_human_readable() {
assert_eq!(duration(8), "8s");
assert_eq!(duration(62), "1m02s");
assert_eq!(duration(3_780), "1h03m");
}
}
+21
View File
@@ -0,0 +1,21 @@
//! 状态层 → Slint 视图模型的单向转换(DTO 值 → `models.slint` 结构体)。
//!
//! 只做「领域值 → 展示值」的搬运与格式化,不含业务判断;
//! 这样 `ui_bind.rs` 里的同步逻辑就是纯粹的「状态灌进属性」。
//! 按领域拆子模块:instances / versions / logs / agent / ui,全量 `pub use`,
//! 调用方统一写 `crate::conv::tiles(...)` 这类路径。
mod agent;
mod instances;
mod logs;
mod ui;
mod versions;
pub use agent::{chat, dialog, toasts};
pub use instances::{running_tiles, tiles};
pub use logs::{diagnosis, log_lines, log_sessions};
pub use ui::{
accent_color, bg_fill, bg_fill_from, category_from, instance_view, instance_view_from, route,
route_from, theme_mode, theme_mode_from, tile_size, tile_size_from, version_category,
};
pub use versions::versions;
+136
View File
@@ -0,0 +1,136 @@
//! UI 偏好/路由枚举的双向映射(Slint 枚举 ↔ 状态层枚举)。
use crate::dto::{self, VersionCategory};
use crate::prefs;
use crate::router;
use crate::{BgFillKind, DownloadCategory, InstanceView, RouteKind, ThemeMode, TileSize};
/// 路由 → 导航高亮/页面选择。
pub fn route(route: &router::Route) -> RouteKind {
match route {
router::Route::Instances => RouteKind::Instances,
router::Route::Download => RouteKind::Download,
router::Route::Logs => RouteKind::Logs,
router::Route::Settings => RouteKind::Settings,
router::Route::Detail(_) => RouteKind::Detail,
router::Route::Agent => RouteKind::Agent,
}
}
/// Slint 侧导航点击 → 路由(详情页保持当前实例,不在导航里触发)。
pub fn route_from(kind: RouteKind) -> Option<router::Route> {
match kind {
RouteKind::Instances => Some(router::Route::Instances),
RouteKind::Download => Some(router::Route::Download),
RouteKind::Logs => Some(router::Route::Logs),
RouteKind::Settings => Some(router::Route::Settings),
RouteKind::Agent => Some(router::Route::Agent),
RouteKind::Detail => None,
}
}
/// 磁贴尺寸。
pub fn tile_size(size: prefs::TileSize) -> TileSize {
match size {
prefs::TileSize::Small => TileSize::Small,
prefs::TileSize::Medium => TileSize::Medium,
prefs::TileSize::Large => TileSize::Large,
}
}
/// 视图模式。
pub fn instance_view(view: prefs::InstanceView) -> InstanceView {
match view {
prefs::InstanceView::Tiles => InstanceView::Tiles,
prefs::InstanceView::List => InstanceView::List,
}
}
/// 主题三态。
pub fn theme_mode(mode: prefs::ThemeMode) -> ThemeMode {
match mode {
prefs::ThemeMode::Auto => ThemeMode::Auto,
prefs::ThemeMode::Light => ThemeMode::Light,
prefs::ThemeMode::Dark => ThemeMode::Dark,
}
}
/// Slint 主题三态 → 偏好枚举。
pub fn theme_mode_from(mode: ThemeMode) -> prefs::ThemeMode {
match mode {
ThemeMode::Auto => prefs::ThemeMode::Auto,
ThemeMode::Light => prefs::ThemeMode::Light,
ThemeMode::Dark => prefs::ThemeMode::Dark,
}
}
/// Slint 磁贴尺寸 → 偏好枚举。
pub fn tile_size_from(size: TileSize) -> prefs::TileSize {
match size {
TileSize::Small => prefs::TileSize::Small,
TileSize::Medium => prefs::TileSize::Medium,
TileSize::Large => prefs::TileSize::Large,
}
}
/// Slint 视图模式 → 偏好枚举。
pub fn instance_view_from(view: InstanceView) -> prefs::InstanceView {
match view {
InstanceView::Tiles => prefs::InstanceView::Tiles,
InstanceView::List => prefs::InstanceView::List,
}
}
/// 下载分类 → core 侧分类枚举。
pub fn version_category(category: DownloadCategory) -> VersionCategory {
match category {
DownloadCategory::Release => VersionCategory::Release,
DownloadCategory::Snapshot => VersionCategory::Snapshot,
DownloadCategory::AncientClassic => VersionCategory::Ancient(dto::AncientKind::Classic),
DownloadCategory::AncientAlpha => VersionCategory::Ancient(dto::AncientKind::OldAlpha),
DownloadCategory::AncientBeta => VersionCategory::Ancient(dto::AncientKind::OldBeta),
DownloadCategory::AncientUnlisted => VersionCategory::Ancient(dto::AncientKind::Unlisted),
DownloadCategory::Modpack => VersionCategory::Modpack,
DownloadCategory::Mod => VersionCategory::Mod,
}
}
/// 下载分类(偏好 → Slint)——供启动时回填。
pub fn category_from(category: VersionCategory) -> DownloadCategory {
match category {
VersionCategory::Release => DownloadCategory::Release,
VersionCategory::Snapshot => DownloadCategory::Snapshot,
VersionCategory::Ancient(dto::AncientKind::Classic) => DownloadCategory::AncientClassic,
VersionCategory::Ancient(dto::AncientKind::OldAlpha) => DownloadCategory::AncientAlpha,
VersionCategory::Ancient(dto::AncientKind::OldBeta) => DownloadCategory::AncientBeta,
VersionCategory::Ancient(dto::AncientKind::Unlisted) => DownloadCategory::AncientUnlisted,
VersionCategory::Modpack => DownloadCategory::Modpack,
VersionCategory::Mod => DownloadCategory::Mod,
}
}
/// 背景图填充模式(core 侧枚举 → Slint)。
pub fn bg_fill(fill: unlucky_core::setting::appearance::BgFill) -> BgFillKind {
match fill {
unlucky_core::setting::appearance::BgFill::Cover => BgFillKind::Cover,
unlucky_core::setting::appearance::BgFill::Contain => BgFillKind::Contain,
unlucky_core::setting::appearance::BgFill::Tile => BgFillKind::Tile,
}
}
/// Slint 填充模式 → core 侧枚举。
pub fn bg_fill_from(fill: BgFillKind) -> unlucky_core::setting::appearance::BgFill {
match fill {
BgFillKind::Cover => unlucky_core::setting::appearance::BgFill::Cover,
BgFillKind::Contain => unlucky_core::setting::appearance::BgFill::Contain,
BgFillKind::Tile => unlucky_core::setting::appearance::BgFill::Tile,
}
}
/// 强调色十六进制串 → Slint 颜色;空串/非法值给透明(= 用出厂 accent)。
pub fn accent_color(hex: &str) -> slint::Color {
match unlucky_core::setting::appearance::hex_to_rgb(hex) {
Some((r, g, b)) => slint::Color::from_rgb_u8(r, g, b),
None => slint::Color::from_argb_u8(0, 0, 0, 0),
}
}
+81
View File
@@ -0,0 +1,81 @@
//! 版本列表与下载分类映射(下载页)。
use crate::dto::{AncientKind, VersionKind as DtoVersionKind};
use crate::state::AppState;
use crate::{UiVersion, VersionKind};
/// 下载页版本行(已按「仅已装」+ 版本号筛选词过滤)。
pub fn versions(state: &AppState) -> Vec<UiVersion> {
let query = state.download_query.trim().to_lowercase();
state
.versions
.iter()
.filter(|version| !state.installed_only || version.installed)
.filter(|version| query.is_empty() || version.id.to_lowercase().contains(&query))
.map(|version| UiVersion {
id: version.id.clone().into(),
kind: version_kind(version.kind),
released: version.released.clone().into(),
installed: version.installed,
ancient: version.kind.is_ancient(),
})
.collect()
}
fn version_kind(kind: DtoVersionKind) -> VersionKind {
match kind {
DtoVersionKind::Release => VersionKind::Release,
DtoVersionKind::Snapshot => VersionKind::Snapshot,
DtoVersionKind::Ancient(AncientKind::Classic) => VersionKind::AncientClassic,
DtoVersionKind::Ancient(AncientKind::OldAlpha) => VersionKind::AncientAlpha,
DtoVersionKind::Ancient(AncientKind::OldBeta) => VersionKind::AncientBeta,
DtoVersionKind::Ancient(AncientKind::Unlisted) => VersionKind::AncientUnlisted,
}
}
#[cfg(test)]
mod tests {
use super::versions;
use crate::dto::{VersionKind, VersionSummary};
use crate::state::AppState;
fn state_with_versions() -> AppState {
let mut state = AppState::new();
let row = |id: &str, installed: bool| VersionSummary {
id: id.to_string(),
kind: VersionKind::Release,
released: "2026-01-01".to_string(),
installed,
};
state.versions = vec![
row("1.21.9", false),
row("1.20.4", true),
row("1.20.1", true),
];
state
}
#[test]
fn installed_only_filter_hides_uninstalled_versions() {
let mut state = state_with_versions();
assert_eq!(versions(&state).len(), 3);
state.installed_only = true;
let filtered = versions(&state);
assert_eq!(filtered.len(), 2);
assert!(filtered.iter().all(|version| version.installed));
}
#[test]
fn query_filters_by_version_id_substring() {
let mut state = state_with_versions();
state.download_query = "1.20".to_string();
let filtered = versions(&state);
assert_eq!(filtered.len(), 2);
state.download_query = "1.21".to_string();
state.installed_only = true;
// 「仅已装」优先:1.21.9 未安装 → 空列表
assert!(versions(&state).is_empty());
}
}
+303
View File
@@ -0,0 +1,303 @@
//! 对话框队列(HMCL 队列语义 + Metro 化,09 §3)。
//!
//! 语义:**一次只显示一条**。新请求按来源插队(用户操作 > 后台任务 > 提示),同来源 FIFO;
//! 当前条被确认/取消后由 [`DialogQueue::advance`] 推进到下一条,UI 只渲染 `current`。
//! 非阻塞提示走 [`crate::toast`],不占模态队列。
/// 对话框标识。
pub type DialogId = u64;
/// 对话框来源:决定插队优先级。
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum DialogSource {
/// 提示类(教程、首次使用说明)
Hint = 0,
/// 后台任务(下载完成、需要选择镜像源)
BackgroundTask = 1,
/// 用户操作触发(AI 敏感写操作的二次确认)
UserAction = 2,
}
impl DialogSource {
/// 数值越大越优先。
pub fn priority(self) -> u8 {
self as u8
}
}
/// 对话框类型(09 §3:确认 / 进度 / 输入 / 错误)。
#[derive(Debug, Clone, PartialEq)]
pub enum DialogKind {
/// 确认:主按钮 + 次按钮
Confirm {
/// 主按钮文字(如「允许」)
primary: String,
/// 次按钮文字(如「拒绝」)
secondary: String,
},
/// 输入:单行文本
Input {
/// 输入框标签
label: String,
/// 初始值
value: String,
/// 主按钮文字
primary: String,
},
/// 进度:不可点主按钮(任务结束后由 [`crate::dto::AppEvent::DialogClosed`] 收起)
Progress {
/// 阶段文案
label: String,
/// 0.0~1.0
progress: f32,
},
/// 错误:含诊断入口提示
Error {
/// 主按钮文字
primary: String,
/// 诊断/修复提示
hint: Option<String>,
},
}
impl DialogKind {
/// 主按钮文字。
pub fn primary_label(&self) -> &str {
match self {
Self::Confirm { primary, .. }
| Self::Input { primary, .. }
| Self::Error { primary, .. } => primary,
Self::Progress { .. } => "取消",
}
}
/// 次按钮文字(None 表示不显示次按钮)。
pub fn secondary_label(&self) -> Option<&str> {
match self {
Self::Confirm { secondary, .. } => Some(secondary),
Self::Error { .. } => Some("忽略"),
Self::Input { .. } | Self::Progress { .. } => None,
}
}
/// 是否可交互(进度条不可点主按钮)。
pub fn is_blocking_progress(&self) -> bool {
matches!(self, Self::Progress { .. })
}
}
/// 一条对话框请求。
#[derive(Debug, Clone, PartialEq)]
pub struct DialogRequest {
/// 队列内唯一 id(由 [`DialogQueue::push_request`] 重新编号)
pub id: DialogId,
/// 来源(决定插队优先级)
pub source: DialogSource,
/// 标题
pub title: String,
/// 正文
pub body: String,
/// 类型与按钮
pub kind: DialogKind,
}
/// 模态队列:一次一条 + 来源插队。
#[derive(Debug, Default)]
pub struct DialogQueue {
current: Option<DialogRequest>,
pending: Vec<DialogRequest>,
next_id: DialogId,
}
impl DialogQueue {
/// 新建空队列。
pub fn new() -> Self {
Self::default()
}
/// 当前应显示的对话框。
pub fn current(&self) -> Option<&DialogRequest> {
self.current.as_ref()
}
/// 排队中(不含当前)条数。
pub fn pending_len(&self) -> usize {
self.pending.len()
}
/// 是否完全没有对话框(当前 + 排队)。
pub fn is_empty(&self) -> bool {
self.current.is_none() && self.pending.is_empty()
}
/// 入队一条请求(UI 内部调用方用,id 由队列自增分配)。没有当前条时立即成为当前条。
///
/// 返回值用于后续 [`Self::close`] / 进度更新。
pub fn push(
&mut self,
source: DialogSource,
title: impl Into<String>,
body: impl Into<String>,
kind: DialogKind,
) -> DialogId {
self.next_id += 1;
self.push_request(DialogRequest {
id: self.next_id,
source,
title: title.into(),
body: body.into(),
kind,
})
}
/// 入队一条已经组装好的请求(事件通道用)。
///
/// **id 归生产者**:这里原样保留 `request.id`(不重编号),因为关闭事件
/// [`crate::dto::AppEvent::DialogClosed`] 携带的是生产者 id;重编号会让
/// 「任务完成 → 自动收起进度框」在多来源弹框时静默失配。生产者负责自身 id 唯一。
pub fn push_request(&mut self, request: DialogRequest) -> DialogId {
let id = request.id;
let source = request.source;
if self.current.is_none() {
self.current = Some(request);
} else {
let at = self
.pending
.iter()
.position(|queued| queued.source < source)
.unwrap_or(self.pending.len());
self.pending.insert(at, request);
}
id
}
/// 关闭指定对话框:若是当前条则推进到下一条,否则从队列移除。
///
/// 返回 `true` 表示确实移除了。
pub fn close(&mut self, id: DialogId) -> bool {
if self
.current
.as_ref()
.is_some_and(|current| current.id == id)
{
self.advance();
return true;
}
if let Some(at) = self.pending.iter().position(|queued| queued.id == id) {
self.pending.remove(at);
return true;
}
false
}
/// 推进到下一条排队请求(当前条已被处理)。
pub fn advance(&mut self) {
self.current = if self.pending.is_empty() {
None
} else {
Some(self.pending.remove(0))
};
}
/// 关闭当前条并推进到下一条(确认 / 取消 / 点遮罩都走这里)。
///
/// 返回 `false` 表示本来就没有当前条(幂等,双击不会误推进队列)。
pub fn close_current(&mut self) -> bool {
if self.current.is_none() {
return false;
}
self.advance();
true
}
/// 更新进度对话框的进度(任务回调直接喂进来)。
pub fn update_progress(&mut self, id: DialogId, progress: f32) {
let Some(current) = &mut self.current else {
return;
};
if current.id != id {
return;
}
if let DialogKind::Progress {
progress: value, ..
} = &mut current.kind
{
*value = progress.clamp(0.0, 1.0);
}
}
}
#[cfg(test)]
mod tests {
use super::{DialogKind, DialogQueue, DialogSource};
fn confirm() -> DialogKind {
DialogKind::Confirm {
primary: "确定".into(),
secondary: "取消".into(),
}
}
#[test]
fn shows_one_dialog_at_a_time() {
let mut queue = DialogQueue::new();
let first = queue.push(DialogSource::BackgroundTask, "A", "", confirm());
let second = queue.push(DialogSource::BackgroundTask, "B", "", confirm());
assert_eq!(queue.current().map(|d| d.id), Some(first));
assert_eq!(queue.pending_len(), 1);
queue.advance();
assert_eq!(queue.current().map(|d| d.id), Some(second));
assert_eq!(queue.pending_len(), 0);
queue.advance();
assert!(queue.is_empty());
}
#[test]
fn user_action_jumps_the_queue() {
let mut queue = DialogQueue::new();
queue.push(DialogSource::Hint, "提示", "", confirm());
queue.push(DialogSource::Hint, "提示2", "", confirm());
queue.push(DialogSource::BackgroundTask, "后台", "", confirm());
let urgent = queue.push(DialogSource::UserAction, "确认删除", "", confirm());
// 当前仍是队首(一次一条),但排队里用户操作插到最前 → 关掉当前条后立刻轮到它
queue.advance();
assert_eq!(queue.current().map(|d| d.id), Some(urgent));
}
#[test]
fn closing_non_current_dialog_removes_it_from_pending() {
let mut queue = DialogQueue::new();
let first = queue.push(DialogSource::Hint, "A", "", confirm());
let second = queue.push(DialogSource::Hint, "B", "", confirm());
assert!(queue.close(second));
assert_eq!(queue.pending_len(), 0);
assert_eq!(queue.current().map(|d| d.id), Some(first));
assert!(!queue.close(999));
}
#[test]
fn progress_dialog_can_be_updated() {
let mut queue = DialogQueue::new();
let id = queue.push(
DialogSource::BackgroundTask,
"下载中",
"",
DialogKind::Progress {
label: "资源".into(),
progress: 0.0,
},
);
queue.update_progress(id, 1.7);
match queue.current().map(|d| &d.kind) {
Some(DialogKind::Progress { progress, .. }) => {
assert!((*progress - 1.0).abs() < f32::EPSILON);
}
other => panic!("unexpected dialog kind: {other:?}"),
}
}
}
+95
View File
@@ -0,0 +1,95 @@
//! AI 会话 DTO:消息、工具调用可视化与 agent 事件。
/// 会话消息角色。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChatRole {
/// 用户
User,
/// 助手(可流式)
Assistant,
/// 工具调用(会话里可见,D4 要求)
Tool,
/// 系统提示(弱化展示)
System,
}
/// 工具调用可视化条目。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolCallView {
/// 工具名(与 ToolSpec 注册表同名)
pub name: String,
/// 是否成功
pub ok: bool,
/// 一行结果摘要
pub summary: String,
}
/// 一条会话消息。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatMessage {
/// 角色
pub role: ChatRole,
/// 正文(流式时持续追加)
pub text: String,
/// role == Tool 时带上工具调用详情
pub tool: Option<ToolCallView>,
/// 流式未收敛
pub streaming: bool,
}
impl ChatMessage {
/// 用户消息。
pub fn user(text: impl Into<String>) -> Self {
Self {
role: ChatRole::User,
text: text.into(),
tool: None,
streaming: false,
}
}
/// 助手流式消息起点(空文本 + streaming)。
pub fn assistant_stream() -> Self {
Self {
role: ChatRole::Assistant,
text: String::new(),
tool: None,
streaming: true,
}
}
}
/// agent 侧事件。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AgentEvent {
/// 追加一条完整消息
MessageAppended(ChatMessage),
/// 给指定序号的流式消息追加增量
MessageDelta {
/// 目标消息在会话里的序号
index: usize,
/// 增量文本
delta: String,
},
/// 流式收敛
MessageFinished {
/// 目标消息序号
index: usize,
},
/// 开始一次工具调用(会话里插入工具条目)
ToolCallStarted {
/// 工具名
name: String,
/// 调用参数摘要
summary: String,
},
/// 工具调用结束
ToolCallFinished {
/// 工具名
name: String,
/// 是否成功
ok: bool,
/// 结果摘要
summary: String,
},
}
+86
View File
@@ -0,0 +1,86 @@
//! 事件与指令:core/agent → app 的事件队列,app → core/agent 的用户意图。
use crate::dialogs::{DialogId, DialogRequest};
use crate::dto::{AgentEvent, DiagnosisReport, InstanceId, InstanceRuntime, InstanceSummary};
use crate::dto::{LogLine, LogSession, SessionId, VersionCategory, VersionSummary};
use crate::toast::Toast;
/// core 侧事件(不可变快照发布 + 事件流,01c §5 的三条通道之二)。
#[derive(Debug, Clone, PartialEq)]
pub enum CoreEvent {
/// 实例列表整体刷新
InstancesChanged(Vec<InstanceSummary>),
/// 单个实例运行时状态变化(启动进度/运行中/失败)
InstanceRuntimeChanged {
/// 实例 id
id: InstanceId,
/// 新状态
runtime: InstanceRuntime,
},
/// 下载页版本列表刷新
VersionListChanged(Vec<VersionSummary>),
/// 日志会话列表刷新
LogSessionsChanged(Vec<LogSession>),
/// 当前会话日志行刷新(P0 整批替换;P1 改增量追加)
LogLinesChanged(Vec<LogLine>),
/// 诊断结论产出
DiagnosisReady(DiagnosisReport),
}
/// 统一事件队列的元素:core / agent / UI 自产(对话框、Toast)都走这一条路,
/// 这样 [`crate::state::AppState::apply`] 是唯一的状态变更入口。
#[derive(Debug, Clone, PartialEq)]
pub enum AppEvent {
/// 来自 core
Core(CoreEvent),
/// 来自 agent
Agent(AgentEvent),
/// core/agent 请求弹对话框(会进队列,一次一条)
DialogRequested(DialogRequest),
/// 关闭指定对话框(任务完成收起进度条)
DialogClosed(DialogId),
/// 右下角 Toast
Toast(Toast),
}
/// app → core/agent 的用户意图。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AppCommand {
/// 重新扫描实例目录
RefreshInstances,
/// 启动实例
LaunchInstance(InstanceId),
/// 停止实例(含取消启动中的管线)
StopInstance(InstanceId),
/// 拉取某分类的版本列表
ListVersions(VersionCategory),
/// 安装指定版本
InstallVersion(String),
/// 刷新日志会话列表
RefreshLogSessions,
/// 打开某个会话(拉取日志行 + 触发诊断)
OpenLogSession(SessionId),
/// 向 AI 提问(会话状态在 app 侧,agent 只回事件)
AskAgent(String),
/// 中断当前 AI 流
StopAgent,
/// YOLO 开关(跳过确认,审计照记)
SetYolo(bool),
}
/// 后端通道:core/agent host 实现它;P0 用 [`crate::mock::MockBackend`] 验证通道语义。
///
/// 轮询模型(而非回调)是为了让 Slint 的定时器成为唯一调度者,
/// 避免跨线程回调里碰 Slint 模型。
pub trait Backend {
/// 取走自上次调用以来积压的事件(FIFO,不可丢序号)。
fn drain_events(&mut self) -> Vec<AppEvent>;
/// 下发一条用户意图。
fn dispatch(&mut self, command: AppCommand);
/// 时间推进(mock 用脚本推进进度;真实后端可以是空实现)。
fn tick(&mut self, elapsed: std::time::Duration) {
let _ = elapsed;
}
}
+151
View File
@@ -0,0 +1,151 @@
//! 实例相关 DTO:磁贴与列表视图的唯一数据源。
use std::path::PathBuf;
/// 实例标识:core::game 生成的稳定 id,app 视为不透明字符串。
pub type InstanceId = String;
/// 加载器种类(磁贴徽标 + 详情页版本链)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoaderKind {
/// 原版(无加载器)
Vanilla,
/// Fabric
Fabric,
/// Quilt
Quilt,
/// Forge
Forge,
/// NeoForge
NeoForge,
/// OptiFine
OptiFine,
/// LiteLoader
LiteLoader,
}
impl LoaderKind {
/// 徽标显示文字。
pub fn label(self) -> &'static str {
match self {
Self::Vanilla => "原版",
Self::Fabric => "Fabric",
Self::Quilt => "Quilt",
Self::Forge => "Forge",
Self::NeoForge => "NeoForge",
Self::OptiFine => "OptiFine",
Self::LiteLoader => "LiteLoader",
}
}
}
/// 加载器 + 版本(例如 Fabric 0.16.5)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoaderInfo {
/// 加载器种类
pub kind: LoaderKind,
/// 加载器版本号;原版为空串
pub version: String,
}
impl LoaderInfo {
/// 徽标文字:原版只写「原版」,装加载器时写「Fabric 0.16.5」。
pub fn badge(&self) -> String {
if self.kind == LoaderKind::Vanilla || self.version.is_empty() {
self.kind.label().to_string()
} else {
format!("{} {}", self.kind.label(), self.version)
}
}
}
/// 字节进度;`total == 0` 表示总量未知(UI 转不确定态)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct Progress {
/// 已完成量
pub done: u64,
/// 总量;0 = 未知
pub total: u64,
}
impl Progress {
/// 0.0~1.0;未知总量返回 0.0。
pub fn ratio(self) -> f32 {
if self.total == 0 {
0.0
} else {
(self.done as f32 / self.total as f32).clamp(0.0, 1.0)
}
}
/// 总量是否已知。
pub fn is_known(self) -> bool {
self.total > 0
}
}
/// 启动管线阶段(磁贴进度环的文案来源;D8 的 10 阶段在 P1 细化)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LaunchStage {
/// 下载资源
Download,
/// 校验文件
Verify,
/// 组装命令行并拉起进程
Launch,
}
impl LaunchStage {
/// 磁贴上的阶段文案。
pub fn label(self) -> &'static str {
match self {
Self::Download => "下载资源",
Self::Verify => "校验文件",
Self::Launch => "启动中",
}
}
}
/// 实例运行时状态(磁贴的四种外观)。
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub enum InstanceRuntime {
/// 空闲
#[default]
Idle,
/// 启动管线进行中
Busy {
/// 当前阶段
stage: LaunchStage,
/// 该阶段进度
progress: Progress,
},
/// 游戏进程存活
Running {
/// 进程号(停止/诊断用)
pid: u32,
},
/// 上次启动失败(磁贴显示「重试」)
Failed {
/// 失败原因(用户可见文案)
reason: String,
},
}
/// 实例摘要:磁贴/列表视图唯一数据源。
#[derive(Debug, Clone, PartialEq)]
pub struct InstanceSummary {
/// 稳定 id
pub id: InstanceId,
/// 显示名
pub name: String,
/// 游戏版本(如 1.20.4)
pub mc_version: String,
/// 加载器信息
pub loader: LoaderInfo,
/// ISO-8601 UTC 最后游玩时间;None = 从未启动
pub last_played: Option<String>,
/// 运行时状态
pub runtime: InstanceRuntime,
/// 实例图标路径(P0 直接给路径;P1 换成 core 提供的图像句柄)
pub icon: Option<PathBuf>,
}
+76
View File
@@ -0,0 +1,76 @@
//! 日志页 DTO:会话列表、日志行与 D8 诊断结论。
/// 一次启动会话(日志页左栏单位)标识。
pub type SessionId = String;
/// 一次运行的结局(G3 左栏图标:✓ 正常 / ✗ 崩溃 / ⚠ 静默失败)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogOutcome {
/// 正常退出
Ok,
/// 崩溃(非零退出码或 hs_err_pid)
Crashed,
/// exit0 但游戏没起来(D8 新增检测)
SilentFail,
}
/// 会话摘要。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogSession {
/// 会话 id
pub id: SessionId,
/// 实例名(会话属于哪个实例)
pub instance: String,
/// 展示用时间(`10-29 19:22`)
pub when: String,
/// 结局
pub outcome: LogOutcome,
/// 时长(秒)
pub duration_secs: u64,
}
/// 日志行等级(错误行高亮)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
/// debug
Debug,
/// info
Info,
/// warn
Warn,
/// error
Error,
}
/// 一行日志。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogLine {
/// 原始文本(含时间戳前缀)
pub text: String,
/// 等级
pub level: LogLevel,
}
/// D8 规则引擎结论(日志页崩溃诊断卡片)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnosis {
/// 命中规则 id(`gpu.driver_old`)
pub rule: String,
/// 结论标题
pub title: String,
/// 0~100 置信度
pub confidence: u8,
/// 建议文案
pub hint: String,
/// 可一键执行的修复动作(无则只给建议)
pub fix: Option<String>,
}
/// 诊断结论 + 归属会话(UI 用它决定卡片显隐)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosisReport {
/// 归属会话
pub session: SessionId,
/// 诊断内容
pub diagnosis: Diagnosis,
}
+23
View File
@@ -0,0 +1,23 @@
//! app ↔ core/agent 的 IPC 边界(01c §5 纪律)。
//!
//! 这里只允许出现「扁平 DTO / 事件 / 指令」:`crates/app` 任何模块都不得 `use unlucky_core::*`
//! 或 `use unlucky_agent::*` 的内部类型。core/agent 侧的 host 层负责把自身类型翻译成本模块的类型,
//! 反向的 [`AppCommand`] 也一样。P0 阶段由 [`crate::mock`] 的假后端实现 [`Backend`] 驱动骨架。
//!
//! 结构:**按领域拆子模块**(instances / versions / logs / agent / events),
//! 全量 `pub use` 出去,调用方依旧写 `crate::dto::InstanceSummary` 这类路径。
//! 契约说明(字段口径、事件顺序、错误语义)见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`。
mod agent;
mod events;
mod instances;
mod logs;
mod versions;
pub use agent::{AgentEvent, ChatMessage, ChatRole, ToolCallView};
pub use events::{AppCommand, AppEvent, Backend, CoreEvent};
pub use instances::{
InstanceId, InstanceRuntime, InstanceSummary, LaunchStage, LoaderInfo, LoaderKind, Progress,
};
pub use logs::{Diagnosis, DiagnosisReport, LogLevel, LogLine, LogOutcome, LogSession, SessionId};
pub use versions::{AncientKind, VersionCategory, VersionKind, VersionSummary};
+60
View File
@@ -0,0 +1,60 @@
//! 下载页 DTO:版本列表与分类(含远古版子类,D16/Q24-4)。
/// 版本类型(远古版按 unlisted-versions 的分类拆开)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionKind {
/// 正式版
Release,
/// 预览版(snapshot)
Snapshot,
/// 远古版(带子类)
Ancient(AncientKind),
}
/// 远古版子类。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AncientKind {
/// classic(rd-*)
Classic,
/// old_alpha(a1.*)
OldAlpha,
/// old_beta(b1.*)
OldBeta,
/// 未列入官方清单的远古版汇总
Unlisted,
}
impl VersionKind {
/// 是否属于「远古版」——列表行要加警示徽标。
pub fn is_ancient(self) -> bool {
matches!(self, Self::Ancient(_))
}
}
/// 下载页版本行。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionSummary {
/// 版本 id(如 `1.20.4` / `rd-132211`)
pub id: String,
/// 版本类型
pub kind: VersionKind,
/// 发布日期(ISO-8601 日期部分)
pub released: String,
/// 本地是否已安装(行尾显示「已装」)
pub installed: bool,
}
/// 下载页左侧分类(页内常驻侧栏的选中项)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VersionCategory {
/// 正式版
Release,
/// 预览版
Snapshot,
/// 远古版某子类
Ancient(AncientKind),
/// 整合包(P1)
Modpack,
/// Mod(P1)
Mod,
}
+94
View File
@@ -0,0 +1,94 @@
//! Unlucky-Launcher 桌面壳(`unlucky_app`):Slint UI + Metro 视觉。
//!
//! 边界(决策 D3 / D16):本 crate 是**唯一**允许依赖 UI 框架的 crate;
//! 它只经「快照 + 事件流 + 注入的显示服务」消费 core/agent,不直接触碰其内部类型
//! (P0 的 host 是 `mock` 假后端,`crate::dto` 是唯一跨界类型集合)。
//!
//! 渲染策略(`DevDocs/PlanDoc/01c-native-gui-options.md` §6):
//! GL 优先(femtovg),启动参数 `--software-renderer` 或 Win7 老机探测失败时切 CPU 软渲染。
//!
//! 主题与外观(D17 / 09 §101-113):
//! - 主题三态 `appearance.theme_mode ∈ {auto, light, dark}`(出厂 auto);
//! - 「外观(高级)」四件(背景图 / 面板半透明度 / 玻璃拟态 / 强调色)出厂全关;
//! - 全部走 `core::setting` 的 schema(`crate::settings_bridge`),AI 可写并且**热切**
//! (tick 里 1s 一次 mtime 比对);系统主题由 `core::platform::theme_probe` 对齐 + 兜底轮询。
//!
//! 架构分层(本文件只有一个职责:把窗口拉起来):
//! - `state.rs` / `prefs.rs` / `router.rs` / `dialogs.rs` / `toast.rs`:纯 Rust 状态(可单测,无 Slint)
//! - `dto/`:跨边界 DTO 与事件/指令
//! - `conv.rs`:状态 → Slint 视图模型
//! - `ui_bind.rs` + `callbacks.rs`:窗口/状态/后端缝合 + 回调接线
//! - `settings_bridge.rs`:`config/launcher.json` 的读写与热切(core::setting 的 schema API)
//! - `bg_image.rs` + `png.rs`:背景图/模糊层加工与截图编码(09 §101/§103 的预生成手法)
//! - `mock.rs` + `mock_data.rs`:P0 假后端(脚本化事件)
//!
//! 关于 unsafe:本 crate 不写 unsafe,workspace lint 已设 `unsafe_code = "deny"`。
//! 这里不能升级成 `#![forbid(unsafe_code)]`——Slint 生成的代码自带 `#[allow(unsafe_code)]`,
//! 而 forbid 无法被内层 allow 覆盖(会直接编译失败)。同理 Slint 生成类型不带文档注释,
//! 只能在 crate 级放开 `missing_docs`(库 crate 仍由 workspace lint 保持 warn)。
// 关于 dead_code:P0 骨架里有一批「已定义、等接线」的公共 API——事件通道 / 偏好键登记 /
// 诊断文案 / mock 数据构造器等,它们被单测覆盖但业务侧要 P1 才用到。逐条 `#[allow]`
// 会把噪音藏进实现细节,这里统一放开并在 P1 接线时逐个转正(届时删掉本行即可暴露真死码)。
#![allow(missing_docs, dead_code)]
mod appearance_bind;
mod bg_image;
mod callbacks;
mod conv;
mod dialogs;
mod dto;
mod mock;
mod mock_data;
mod png;
mod prefs;
mod router;
mod settings_bridge;
mod state;
mod theme_runtime;
mod toast;
mod ui_bind;
slint::include_modules!();
fn main() -> Result<(), slint::PlatformError> {
apply_renderer_flag();
let app = ui_bind::AppUi::new(MainWindow::new()?);
// 截图验收通道(M41 视觉验收;无交互桌面/无 GPU 环境下的唯一可靠取图方式:
// 不截屏幕,而是让 Slint 把当前场景渲染进内存像素缓冲再自己编码 PNG)。
if let Some(path) = screenshot_path() {
if std::env::args().any(|arg| arg == "--screenshot-settings") {
app.open_settings_appearance();
}
app.render_screenshot(&path)?;
return Ok(());
}
app.start_timer();
app.run()
}
/// Win7 老机 / 无可用 OpenGL 驱动时的软渲染兜底开关(01c §6 的 Slint 核心卖点)。
fn apply_renderer_flag() {
let software = std::env::args()
.skip(1)
.any(|arg| arg == "--software-renderer");
if software {
std::env::set_var("SLINT_BACKEND", "winit-software");
}
}
/// `--screenshot <path>` / `--screenshot=<path>`:渲染一帧并写 PNG 后退出。
fn screenshot_path() -> Option<String> {
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
if let Some(value) = arg.strip_prefix("--screenshot=") {
return Some(value.to_owned());
}
if arg == "--screenshot" {
return args.next();
}
}
None
}
+366
View File
@@ -0,0 +1,366 @@
//! P0 假后端:用脚本化事件驱动骨架,验证 app ↔ core/agent 通道语义。
//!
//! 覆盖四条通道:实例运行状态(磁贴进度环)、AI 流式会话(含工具调用)、
//! 对话框队列(进度对话框)、Toast。阶段 B 里由真正的 core/agent host 替换
//! [`MockBackend`],[`crate::dto::Backend`] 之上的 state/reducer 不动。
//! 假数据本体在 [`crate::mock_data`]。
use std::collections::VecDeque;
use std::time::Duration;
use crate::dialogs::{DialogKind, DialogRequest, DialogSource};
use crate::dto::{
AgentEvent, AppCommand, AppEvent, Backend, ChatMessage, ChatRole, CoreEvent, InstanceId,
InstanceRuntime, LaunchStage, Progress,
};
use crate::mock_data::{mock_instances, mock_log_lines, mock_log_sessions, mock_versions};
use crate::toast::{Toast, ToastKind};
/// 启动脚本:按时间推进 download → verify → launch → running。
#[derive(Debug)]
struct LaunchScript {
id: InstanceId,
elapsed_ms: u64,
}
/// AI 流式脚本:每条提问回一段可切分的话 + 一次工具调用。
#[derive(Debug)]
struct ChatScript {
elapsed_ms: u64,
chunks: VecDeque<String>,
/// 流式助手消息在 app 会话里的序号
message_index: usize,
}
/// 假后端。
#[derive(Debug, Default)]
pub struct MockBackend {
events: VecDeque<AppEvent>,
launch: Option<LaunchScript>,
chat: Option<ChatScript>,
/// 已投递给 app 的会话消息条数(用来给 MessageDelta 算序号)
emitted_messages: usize,
next_dialog: u64,
}
impl MockBackend {
/// 预置一批假数据事件(实例/版本/日志会话)。
pub fn new() -> Self {
let mut backend = Self::default();
backend.seed();
backend
}
fn seed(&mut self) {
self.events.push_back(AppEvent::Core(
CoreEvent::InstancesChanged(mock_instances()),
));
self.events
.push_back(AppEvent::Core(CoreEvent::VersionListChanged(
mock_versions(),
)));
self.events
.push_back(AppEvent::Core(CoreEvent::LogSessionsChanged(
mock_log_sessions(),
)));
self.events
.push_back(AppEvent::Core(CoreEvent::LogLinesChanged(mock_log_lines())));
}
fn emit(&mut self, event: AppEvent) {
self.events.push_back(event);
}
fn next_dialog_id(&mut self) -> u64 {
self.next_dialog += 1;
self.next_dialog
}
fn script_launch(&mut self, id: InstanceId) {
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
id: id.clone(),
runtime: InstanceRuntime::Busy {
stage: LaunchStage::Download,
progress: Progress {
done: 0,
total: 1_500,
},
},
}));
self.launch = Some(LaunchScript { id, elapsed_ms: 0 });
}
fn step_launch(&mut self, elapsed: Duration) {
let Some((id, elapsed_ms)) = self.launch.as_mut().map(|script| {
script.elapsed_ms += u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
(script.id.clone(), script.elapsed_ms)
}) else {
return;
};
// 0~1.5s 下载、1.5~2.5s 校验、2.5~3s 启动、3s 后转为运行中
let runtime = if elapsed_ms < 1_500 {
InstanceRuntime::Busy {
stage: LaunchStage::Download,
progress: Progress {
done: elapsed_ms,
total: 1_500,
},
}
} else if elapsed_ms < 2_500 {
InstanceRuntime::Busy {
stage: LaunchStage::Verify,
progress: Progress {
done: elapsed_ms - 1_500,
total: 1_000,
},
}
} else if elapsed_ms < 3_000 {
InstanceRuntime::Busy {
stage: LaunchStage::Launch,
progress: Progress {
done: elapsed_ms - 2_500,
total: 500,
},
}
} else {
self.launch = None;
self.emit(AppEvent::Toast(Toast {
id: 0,
kind: ToastKind::Success,
text: "游戏已启动".to_string(),
remaining_ms: 0,
}));
InstanceRuntime::Running { pid: 12_345 }
};
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
id,
runtime,
}));
}
fn script_chat(&mut self, text: String) {
let user_index = self.emitted_messages;
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(
ChatMessage::user(text),
)));
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(
ChatMessage::assistant_stream(),
)));
self.emitted_messages += 2;
self.chat = Some(ChatScript {
elapsed_ms: 0,
chunks: VecDeque::from(vec![
"先确认版本:".to_string(),
"官方 1.20.4 是正式版,".to_string(),
"装完再用 Fabric 加加载器。".to_string(),
]),
message_index: user_index + 1,
});
}
fn step_chat(&mut self, elapsed: Duration) {
let Some(chat) = self.chat.as_mut() else {
return;
};
chat.elapsed_ms += u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX);
if chat.elapsed_ms < 300 {
return;
}
chat.elapsed_ms = 0;
let index = chat.message_index;
let chunk = chat.chunks.pop_front();
if let Some(delta) = chunk {
self.emit(AppEvent::Agent(AgentEvent::MessageDelta { index, delta }));
return;
}
// 流结束后补一次工具调用(工具执行在会话里可见)+ 收尾消息
self.emit(AppEvent::Agent(AgentEvent::ToolCallStarted {
name: "read_game_log".to_string(),
summary: "读取最近一次崩溃日志".to_string(),
}));
self.emit(AppEvent::Agent(AgentEvent::ToolCallFinished {
name: "read_game_log".to_string(),
ok: true,
summary: "读到 128 行,无 ERROR".to_string(),
}));
self.emit(AppEvent::Agent(AgentEvent::MessageFinished { index }));
self.emit(AppEvent::Agent(AgentEvent::MessageAppended(ChatMessage {
role: ChatRole::Assistant,
text: "日志没有 ERROR,问题更可能在 Java 版本。".to_string(),
tool: None,
streaming: false,
})));
self.emitted_messages += 2;
self.chat = None;
}
fn script_install(&mut self, version: String) {
let id = self.next_dialog_id();
self.emit(AppEvent::DialogRequested(DialogRequest {
id,
source: DialogSource::BackgroundTask,
title: format!("正在安装 {version}"),
body: String::new(),
kind: DialogKind::Progress {
label: "下载资源".to_string(),
progress: 0.0,
},
}));
self.emit(AppEvent::DialogClosed(id));
self.emit(AppEvent::Toast(Toast {
id: 0,
kind: ToastKind::Success,
text: format!("{version} 安装完成"),
remaining_ms: 0,
}));
}
}
impl Backend for MockBackend {
fn drain_events(&mut self) -> Vec<AppEvent> {
self.events.drain(..).collect()
}
fn dispatch(&mut self, command: AppCommand) {
match command {
AppCommand::LaunchInstance(id) => self.script_launch(id),
AppCommand::StopInstance(id) => {
self.launch = None;
self.emit(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
id,
runtime: InstanceRuntime::Idle,
}));
}
AppCommand::AskAgent(text) => self.script_chat(text),
AppCommand::InstallVersion(version) => self.script_install(version),
AppCommand::SetYolo(enabled) => self.emit(AppEvent::Toast(Toast {
id: 0,
kind: ToastKind::Info,
text: if enabled {
"YOLO 已开启(审计照记)"
} else {
"YOLO 已关闭"
}
.to_string(),
remaining_ms: 0,
})),
AppCommand::ListVersions(category) => {
self.emit(AppEvent::Core(CoreEvent::VersionListChanged(
crate::mock_data::mock_versions_for(category),
)));
}
AppCommand::OpenLogSession(id) => {
// P0:换会话 = 换一批假日志行 + 一条诊断结论(日志页诊断卡片可见)
self.emit(AppEvent::Core(CoreEvent::LogLinesChanged(mock_log_lines())));
self.emit(AppEvent::Core(CoreEvent::DiagnosisReady(
crate::mock_data::mock_diagnosis(id),
)));
}
AppCommand::RefreshInstances
| AppCommand::RefreshLogSessions
| AppCommand::StopAgent => {}
}
}
fn tick(&mut self, elapsed: Duration) {
self.step_launch(elapsed);
self.step_chat(elapsed);
}
}
#[cfg(test)]
mod tests {
use super::MockBackend;
use crate::dto::{AgentEvent, AppCommand, AppEvent, Backend, CoreEvent, InstanceRuntime};
#[test]
fn seeds_instances_and_versions() {
let mut backend = MockBackend::new();
let events = backend.drain_events();
assert_eq!(events.len(), 4);
assert!(events
.iter()
.all(|event| matches!(event, AppEvent::Core(_))));
assert!(backend.drain_events().is_empty());
}
#[test]
fn launching_emits_progress_then_running() {
let mut backend = MockBackend::new();
backend.drain_events();
backend.dispatch(AppCommand::LaunchInstance("survival".to_string()));
let first = backend.drain_events();
assert!(matches!(
first[0],
AppEvent::Core(CoreEvent::InstanceRuntimeChanged { .. })
));
backend.tick(std::time::Duration::from_millis(1_600));
let verify = backend.drain_events();
match &verify[0] {
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
runtime: InstanceRuntime::Busy { stage, .. },
..
}) => assert_eq!(*stage, crate::dto::LaunchStage::Verify),
other => panic!("unexpected event: {other:?}"),
}
backend.tick(std::time::Duration::from_millis(2_000));
let done = backend.drain_events();
assert!(done.iter().any(|event| matches!(
event,
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
runtime: InstanceRuntime::Running { .. },
..
})
)));
}
#[test]
fn stopping_cancels_the_launch_script() {
let mut backend = MockBackend::new();
backend.drain_events();
backend.dispatch(AppCommand::LaunchInstance("a".to_string()));
backend.drain_events();
backend.dispatch(AppCommand::StopInstance("a".to_string()));
let events = backend.drain_events();
assert!(matches!(
events[0],
AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
runtime: InstanceRuntime::Idle,
..
})
));
// 脚本已取消:再推进时间也不会再产出事件
backend.tick(std::time::Duration::from_millis(5_000));
assert!(backend.drain_events().is_empty());
}
#[test]
fn asking_the_agent_streams_and_finishes() {
let mut backend = MockBackend::new();
backend.drain_events();
backend.dispatch(AppCommand::AskAgent("装哪个版本".to_string()));
let start = backend.drain_events();
assert_eq!(start.len(), 2);
let mut deltas = 0;
for _ in 0..6 {
backend.tick(std::time::Duration::from_millis(400));
let events = backend.drain_events();
deltas += events
.iter()
.filter(|event| matches!(event, AppEvent::Agent(AgentEvent::MessageDelta { .. })))
.count();
}
assert_eq!(deltas, 3);
}
}
+226
View File
@@ -0,0 +1,226 @@
//! P0 假数据:实例 / 版本 / 日志 / 诊断 / 工具调用样例。
//!
//! 只被 [`crate::mock`] 与阶段 B 的 main.rs 使用;真实后端接入后整文件可删。
use crate::dto::{
AncientKind, ChatMessage, ChatRole, Diagnosis, DiagnosisReport, InstanceRuntime,
InstanceSummary, LoaderInfo, LoaderKind, LogLevel, LogLine, LogOutcome, LogSession, SessionId,
ToolCallView, VersionCategory, VersionKind, VersionSummary,
};
/// P0 演示实例:覆盖空闲 / 失败两种磁贴状态(运行中由启动脚本产生)。
pub fn mock_instances() -> Vec<InstanceSummary> {
vec![
InstanceSummary {
id: "survival".to_string(),
name: "生存整合包".to_string(),
mc_version: "1.20.4".to_string(),
loader: LoaderInfo {
kind: LoaderKind::Fabric,
version: "0.16.5".to_string(),
},
last_played: Some("2026-10-29T19:22:00Z".to_string()),
runtime: InstanceRuntime::Idle,
icon: None,
},
InstanceSummary {
id: "vanilla-latest".to_string(),
name: "原版最新".to_string(),
mc_version: "1.21.9".to_string(),
loader: LoaderInfo {
kind: LoaderKind::Vanilla,
version: String::new(),
},
last_played: Some("2026-10-28T21:03:00Z".to_string()),
runtime: InstanceRuntime::Idle,
icon: None,
},
InstanceSummary {
id: "ancient-1.7.10".to_string(),
name: "远古 1.7.10".to_string(),
mc_version: "1.7.10".to_string(),
loader: LoaderInfo {
kind: LoaderKind::Forge,
version: "10.13.4.1614".to_string(),
},
last_played: None,
runtime: InstanceRuntime::Idle,
icon: None,
},
InstanceSummary {
id: "modded-dev".to_string(),
name: "开发测试".to_string(),
mc_version: "1.21.1".to_string(),
loader: LoaderInfo {
kind: LoaderKind::NeoForge,
version: "21.1.72".to_string(),
},
last_played: Some("2026-10-27T12:40:00Z".to_string()),
runtime: InstanceRuntime::Failed {
reason: "exit0 静默失败".to_string(),
},
icon: None,
},
]
}
/// P0 演示版本列表(含远古版三子类,验证分类侧栏与警示徽标)。
pub fn mock_versions() -> Vec<VersionSummary> {
fn row(id: &str, kind: VersionKind, released: &str, installed: bool) -> VersionSummary {
VersionSummary {
id: id.to_string(),
kind,
released: released.to_string(),
installed,
}
}
vec![
row("1.21.9", VersionKind::Release, "2026-09-20", false),
row("1.21.8", VersionKind::Release, "2026-07-11", true),
row("1.20.4", VersionKind::Release, "2023-12-07", true),
row("1.21.9-pre3", VersionKind::Snapshot, "2026-09-01", false),
row(
"rd-132211",
VersionKind::Ancient(AncientKind::Classic),
"2009-05-13",
false,
),
row(
"a1.2.6",
VersionKind::Ancient(AncientKind::OldAlpha),
"2010-08-11",
false,
),
row(
"b1.7.3",
VersionKind::Ancient(AncientKind::OldBeta),
"2011-07-08",
false,
),
]
}
/// 日志会话样例(✓ / ✗ / ⚠ 三种结局各一条)。
pub fn mock_log_sessions() -> Vec<LogSession> {
vec![
LogSession {
id: "s-1029-1922".to_string(),
instance: "生存整合包".to_string(),
when: "10-29 19:22".to_string(),
outcome: LogOutcome::Ok,
duration_secs: 3_780,
},
LogSession {
id: "s-1029-1840".to_string(),
instance: "开发测试".to_string(),
when: "10-29 18:40".to_string(),
outcome: LogOutcome::Crashed,
duration_secs: 62,
},
LogSession {
id: "s-1029-1755".to_string(),
instance: "原版最新".to_string(),
when: "10-29 17:55".to_string(),
outcome: LogOutcome::SilentFail,
duration_secs: 8,
},
]
}
/// 日志行样例(含一条 ERROR 供高亮验证)。
pub fn mock_log_lines() -> Vec<LogLine> {
fn line(text: &str, level: LogLevel) -> LogLine {
LogLine {
text: text.to_string(),
level,
}
}
vec![
line(
"[19:22:01] [main/INFO] Launching Minecraft 1.20.4",
LogLevel::Info,
),
line("[19:22:02] [main/INFO] Loading 42 mods", LogLevel::Info),
line(
"[19:22:03] [Render thread/WARN] GL vendor: unknown",
LogLevel::Warn,
),
line(
"[19:22:05] [Render thread/ERROR] OpenGL 2.1 not supported",
LogLevel::Error,
),
line("[19:22:05] [main/INFO] Stopping!", LogLevel::Info),
]
}
/// 崩溃诊断样例(验证日志页诊断卡片 + 「让 AI 详解」入口)。
pub fn mock_diagnosis(session: SessionId) -> DiagnosisReport {
DiagnosisReport {
session,
diagnosis: Diagnosis {
rule: "gpu.driver_old".to_string(),
title: "显卡驱动过旧(OpenGL 版本不足)".to_string(),
confidence: 92,
hint: "升级显卡驱动,或在启动参数里改用软件渲染".to_string(),
fix: Some("switch_software_renderer".to_string()),
},
}
}
/// 工具调用条目样例(AI 面板静态填充用)。
pub fn mock_tool_message() -> ChatMessage {
ChatMessage {
role: ChatRole::Tool,
text: "读到 128 行,无 ERROR".to_string(),
tool: Some(ToolCallView {
name: "read_game_log".to_string(),
ok: true,
summary: "读到 128 行,无 ERROR".to_string(),
}),
streaming: false,
}
}
/// 分类 → 该分类下的假版本(下载页切换分类时用)。
pub fn mock_versions_for(category: VersionCategory) -> Vec<VersionSummary> {
mock_versions()
.into_iter()
.filter(|version| match category {
VersionCategory::Release => version.kind == VersionKind::Release,
VersionCategory::Snapshot => version.kind == VersionKind::Snapshot,
VersionCategory::Ancient(kind) => version.kind == VersionKind::Ancient(kind),
VersionCategory::Modpack | VersionCategory::Mod => false,
})
.collect()
}
#[cfg(test)]
mod tests {
use crate::dto::{AncientKind, VersionCategory, VersionKind};
use crate::mock_data::{mock_instances, mock_versions_for};
#[test]
fn mock_instances_cover_the_tile_states() {
let instances = mock_instances();
assert_eq!(instances.len(), 4);
assert!(instances.iter().any(|instance| matches!(
instance.runtime,
crate::dto::InstanceRuntime::Failed { .. }
)));
}
#[test]
fn versions_are_filtered_by_category() {
let release = mock_versions_for(VersionCategory::Release);
assert!(release
.iter()
.all(|version| version.kind == VersionKind::Release));
assert_eq!(release.len(), 3);
let classic = mock_versions_for(VersionCategory::Ancient(AncientKind::Classic));
assert_eq!(classic.len(), 1);
assert_eq!(classic[0].id, "rd-132211");
assert!(mock_versions_for(VersionCategory::Mod).is_empty());
}
}
+140
View File
@@ -0,0 +1,140 @@
//! 极简 PNG 编码器(只做「无压缩 stored deflate」),给截图验收用。
//!
//! 为什么不引 `image` / `png` crate:截屏只是开发期验收工具(`--screenshot`),
//! 为它加一个依赖违反「新依赖过 deny.toml 白名单」的成本收益。PNG 规范里 zlib 流允许
//! **stored(未压缩)块**,于是我们只需要 CRC32 + Adler32 两个校验和就能产出合法 PNG——
//! 文件大一些,但任何看图工具都认。
//!
//! 输出:8bit RGBA(color type 6),逐行 filter=0(None)。
use slint::{Rgba8Pixel, SharedPixelBuffer};
/// 把 RGBA8 像素缓冲写成 PNG 字节流。
#[must_use]
pub fn encode_rgba8(buffer: &SharedPixelBuffer<Rgba8Pixel>) -> Vec<u8> {
let width = buffer.width();
let height = buffer.height();
let pixels = buffer.as_slice();
// 原始扫描线:每行前面加一个 filter 字节 0
let stride = width as usize * 4;
let mut raw = Vec::with_capacity((stride + 1) * height as usize);
for y in 0..height as usize {
raw.push(0u8);
for x in 0..width as usize {
let pixel = pixels[y * width as usize + x];
raw.extend_from_slice(&[pixel.r, pixel.g, pixel.b, pixel.a]);
}
}
let mut out = Vec::new();
out.extend_from_slice(&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
let mut ihdr = Vec::with_capacity(13);
ihdr.extend_from_slice(&width.to_be_bytes());
ihdr.extend_from_slice(&height.to_be_bytes());
ihdr.extend_from_slice(&[8, 6, 0, 0, 0]); // 位深 8、RGBA、deflate、无交错
push_chunk(&mut out, b"IHDR", &ihdr);
push_chunk(&mut out, b"IDAT", &zlib_stored(&raw));
push_chunk(&mut out, b"IEND", &[]);
out
}
fn push_chunk(out: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(kind);
out.extend_from_slice(data);
let mut crc_input = Vec::with_capacity(4 + data.len());
crc_input.extend_from_slice(kind);
crc_input.extend_from_slice(data);
out.extend_from_slice(&crc32(&crc_input).to_be_bytes());
}
/// zlib 容器 + 全 stored deflate 块(每块上限 65535 字节)。
fn zlib_stored(raw: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(raw.len() + raw.len() / 65_535 * 5 + 16);
out.extend_from_slice(&[0x78, 0x01]); // CMF/FLG:deflate、32K 窗口、无字典、最快
let mut offset = 0usize;
while offset < raw.len() {
let len = (raw.len() - offset).min(65_535);
let last = offset + len >= raw.len();
out.push(u8::from(last)); // BFINAL + BTYPE=00
let len_u16 = len as u16;
out.extend_from_slice(&len_u16.to_le_bytes());
out.extend_from_slice(&(!len_u16).to_le_bytes());
out.extend_from_slice(&raw[offset..offset + len]);
offset += len;
}
if raw.is_empty() {
out.push(1);
out.extend_from_slice(&[0, 0, 0xff, 0xff]);
}
out.extend_from_slice(&adler32(raw).to_be_bytes());
out
}
fn crc32(data: &[u8]) -> u32 {
let mut crc = 0xffff_ffffu32;
for byte in data {
crc ^= u32::from(*byte);
for _ in 0..8 {
let mask = (crc & 1).wrapping_neg();
crc = (crc >> 1) ^ (0xedb8_8320 & mask);
}
}
!crc
}
fn adler32(data: &[u8]) -> u32 {
let mut a: u32 = 1;
let mut b: u32 = 0;
for byte in data {
a = (a + u32::from(*byte)) % 65_521;
b = (b + a) % 65_521;
}
(b << 16) | a
}
#[cfg(test)]
mod tests {
use super::*;
fn pixel(r: u8, g: u8, b: u8) -> Rgba8Pixel {
Rgba8Pixel { r, g, b, a: 255 }
}
#[test]
fn header_and_chunks_are_well_formed() {
let mut buffer = SharedPixelBuffer::<Rgba8Pixel>::new(3, 2);
buffer.make_mut_slice().fill(pixel(1, 2, 3));
let bytes = encode_rgba8(&buffer);
assert_eq!(
&bytes[..8],
&[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]
);
// IHDR:宽 3 高 2、8bit、RGBA(6)
assert_eq!(&bytes[8..12], &13u32.to_be_bytes());
assert_eq!(&bytes[12..16], b"IHDR");
assert_eq!(&bytes[16..20], &3u32.to_be_bytes());
assert_eq!(&bytes[20..24], &2u32.to_be_bytes());
assert_eq!(bytes[24], 8);
assert_eq!(bytes[25], 6);
// 结尾是 IEND 块
assert_eq!(&bytes[bytes.len() - 8..bytes.len() - 4], b"IEND");
}
#[test]
fn checksums_match_known_vectors() {
// CRC32("IEND") 是公认值 0xAE426082(写进 IEND 块尾)
assert_eq!(crc32(b"IEND"), 0xae42_6082);
// Adler32("Wikipedia") = 0x11E60398
assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
}
#[test]
fn empty_buffer_still_produces_valid_stream() {
let buffer = SharedPixelBuffer::<Rgba8Pixel>::new(0, 0);
let bytes = encode_rgba8(&buffer);
assert!(bytes.windows(4).any(|window| window == b"IDAT"));
}
}
+288
View File
@@ -0,0 +1,288 @@
//! UI 偏好项与持久化键登记(导航折叠、AI 栏折叠、磁贴尺寸、视图、主题三态与外观四件、下载分类)。
//!
//! 偏好不自己写盘:core::setting 的 schema 按 [`keys::ALL`] 登记这些键,
//! app 启动时读一次、变更时写回(跨模块约定见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`)。
//! 落盘实现是 [`crate::settings_bridge`](同一份 `config/launcher.json`,与 `ull config set` 同源),
//! 主题三态 + `appearance.*` 高级键已接(M41);其余 UI 偏好键仍只在内存里(后续 mission 接)。
/// 背景图填充模式(09 §101)。直接复用 core 的枚举:取值与落盘词表只有一处真相。
pub use unlucky_core::setting::appearance::BgFill;
use crate::dto::VersionCategory;
/// 预设强调色板(09 §104)。**必须**与 `ui/pages/settings-appearance.slint` 的 `swatch-colors`
/// 同序同值:Slint 侧只回传索引,十六进制串由这张表给出(一处真相)。
pub const ACCENT_PRESETS: [&str; 8] = [
"#0078D4", "#0F6CBD", "#107C10", "#9D5D00", "#C42B1C", "#8764B8", "#C239B3", "#00B7C3",
];
/// 磁贴尺寸(Q24-3:小 6 列 / 中 4 列 / 大 3 列)。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TileSize {
/// 小:6 列,只留图标/名字/启动键
Small,
/// 中:4 列(D16 默认)
#[default]
Medium,
/// 大:3 列,显示完整徽标与最后游玩时间
Large,
}
impl TileSize {
/// 该尺寸对应的网格列数。
pub fn columns(self) -> usize {
match self {
Self::Small => 6,
Self::Medium => 4,
Self::Large => 3,
}
}
/// 设置页/实例页分段控件的文案。
pub fn label(self) -> &'static str {
match self {
Self::Small => "小",
Self::Medium => "中",
Self::Large => "大",
}
}
}
/// 实例页视图模式。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InstanceView {
/// 磁贴网格(默认)
#[default]
Tiles,
/// 紧凑列表
List,
}
/// 主题三态(D17,P0 交付):`appearance.theme_mode ∈ {light, dark, auto}`,出厂 auto。
///
/// auto 由 `theme/tokens.slint` 读 Slint 原生 `Palette.color-scheme` 跟随系统(后端随 OS 热更);
/// light/dark 由 `Theme.theme-mode` 钉死**自绘体系**;std-widgets 内部件(ListView 滚动条 /
/// ProgressIndicator / AboutSlint)目前仍跟随系统色,`Palette.color-scheme` 的钉死留 P1。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ThemeMode {
/// 跟随系统(默认)
#[default]
Auto,
/// 强制浅色
Light,
/// 强制深色
Dark,
}
impl ThemeMode {
/// 落盘取值(`appearance.theme_mode`):`auto` / `light` / `dark`。
pub fn as_str(self) -> &'static str {
match self {
Self::Auto => "auto",
Self::Light => "light",
Self::Dark => "dark",
}
}
/// 从落盘取值解析;未知值按 `auto` 兜底(配置被手改坏也不崩)。
pub fn from_key_value(value: &str) -> Self {
match value {
"light" => Self::Light,
"dark" => Self::Dark,
_ => Self::Auto,
}
}
}
/// 09 §101-104「外观(高级)」四件的取值快照(出厂全部关闭)。
///
/// 与 `unlucky_core::setting::appearance::Appearance` 一一对应,但字段类型是 UI 侧好用的
/// `f32`/`String`;落盘由 [`crate::settings_bridge`] 转成 schema 键。
#[derive(Debug, Clone, PartialEq, Default)]
pub struct AppearancePrefs {
/// 背景图总开关
pub bg_image_enabled: bool,
/// 背景图路径(PNG;空 = 未设置)
pub bg_image: String,
/// 填充模式
pub bg_fill: BgFill,
/// 暗化层强度 0.0~0.9
pub bg_dim: f32,
/// 面板半透明度 0.4~1.0
pub panel_alpha: f32,
/// 玻璃拟态卡片
pub glass: bool,
/// 自定义强调色 `#RRGGBB`;空 = 出厂 [#0078D4]
pub accent_color: String,
}
impl AppearancePrefs {
/// 出厂态:Metro 纯色,四个高级特性全关。
pub fn factory() -> Self {
Self {
bg_image_enabled: false,
bg_image: String::new(),
bg_fill: BgFill::Cover,
bg_dim: 0.35,
panel_alpha: 1.0,
glass: false,
accent_color: String::new(),
}
}
/// 背景图是否真的生效(开关打开且路径非空)。
pub fn bg_active(&self) -> bool {
self.bg_image_enabled && !self.bg_image.trim().is_empty()
}
/// 规范化写入强调色:`#RRGGBB` 才接受(空串 = 恢复出厂)。
///
/// 返回 `false` 表示输入不合法(调用方据此亮设置页的 warn 行,不改现状)。
pub fn set_accent(&mut self, text: &str) -> bool {
let trimmed = text.trim();
if trimmed.is_empty() {
self.accent_color.clear();
return true;
}
match unlucky_core::setting::appearance::normalize_hex(trimmed) {
Some(hex) => {
self.accent_color = hex;
true
}
None => false,
}
}
/// 用预设色板第 `index` 个颜色(越界忽略)。
pub fn set_accent_preset(&mut self, index: usize) -> bool {
match ACCENT_PRESETS.get(index) {
Some(hex) => self.set_accent(hex),
None => false,
}
}
}
/// 需要跨会话记忆的 UI 偏好。
///
/// 注意:`Eq` 不成立([`AppearancePrefs`] 带 `f32` 滑条值),用到的地方按 `PartialEq` 比。
#[derive(Debug, Clone, PartialEq)]
pub struct UiPrefs {
/// 左侧导航栏折叠成图标条
pub nav_collapsed: bool,
/// 右侧 AI 栏折叠成 icon 轨
pub ai_collapsed: bool,
/// 磁贴尺寸
pub tile_size: TileSize,
/// 实例页视图
pub instance_view: InstanceView,
/// 主题模式
pub theme: ThemeMode,
/// 外观(高级)四件(09 §101-104)
pub appearance: AppearancePrefs,
/// 下载页选中的分类
pub download_category: VersionCategory,
}
impl Default for UiPrefs {
fn default() -> Self {
Self {
nav_collapsed: false,
ai_collapsed: false,
// D16 默认中磁贴(4 列)
tile_size: TileSize::Medium,
instance_view: InstanceView::Tiles,
theme: ThemeMode::Auto,
appearance: AppearancePrefs::factory(),
download_category: VersionCategory::Release,
}
}
}
/// 持久化键名登记(core::setting schema 按此注册;改名等于迁移,慎动)。
pub mod keys {
/// 导航栏折叠
pub const NAV_COLLAPSED: &str = "ui.nav.collapsed";
/// AI 栏折叠
pub const AI_COLLAPSED: &str = "ui.ai.collapsed";
/// 磁贴尺寸
pub const TILE_SIZE: &str = "ui.instances.tile_size";
/// 实例页视图(磁贴/列表)
pub const INSTANCE_VIEW: &str = "ui.instances.view";
/// 主题三态(D17;与设置页「外观」分组同名,取值见 [`super::ThemeMode::as_str`])
pub const THEME_MODE: &str = "appearance.theme_mode";
/// 背景图开关(09 §101)
pub const BG_IMAGE_ENABLED: &str = "appearance.bg_image_enabled";
/// 背景图路径
pub const BG_IMAGE: &str = "appearance.bg_image";
/// 背景图填充模式
pub const BG_FILL: &str = "appearance.bg_fill";
/// 暗化层强度
pub const BG_DIM: &str = "appearance.bg_dim";
/// 面板半透明度(09 §102)
pub const PANEL_ALPHA: &str = "appearance.panel_alpha";
/// 玻璃拟态卡片(09 §103)
pub const GLASS: &str = "appearance.glass";
/// 自定义强调色(09 §104)
pub const ACCENT_COLOR: &str = "appearance.accent_color";
/// 下载页分类
pub const DOWNLOAD_CATEGORY: &str = "ui.download.category";
/// 本模块登记的全部键(自检/迁移用)。
pub const ALL: [&str; 13] = [
NAV_COLLAPSED,
AI_COLLAPSED,
TILE_SIZE,
INSTANCE_VIEW,
THEME_MODE,
BG_IMAGE_ENABLED,
BG_IMAGE,
BG_FILL,
BG_DIM,
PANEL_ALPHA,
GLASS,
ACCENT_COLOR,
DOWNLOAD_CATEGORY,
];
}
#[cfg(test)]
mod tests {
use super::{keys, InstanceView, ThemeMode, TileSize, UiPrefs};
#[test]
fn defaults_match_d16() {
let prefs = UiPrefs::default();
assert_eq!(prefs.tile_size, TileSize::Medium);
assert_eq!(prefs.tile_size.columns(), 4);
assert_eq!(prefs.instance_view, InstanceView::Tiles);
assert_eq!(prefs.theme, ThemeMode::Auto);
assert_eq!(prefs.theme.as_str(), "auto");
assert!(!prefs.nav_collapsed);
assert!(!prefs.ai_collapsed);
}
#[test]
fn tile_size_columns_follow_q24() {
assert_eq!(TileSize::Small.columns(), 6);
assert_eq!(TileSize::Medium.columns(), 4);
assert_eq!(TileSize::Large.columns(), 3);
}
#[test]
fn theme_mode_round_trips_through_key_values() {
for mode in [ThemeMode::Auto, ThemeMode::Light, ThemeMode::Dark] {
assert_eq!(ThemeMode::from_key_value(mode.as_str()), mode);
}
// 坏值兜底
assert_eq!(ThemeMode::from_key_value("solarized"), ThemeMode::Auto);
}
#[test]
fn pref_keys_are_unique() {
let mut keys = keys::ALL.to_vec();
let total = keys.len();
keys.sort_unstable();
keys.dedup();
assert_eq!(keys.len(), total);
}
}
+184
View File
@@ -0,0 +1,184 @@
//! 页面路由与 AI 助手栏形态(09 §1 / D16)。
//!
//! 栈语义抄 HMCL 的导航栈:**顶层页面互相替换**(实例/下载/日志/设置),
//! 子页面(实例详情、AI 独立页)压栈,`back()` 逐层回退。
//! 本模块刻意不依赖 Slint 类型,便于单元测试;UI 侧枚举映射在 main.rs 的转换层做。
use crate::dto::InstanceId;
/// 一级导航项(左侧导航栏高亮单位)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NavSection {
/// 实例
Instances,
/// 下载
Download,
/// 日志
Logs,
/// 设置
Settings,
}
/// 页面路由。
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
/// G1 实例页(主页)
Instances,
/// G2 下载页
Download,
/// G3 日志页
Logs,
/// G6 设置页
Settings,
/// 实例详情(G4):从磁贴点进来,返回时回到实例页
Detail(InstanceId),
/// AI 助手独立页(D16 双形态之一)
Agent,
}
impl Route {
/// 是否是一级导航页(互相替换,不进栈)。
pub fn is_top_level(&self) -> bool {
matches!(
self,
Self::Instances | Self::Download | Self::Logs | Self::Settings
)
}
/// 该路由高亮哪个导航项(None = 没有导航项高亮,如 AI 独立页)。
pub fn nav(&self) -> Option<NavSection> {
match self {
Self::Instances | Self::Detail(_) => Some(NavSection::Instances),
Self::Download => Some(NavSection::Download),
Self::Logs => Some(NavSection::Logs),
Self::Settings => Some(NavSection::Settings),
Self::Agent => None,
}
}
}
/// AI 栏形态:右侧栏 / 独立全宽页(两形态共享同一份会话状态)。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AiPanelMode {
/// 右侧常驻栏
Docked,
/// 拆出的独立全宽页
Page,
}
/// 导航栈。
#[derive(Debug, Clone)]
pub struct Router {
stack: Vec<Route>,
}
impl Default for Router {
fn default() -> Self {
Self::new()
}
}
impl Router {
/// 启动时停在实例页。
pub fn new() -> Self {
Self {
stack: vec![Route::Instances],
}
}
/// 当前页面。
pub fn route(&self) -> &Route {
// 栈不变量:构造后永远非空(navigate/back 都不允许清空)
self.stack.last().expect("router stack is never empty")
}
/// 栈深度(1 表示没有可回退的子页面)。
pub fn depth(&self) -> usize {
self.stack.len()
}
/// 是否能回退。
pub fn can_go_back(&self) -> bool {
self.stack.len() > 1
}
/// 跳转到某路由:一级页替换整栈,子页面压栈(重复目标不重复压栈)。
pub fn navigate(&mut self, route: Route) {
if route.is_top_level() {
self.stack.clear();
self.stack.push(route);
return;
}
if self.stack.last() == Some(&route) {
return;
}
self.stack.push(route);
}
/// 回退一层;已在根页面时返回 `false`。
pub fn back(&mut self) -> bool {
if self.stack.len() <= 1 {
return false;
}
self.stack.pop();
true
}
/// 当前 AI 栏形态(栈顶是 Agent 页即为独立页形态)。
pub fn ai_mode(&self) -> AiPanelMode {
if self.route() == &Route::Agent {
AiPanelMode::Page
} else {
AiPanelMode::Docked
}
}
}
#[cfg(test)]
mod tests {
use super::{AiPanelMode, NavSection, Route, Router};
#[test]
fn top_level_navigation_replaces_the_stack() {
let mut router = Router::new();
router.navigate(Route::Detail("a".into()));
assert_eq!(router.depth(), 2);
router.navigate(Route::Download);
assert_eq!(router.depth(), 1);
assert_eq!(router.route(), &Route::Download);
}
#[test]
fn detail_pushes_and_back_pops_to_instances() {
let mut router = Router::new();
router.navigate(Route::Detail("survival".into()));
assert!(router.can_go_back());
assert_eq!(router.route().nav(), Some(NavSection::Instances));
assert!(router.back());
assert_eq!(router.route(), &Route::Instances);
assert!(!router.back());
}
#[test]
fn agent_page_switches_ai_panel_mode() {
let mut router = Router::new();
assert_eq!(router.ai_mode(), AiPanelMode::Docked);
router.navigate(Route::Agent);
assert_eq!(router.ai_mode(), AiPanelMode::Page);
router.back();
assert_eq!(router.ai_mode(), AiPanelMode::Docked);
}
#[test]
fn navigating_to_the_same_sub_route_does_not_grow_the_stack() {
let mut router = Router::new();
router.navigate(Route::Agent);
router.navigate(Route::Agent);
assert_eq!(router.depth(), 2);
assert_eq!(router.route().nav(), None);
}
}
+294
View File
@@ -0,0 +1,294 @@
//! 设置持久化桥:把 UI 偏好落到 `core::setting` 的 schema 文件里,并支持**外部热改热切**。
//!
//! 三条纪律(`DevDocs/SubAgentsTalk/app-DTO通道约定.md` §6 / AGENTS §6):
//!
//! 1. **不另立配置文件**:读写的就是 `ull config set/get` 与 AI `set_config` 用的那一份
//! `<data root>/config/launcher.json`(`core::platform::data_dir` 解析数据根、`layout` 给路径);
//! 2. **不自己拼 JSON**:一律过 `core::setting::store::SettingStore`(schema 校验 + 原子写);
//! 3. **不 import 领域类型**:跨边界只看「键名 + 取值」,领域模型留在 core。
//!
//! 热切:文件 `mtime` 变了就整份重读(AI / CLI 改完下一拍即生效),见 [`SettingsBridge::reload_if_changed`]。
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use unlucky_core::platform::data_dir::{DataDirRequest, DataMode, Resolver};
use unlucky_core::platform::layout::LauncherLayout;
use unlucky_core::platform::paths::Platform;
use unlucky_core::setting::appearance::Appearance;
use unlucky_core::setting::keys::launcher_schema;
use unlucky_core::setting::store::SettingStore;
use crate::prefs::{AppearancePrefs, ThemeMode};
/// 数据根配置键(决定 `launcher.json` 落在哪个数据目录;与 CLI 的 `DATA_ROOT_KEYS` 同源同义)。
const DATA_ROOT_KEYS: [&str; 4] = [
"core.data_mode",
"core.data_custom_root",
"core.launcher_home",
"core.game_home",
];
/// 设置文件桥(一个进程一份)。
#[derive(Debug)]
pub struct SettingsBridge {
/// `config/launcher.json`;`None` = 数据根解析不出来(内存态运行,不落盘)
path: Option<PathBuf>,
store: Option<SettingStore>,
/// 上次读/写之后的文件 `mtime`(热切探测用)
last_mtime: Option<SystemTime>,
}
impl SettingsBridge {
/// 按三模式数据根打开真实配置文件(启动时调用一次)。
#[must_use]
pub fn open() -> Self {
match resolve_config_path() {
Some(path) => Self::with_path(path),
None => Self::memory_only(),
}
}
/// 指定路径打开(测试与特殊数据根用)。
#[must_use]
pub fn with_path(path: impl Into<PathBuf>) -> Self {
let path = path.into();
let store = SettingStore::load(&path, launcher_schema());
let last_mtime = mtime(&path);
Self {
path: Some(path),
store: Some(store),
last_mtime,
}
}
/// 不落盘(数据根解析失败 / 单测)。
#[must_use]
pub fn memory_only() -> Self {
Self {
path: None,
store: None,
last_mtime: None,
}
}
/// 配置文件路径(诊断/日志用)。
#[must_use]
pub fn path(&self) -> Option<&Path> {
self.path.as_deref()
}
/// 当前生效的外观配置与主题模式。
#[must_use]
pub fn load(&self) -> (AppearancePrefs, ThemeMode) {
let Some(store) = &self.store else {
return (AppearancePrefs::factory(), ThemeMode::Auto);
};
let appearance = Appearance::from_store(store);
let theme = ThemeMode::from_key_value(&appearance.theme_mode);
(
AppearancePrefs {
bg_image_enabled: appearance.bg_image_enabled,
bg_image: appearance.bg_image,
bg_fill: appearance.bg_fill,
bg_dim: appearance.bg_dim as f32,
panel_alpha: appearance.panel_alpha as f32,
glass: appearance.glass,
accent_color: appearance.accent_color,
},
theme,
)
}
/// 落盘(只写出现过的键;失败静默——配置写不进去不该把 UI 卡住,诊断走日志)。
pub fn persist(&mut self, appearance: &AppearancePrefs, theme: ThemeMode) {
let Some(store) = self.store.as_mut() else {
return;
};
let mut snapshot = Appearance::from_store(store);
snapshot.theme_mode = theme.as_str().to_owned();
snapshot.bg_image_enabled = appearance.bg_image_enabled;
snapshot.bg_image = appearance.bg_image.clone();
snapshot.bg_fill = appearance.bg_fill;
snapshot.bg_dim = f64::from(appearance.bg_dim);
snapshot.panel_alpha = f64::from(appearance.panel_alpha);
snapshot.glass = appearance.glass;
snapshot.accent_color = appearance.accent_color.clone();
if snapshot.write(store).is_err() {
return;
}
let _ = store.save();
if let Some(path) = self.path() {
self.last_mtime = mtime(path);
}
}
/// 文件被外部(AI / `ull config set`)改过就重读;返回新的生效值。
///
/// `mtime` 采样不到(某些文件系统精度/权限)时返回 `None`,退化为「只在启动时读一次」。
pub fn reload_if_changed(&mut self) -> Option<(AppearancePrefs, ThemeMode)> {
let path = self.path.clone()?;
let current = mtime(&path);
if current.is_none() || current == self.last_mtime {
return None;
}
self.last_mtime = current;
let store = self.store.as_mut()?;
store.reload();
Some(self.load())
}
}
/// 数据根解析 → `config/launcher.json`。
///
/// 与 CLI 同一套语义:先读便携目录那份 `launcher.json` 的 `core.*`(数据根决定键),
/// 再交 `Resolver` 解析(含 `redirect.json` 跟随)。任何一步失败都退回内存态。
fn resolve_config_path() -> Option<PathBuf> {
let exe_dir = std::env::current_exe()
.ok()
.and_then(|path| path.parent().map(Path::to_path_buf));
let exe_dir = exe_dir?;
let request = request_from_portable(&exe_dir);
let resolver = Resolver::new(Platform::current(), Some(exe_dir.clone()));
match resolver.resolve_default(&request) {
Ok(resolved) => Some(resolved.layout().launcher_config()),
// 连 exe 目录都解析不了(极端情况):仍旧用便携落点,至少设置能存下来
Err(_) => Some(LauncherLayout::new(exe_dir.join(".ULL")).launcher_config()),
}
}
/// 便携目录那份 `launcher.json` → 三模式请求(只读 `core.*` 四个键)。
fn request_from_portable(exe_dir: &Path) -> DataDirRequest {
let mut request = DataDirRequest::default();
let path = portable_config_path(exe_dir);
if !path.is_file() {
return request;
}
let store = SettingStore::load(&path, launcher_schema());
let text = |key: &str| store.doc().effective_str(key).map(str::to_string);
if let Some(mode) = text(DATA_ROOT_KEYS[0]).as_deref().and_then(DataMode::parse) {
request.mode = mode;
}
if let Some(root) = text(DATA_ROOT_KEYS[1]) {
request.custom_root = Some(PathBuf::from(root));
}
if let Some(home) = text(DATA_ROOT_KEYS[2]) {
request.launcher_home = Some(PathBuf::from(home));
}
if let Some(home) = text(DATA_ROOT_KEYS[3]) {
request.game_home = Some(PathBuf::from(home));
}
request
}
/// `<exe 目录>/.ULL/config/launcher.json`。
fn portable_config_path(exe_dir: &Path) -> PathBuf {
LauncherLayout::new(exe_dir.join(".ULL")).launcher_config()
}
fn mtime(path: &Path) -> Option<SystemTime> {
std::fs::metadata(path).ok()?.modified().ok()
}
#[cfg(test)]
mod tests {
use super::*;
use unlucky_core::setting::appearance::BgFill;
fn temp_config(label: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!(
"ull-bridge-{label}-{}-{}",
std::process::id(),
line!()
));
std::fs::create_dir_all(dir.join("config")).expect("临时目录");
let path = dir.join("config/launcher.json");
let _ = std::fs::remove_file(&path);
path
}
#[test]
fn factory_defaults_when_file_missing() {
let path = temp_config("factory");
let bridge = SettingsBridge::with_path(&path);
let (appearance, theme) = bridge.load();
assert_eq!(appearance, AppearancePrefs::factory());
assert_eq!(theme, ThemeMode::Auto);
assert!(!path.exists(), "只读不写:缺文件不该被创建");
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
}
#[test]
fn persist_then_reload_round_trips() {
let path = temp_config("roundtrip");
let mut bridge = SettingsBridge::with_path(&path);
let mut appearance = AppearancePrefs::factory();
appearance.bg_image_enabled = true;
appearance.bg_image = "D:/wall/p.png".to_owned();
appearance.bg_fill = BgFill::Contain;
appearance.bg_dim = 0.5;
appearance.panel_alpha = 0.8;
appearance.glass = true;
assert!(appearance.set_accent("#0f6cbd"));
bridge.persist(&appearance, ThemeMode::Dark);
let reloaded = SettingsBridge::with_path(&path);
let (value, theme) = reloaded.load();
assert_eq!(value, appearance);
assert_eq!(theme, ThemeMode::Dark);
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
}
#[test]
fn external_edit_is_picked_up_by_reload() {
let path = temp_config("hotreload");
let mut bridge = SettingsBridge::with_path(&path);
// 先落一份(建立 mtime 基线)
bridge.persist(&AppearancePrefs::factory(), ThemeMode::Light);
assert!(bridge.reload_if_changed().is_none(), "自己写完不该报告变更");
// 模拟外部写入(AI / `ull config set`):改主题 + 打开背景图
let mut external = SettingsBridge::with_path(&path);
let mut appearance = AppearancePrefs::factory();
appearance.bg_image_enabled = true;
appearance.bg_image = "D:/wall/x.png".to_owned();
external.persist(&appearance, ThemeMode::Dark);
// mtime 精度:有的文件系统 1s 粒度,这里显式等到时间戳变化
for _ in 0..50 {
if let Some((value, theme)) = bridge.reload_if_changed() {
assert_eq!(theme, ThemeMode::Dark);
assert!(value.bg_image_enabled);
assert_eq!(value.bg_image, "D:/wall/x.png");
std::fs::remove_dir_all(path.parent().unwrap().parent().unwrap()).ok();
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
}
panic!("外部修改没有被 mtime 热切捕获");
}
#[test]
fn accent_preset_and_validation() {
let mut appearance = AppearancePrefs::factory();
assert_eq!(appearance.accent_color, "");
assert!(appearance.set_accent_preset(1));
assert_eq!(appearance.accent_color, "#0F6CBD");
assert!(!appearance.set_accent("not-a-color"), "非法输入不改现状");
assert_eq!(appearance.accent_color, "#0F6CBD");
assert!(appearance.set_accent(""), "空串恢复出厂");
assert_eq!(appearance.accent_color, "");
assert!(!appearance.set_accent_preset(99));
}
#[test]
fn bg_active_needs_both_switch_and_path() {
let mut appearance = AppearancePrefs::factory();
appearance.bg_image = "D:/wall/p.png".to_owned();
assert!(!appearance.bg_active(), "开关没开不算生效");
appearance.bg_image_enabled = true;
assert!(appearance.bg_active());
appearance.bg_image.clear();
assert!(!appearance.bg_active(), "路径空也不算生效");
}
}
+304
View File
@@ -0,0 +1,304 @@
//! UI 状态与 reducer:Slint 只负责渲染,所有状态变更都汇聚到 [`AppState::apply`]。
//!
//! 数据流向:mock/host 后端 → [`crate::dto::AppEvent`] 队列 → `apply` → 状态字段 → Slint 属性。
//! 偏好项在 [`crate::prefs`] 里登记了持久化键名,core::setting 的 schema 落地后按这些键读写。
use crate::dialogs::DialogQueue;
use crate::dto::{
AgentEvent, AppEvent, ChatMessage, ChatRole, CoreEvent, DiagnosisReport, InstanceRuntime,
InstanceSummary, LogLine, LogSession, Progress, ToolCallView, VersionSummary,
};
use crate::prefs::UiPrefs;
use crate::router::{AiPanelMode, Route, Router};
use crate::toast::ToastCenter;
/// AI 会话状态(右侧栏与独立页共享同一份,切换不丢)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AiSession {
/// 会话消息(user / assistant / tool / system)
pub messages: Vec<ChatMessage>,
/// 是否有流式消息在跑
pub streaming: bool,
/// YOLO 开关(跳过确认,审计照记)
pub yolo: bool,
/// 输入框草稿(切形态不丢)
pub draft: String,
/// 端点标签(显示在栏顶)
pub endpoint_label: String,
}
impl Default for AiSession {
fn default() -> Self {
Self::new()
}
}
impl AiSession {
/// 默认端点标签(P0 是本地 llama.cpp;P1 由设置页决定)。
pub fn new() -> Self {
Self {
messages: Vec::new(),
streaming: false,
yolo: false,
draft: String::new(),
endpoint_label: "llama.cpp · 本地".to_string(),
}
}
/// 流式收敛:清掉全部流式标记。
pub fn finish_stream(&mut self) {
self.streaming = false;
for message in &mut self.messages {
message.streaming = false;
}
}
}
/// 磁贴网格单元:位置由 [`grid_positions`] 算好,Slint 只消费 row/col。
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TileCell<'a> {
/// 实例数据
pub instance: &'a InstanceSummary,
/// 网格行号(0 起)
pub row: usize,
/// 网格列号(0 起)
pub col: usize,
}
/// 纯函数:把 n 个磁贴摊到 `columns` 列的网格上,返回 `(row, col)`。
///
/// 特意放在 Rust 侧:Slint DSL 里做整数除法会引入隐式浮点,且这段逻辑可以单测。
pub fn grid_positions(count: usize, columns: usize) -> Vec<(usize, usize)> {
let columns = columns.max(1);
(0..count)
.map(|index| (index / columns, index % columns))
.collect()
}
/// 应用全局状态。
#[derive(Debug)]
pub struct AppState {
/// UI 偏好(记忆项)
pub prefs: UiPrefs,
/// 导航栈
pub router: Router,
/// 实例列表快照
pub instances: Vec<InstanceSummary>,
/// 当前分类的版本列表
pub versions: Vec<VersionSummary>,
/// 日志会话列表
pub log_sessions: Vec<LogSession>,
/// 当前会话日志行
pub log_lines: Vec<LogLine>,
/// 最近一次诊断结论
pub diagnosis: Option<DiagnosisReport>,
/// 选中的日志会话
pub selected_session: Option<String>,
/// AI 会话状态
pub ai: AiSession,
/// 对话框队列(一次一条)
pub dialogs: DialogQueue,
/// Toast 中心
pub toasts: ToastCenter,
/// 实例页搜索词
pub instance_query: String,
/// 下载页「仅已装」过滤
pub installed_only: bool,
/// 下载页版本号筛选词
pub download_query: String,
}
impl Default for AppState {
fn default() -> Self {
Self::new()
}
}
impl AppState {
/// 空状态(数据由后端事件填充,P0 是 mock)。
pub fn new() -> Self {
Self {
prefs: UiPrefs::default(),
router: Router::new(),
instances: Vec::new(),
versions: Vec::new(),
log_sessions: Vec::new(),
log_lines: Vec::new(),
diagnosis: None,
selected_session: None,
ai: AiSession::new(),
dialogs: DialogQueue::new(),
toasts: ToastCenter::new(),
instance_query: String::new(),
installed_only: false,
download_query: String::new(),
}
}
/// 当前页面。
pub fn route(&self) -> &Route {
self.router.route()
}
/// 跳转(一级页替换、子页面压栈;去 AI 独立页时自动展开 AI 栏偏好)。
pub fn navigate(&mut self, route: Route) {
if route == Route::Agent {
self.prefs.ai_collapsed = false;
}
self.router.navigate(route);
}
/// 回退一层。
pub fn back(&mut self) -> bool {
self.router.back()
}
/// AI 栏当前形态(跟着路由走)。
pub fn ai_mode(&self) -> AiPanelMode {
self.router.ai_mode()
}
/// 应用一条事件(唯一状态变更入口)。
pub fn apply(&mut self, event: AppEvent) {
match event {
AppEvent::Core(core) => self.apply_core(core),
AppEvent::Agent(agent) => self.apply_agent(agent),
AppEvent::DialogRequested(request) => {
self.dialogs.push_request(request);
}
AppEvent::DialogClosed(id) => {
self.dialogs.close(id);
}
AppEvent::Toast(toast) => {
self.toasts.push_request(toast);
}
}
}
/// core 事件。
pub fn apply_core(&mut self, event: CoreEvent) {
match event {
CoreEvent::InstancesChanged(instances) => self.instances = instances,
CoreEvent::InstanceRuntimeChanged { id, runtime } => {
if let Some(instance) = self.instances.iter_mut().find(|item| item.id == id) {
instance.runtime = runtime;
}
}
CoreEvent::VersionListChanged(versions) => self.versions = versions,
CoreEvent::LogSessionsChanged(sessions) => self.log_sessions = sessions,
CoreEvent::LogLinesChanged(lines) => self.log_lines = lines,
CoreEvent::DiagnosisReady(report) => self.diagnosis = Some(report),
}
}
/// agent 事件。
pub fn apply_agent(&mut self, event: AgentEvent) {
match event {
AgentEvent::MessageAppended(message) => {
// 流式占位到达即视为「一轮回复进行中」:UI 的发送键/停止键据此切换
if message.streaming {
self.ai.streaming = true;
}
self.ai.messages.push(message);
}
AgentEvent::MessageDelta { index, delta } => {
if let Some(message) = self.ai.messages.get_mut(index) {
message.text.push_str(&delta);
}
}
AgentEvent::MessageFinished { index } => {
if let Some(message) = self.ai.messages.get_mut(index) {
message.streaming = false;
}
self.ai.streaming = false;
}
AgentEvent::ToolCallStarted { name, summary } => {
self.ai.streaming = true;
self.ai.messages.push(ChatMessage {
role: ChatRole::Tool,
text: summary.clone(),
tool: Some(ToolCallView {
name,
ok: false,
summary,
}),
streaming: true,
});
}
AgentEvent::ToolCallFinished { name, ok, summary } => {
let target =
self.ai.messages.iter_mut().rev().find(|message| {
message.tool.as_ref().is_some_and(|tool| tool.name == name)
});
if let Some(message) = target {
message.text.clone_from(&summary);
message.streaming = false;
if let Some(tool) = &mut message.tool {
tool.ok = ok;
tool.summary = summary;
}
}
}
}
}
/// 按搜索词过滤后的磁贴网格(顺序稳定 = 实例列表顺序)。
pub fn tiles(&self) -> Vec<TileCell<'_>> {
let query = self.instance_query.trim().to_lowercase();
let filtered: Vec<&InstanceSummary> = self
.instances
.iter()
.filter(|instance| query.is_empty() || instance.name.to_lowercase().contains(&query))
.collect();
let positions = grid_positions(filtered.len(), self.prefs.tile_size.columns());
filtered
.into_iter()
.zip(positions)
.map(|(instance, (row, col))| TileCell { instance, row, col })
.collect()
}
/// 运行中的实例(实例页顶部迷你状态条)。
pub fn running(&self) -> Vec<&InstanceSummary> {
self.instances
.iter()
.filter(|instance| {
matches!(
instance.runtime,
InstanceRuntime::Running { .. } | InstanceRuntime::Busy { .. }
)
})
.collect()
}
/// 覆盖某实例的启动进度(mock / 真实后端共用同一入口)。
pub fn set_progress(&mut self, id: &str, progress: Progress) {
if let Some(instance) = self.instances.iter_mut().find(|item| item.id == id) {
if let InstanceRuntime::Busy {
progress: current, ..
} = &mut instance.runtime
{
*current = progress;
}
}
}
/// 折叠/展开导航栏。
pub fn toggle_nav(&mut self) {
self.prefs.nav_collapsed = !self.prefs.nav_collapsed;
}
/// 折叠/展开 AI 栏;若正处在独立页形态则先收回侧栏。
pub fn toggle_ai(&mut self) {
if self.route() == &Route::Agent {
self.router.back();
self.prefs.ai_collapsed = false;
return;
}
self.prefs.ai_collapsed = !self.prefs.ai_collapsed;
}
}
#[cfg(test)]
#[path = "state_tests.rs"]
mod tests;
+262
View File
@@ -0,0 +1,262 @@
//! state.rs 的单元测试(拆文件保持单文件 ≤400 行)。
use super::{grid_positions, AiSession, AppState};
use crate::dialogs::{DialogKind, DialogRequest, DialogSource};
use crate::dto::{
AgentEvent, AppEvent, ChatMessage, ChatRole, CoreEvent, Diagnosis, DiagnosisReport,
InstanceRuntime, InstanceSummary, LoaderInfo, LoaderKind,
};
use crate::prefs::TileSize;
use crate::router::Route;
use crate::toast::Toast;
use crate::toast::ToastKind;
fn instance(id: &str, name: &str) -> InstanceSummary {
InstanceSummary {
id: id.to_string(),
name: name.to_string(),
mc_version: "1.20.4".to_string(),
loader: LoaderInfo {
kind: LoaderKind::Fabric,
version: "0.16.5".to_string(),
},
last_played: None,
runtime: InstanceRuntime::Idle,
icon: None,
}
}
#[test]
fn grid_positions_wrap_by_column_count() {
assert_eq!(grid_positions(0, 4), vec![]);
assert_eq!(grid_positions(3, 2), vec![(0, 0), (0, 1), (1, 0)]);
// columns == 0 时按 1 列兜底,不允许除零
assert_eq!(grid_positions(2, 0), vec![(0, 0), (1, 0)]);
}
#[test]
fn tiles_follow_tile_size_and_search() {
let mut state = AppState::new();
state.instances = vec![
instance("a", "生存"),
instance("b", "创造"),
instance("c", "Demo"),
];
assert_eq!(state.tiles().len(), 3);
assert_eq!((state.tiles()[2].row, state.tiles()[2].col), (0, 2));
state.prefs.tile_size = TileSize::Large;
assert_eq!((state.tiles()[2].row, state.tiles()[2].col), (0, 2));
state.prefs.tile_size = TileSize::Small;
assert_eq!(state.tiles().len(), 3);
state.instance_query = "demo".to_string();
let tiles = state.tiles();
assert_eq!(tiles.len(), 1);
assert_eq!(tiles[0].instance.id, "c");
assert_eq!((tiles[0].row, tiles[0].col), (0, 0));
}
#[test]
fn tiles_reflow_when_tile_size_shrinks() {
let mut state = AppState::new();
state.instances = (0..8)
.map(|i| instance(&format!("i{i}"), &format!("实例{i}")))
.collect();
state.prefs.tile_size = TileSize::Medium;
let medium_rows = state.tiles().iter().map(|cell| cell.row).max();
state.prefs.tile_size = TileSize::Small;
let small_rows = state.tiles().iter().map(|cell| cell.row).max();
assert_eq!(medium_rows, Some(1)); // 8 / 4 列 = 2 行
assert_eq!(small_rows, Some(1)); // 8 / 6 列 = 2 行
}
#[test]
fn runtime_events_update_the_matching_instance() {
let mut state = AppState::new();
state.instances = vec![instance("a", "生存"), instance("b", "创造")];
state.apply(AppEvent::Core(CoreEvent::InstanceRuntimeChanged {
id: "b".to_string(),
runtime: InstanceRuntime::Running { pid: 42 },
}));
assert_eq!(state.instances[0].runtime, InstanceRuntime::Idle);
assert_eq!(
state.instances[1].runtime,
InstanceRuntime::Running { pid: 42 }
);
assert_eq!(state.running().len(), 1);
assert_eq!(state.running()[0].id, "b");
}
#[test]
fn progress_events_only_touch_busy_instances() {
let mut state = AppState::new();
state.instances = vec![instance("a", "生存")];
state.instances[0].runtime = InstanceRuntime::Busy {
stage: crate::dto::LaunchStage::Download,
progress: crate::dto::Progress {
done: 0,
total: 100,
},
};
state.set_progress(
"a",
crate::dto::Progress {
done: 50,
total: 100,
},
);
match &state.instances[0].runtime {
InstanceRuntime::Busy { progress, .. } => {
assert!((progress.ratio() - 0.5).abs() < f32::EPSILON);
}
other => panic!("unexpected runtime: {other:?}"),
}
// 不存在的 id / 非 Busy 状态不改变任何东西
state.set_progress("missing", crate::dto::Progress { done: 1, total: 1 });
assert_eq!(state.instances.len(), 1);
}
#[test]
fn ai_stream_deltas_accumulate_and_finish() {
let mut state = AppState::new();
state.apply(AppEvent::Agent(AgentEvent::MessageAppended(
ChatMessage::user("怎么装 1.20.4"),
)));
state.apply(AppEvent::Agent(AgentEvent::MessageAppended(
ChatMessage::assistant_stream(),
)));
assert_eq!(state.ai.messages.len(), 2);
assert!(state.ai.streaming);
assert_eq!(state.ai.messages[1].role, ChatRole::Assistant);
state.apply(AppEvent::Agent(AgentEvent::MessageDelta {
index: 1,
delta: "先".to_string(),
}));
state.apply(AppEvent::Agent(AgentEvent::MessageDelta {
index: 1,
delta: "下载".to_string(),
}));
state.apply(AppEvent::Agent(AgentEvent::MessageFinished { index: 1 }));
assert_eq!(state.ai.messages[1].text, "先下载");
assert!(!state.ai.messages[1].streaming);
assert!(!state.ai.streaming);
}
#[test]
fn ai_session_finish_stream_clears_every_flag() {
let mut session = AiSession::new();
session.messages.push(ChatMessage::user("hi"));
session.messages.push(ChatMessage::assistant_stream());
session.finish_stream();
assert!(session.messages.iter().all(|message| !message.streaming));
assert!(!session.streaming);
}
#[test]
fn tool_call_finish_updates_the_last_matching_message() {
let mut state = AppState::new();
state.apply(AppEvent::Agent(AgentEvent::ToolCallStarted {
name: "get_config".to_string(),
summary: "读取设置".to_string(),
}));
state.apply(AppEvent::Agent(AgentEvent::ToolCallFinished {
name: "get_config".to_string(),
ok: true,
summary: "读取到 3 项".to_string(),
}));
let tool = &state.ai.messages[0];
assert_eq!(tool.role, ChatRole::Tool);
assert_eq!(tool.text, "读取到 3 项");
assert!(!tool.streaming);
assert!(tool.tool.as_ref().is_some_and(|call| call.ok));
}
#[test]
fn dialogs_and_toasts_flow_through_apply() {
let mut state = AppState::new();
state.apply(AppEvent::DialogRequested(DialogRequest {
id: 42,
source: DialogSource::UserAction,
title: "AI 想修改内存".to_string(),
body: "改为 8G".to_string(),
kind: DialogKind::Confirm {
primary: "允许".to_string(),
secondary: "拒绝".to_string(),
},
}));
state.apply(AppEvent::Toast(Toast {
id: 0,
kind: ToastKind::Success,
text: "下载完成".to_string(),
remaining_ms: 0,
}));
assert_eq!(state.dialogs.pending_len(), 0);
// id 归生产者:队列原样保留,DialogClosed(42) 才能命中同一条
assert_eq!(state.dialogs.current().map(|dialog| dialog.id), Some(42));
assert_eq!(state.toasts.len(), 1);
state.apply(AppEvent::DialogClosed(42));
assert!(state.dialogs.is_empty());
}
#[test]
fn navigate_to_agent_page_expands_the_ai_panel() {
let mut state = AppState::new();
state.prefs.ai_collapsed = true;
state.navigate(Route::Agent);
assert_eq!(state.route(), &Route::Agent);
assert_eq!(state.ai_mode(), crate::router::AiPanelMode::Page);
assert!(!state.prefs.ai_collapsed);
}
#[test]
fn toggling_ai_from_the_page_form_docks_it_again() {
let mut state = AppState::new();
state.navigate(Route::Agent);
state.toggle_ai();
assert_eq!(state.route(), &Route::Instances);
assert_eq!(state.ai_mode(), crate::router::AiPanelMode::Docked);
assert!(!state.prefs.ai_collapsed);
state.toggle_ai();
assert!(state.prefs.ai_collapsed);
}
#[test]
fn toggle_nav_flips_the_pref() {
let mut state = AppState::new();
state.toggle_nav();
assert!(state.prefs.nav_collapsed);
state.toggle_nav();
assert!(!state.prefs.nav_collapsed);
}
#[test]
fn diagnosis_report_lands_on_state() {
let mut state = AppState::new();
state.apply(AppEvent::Core(CoreEvent::DiagnosisReady(DiagnosisReport {
session: "s1".to_string(),
diagnosis: Diagnosis {
rule: "gpu.driver_old".to_string(),
title: "显卡驱动过旧".to_string(),
confidence: 92,
hint: "升级驱动".to_string(),
fix: Some("open_driver_page".to_string()),
},
})));
assert!(state.diagnosis.is_some());
}
+152
View File
@@ -0,0 +1,152 @@
//! 主题与外观的运行期逻辑(从 `ui_bind.rs` 拆出,守住单文件 ≤400 行)。
//!
//! 全是 `impl Inner` 的方法:配置热切轮询、系统主题对齐、外观令牌下发、背景图/模糊层重建。
//! 拆出来的边界是「时间驱动的状态维护」——`ui_bind.rs` 只留「建窗口 + 每拍驱动 + 灌属性」。
use slint::ComponentHandle;
use crate::bg_image::{self, BackgroundLayers};
use crate::conv;
use crate::prefs::{AppearancePrefs, BgFill, ThemeMode};
use crate::toast::ToastKind;
use crate::ui_bind::{
BackgroundKey, Inner, CONFIG_POLL_TICKS, SYSTEM_THEME_POLL_TICKS, TILE_REGENERATE_STEP,
};
impl Inner {
pub(crate) fn poll_settings(&self) {
if !self.ticks.get().is_multiple_of(CONFIG_POLL_TICKS) {
return;
}
let Some((appearance, theme)) = self.bridge.borrow_mut().reload_if_changed() else {
return;
};
{
let mut state = self.state.borrow_mut();
state.prefs.appearance = appearance;
state.prefs.theme = theme;
}
self.apply_theme();
self.apply_appearance();
}
/// 系统主题对齐:启动时先读一次真实系统主题(避免 auto 首帧按浅色画再翻黑);
/// 之后仅在「auto + 后端不认识系统主题」(`Theme.system-theme-known == false`)时兜底轮询。
pub(crate) fn poll_system_theme(&self) {
let auto = matches!(self.state.borrow().prefs.theme, ThemeMode::Auto);
let backend_known = self.ui.get_system_theme_known();
let due = !self.system_theme_probed.get()
|| (auto && !backend_known && self.ticks.get().is_multiple_of(SYSTEM_THEME_POLL_TICKS));
if !due {
return;
}
self.system_theme_probed.set(true);
let value = match unlucky_core::platform::theme_probe::probe() {
unlucky_core::platform::theme_probe::SystemTheme::Light => 1,
unlucky_core::platform::theme_probe::SystemTheme::Dark => 2,
unlucky_core::platform::theme_probe::SystemTheme::Unknown => 0,
};
if self.ui.get_system_theme() != value {
self.ui.set_system_theme(value);
}
}
/// 启动时的系统主题对齐(首帧前调用一次)。
pub(crate) fn align_system_theme(&self) {
self.poll_system_theme();
}
/// 主题三态 → 根组件属性;`ui/main.slint` 里的 changed 处理器再赋给 `Theme` 全局
/// (auto 时 Theme 内部读系统的 `Palette.color-scheme` 与本进程探测到的系统主题)。
pub(crate) fn apply_theme(&self) {
let mode = self.state.borrow().prefs.theme;
self.ui.set_theme_mode(conv::theme_mode(mode));
}
/// 外观(高级)四件 → 根组件属性(进而写进 `Theme` 全局)。
///
/// 背景图只在「开关打开 + 路径非空 + 换了输入」时才重新解码/生成模糊层。
pub(crate) fn apply_appearance(&self) {
let appearance = self.state.borrow().prefs.appearance.clone();
self.ui.set_bg_fill(conv::bg_fill(appearance.bg_fill));
self.ui.set_bg_dim(appearance.bg_dim.clamp(0.0, 0.9));
self.ui
.set_panel_alpha(appearance.panel_alpha.clamp(0.4, 1.0));
self.ui.set_glass(appearance.glass);
self.ui
.set_accent_color(conv::accent_color(&appearance.accent_color));
self.ui
.set_accent_hex(appearance.accent_color.clone().into());
self.refresh_background(&appearance);
}
/// 按需重建背景图 + 模糊层。
fn refresh_background(&self, appearance: &AppearancePrefs) {
if !appearance.bg_active() {
let had = self.background_key.borrow_mut().take().is_some();
if had {
self.background.replace(BackgroundLayers::default());
self.ui.set_background_image(slint::Image::default());
self.ui.set_background_blur(slint::Image::default());
}
return;
}
let key = BackgroundKey {
path: appearance.bg_image.clone(),
fill: appearance.bg_fill,
viewport: self.tile_viewport(appearance.bg_fill),
};
if self.background_key.borrow().as_ref() == Some(&key) {
return;
}
self.background_key.replace(Some(key.clone()));
// 模糊层按窗口物理尺寸放大(软件渲染器不做图片缩放插值,见 bg_image::prepare);
// tile 之外的模式窗口缩放不重建画布,模糊层被拉伸也无感。
let real_viewport = self.window_physical_size();
match bg_image::prepare(&key.path, key.fill, real_viewport) {
Some(layers) => {
self.ui.set_background_image(layers.image.clone());
self.ui.set_background_blur(layers.blur.clone());
self.background.replace(layers);
}
None => {
// 载入失败(路径不存在 / 不是 PNG):清空图层并提示一次,别留上一张图的残影
self.background.replace(BackgroundLayers::default());
self.ui.set_background_image(slint::Image::default());
self.ui.set_background_blur(slint::Image::default());
self.state.borrow_mut().toasts.push(
ToastKind::Warn,
"背景图载入失败(当前只支持 PNG,且路径需存在)",
);
}
}
}
/// tile 画布的窗口尺寸(量化到 [`TILE_REGENERATE_STEP`],避免拖动窗口时反复重算)。
fn tile_viewport(&self, fill: BgFill) -> (u32, u32) {
if fill != BgFill::Tile {
return (0, 0);
}
let (width, height) = self.window_physical_size();
(
width / TILE_REGENERATE_STEP * TILE_REGENERATE_STEP,
height / TILE_REGENERATE_STEP * TILE_REGENERATE_STEP,
)
}
/// 窗口物理像素尺寸(取不到时 (0, 0),tile 退化为单块)。
fn window_physical_size(&self) -> (u32, u32) {
let size = self.ui.window().size();
(size.width, size.height)
}
/// 落盘当前偏好(主题 + 外观四件)。
pub(crate) fn persist_settings(&self) {
let state = self.state.borrow();
self.bridge
.borrow_mut()
.persist(&state.prefs.appearance, state.prefs.theme);
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Toast 中心:右下角非阻塞提示(下载完成 / 复制成功 / 后台任务结论)。
//!
//! 与模态对话框队列([`crate::dialogs`])分开:Toast 不阻塞、不排序、可叠加,
//! 只做「先进先出 + 上限裁剪 + TTL 到期」。UI 侧由 Rust 定时器每帧调用 [`ToastCenter::expire`]。
/// Toast 标识。
pub type ToastId = u64;
/// Toast 语义色。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToastKind {
/// 一般信息
Info,
/// 成功
Success,
/// 警告
Warn,
/// 错误
Error,
}
/// 一条 Toast;`remaining_ms` 由 [`ToastCenter::expire`] 递减。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Toast {
/// 队列内唯一 id(由 [`ToastCenter::push_request`] 重新编号)
pub id: ToastId,
/// 语义色
pub kind: ToastKind,
/// 提示文案
pub text: String,
/// 剩余存活毫秒(0 = 用默认 TTL,入队时补)
pub remaining_ms: u64,
}
/// Toast 中心:先进先出,超出上限丢最旧的。
#[derive(Debug)]
pub struct ToastCenter {
items: Vec<Toast>,
next_id: ToastId,
ttl_ms: u64,
}
impl Default for ToastCenter {
fn default() -> Self {
Self::new()
}
}
impl ToastCenter {
/// 默认 4s 后自动消失。
pub fn new() -> Self {
Self {
items: Vec::new(),
next_id: 0,
ttl_ms: 4_000,
}
}
/// 同时最多显示的条数。
pub const MAX_VISIBLE: usize = 4;
/// 入队一条 Toast。
pub fn push(&mut self, kind: ToastKind, text: impl Into<String>) -> ToastId {
self.push_request(Toast {
id: 0,
kind,
text: text.into(),
remaining_ms: 0,
})
}
/// 入队一条已组装好的 Toast(事件通道用);id 重新编号,`remaining_ms == 0` 视为用默认 TTL。
pub fn push_request(&mut self, mut toast: Toast) -> ToastId {
self.next_id += 1;
toast.id = self.next_id;
if toast.remaining_ms == 0 {
toast.remaining_ms = self.ttl_ms;
}
let id = toast.id;
self.items.push(toast);
while self.items.len() > Self::MAX_VISIBLE {
self.items.remove(0);
}
id
}
/// 当前显示列表(UI 模型来源)。
pub fn items(&self) -> &[Toast] {
&self.items
}
/// 手动关闭(点了关闭按钮)。
pub fn dismiss(&mut self, id: ToastId) -> bool {
if let Some(at) = self.items.iter().position(|toast| toast.id == id) {
self.items.remove(at);
true
} else {
false
}
}
/// 时间推进:移除到期 Toast。
pub fn expire(&mut self, elapsed_ms: u64) {
for toast in &mut self.items {
toast.remaining_ms = toast.remaining_ms.saturating_sub(elapsed_ms);
}
self.items.retain(|toast| toast.remaining_ms > 0);
}
/// 当前条数。
pub fn len(&self) -> usize {
self.items.len()
}
/// 是否没有 Toast。
pub fn is_empty(&self) -> bool {
self.items.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::{ToastCenter, ToastKind};
#[test]
fn toasts_expire_and_cap_the_stack() {
let mut center = ToastCenter::new();
center.push(ToastKind::Info, "a");
center.push(ToastKind::Info, "b");
assert_eq!(center.len(), 2);
for i in 0..10 {
center.push(ToastKind::Success, format!("t{i}"));
}
assert_eq!(center.len(), ToastCenter::MAX_VISIBLE);
center.expire(3_000);
assert_eq!(center.len(), ToastCenter::MAX_VISIBLE);
center.expire(1_001);
assert!(center.is_empty());
}
#[test]
fn dismiss_removes_one_toast() {
let mut center = ToastCenter::new();
let first = center.push(ToastKind::Info, "a");
center.push(ToastKind::Warn, "b");
assert!(center.dismiss(first));
assert!(!center.dismiss(first));
assert_eq!(center.len(), 1);
}
}
+333
View File
@@ -0,0 +1,333 @@
//! 绑定层(核心):窗口/状态/后端的持有与同步;回调接线在 [`crate::callbacks`]。
//!
//! P0 的“后端”是 [`MockBackend`](脚本化假数据);把 `Box<dyn Backend>` 换成真实的 core/agent
//! host 时,除本文件、`conv.rs`、`callbacks.rs` 外都不需要改
//! (通道语义见 `DevDocs/SubAgentsTalk/app-DTO通道约定.md`)。
//!
//! 主题与外观(D17 / 09 §101-113):落盘配置由 [`SettingsBridge`] 读写(`config/launcher.json`,
//! 与 `ull config set` 同一份),tick 里 1s 一次 `mtime` 热切;系统主题由
//! `core::platform::theme_probe` 做启动对齐 + 后端不支持时的兜底轮询。
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::time::Duration;
use slint::{ComponentHandle, ModelRc, VecModel};
use crate::bg_image::BackgroundLayers;
use crate::conv;
use crate::dto::{AppCommand, Backend, InstanceId};
use crate::mock::MockBackend;
use crate::prefs::BgFill;
use crate::settings_bridge::SettingsBridge;
use crate::state::AppState;
use crate::{MainWindow, SettingSection};
/// 定时器节拍:33ms ≈ 30fps(磁贴进度环 / 流式文本 / Toast TTL 的刷新下限)。
const TICK_MS: u64 = 33;
/// 配置热切轮询间隔(拍数):约 1s 一次 `mtime` 比对,AI/CLI 改完下一拍即生效。
pub(crate) const CONFIG_POLL_TICKS: u64 = 30;
/// 系统主题兜底轮询间隔(拍数):只在 `auto` 且后端不认识系统主题时启动(约 3s)。
pub(crate) const SYSTEM_THEME_POLL_TICKS: u64 = 90;
/// tile 模式重建画布的窗口尺寸粒度(像素):避免拖动窗口时反复重算平铺画布。
pub(crate) const TILE_REGENERATE_STEP: u32 = 128;
/// 应用外壳:持有窗口、状态与后端,把三者缝在一起。
pub struct AppUi {
inner: Rc<Inner>,
timer: slint::Timer,
}
pub(crate) struct Inner {
pub(crate) ui: MainWindow,
pub(crate) state: RefCell<AppState>,
pub(crate) backend: RefCell<Box<dyn Backend>>,
/// `config/launcher.json` 读写桥(app 不自己写盘:一律走 core::setting 的 schema API)
pub(crate) bridge: RefCell<SettingsBridge>,
/// 当前背景图 / 模糊层(避免每次同步都重新解码)
pub(crate) background: RefCell<BackgroundLayers>,
/// 生成 `background` 时的输入(路径 / 填充模式 / 窗口粒度尺寸)
pub(crate) background_key: RefCell<Option<BackgroundKey>>,
/// 拍数(轮询节拍)
pub(crate) ticks: Cell<u64>,
/// 是否已经做过启动时的系统主题对齐
pub(crate) system_theme_probed: Cell<bool>,
}
/// 背景图加工输入(值相同就不重新解码)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct BackgroundKey {
pub(crate) path: String,
pub(crate) fill: BgFill,
/// tile 用的窗口尺寸(按 [`TILE_REGENERATE_STEP`] 量化;cover/contain 恒为 (0, 0))
pub(crate) viewport: (u32, u32),
}
impl AppUi {
/// 建状态 + 假后端、读配置、接全部回调、灌初始事件并做第一次同步。
pub fn new(ui: MainWindow) -> Self {
// 先读一次落盘配置:主题三态 + 外观四件必须在首帧前就位(否则会闪一下出厂外观)
let bridge = SettingsBridge::open();
let (appearance, theme) = bridge.load();
let mut state = AppState::new();
state.prefs.appearance = appearance;
state.prefs.theme = theme;
let inner = Rc::new(Inner {
ui,
state: RefCell::new(state),
backend: RefCell::new(Box::new(MockBackend::new())),
bridge: RefCell::new(bridge),
background: RefCell::new(BackgroundLayers::default()),
background_key: RefCell::new(None),
ticks: Cell::new(0),
system_theme_probed: Cell::new(false),
});
crate::callbacks::wire(Rc::downgrade(&inner));
inner.drain_events();
inner.align_system_theme();
inner.apply_theme();
inner.apply_appearance();
inner.sync();
Self {
inner,
timer: slint::Timer::default(),
}
}
/// 进入 Slint 事件循环(窗口句柄由本结构持有,直到循环退出)。
pub fn run(&self) -> Result<(), slint::PlatformError> {
self.inner.ui.run()
}
/// 启动 33ms 节拍(后端 tick → 事件 → 状态 → UI)。
pub fn start_timer(&self) {
let inner = Rc::clone(&self.inner);
self.timer.start(
slint::TimerMode::Repeated,
Duration::from_millis(TICK_MS),
move || inner.tick(),
);
}
/// 推进一拍(截图通道用:没有事件循环时手动把 tick 走起来,让 mock 事件灌进状态)。
pub fn tick_once(&self) {
self.inner.tick();
slint::platform::update_timers_and_animations();
}
/// 直接跳到「设置 → 外观」页(截图验收用:证明外观分组的四组控件真的接线了)。
pub fn open_settings_appearance(&self) {
self.inner
.state
.borrow_mut()
.navigate(crate::router::Route::Settings);
self.inner.sync();
self.inner
.ui
.set_settings_section(SettingSection::Appearance);
slint::platform::update_timers_and_animations();
}
/// 渲染当前场景并存成 PNG(`--screenshot` 通道;见 `crate::png`)。
///
/// 为什么要这条通道:验收环境可能没有交互桌面(`CopyFromScreen` 直接失败),
/// 而 Slint 的软件渲染器可以把场景渲染进内存像素缓冲(`Window::take_snapshot`),
/// 结果与屏幕上看到的逐像素一致,且不需要 GPU。
///
/// # Errors
/// 窗口显示失败、快照失败或写文件失败时返回错误。
pub fn render_screenshot(&self, path: &str) -> Result<(), slint::PlatformError> {
let ui = &self.inner.ui;
ui.show()?;
// 固定逻辑尺寸 = main.slint 的默认窗口口径,保证验收图可比
ui.window()
.set_size(slint::WindowSize::Logical(slint::LogicalSize::new(
1180.0, 760.0,
)));
// 先走几拍:把 mock 事件(实例/版本/日志)与 33ms 节拍的效果灌进去
for _ in 0..4 {
self.tick_once();
std::thread::sleep(Duration::from_millis(TICK_MS));
}
let buffer = ui.window().take_snapshot()?;
let bytes = crate::png::encode_rgba8(&buffer);
std::fs::write(path, bytes)
.map_err(|error| slint::PlatformError::Other(format!("写截图失败 {path}: {error}")))?;
Ok(())
}
}
/// 发送一条 AI 提问:**只发指令 + 回流事件**,绝不做本地乐观回显。
///
/// 契约 §3 规定 host 先发 `MessageAppended(user)`:本地再 push 一次用户消息就会重复;
/// 且流式气泡的收敛依赖事件里的 `MessageFinished{index}`,本地多建的占位会变成
/// 永不收敛的「幽灵气泡」(review P1-1)。callbacks 与单测都走这一个入口。
pub(crate) fn send_agent_message(state: &mut AppState, backend: &mut dyn Backend, text: &str) {
backend.dispatch(AppCommand::AskAgent(text.to_string()));
for event in backend.drain_events() {
state.apply(event);
}
}
impl Inner {
/// 走一次完整的「提问 → 事件回流」。
pub(crate) fn ask_agent(&self, text: &str) {
let mut state = self.state.borrow_mut();
let mut backend = self.backend.borrow_mut();
send_agent_message(&mut state, backend.as_mut(), text);
}
pub(crate) fn dispatch(&self, command: AppCommand) {
self.backend.borrow_mut().dispatch(command);
self.drain_events();
}
pub(crate) fn drain_events(&self) {
let events = self.backend.borrow_mut().drain_events();
if events.is_empty() {
return;
}
let mut state = self.state.borrow_mut();
for event in events {
state.apply(event);
}
}
fn tick(&self) {
self.backend
.borrow_mut()
.tick(Duration::from_millis(TICK_MS));
self.drain_events();
self.state.borrow_mut().toasts.expire(TICK_MS);
self.ticks.set(self.ticks.get() + 1);
self.poll_settings();
self.poll_system_theme();
self.sync();
}
pub(crate) fn sync(&self) {
let state = self.state.borrow();
let ui = &self.ui;
ui.set_route(conv::route(state.route()));
ui.set_nav_collapsed(state.prefs.nav_collapsed);
ui.set_ai_collapsed(state.prefs.ai_collapsed);
ui.set_tile_size(conv::tile_size(state.prefs.tile_size));
ui.set_instance_view(conv::instance_view(state.prefs.instance_view));
ui.set_download_category(conv::category_from(state.prefs.download_category));
ui.set_download_installed_only(state.installed_only);
ui.set_theme_mode(conv::theme_mode(state.prefs.theme));
ui.set_tiles(model(conv::tiles(&state)));
ui.set_running_tiles(model(conv::running_tiles(&state)));
ui.set_versions(model(conv::versions(&state)));
ui.set_log_sessions(model(conv::log_sessions(&state)));
ui.set_log_lines(model(conv::log_lines(&state)));
ui.set_toasts(model(conv::toasts(&state)));
let (diagnosis, has_diagnosis) = conv::diagnosis(&state);
ui.set_diagnosis(diagnosis);
ui.set_has_diagnosis(has_diagnosis);
ui.set_selected_session(state.selected_session.clone().unwrap_or_default().into());
ui.set_ai_messages(model(conv::chat(&state)));
ui.set_ai_streaming(state.ai.streaming);
ui.set_yolo(state.ai.yolo);
ui.set_ai_endpoint_label(state.ai.endpoint_label.clone().into());
let (dialog, open, queued) = conv::dialog(&state);
ui.set_dialog(dialog);
ui.set_dialog_open(open);
ui.set_dialog_queued(queued);
}
}
pub(crate) fn model<T: Clone + 'static>(items: Vec<T>) -> ModelRc<T> {
ModelRc::new(VecModel::from(items))
}
/// 停止实例的指令构造(阶段 C 的磁贴「停止」键用;P0 只保留 API)。
#[allow(dead_code)]
pub fn stop_instance(id: &InstanceId) -> AppCommand {
AppCommand::StopInstance(id.clone())
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::send_agent_message;
use crate::dto::{Backend, ChatRole};
use crate::mock::MockBackend;
use crate::state::AppState;
/// 集成测试(callbacks→state→mock 全链路):发一次提问后
/// ①用户消息恰出现一次(无本地回显重复)②所有 assistant 气泡收敛(无幽灵气泡)。
///
/// 分层单测漏掉这条正是 review P1-1 的根因,故这里用真实 mock 后端跑完整事件流。
#[test]
fn send_path_has_no_duplicate_user_message_and_no_ghost_stream() {
let mut state = AppState::new();
let mut backend = MockBackend::new();
// 先灌入种子事件(实例/版本/日志快照)
for event in backend.drain_events() {
state.apply(event);
}
send_agent_message(&mut state, &mut backend, "装哪个版本");
fn user_count(state: &AppState) -> usize {
state
.ai
.messages
.iter()
.filter(|message| message.role == ChatRole::User)
.count()
}
assert_eq!(
user_count(&state),
1,
"用户消息必须恰好一条(本地回显会造成两条)"
);
assert!(state.ai.streaming);
// 推进到流式收敛(mock 300ms/片 + 工具调用 + 收尾消息)
for _ in 0..12 {
backend.tick(Duration::from_millis(400));
for event in backend.drain_events() {
state.apply(event);
}
}
assert_eq!(user_count(&state), 1, "事件回流后用户消息仍应只有一条");
assert!(
state.ai.messages.iter().all(|message| !message.streaming),
"所有气泡必须收敛(幽灵气泡会永久 streaming)"
);
assert!(!state.ai.streaming);
assert!(
state
.ai
.messages
.iter()
.any(|message| message.role == ChatRole::Assistant && !message.text.is_empty()),
"增量应累积到 assistant 正文"
);
assert_eq!(
state
.ai
.messages
.iter()
.filter(|message| message.role == ChatRole::Assistant)
.count(),
2,
"一轮对话 = 流式回复 + 收尾回复"
);
}
}
+283
View File
@@ -0,0 +1,283 @@
// 右侧 AI 常驻栏(D16 §1):默认 320px 可折叠;可「展开为页面」变成全宽独立页,
// 两形态共享同一份会话模型(由 Rust 侧 AiSession 持有,这里只渲染,切换不丢状态)。
// 栏顶承载 YOLO 快捷开关(D4 补充)与端点标签。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiChatMessage, ChatRole } from "../models.slint";
import { UiText, TextRole } from "label.slint";
import { AppIcon, IconKind } from "icons.slint";
import { MetroButton, ButtonKind } from "../widgets/button.slint";
import { PlainInput } from "../widgets/inputs.slint";
import { GlassBase } from "glass.slint";
import { ListView } from "std-widgets.slint";
// 一条会话消息:user 靠右(accent-soft 块)/ assistant 靠左 / tool 用状态边框 / system 居中弱化
component ChatBubble inherits Rectangle {
in property <UiChatMessage> message;
property <bool> is-tool: message.role == ChatRole.tool;
property <bool> is-system: message.role == ChatRole.system;
property <length> text-width: root.width - 2 * Metrics.gap-2;
property <length> tool-row: is-tool ? 16px : 0px;
height: text-node.preferred-height + 2 * Metrics.gap-2 + tool-row;
background: message.role == ChatRole.user
? Theme.accent-soft
: is-tool ? Theme.bg-canvas
: is-system ? transparent
: Theme.bg-elevated;
border-radius: Metrics.radius-md;
border-width: is-tool ? 1px : 0px;
border-color: message.tool_ok ? Theme.state-success : Theme.state-danger;
// 工具调用可视化(D4 要求:工具执行在会话里可见)
if is-tool : AppIcon {
x: Metrics.gap-2;
y: Metrics.gap-2 + 1px;
icon-size: 12px;
kind: message.tool_ok ? IconKind.check : IconKind.error;
tint: message.tool_ok ? Theme.state-success : Theme.state-danger;
}
if is-tool : UiText {
x: Metrics.gap-2 + 16px;
y: Metrics.gap-2;
width: text-width - 16px;
height: 14px;
role: TextRole.caption;
text: "工具 · " + message.tool_name;
color: message.tool_ok ? Theme.state-success : Theme.state-danger;
}
text-node := UiText {
x: Metrics.gap-2;
y: Metrics.gap-2 + tool-row;
width: text-width;
height: text-node.preferred-height;
role: TextRole.body;
text: message.text;
wrap: word-wrap;
overflow: elide;
vertical-alignment: top;
horizontal-alignment: message.role == ChatRole.user ? right : left;
color: is-system ? Theme.fg-secondary : Theme.fg-primary;
}
// 流式未收敛:末尾的 accent 光标块
if message.streaming : Rectangle {
x: 0;
y: root.height - 10px;
width: 8px;
height: 10px;
background: Theme.accent;
}
}
export component AiPanel inherits Rectangle {
in property <[UiChatMessage]> messages;
in-out property <bool> collapsed: false;
/// true = 停在右侧栏形态;false = 已拆成独立全宽页
in property <bool> docked: true;
in property <bool> yolo: false;
in property <bool> streaming: false;
in property <string> endpoint-label: "llama.cpp · 本地";
in-out property <string> draft: "";
callback toggle-collapsed();
callback expand();
callback dock();
callback toggle-yolo();
callback send(string);
callback stop();
// 栏形态用 min/max 钉死宽度(布局里等价于固定宽度),页形态交给父容器铺满
min-width: docked ? (collapsed ? Metrics.ai-rail-width : Metrics.ai-panel-width) : 0px;
max-width: docked ? (collapsed ? Metrics.ai-rail-width : Metrics.ai-panel-width) : 100000px;
horizontal-stretch: docked ? 0 : 1;
height: 100%;
background: Theme.bg-surface;
// 玻璃拟态底(D17 高级特性;关闭态不画东西)——排在内容之前,压在最底层
GlassBase { card-radius: 0px; }
// 左边界线
Rectangle {
x: 0;
y: 0;
width: 1px;
height: root.height;
background: Theme.stroke;
}
// ── 折叠态:icon 轨 ─────────────────────────────────────────
if docked && collapsed : VerticalLayout {
x: 1px;
width: root.width - 1px;
height: root.height;
padding-top: Metrics.gap-2;
padding-bottom: Metrics.gap-2;
spacing: Metrics.gap-2;
AppIcon {
kind: IconKind.ai;
icon-size: 18px;
tint: Theme.accent;
TouchArea {
mouse-cursor: pointer;
clicked => { root.toggle-collapsed(); }
}
}
AppIcon {
kind: IconKind.expand;
icon-size: 14px;
tint: Theme.fg-secondary;
TouchArea {
mouse-cursor: pointer;
clicked => { root.expand(); }
}
}
Rectangle { vertical-stretch: 1; background: transparent; }
// YOLO 指示点:开启时实心 accent
Rectangle {
width: 6px;
height: 6px;
border-radius: 3px;
background: root.yolo ? Theme.accent : Theme.stroke-strong;
}
}
// ── 展开态:栏内 / 独立页共用 ────────────────────────────────
if !(docked && collapsed) : VerticalLayout {
x: 1px;
width: root.width - 1px;
height: root.height;
// 头部
Rectangle {
height: 52px;
background: transparent;
HorizontalLayout {
padding-left: Metrics.gap-3;
padding-right: Metrics.gap-2;
spacing: Metrics.gap-2;
AppIcon { kind: IconKind.ai; icon-size: 16px; tint: Theme.accent; }
VerticalLayout {
spacing: 0px;
vertical-stretch: 1;
UiText {
role: TextRole.bodyStrong;
text: "AI 助手";
horizontal-stretch: 1;
}
UiText {
role: TextRole.caption;
text: root.endpoint-label;
horizontal-stretch: 1;
}
}
MetroButton {
kind: root.yolo ? ButtonKind.accent : ButtonKind.subtle;
text: "YOLO";
button-height: 24px;
clicked => { root.toggle-yolo(); }
}
if root.docked : MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.expand;
icon-only: true;
button-height: 24px;
clicked => { root.expand(); }
}
if !root.docked : MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.sidebar;
icon-only: true;
button-height: 24px;
clicked => { root.dock(); }
}
if root.docked : MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.chevronRight;
icon-only: true;
button-height: 24px;
clicked => { root.toggle-collapsed(); }
}
}
}
Rectangle { height: 1px; background: Theme.stroke; }
// 对话流(ListView 行虚拟化,research/01 已确认)
ListView {
vertical-stretch: 1;
for m in root.messages : ChatBubble {
message: m;
width: root.width - 2 * Metrics.gap-3;
}
}
if root.messages.length == 0 : UiText {
role: TextRole.caption;
text: "问点什么:装哪个版本、崩溃怎么修、帮我改设置…";
horizontal-alignment: center;
height: 40px;
}
Rectangle { height: 1px; background: Theme.stroke; }
// 输入区
Rectangle {
height: 56px;
background: transparent;
HorizontalLayout {
padding: Metrics.gap-2;
spacing: Metrics.gap-2;
input-box := Rectangle {
horizontal-stretch: 1;
vertical-stretch: 1;
background: Theme.bg-input;
border-radius: Metrics.radius-sm;
border-width: 1px;
border-color: input-field.focused ? Theme.accent : Theme.stroke;
input-field := PlainInput {
text-padding: Metrics.gap-2;
placeholder: "输入消息,Enter 发送";
text <=> root.draft;
accepted(t) => {
if (t != "") {
root.send(t);
}
}
}
}
MetroButton {
kind: ButtonKind.accent;
icon: root.streaming ? IconKind.stop : IconKind.send;
icon-only: true;
clicked => {
if (root.streaming) {
root.stop();
} else if (root.draft != "") {
root.send(root.draft);
}
}
}
}
}
}
}
+27
View File
@@ -0,0 +1,27 @@
// 徽标:MC 版本 / 加载器 / 已装 / 远古版 等短标记。Metro 做法是细边框小方块,不用药丸圆角。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiText, TextRole } from "../components/label.slint";
export component Badge inherits Rectangle {
in property <string> text: "";
in property <color> tint: Theme.fg-secondary;
in property <color> fill: transparent;
height: 18px;
width: label.preferred-width + 2 * Metrics.gap-1 + 2px;
background: fill;
border-width: 1px;
border-color: tint;
border-radius: Metrics.radius-sm;
label := UiText {
role: TextRole.caption;
text: root.text;
color: root.tint;
font-size: 11px;
horizontal-alignment: center;
x: Metrics.gap-1 + 1px;
width: label.preferred-width;
}
}
+59
View File
@@ -0,0 +1,59 @@
// 玻璃拟态卡片的公共底座(09 §103:Slint 没有 backdrop-filter,用「预生成模糊背景层」替代)。
//
// 手法:Rust 侧把背景图降采样成一张极小的图(`Theme.bg-blur`),渲染时被平滑放大 → 天然模糊。
// 卡片里把它按 `absolute-position` **反向偏移**画出来,于是卡片显示的是「自己这一块屏幕区域的
// 模糊影像」,视觉上就是毛玻璃;再叠一层半透明面板色保证文字可读(对比度优先)。
//
// 关闭态(`Theme.glass == false` 或无背景图)不画任何东西:卡片保持 Metro 纯色观感。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
export component GlassBase inherits Rectangle {
/// 卡片圆角(跟随宿主卡片)
in property <length> card-radius: Metrics.radius-md;
/// 叠在模糊层上的半透明面板色(保证前景对比度)
in property <color> tint: Theme.surface-solid;
out property <bool> active: Theme.glass && Theme.bg-blur.width > 0 && Theme.bg-image.width > 0;
x: 0;
y: 0;
width: 100%;
height: 100%;
border-radius: root.card-radius;
clip: true;
background: transparent;
if root.active : Image {
// 整窗模糊层 + 反向偏移 = 只露出「卡片所在那一块」。
// 必须用 `parent`(本组件自身)的绝对位置:用 `self` 会与自身 x 形成绑定环
// (absolute-position 依赖 x,x 又依赖 absolute-position)。
source: Theme.bg-blur;
x: -parent.absolute-position.x;
y: -parent.absolute-position.y;
width: Theme.window-width;
height: Theme.window-height;
image-fit: cover;
}
if root.active : Rectangle {
// 暗化层要**重画一次**:模糊层在卡片内部、盖在窗口的暗化层之上,
// 不补这一层的话玻璃卡片会比周围亮一大截(05 截图验收时的真实问题)。
background: rgba(0, 0, 0, Theme.bg-dim);
border-radius: root.card-radius;
}
if root.active : Rectangle {
// 玻璃染色:面板底色 55% 不透明,字压得住背景(对比度优先于「更透」)
background: root.tint.with-alpha(0.55);
border-radius: root.card-radius;
}
if root.active : Rectangle {
// 上缘一道细高光,玻璃的「厚度感」
y: 0;
height: 1px;
width: root.width;
background: Theme.stroke.with-alpha(0.35);
}
}
+192
View File
@@ -0,0 +1,192 @@
// 图标:18×18 viewbox 的矢量绘制(Metro 要求线性几何图标,不用 emoji/位图)。
// 只用 M/L/Q/Z 命令 + 直线,避免依赖字体字形;描边图标 stroke,实心图标 fill。
import { Theme } from "../theme/tokens.slint";
export enum IconKind {
instances,
download,
logs,
settings,
ai,
play,
stop,
search,
plus,
close,
minimize,
maximize,
chevronLeft,
chevronRight,
chevronDown,
expand,
send,
check,
warn,
error,
more,
sidebar,
restore,
}
export component AppIcon inherits Rectangle {
in property <IconKind> kind: IconKind.instances;
in property <color> tint: Theme.fg-secondary;
in property <length> icon-size: 18px;
width: icon-size;
height: icon-size;
background: transparent;
if kind == IconKind.instances : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 2 2 L 8 2 L 8 8 L 2 8 Z M 10 2 L 16 2 L 16 8 L 10 8 Z M 2 10 L 8 10 L 8 16 L 2 16 Z M 10 10 L 16 10 L 16 16 L 10 16 Z";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.download : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 9 2 L 9 11 M 4 7 L 9 12 L 14 7 M 3 15 L 15 15";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.logs : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 4 L 15 4 M 3 9 L 15 9 M 3 14 L 11 14";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.settings : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 5 L 15 5 M 3 9 L 15 9 M 3 13 L 15 13";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.settings : Rectangle {
x: 5px;
width: 5px; height: 5px; y: 3px;
border-radius: 2.5px; background: root.tint;
}
if kind == IconKind.settings : Rectangle {
x: 10px; y: 7px; width: 5px; height: 5px;
border-radius: 2.5px; background: root.tint;
}
if kind == IconKind.settings : Rectangle {
x: 3px; y: 11px; width: 5px; height: 5px;
border-radius: 2.5px; background: root.tint;
}
if kind == IconKind.ai : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 9 1.5 L 10.7 7.3 L 16.5 9 L 10.7 10.7 L 9 16.5 L 7.3 10.7 L 1.5 9 L 7.3 7.3 Z";
fill: root.tint; stroke: transparent; stroke-width: 1px;
}
if kind == IconKind.play : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 5 3 L 15 9 L 5 15 Z";
fill: root.tint; stroke: transparent; stroke-width: 1px;
}
if kind == IconKind.stop : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 5 5 L 13 5 L 13 13 L 5 13 Z";
fill: root.tint; stroke: transparent; stroke-width: 1px;
}
if kind == IconKind.search : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 8 3 Q 13 3 13 8 Q 13 13 8 13 Q 3 13 3 8 Q 3 3 8 3 Z M 11.5 11.5 L 16 16";
fill: transparent; stroke: root.tint; stroke-width: 1.5px;
}
if kind == IconKind.plus : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 9 3 L 9 15 M 3 9 L 15 9";
fill: transparent; stroke: root.tint; stroke-width: 1.8px;
}
if kind == IconKind.close : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 4 4 L 14 14 M 14 4 L 4 14";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.minimize : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 4 9 L 14 9";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.maximize : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 4.5 4.5 L 13.5 4.5 L 13.5 13.5 L 4.5 13.5 Z";
fill: transparent; stroke: root.tint; stroke-width: 1.2px;
}
if kind == IconKind.chevronLeft : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 11 3 L 6 9 L 11 15";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.chevronRight : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 7 3 L 12 9 L 7 15";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.chevronDown : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 7 L 9 13 L 15 7";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.expand : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 7 L 3 3 L 7 3 M 11 3 L 15 3 L 15 7 M 15 11 L 15 15 L 11 15 M 7 15 L 3 15 L 3 11";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.send : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 2 9 L 16 9 M 11 4 L 16 9 L 11 14";
fill: transparent; stroke: root.tint; stroke-width: 1.6px;
}
if kind == IconKind.check : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 9 L 7 13 L 15 4";
fill: transparent; stroke: root.tint; stroke-width: 1.8px;
}
if kind == IconKind.warn : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 9 2 L 16 15 L 2 15 Z M 9 6.5 L 9 10.5";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
if kind == IconKind.error : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 9 2 Q 16 2 16 9 Q 16 16 9 16 Q 2 16 2 9 Q 2 2 9 2 Z M 9 5 L 9 10";
fill: transparent; stroke: root.tint; stroke-width: 1.5px;
}
if kind == IconKind.more : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 4 7 L 6 7 L 6 9 L 4 9 Z M 8 7 L 10 7 L 10 9 L 8 9 Z M 12 7 L 14 7 L 14 9 L 12 9 Z";
fill: root.tint; stroke: transparent; stroke-width: 1px;
}
if kind == IconKind.sidebar : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 3 4 L 15 4 L 15 14 L 3 14 Z M 7 4 L 7 14";
fill: transparent; stroke: root.tint; stroke-width: 1.4px;
}
// 还原(已最大化时的标题栏按钮):两层叠放方框
if kind == IconKind.restore : Path {
width: root.width; height: root.height;
viewbox-width: 18; viewbox-height: 18;
commands: "M 6 3 L 15 3 L 15 12 M 3 6 L 12 6 L 12 15 L 3 15 Z";
fill: transparent; stroke: root.tint; stroke-width: 1.2px;
}
}
+34
View File
@@ -0,0 +1,34 @@
// 排版角色封装:所有文字都走 UiText,不在页面里散落 font-size/font-family 字面量。
// 角色 → 字号/字重/默认前景色由 tokens.slint 的 ramp 决定;外部赋值可覆盖(例如强调色标题)。
import { Theme } from "../theme/tokens.slint";
export enum TextRole {
display,
title,
subtitle,
body,
bodyStrong,
caption,
mono,
monoSmall,
}
export component UiText inherits Text {
in property <TextRole> role: TextRole.body;
color: role == TextRole.caption ? Theme.fg-secondary : Theme.fg-primary;
font-family: (role == TextRole.mono || role == TextRole.monoSmall)
? Theme.font-family-mono
: Theme.font-family;
font-size: (role == TextRole.display) ? Theme.font-size-display
: (role == TextRole.title) ? Theme.font-size-title
: (role == TextRole.subtitle) ? Theme.font-size-subtitle
: (role == TextRole.caption || role == TextRole.monoSmall) ? Theme.font-size-caption
: Theme.font-size-body;
font-weight: (role == TextRole.bodyStrong || role == TextRole.title || role == TextRole.display)
? 600
: 400;
vertical-alignment: center;
wrap: no-wrap;
overflow: elide;
}
+182
View File
@@ -0,0 +1,182 @@
// 左侧主导航(D16 §1):图标+文字,选中项 accent 色块;可折叠成纯图标窄条(偏好记忆)。
// 折叠宽度/展开宽度取 Metrics,动画时长取 Theme.motion-normal。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { RouteKind } from "../models.slint";
import { UiText, TextRole } from "label.slint";
import { AppIcon, IconKind } from "icons.slint";
component NavItem inherits Rectangle {
in property <IconKind> icon: IconKind.instances;
in property <string> label: "";
in property <bool> active: false;
in property <bool> collapsed: false;
callback clicked();
height: root.collapsed ? 48px : 64px;
background: root.active
? Theme.accent-soft
: touch.has-hover ? Theme.bg-hover : transparent;
animate background { duration: Theme.motion-fast; }
// 选中态:左侧 accent 竖条(Metro 侧栏语义)
Rectangle {
visible: root.active;
x: 0;
y: 0;
width: 3px;
height: root.height;
background: Theme.accent;
}
AppIcon {
kind: root.icon;
icon-size: 20px;
x: (root.width - self.width) / 2;
y: root.collapsed ? (root.height - self.height) / 2 : 12px;
tint: root.active ? Theme.accent : Theme.fg-secondary;
}
UiText {
visible: !root.collapsed;
role: TextRole.caption;
text: root.label;
color: root.active ? Theme.accent : Theme.fg-secondary;
horizontal-alignment: center;
x: 0;
y: 38px;
width: root.width;
}
touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.clicked(); }
}
accessible-role: button;
accessible-label: root.label;
}
export component Nav inherits Rectangle {
in property <RouteKind> active: RouteKind.instances;
in-out property <bool> collapsed: false;
in property <string> account-name: "未登录";
in property <color> account-hue: #5C2D91;
in property <string> account-initial: "?";
callback navigate(RouteKind);
callback toggle-collapsed();
callback account-clicked();
width: collapsed ? Metrics.nav-collapsed-width : Metrics.nav-expanded-width;
height: 100%;
background: Theme.bg-surface;
animate width { duration: Theme.motion-normal; easing: ease-in-out; }
// 右边界线
Rectangle {
x: root.width - 1px;
y: 0;
width: 1px;
height: root.height;
background: Theme.stroke;
}
VerticalLayout {
x: 0;
y: Metrics.gap-2;
width: root.width;
height: root.height - Metrics.gap-2 - Metrics.gap-2;
NavItem {
icon: IconKind.instances;
label: "实例";
active: root.active == RouteKind.instances || root.active == RouteKind.detail;
collapsed: root.collapsed;
clicked => { root.navigate(RouteKind.instances); }
}
NavItem {
icon: IconKind.download;
label: "下载";
active: root.active == RouteKind.download;
collapsed: root.collapsed;
clicked => { root.navigate(RouteKind.download); }
}
NavItem {
icon: IconKind.logs;
label: "日志";
active: root.active == RouteKind.logs;
collapsed: root.collapsed;
clicked => { root.navigate(RouteKind.logs); }
}
NavItem {
icon: IconKind.settings;
label: "设置";
active: root.active == RouteKind.settings;
collapsed: root.collapsed;
clicked => { root.navigate(RouteKind.settings); }
}
Rectangle { vertical-stretch: 1; background: transparent; }
// 底部:账户头像(点击进设置·账户)
Rectangle {
height: 56px;
background: account-touch.has-hover ? Theme.bg-hover : transparent;
Rectangle {
width: 28px;
height: 28px;
border-radius: 14px;
background: root.account-hue;
x: (root.width - self.width) / 2;
y: 8px;
UiText {
text: root.account-initial;
font-size: 12px;
font-weight: 600;
color: Theme.fg-on-accent;
horizontal-alignment: center;
vertical-alignment: center;
}
}
UiText {
visible: !root.collapsed;
role: TextRole.caption;
text: root.account-name;
horizontal-alignment: center;
x: 0;
y: 38px;
width: root.width;
}
account-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.account-clicked(); }
}
}
// 折叠开关(偏好由 Rust 侧持久化到 ui.nav.collapsed)
Rectangle {
height: 40px;
background: toggle-touch.has-hover ? Theme.bg-hover : transparent;
AppIcon {
kind: root.collapsed ? IconKind.chevronRight : IconKind.chevronLeft;
icon-size: 16px;
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
tint: Theme.fg-secondary;
}
toggle-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.toggle-collapsed(); }
}
accessible-role: button;
accessible-label: root.collapsed ? "展开导航栏" : "折叠导航栏";
}
}
}
@@ -0,0 +1,22 @@
// 启动进度环:磁贴「启动中」状态用(下载/校验/启动三个阶段共用一个环)。
// 用 std-widgets 的 ProgressIndicator:progress <= 0 时转为不确定态(转圈)。
// P1 若要完全贴合 Metro 强调色,需自绘弧线(Slint 无 arc 命令,得用旋转遮罩法)。
import { Theme } from "../theme/tokens.slint";
import { ProgressIndicator } from "std-widgets.slint";
export component ProgressRing inherits Rectangle {
/// 0.0~1.0;<= 0 表示未知进度
in property <float> progress: 0;
in property <length> ring-size: 28px;
width: ring-size;
height: ring-size;
background: transparent;
ProgressIndicator {
width: root.ring-size;
height: root.ring-size;
progress: root.progress;
indeterminate: root.progress <= 0;
}
}
+198
View File
@@ -0,0 +1,198 @@
// 实例磁贴(G1):图标 / 名字 / MC 版本徽标 / 加载器徽标 / 最后游玩 / 大启动键 + 设置键。
// 三档尺寸由 Metrics.tile-* 决定(小磁贴藏徽标与时间,只留名字+启动);
// 启动中把底部按钮行替换成「进度环 + 阶段文案 + 停止」。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiTile, RuntimePhase, LoaderKind } from "../models.slint";
import { UiText, TextRole } from "label.slint";
import { AppIcon, IconKind } from "icons.slint";
import { Badge } from "badge.slint";
import { ProgressRing } from "progress-ring.slint";
import { GlassBase } from "glass.slint";
import { MetroButton, ButtonKind } from "../widgets/button.slint";
component TileIcon inherits Rectangle {
in property <UiTile> data;
in property <length> box-size: 44px;
width: box-size;
height: box-size;
border-radius: Metrics.radius-md;
background: root.data.hue;
if root.data.icon.width > 0 : Image {
x: 0;
y: 0;
width: root.width;
height: root.height;
source: root.data.icon;
image-fit: cover;
}
if root.data.icon.width <= 0 : UiText {
text: root.data.initial;
font-size: 18px;
font-weight: 600;
color: Theme.fg-on-accent;
horizontal-alignment: center;
vertical-alignment: center;
}
}
export component InstanceTile inherits Rectangle {
in property <UiTile> data;
in property <bool> compact: false;
callback open();
callback launch();
callback configure();
/// 启动中/运行中的停止键(dispatch StopInstance)
callback stop();
height: Metrics.tile-height;
background: touch.has-hover ? Theme.bg-elevated : Theme.bg-surface;
border-radius: Metrics.radius-md;
border-width: 1px;
border-color: root.data.phase == RuntimePhase.running ? Theme.accent : Theme.stroke;
drop-shadow-blur: touch.has-hover ? 12px : 0px;
drop-shadow-color: Theme.shadow;
drop-shadow-offset-y: 2px;
animate background { duration: Theme.motion-fast; }
animate drop-shadow-blur { duration: Theme.motion-normal; }
// 玻璃拟态底(关闭态什么都不画,卡片就是 Metro 纯色);必须排在最前,否则盖住 accent 细线
GlassBase {
card-radius: root.border-radius;
}
// 运行中:顶部 accent 细线(Metro 色块语义)
Rectangle {
visible: root.data.phase == RuntimePhase.running;
x: 0;
y: 0;
width: root.width;
height: 2px;
background: Theme.accent;
}
// 磁贴主体点击 → 实例详情(G4);按钮的 TouchArea 后声明,命中优先
touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.open(); }
}
VerticalLayout {
padding: Metrics.gap-3;
spacing: Metrics.gap-2;
HorizontalLayout {
spacing: Metrics.gap-2;
TileIcon {
data: root.data;
box-size: Metrics.tile-icon-size;
}
VerticalLayout {
spacing: 2px;
vertical-stretch: 1;
UiText {
role: TextRole.bodyStrong;
text: root.data.name;
horizontal-stretch: 1;
}
UiText {
role: TextRole.caption;
text: root.data.last_played;
visible: !root.compact;
}
}
}
HorizontalLayout {
visible: !root.compact;
spacing: Metrics.gap-1;
Badge {
text: root.data.mc_version;
tint: Theme.fg-secondary;
}
Badge {
text: root.data.loader_label;
tint: root.data.loader == LoaderKind.vanilla ? Theme.fg-secondary : Theme.accent;
}
}
Rectangle { vertical-stretch: 1; background: transparent; }
// 空闲/失败:大启动键 + 设置键
HorizontalLayout {
visible: root.data.phase == RuntimePhase.idle || root.data.phase == RuntimePhase.failed;
spacing: Metrics.gap-2;
MetroButton {
kind: ButtonKind.accent;
text: root.data.phase == RuntimePhase.failed ? "重试" : "启动";
show-icon: true;
icon: IconKind.play;
grow: true;
clicked => { root.launch(); }
}
MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.settings;
icon-only: true;
clicked => { root.configure(); }
}
}
// 启动中:进度环 + 阶段文案 + 停止
HorizontalLayout {
visible: root.data.phase == RuntimePhase.downloading
|| root.data.phase == RuntimePhase.verifying
|| root.data.phase == RuntimePhase.launching;
spacing: Metrics.gap-2;
ProgressRing {
progress: root.data.progress;
ring-size: 22px;
}
UiText {
role: TextRole.caption;
text: root.data.phase_label;
horizontal-stretch: 1;
}
MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.stop;
icon-only: true;
clicked => { root.stop(); }
}
}
// 运行中:状态点 + 停止
HorizontalLayout {
visible: root.data.phase == RuntimePhase.running;
spacing: Metrics.gap-2;
Rectangle {
width: 8px;
height: 8px;
border-radius: 4px;
background: Theme.state-success;
}
UiText {
role: TextRole.caption;
text: "运行中";
color: Theme.state-success;
horizontal-stretch: 1;
}
MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.stop;
icon-only: true;
clicked => { root.stop(); }
}
}
}
}
+126
View File
@@ -0,0 +1,126 @@
// 自绘无边框标题栏(D16 §1):Metro 一体感 + accent 顶线。
// 拖拽/最大化/最小化/关闭只发回调,原生窗口操作由 main.rs 接到 Slint Window 平台上
// (Slint DSL 内无法移动原生窗口)。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiText, TextRole } from "label.slint";
import { AppIcon, IconKind } from "icons.slint";
component WindowButton inherits Rectangle {
in property <IconKind> icon: IconKind.minimize;
/// 关闭键:hover 用 Metro 红底白字
in property <bool> danger: false;
callback clicked();
width: Metrics.titlebar-button-width;
height: Metrics.titlebar-height;
background: touch.pressed
? (danger ? Theme.state-danger-hover : Theme.bg-pressed)
: touch.has-hover ? (danger ? Theme.state-danger : Theme.bg-hover) : transparent;
animate background { duration: Theme.motion-fast; }
AppIcon {
kind: root.icon;
icon-size: 12px;
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
tint: root.danger && touch.has-hover ? Theme.fg-on-accent : Theme.fg-primary;
}
touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.clicked(); }
}
}
export component TitleBar inherits Rectangle {
in property <string> title: "Unlucky Launcher";
in property <string> subtitle: "";
in property <bool> maximized: false;
callback toggle-maximize();
callback minimize();
callback request-close();
height: Metrics.titlebar-height;
background: Theme.bg-titlebar;
// accent 顶线(Metro 强调色贯穿)
Rectangle {
x: 0;
y: 0;
width: root.width;
height: Metrics.accent-line;
background: Theme.accent;
}
// 拖拽区:交给原生 `WindowMoveArea`(Slint 1.18 内置,拖过阈值才移动窗口,
// 并保持子元素可交互)。只覆盖左侧,右侧三个窗口按钮留出来。
// 平台不支持「系统级窗口移动」时该元素退化为无操作(Qt/部分 Wayland 组合),
// winit on Windows/macOS/X11 可用——Win7 落在这条路上。
WindowMoveArea {
x: 0;
y: Metrics.accent-line;
width: root.width - 3 * Metrics.titlebar-button-width;
height: root.height - Metrics.accent-line;
}
// 应用标记 + 标题
HorizontalLayout {
x: Metrics.gap-3;
y: Metrics.accent-line;
width: root.width - 3 * Metrics.titlebar-button-width - 2 * Metrics.gap-3;
height: root.height - Metrics.accent-line;
spacing: Metrics.gap-2;
Rectangle {
width: 14px;
height: 14px;
border-radius: Metrics.radius-sm;
background: Theme.accent;
UiText {
text: "U";
font-size: 10px;
font-weight: 700;
color: Theme.fg-on-accent;
horizontal-alignment: center;
vertical-alignment: center;
}
}
UiText {
role: TextRole.caption;
text: root.title;
font-weight: 600;
horizontal-stretch: 1;
}
UiText {
role: TextRole.caption;
text: root.subtitle;
color: Theme.fg-secondary;
}
}
HorizontalLayout {
x: root.width - 3 * Metrics.titlebar-button-width;
y: Metrics.accent-line;
width: 3 * Metrics.titlebar-button-width;
height: root.height - Metrics.accent-line;
spacing: 0px;
WindowButton {
icon: IconKind.minimize;
clicked => { root.minimize(); }
}
WindowButton {
icon: root.maximized ? IconKind.restore : IconKind.maximize;
clicked => { root.toggle-maximize(); }
}
WindowButton {
icon: IconKind.close;
danger: true;
clicked => { root.request-close(); }
}
}
}
+303
View File
@@ -0,0 +1,303 @@
// Unlucky-Launcher · 主入口窗口(P0 阶段 B 接线)
//
// 布局真相源:DevDocs/PlanDoc/09-ui-layout.md(D16:左侧固定导航 + 右侧 AI 常驻栏 + 磁贴实例页)。
// 本文件只做三件事:①无边框窗口与字体/缩放口径 ②实例化 `AppShell` ③把 AppShell 的全部
// 属性/回调原样上抛给 src/main.rs(Slint 只能从根组件访问属性与回调,所以这层转发是必需的)。
//
// 与 M11 骨架的关系:M11 的 `Metro` palette global(accent/surface/sidebar/tile/text/muted/pad/gap)
// 已由 `theme/tokens.slint` 的 `Theme` 继承并扩展——同一「palette global 令牌化」思路,但多了
// 亮/暗双套色板(LightPalette/DarkPalette)、主题三态解析、排版 ramp 与字体栈;M11 的占位
// NavItem/Tile 组件由 `components/nav.slint` 与 `components/tile.slint` 取代,占位内核不再保留。
import { AppShell } from "shell.slint";
import { Theme } from "theme/tokens.slint";
import { Metrics } from "theme/metrics.slint";
import {
RouteKind, TileSize, InstanceView, SettingSection, DownloadCategory, ThemeMode, BgFillKind,
UiTile, UiVersion, UiLogSession, UiLogLine, UiDiagnosis, UiChatMessage, UiDialog, UiToast,
} from "models.slint";
export component MainWindow inherits Window {
title: root.app-title;
// 默认尺寸取 D16 线框口径;最小尺寸保证 5 列磁贴 + 导航 + AI 栏不挤压
width: 1180px;
height: 760px;
// Metro 一体感:自绘标题栏(components/titlebar.slint)
no-frame: true;
// 无边框窗口必须显式给边缘缩放热区,否则用户无法拖拽改窗口大小
resize-border-width: 4px;
default-font-family: Theme.font-family;
default-font-size: Theme.font-size-body;
// 窗口自身底色必须**不透明**:面板半透明度(panel-alpha)只该透出背景图,不该透到桌面
background: Theme.canvas-solid;
// ── 从 main.rs 灌入的状态 ───────────────────────────────────
in-out property <string> app-title: "Unlucky Launcher";
in property <RouteKind> route: RouteKind.instances;
in property <bool> nav-collapsed: false;
in property <string> account-name: "未登录";
in property <string> account-initial: "?";
in property <color> account-hue: #5C2D91;
in-out property <bool> ai-collapsed: false;
in property <[UiChatMessage]> ai-messages;
in property <bool> ai-streaming: false;
in-out property <bool> yolo: false;
in property <string> ai-endpoint-label: "llama.cpp · 本地";
in-out property <string> ai-draft: "";
in property <[UiTile]> tiles;
in property <[UiTile]> running-tiles;
in property <[UiVersion]> versions;
in property <[UiLogSession]> log-sessions;
in property <[UiLogLine]> log-lines;
in property <UiDiagnosis> diagnosis;
in property <bool> has-diagnosis: false;
in property <string> selected-session: "";
in-out property <TileSize> tile-size: TileSize.medium;
in-out property <InstanceView> instance-view: InstanceView.tiles;
in-out property <string> instance-query: "";
in-out property <SettingSection> settings-section: SettingSection.general;
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
// 系统主题(M41):0 = 未知(回落 Slint 后端),1 = 浅色,2 = 深色
in property <int> system-theme: 0;
/// 后端是否认得系统主题(`false` 时 Rust 侧才需要轮询探测兜底)
out property <bool> system-theme-known: Theme.system-theme-known;
// ── 外观(高级)P1 四件(09 §101-104,出厂全部关闭)──────────────
// 图片由 Rust 灌入(`in`);其余是 in-out:设置页控件会写回,回调里再原样上抛给 Rust。
in property <image> background-image;
in property <image> background-blur;
in-out property <bool> bg-image-enabled: false;
in-out property <string> bg-image: "";
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
in-out property <float> bg-dim: 0.35;
in-out property <float> panel-alpha: 1.0;
in-out property <bool> glass: false;
in-out property <color> accent-color: transparent;
/// 设置页「强调色(十六进制)」输入框的内容(Rust 写入规范化后的值)
in-out property <string> accent-hex: "";
/// 强调色输入是否非法(设置页亮 warn 行)
in-out property <bool> accent-invalid: false;
in-out property <DownloadCategory> download-category: DownloadCategory.release;
in-out property <bool> download-installed-only: false;
in-out property <string> download-query: "";
in property <UiDialog> dialog;
in property <bool> dialog-open: false;
in property <int> dialog-queued: 0;
in property <[UiToast]> toasts;
// 主题/外观:handler 里整体赋值给 `Theme` 全局(Slint 不允许在组件体内给全局属性做绑定,
// 但允许在回调/init 里赋值)。auto 分支由 Theme 自己读系统的 Palette.color-scheme。
init => {
Theme.theme-mode = root.theme-mode;
Theme.system-theme = root.system-theme;
Theme.bg-image = root.background-image;
Theme.bg-blur = root.background-blur;
Theme.bg-dim = root.bg-dim;
Theme.panel-alpha = root.panel-alpha;
Theme.glass = root.glass;
Theme.accent-override = root.accent-color;
}
changed theme-mode => { Theme.theme-mode = root.theme-mode; }
changed system-theme => { Theme.system-theme = root.system-theme; }
changed background-image => { Theme.bg-image = root.background-image; }
changed background-blur => { Theme.bg-blur = root.background-blur; }
changed bg-dim => { Theme.bg-dim = root.bg-dim; }
changed panel-alpha => { Theme.panel-alpha = root.panel-alpha; }
changed glass => { Theme.glass = root.glass; }
changed accent-color => { Theme.accent-override = root.accent-color; }
// ── 用户操作(main.rs 转成 AppCommand 或纯 UI 偏好)──────────────
callback toggle-maximize();
callback minimize();
callback request-close();
callback navigate(RouteKind);
callback toggle-nav();
callback toggle-ai();
callback expand-ai();
callback dock-ai();
callback toggle-yolo();
callback ai-send(string);
callback ai-stop();
callback instance-launch(string);
callback instance-configure(string);
callback instance-stop(string);
callback instance-open(string);
callback new-instance();
callback instance-view-changed(InstanceView);
callback tile-size-changed(TileSize);
callback instance-query-changed(string);
callback download-category-changed(DownloadCategory);
callback download-install(string);
callback installed-only-changed(bool);
callback download-query-changed(string);
callback ancient-help();
callback log-select(string);
callback log-ask-ai(string);
callback log-apply-fix();
callback settings-section-changed(SettingSection);
callback theme-changed(ThemeMode);
callback bg-image-enabled-changed(bool);
callback bg-image-changed(string);
callback bg-fill-changed(BgFillKind);
callback bg-dim-changed(float);
callback panel-alpha-changed(float);
callback glass-changed(bool);
callback accent-color-changed(string);
callback accent-swatch-picked(int);
callback yolo-changed(bool);
callback mcp-changed(bool);
callback ai-endpoint-changed(int);
callback dialog-primary();
callback dialog-secondary();
callback dialog-dismissed();
callback toast-dismissed(string);
AppShell {
app-title: root.app-title;
// 直接复用 Window 的内建 `maximized`(后端随窗口状态更新,无需自建属性)
maximized: root.maximized;
route: root.route;
nav-collapsed: root.nav-collapsed;
account-name: root.account-name;
account-initial: root.account-initial;
account-hue: root.account-hue;
ai-collapsed: root.ai-collapsed;
ai-messages: root.ai-messages;
ai-streaming: root.ai-streaming;
yolo: root.yolo;
ai-endpoint-label: root.ai-endpoint-label;
ai-draft: root.ai-draft;
tiles: root.tiles;
running-tiles: root.running-tiles;
versions: root.versions;
log-sessions: root.log-sessions;
log-lines: root.log-lines;
diagnosis: root.diagnosis;
has-diagnosis: root.has-diagnosis;
selected-session: root.selected-session;
tile-size: root.tile-size;
instance-view: root.instance-view;
instance-query: root.instance-query;
settings-section: root.settings-section;
theme-mode: root.theme-mode;
bg-image-enabled: root.bg-image-enabled;
bg-image: root.bg-image;
bg-fill: root.bg-fill;
bg-dim: root.bg-dim;
panel-alpha: root.panel-alpha;
glass: root.glass;
accent-hex: root.accent-hex;
accent-invalid: root.accent-invalid;
download-category: root.download-category;
download-installed-only: root.download-installed-only;
download-query: root.download-query;
dialog: root.dialog;
dialog-open: root.dialog-open;
dialog-queued: root.dialog-queued;
toasts: root.toasts;
toggle-maximize => { root.toggle-maximize(); }
minimize => { root.minimize(); }
request-close => { root.request-close(); }
navigate(r) => { root.navigate(r); }
toggle-nav => { root.toggle-nav(); }
toggle-ai => { root.toggle-ai(); }
expand-ai => { root.expand-ai(); }
dock-ai => { root.dock-ai(); }
toggle-yolo => { root.toggle-yolo(); }
ai-send(text) => { root.ai-send(text); }
ai-stop => { root.ai-stop(); }
instance-launch(id) => { root.instance-launch(id); }
instance-configure(id) => { root.instance-configure(id); }
instance-stop(id) => { root.instance-stop(id); }
instance-open(id) => { root.instance-open(id); }
new-instance => { root.new-instance(); }
instance-view-changed(view) => {
root.instance-view = view;
root.instance-view-changed(view);
}
tile-size-changed(size) => {
root.tile-size = size;
root.tile-size-changed(size);
}
instance-query-changed(query) => { root.instance-query-changed(query); }
download-category-changed(category) => {
root.download-category = category;
root.download-category-changed(category);
}
download-install(id) => { root.download-install(id); }
download-query-changed(query) => {
root.download-query = query;
root.download-query-changed(query);
}
ancient-help => { root.ancient-help(); }
installed-only-changed(only) => {
root.download-installed-only = only;
root.installed-only-changed(only);
}
log-select(id) => { root.log-select(id); }
log-ask-ai(id) => { root.log-ask-ai(id); }
log-apply-fix => { root.log-apply-fix(); }
settings-section-changed(section) => {
root.settings-section = section;
root.settings-section-changed(section);
}
theme-changed(mode) => {
root.theme-mode = mode;
root.theme-changed(mode);
}
bg-image-enabled-changed(v) => {
root.bg-image-enabled = v;
root.bg-image-enabled-changed(v);
}
bg-image-changed(path) => {
root.bg-image = path;
root.bg-image-changed(path);
}
bg-fill-changed(fill) => {
root.bg-fill = fill;
root.bg-fill-changed(fill);
}
bg-dim-changed(v) => {
root.bg-dim = v;
root.bg-dim-changed(v);
}
panel-alpha-changed(v) => {
root.panel-alpha = v;
root.panel-alpha-changed(v);
}
glass-changed(v) => {
root.glass = v;
root.glass-changed(v);
}
accent-color-changed(text) => {
root.accent-hex = text;
root.accent-color-changed(text);
}
accent-swatch-picked(index) => { root.accent-swatch-picked(index); }
yolo-changed(enabled) => { root.yolo-changed(enabled); }
mcp-changed(enabled) => { root.mcp-changed(enabled); }
ai-endpoint-changed(index) => { root.ai-endpoint-changed(index); }
dialog-primary => { root.dialog-primary(); }
dialog-secondary => { root.dialog-secondary(); }
dialog-dismissed => { root.dialog-dismissed(); }
toast-dismissed(id) => { root.toast-dismissed(id); }
}
}
+218
View File
@@ -0,0 +1,218 @@
// UI 视图模型:Rust 的 dto.rs 做单向转换后喂给 Slint(app 不 import core 内部类型,01c §5)。
// 命名一律 kebab-case,Rust 侧 slint-build 会生成 snake_case 字段。
// 约定:这里只放「界面要显示什么」,不放领域语义(版本继承链、下载源健康度等留在 core)。
// ── 共享枚举 ─────────────────────────────────────────────────────
export enum RouteKind {
instances,
download,
logs,
settings,
detail,
agent,
}
export enum TileSize {
small,
medium,
large,
}
export enum InstanceView {
tiles,
list,
}
/// D17 主题三态:auto 跟随系统(Slint Palette.color-scheme 热更),light/dark 钉死。
/// 键值 `appearance.theme_mode ∈ {light, dark, auto}`,出厂 auto。
export enum ThemeMode {
auto,
light,
dark,
}
/// 背景图填充模式(09 §101:cover / contain / tile)。与 `core::setting::appearance::BgFill` 同序。
export enum BgFillKind {
cover,
contain,
tile,
}
export enum LoaderKind {
vanilla,
fabric,
quilt,
forge,
neoforge,
optifine,
liteloader,
}
export enum RuntimePhase {
idle,
downloading,
verifying,
launching,
running,
failed,
}
export enum ChatRole {
user,
assistant,
tool,
system,
}
export enum DialogKind {
confirm,
input,
progress,
error,
}
export enum ToastKind {
info,
success,
warn,
error,
}
export enum VersionKind {
release,
snapshot,
ancientClassic,
ancientAlpha,
ancientBeta,
ancientUnlisted,
modpack,
mod,
}
// 下载页分类侧栏的选中项(远古版把四个子类提升为平级枚值,便于单选高亮)
export enum DownloadCategory {
release,
snapshot,
ancientClassic,
ancientAlpha,
ancientBeta,
ancientUnlisted,
modpack,
mod,
}
export enum LogOutcome {
ok,
crashed,
silentFail,
}
export enum LogLevel {
debug,
info,
warn,
error,
}
export enum SettingSection {
general,
/// D17「外观(高级)」:主题三态 / 背景图 / 半透明度 / 玻璃拟态 / 强调色 / 动画强度
appearance,
data,
download,
java,
account,
ai,
proxy,
about,
}
// ── 磁贴 ────────────────────────────────────────────────────────
// row/col 由 Rust state.rs 的 tile_grid() 按当前磁贴尺寸算好(小 6 / 中 4 / 大 3 列),
// 这样 Slint 侧 GridLayout 只消费整数位置,不必在 DSL 里做除法。
export struct UiTile {
id: string,
name: string,
mc_version: string,
loader: LoaderKind,
loader_version: string,
/// 加载器徽标文字(「原版」/「Fabric 0.16.5」):由 Rust 侧用 `LoaderInfo::badge()` 拼好,
/// DSL 不做枚举→字符串映射(少一处双份真相)。
loader_label: string,
last_played: string,
phase: RuntimePhase,
/// 启动中阶段文案(「下载资源」/「校验文件」/「启动中」),idle 时为空。
phase_label: string,
/// 0.0~1.0;<= 0 表示进度未知(进度环转为不确定态)。
progress: float,
/// 实例图标;空 image 时退回「名字首字 + hue 底色」占位。
icon: image,
hue: color,
/// 名字首字,无图标时的占位字母(Rust 侧取首个字素)。
initial: string,
row: int,
col: int,
}
// ── 下载页 ──────────────────────────────────────────────────────
export struct UiVersion {
id: string,
kind: VersionKind,
released: string,
installed: bool,
/// 远古版(classic/alpha/beta/unlisted)——列表行带徽标 + 页顶兼容性提示。
ancient: bool,
}
// ── 日志页 ──────────────────────────────────────────────────────
export struct UiLogSession {
id: string,
when: string,
instance: string,
outcome: LogOutcome,
duration: string,
}
export struct UiLogLine {
text: string,
level: LogLevel,
}
/// D8 规则引擎结论(core::diagnose 的 DTO,app 只负责展示)。
export struct UiDiagnosis {
rule: string,
title: string,
confidence: int,
hint: string,
has_fix: bool,
}
// ── AI 栏 ───────────────────────────────────────────────────────
export struct UiChatMessage {
role: ChatRole,
text: string,
/// role == tool 时的工具名。
tool_name: string,
tool_ok: bool,
/// 流式未完成时 true(末尾显示光标块)。
streaming: bool,
}
// ── 对话框 / Toast ──────────────────────────────────────────────
export struct UiDialog {
id: string,
kind: DialogKind,
title: string,
body: string,
primary: string,
secondary: string,
progress: float,
input_label: string,
input_value: string,
}
export struct UiToast {
id: string,
kind: ToastKind,
text: string,
}
+270
View File
@@ -0,0 +1,270 @@
// G2 下载页(09 §2 P0·G2 / Q24-4 定案):页内独立左侧分类栏(常驻,非 tab)+ 右侧版本列表。
// 远古版入口显式可达(ULL 对 HMCL「隐藏」行为的纠偏),下挂 classic/alpha/beta/unlisted 子类树,
// 进入远古版分类时顶部提示兼容性 + 每行带「远古版」徽标(防误装)。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiVersion, VersionKind, DownloadCategory } from "../models.slint";
import { UiText, TextRole } from "../components/label.slint";
import { AppIcon, IconKind } from "../components/icons.slint";
import { Badge } from "../components/badge.slint";
import { MetroButton, ButtonKind } from "../widgets/button.slint";
import { SearchField, CheckBox } from "../widgets/inputs.slint";
import { ListView } from "std-widgets.slint";
component CategoryRow inherits Rectangle {
in property <string> label: "";
in property <bool> active: false;
in property <bool> sub: false;
in property <bool> disabled: false;
callback clicked();
height: 34px;
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
if root.active : Rectangle {
x: 0;
y: 0;
width: 3px;
height: root.height;
background: Theme.accent;
}
UiText {
x: root.sub ? Metrics.gap-5 : Metrics.gap-3;
width: root.width - (root.sub ? Metrics.gap-5 : Metrics.gap-3) - Metrics.gap-2;
height: root.height;
role: TextRole.body;
text: root.label;
color: root.disabled ? Theme.fg-disabled
: root.active ? Theme.accent
: Theme.fg-primary;
}
row-touch := TouchArea {
mouse-cursor: root.disabled ? default : pointer;
clicked => {
if (!root.disabled) {
root.clicked();
}
}
}
}
component VersionRow inherits Rectangle {
in property <UiVersion> data;
callback install();
height: Metrics.row-height + 8px;
background: row-touch.has-hover ? Theme.bg-hover : transparent;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-2;
UiText {
role: TextRole.bodyStrong;
text: root.data.id;
width: 160px;
}
Badge {
text: root.data.kind == VersionKind.release ? "正式版"
: root.data.kind == VersionKind.snapshot ? "预览版"
: "远古版";
tint: root.data.ancient ? Theme.state-warn : Theme.fg-secondary;
}
UiText {
role: TextRole.caption;
text: root.data.released;
horizontal-stretch: 1;
}
if root.data.installed : HorizontalLayout {
spacing: Metrics.gap-1;
AppIcon { kind: IconKind.check; icon-size: 12px; tint: Theme.state-success; }
UiText {
role: TextRole.caption;
text: "已装";
color: Theme.state-success;
}
}
MetroButton {
kind: ButtonKind.standard;
text: root.data.installed ? "重装" : "安装";
button-height: 26px;
clicked => { root.install(); }
}
}
row-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.install(); }
}
}
export component DownloadPage inherits Rectangle {
in property <[UiVersion]> versions;
in-out property <DownloadCategory> category: DownloadCategory.release;
in-out property <bool> installed-only: false;
in-out property <string> query: "";
/// 远古版子类树是否展开(默认展开,显式可达)
in-out property <bool> ancient-expanded: true;
callback category-changed(DownloadCategory);
callback install(string);
callback installed-only-changed(bool);
callback query-changed(string);
callback toggle-ancient();
/// 远古版兼容性说明(P1 出说明页;当前由 Rust 侧弹 Toast 占位)
callback ancient-help();
background: Theme.bg-canvas;
HorizontalLayout {
// ── 页内分类侧栏(常驻)───────────────────────────────────
Rectangle {
width: 200px;
background: Theme.bg-surface;
border-width: 1px;
border-color: Theme.stroke;
VerticalLayout {
padding-top: Metrics.gap-2;
CategoryRow {
label: "正式版 release";
active: root.category == DownloadCategory.release;
clicked => { root.category-changed(DownloadCategory.release); }
}
CategoryRow {
label: "预览版 snapshot";
active: root.category == DownloadCategory.snapshot;
clicked => { root.category-changed(DownloadCategory.snapshot); }
}
// 远古版:可展开的父节点 + 子类树
CategoryRow {
label: root.ancient-expanded ? "远古版 ▾" : "远古版 ▸";
active: root.category == DownloadCategory.ancientClassic
|| root.category == DownloadCategory.ancientAlpha
|| root.category == DownloadCategory.ancientBeta
|| root.category == DownloadCategory.ancientUnlisted;
clicked => { root.toggle-ancient(); }
}
if root.ancient-expanded : CategoryRow {
label: "classic(rd-*)";
sub: true;
active: root.category == DownloadCategory.ancientClassic;
clicked => { root.category-changed(DownloadCategory.ancientClassic); }
}
if root.ancient-expanded : CategoryRow {
label: "old_alpha(a1.*)";
sub: true;
active: root.category == DownloadCategory.ancientAlpha;
clicked => { root.category-changed(DownloadCategory.ancientAlpha); }
}
if root.ancient-expanded : CategoryRow {
label: "old_beta(b1.*)";
sub: true;
active: root.category == DownloadCategory.ancientBeta;
clicked => { root.category-changed(DownloadCategory.ancientBeta); }
}
if root.ancient-expanded : CategoryRow {
label: "unlisted 汇总";
sub: true;
active: root.category == DownloadCategory.ancientUnlisted;
clicked => { root.category-changed(DownloadCategory.ancientUnlisted); }
}
CategoryRow {
label: "整合包(P1)";
disabled: true;
}
CategoryRow {
label: "Mod(P1)";
disabled: true;
}
Rectangle { vertical-stretch: 1; background: transparent; }
}
}
// ── 右侧版本列表 ──────────────────────────────────────────
VerticalLayout {
vertical-stretch: 1;
Rectangle {
height: Metrics.page-header-height;
background: Theme.bg-canvas;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-3;
UiText {
role: TextRole.subtitle;
text: "版本获取";
width: 96px;
}
SearchField {
width: 220px;
placeholder: "筛选版本号";
text <=> root.query;
edited(t) => { root.query-changed(t); }
}
CheckBox {
text: "仅已装";
checked: root.installed-only;
toggled(v) => { root.installed-only-changed(v); }
}
Rectangle { horizontal-stretch: 1; background: transparent; }
}
}
// 远古版兼容性提示条(首次进入显示,显式可达的代价告知)
Rectangle {
height: 44px;
visible: root.category == DownloadCategory.ancientClassic
|| root.category == DownloadCategory.ancientAlpha
|| root.category == DownloadCategory.ancientBeta
|| root.category == DownloadCategory.ancientUnlisted;
background: Theme.state-warn-soft;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-2;
AppIcon { kind: IconKind.warn; icon-size: 16px; tint: Theme.state-warn; }
UiText {
role: TextRole.caption;
text: "远古版(classic/alpha/beta)需要旧版 Java 与旧启动参数,装完请先看兼容性说明。";
wrap: word-wrap;
horizontal-stretch: 1;
}
MetroButton {
kind: ButtonKind.subtle;
text: "说明";
button-height: 26px;
clicked => { root.ancient-help(); }
}
}
}
Rectangle { height: 1px; background: Theme.stroke; }
ListView {
vertical-stretch: 1;
for v in root.versions : VersionRow {
data: v;
install => { root.install(v.id); }
}
}
}
}
}
+260
View File
@@ -0,0 +1,260 @@
// G1 实例页(09 §2 P0·G1):顶栏(搜索/新建/视图切换/磁贴尺寸)+ 磁贴网格 + 运行中迷你状态条。
// 网格用 GridLayout:列数由 Rust 按磁贴尺寸算好(小 6 / 中 4 / 大 3),row/col 随 UiTile 一起给。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiTile, InstanceView, TileSize, RuntimePhase } from "../models.slint";
import { UiText, TextRole } from "../components/label.slint";
import { AppIcon, IconKind } from "../components/icons.slint";
import { MetroButton, ButtonKind } from "../widgets/button.slint";
import { SearchField, SegmentedControl } from "../widgets/inputs.slint";
import { InstanceTile } from "../components/tile.slint";
import { ListView } from "std-widgets.slint";
// 列表视图的一行(与磁贴共用同一份 UiTile 数据)
component InstanceRow inherits Rectangle {
in property <UiTile> data;
callback open();
callback launch();
height: Metrics.row-height + 8px;
background: row-touch.has-hover ? Theme.bg-hover : transparent;
// 行点击区先声明,按钮后声明 → 按钮命中优先
row-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.open(); }
}
HorizontalLayout {
padding-left: Metrics.gap-3;
padding-right: Metrics.gap-3;
spacing: Metrics.gap-3;
Rectangle {
width: 28px;
height: 28px;
border-radius: Metrics.radius-sm;
background: root.data.hue;
UiText {
text: root.data.initial;
font-size: 13px;
font-weight: 600;
color: Theme.fg-on-accent;
horizontal-alignment: center;
vertical-alignment: center;
}
}
UiText {
role: TextRole.body;
text: root.data.name;
horizontal-stretch: 1;
}
UiText {
role: TextRole.caption;
text: root.data.mc_version;
width: 88px;
}
UiText {
role: TextRole.caption;
text: root.data.loader_label;
width: 88px;
}
UiText {
role: TextRole.caption;
text: root.data.last_played;
width: 120px;
}
MetroButton {
kind: ButtonKind.subtle;
icon: IconKind.play;
icon-only: true;
enabled: root.data.phase == RuntimePhase.idle
|| root.data.phase == RuntimePhase.failed;
clicked => { root.launch(); }
}
}
}
export component InstancesPage inherits Rectangle {
in property <[UiTile]> tiles;
in property <[UiTile]> running;
in property <InstanceView> view: InstanceView.tiles;
in-out property <TileSize> tile-size: TileSize.medium;
in-out property <string> query: "";
callback launch(string);
callback configure(string);
callback stop(string);
callback open(string);
callback new-instance();
callback view-changed(InstanceView);
callback tile-size-changed(TileSize);
callback query-changed(string);
background: Theme.bg-canvas;
VerticalLayout {
// ── 顶栏 ────────────────────────────────────────────────
Rectangle {
height: Metrics.page-header-height;
background: Theme.bg-surface;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-2;
UiText {
role: TextRole.subtitle;
text: "实例";
width: 72px;
}
SearchField {
width: 240px;
placeholder: "搜索实例";
text <=> root.query;
edited(t) => { root.query-changed(t); }
}
Rectangle { horizontal-stretch: 1; background: transparent; }
SegmentedControl {
width: 120px;
options: ["磁贴", "列表"];
selected: root.view == InstanceView.tiles ? 0 : 1;
changed(i) => {
root.view-changed(i == 0 ? InstanceView.tiles : InstanceView.list);
}
}
SegmentedControl {
width: 132px;
visible: root.view == InstanceView.tiles;
options: ["小", "中", "大"];
selected: root.tile-size == TileSize.small ? 0
: root.tile-size == TileSize.large ? 2 : 1;
changed(i) => {
root.tile-size-changed(
i == 0 ? TileSize.small : i == 2 ? TileSize.large : TileSize.medium);
}
}
MetroButton {
kind: ButtonKind.accent;
text: "新建实例";
show-icon: true;
icon: IconKind.plus;
clicked => { root.new-instance(); }
}
}
}
Rectangle { height: 1px; background: Theme.stroke; }
// ── 运行中迷你状态条 ──────────────────────────────────────
Rectangle {
height: Metrics.running-strip-height;
visible: root.running.length > 0;
background: Theme.state-info-soft;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-2;
Rectangle {
width: 8px;
height: 8px;
border-radius: 4px;
background: Theme.state-success;
}
UiText {
role: TextRole.caption;
text: root.running.length + " 个实例运行中";
color: Theme.state-success;
horizontal-stretch: 1;
}
for r in root.running : UiText {
role: TextRole.caption;
text: r.name;
}
}
}
// ── 磁贴网格 ─────────────────────────────────────────────
body := Flickable {
vertical-stretch: 1;
visible: root.view == InstanceView.tiles && root.tiles.length > 0;
content-width: self.width;
content-height: grid-content.height;
grid-content := Rectangle {
width: body.width;
height: grid.preferred-height;
background: transparent;
grid := GridLayout {
padding: Metrics.gap-4;
spacing: Metrics.gap-3;
for t in root.tiles : InstanceTile {
row: t.row;
col: t.col;
data: t;
compact: root.tile-size == TileSize.small;
open => { root.open(t.id); }
launch => { root.launch(t.id); }
configure => { root.configure(t.id); }
stop => { root.stop(t.id); }
}
}
}
}
// ── 列表视图 ─────────────────────────────────────────────
ListView {
vertical-stretch: 1;
visible: root.view == InstanceView.list && root.tiles.length > 0;
for t in root.tiles : InstanceRow {
data: t;
open => { root.open(t.id); }
launch => { root.launch(t.id); }
}
}
// ── 空态 ────────────────────────────────────────────────
VerticalLayout {
vertical-stretch: 1;
visible: root.tiles.length == 0;
alignment: center;
spacing: Metrics.gap-3;
UiText {
role: TextRole.title;
text: "还没有实例";
horizontal-alignment: center;
color: Theme.fg-secondary;
}
UiText {
role: TextRole.caption;
text: "新建一个实例,或者先去下载页装个版本";
horizontal-alignment: center;
}
HorizontalLayout {
alignment: center;
MetroButton {
kind: ButtonKind.accent;
text: "新建实例";
show-icon: true;
icon: IconKind.plus;
clicked => { root.new-instance(); }
}
}
}
}
}
+259
View File
@@ -0,0 +1,259 @@
// G3 日志页(09 §2 P0·G3):左侧会话列表(✓正常 / ✗崩溃 / ⚠静默失败)+ 右侧日志流 + 崩溃诊断卡片。
// 诊断卡片 = D8 规则引擎结论(命中规则 + 置信度 + 修复动作 + 跳 AI 栏带上下文)。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { UiLogSession, UiLogLine, UiDiagnosis, LogOutcome, LogLevel } from "../models.slint";
import { UiText, TextRole } from "../components/label.slint";
import { AppIcon, IconKind } from "../components/icons.slint";
import { Badge } from "../components/badge.slint";
import { MetroButton, ButtonKind } from "../widgets/button.slint";
import { SearchField } from "../widgets/inputs.slint";
import { ListView } from "std-widgets.slint";
component SessionRow inherits Rectangle {
in property <UiLogSession> data;
in property <bool> active: false;
callback clicked();
height: 52px;
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
if root.active : Rectangle {
x: 0;
y: 0;
width: 3px;
height: root.height;
background: Theme.accent;
}
HorizontalLayout {
padding-left: Metrics.gap-3;
padding-right: Metrics.gap-2;
spacing: Metrics.gap-2;
AppIcon {
icon-size: 14px;
kind: root.data.outcome == LogOutcome.ok ? IconKind.check
: root.data.outcome == LogOutcome.crashed ? IconKind.error
: IconKind.warn;
tint: root.data.outcome == LogOutcome.ok ? Theme.state-success
: root.data.outcome == LogOutcome.crashed ? Theme.state-danger
: Theme.state-warn;
}
VerticalLayout {
spacing: 0px;
vertical-stretch: 1;
UiText {
role: TextRole.body;
text: root.data.instance;
horizontal-stretch: 1;
}
UiText {
role: TextRole.caption;
text: root.data.when;
horizontal-stretch: 1;
}
}
UiText {
role: TextRole.caption;
text: root.data.duration;
width: 56px;
horizontal-alignment: right;
}
}
row-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.clicked(); }
}
}
component LogRow inherits Rectangle {
in property <UiLogLine> line;
height: 18px;
background: root.line.level == LogLevel.error
? Theme.state-danger-soft
: transparent;
UiText {
x: Metrics.gap-2;
y: 0;
width: root.width - 2 * Metrics.gap-2;
height: root.height;
role: TextRole.monoSmall;
text: root.line.text;
color: root.line.level == LogLevel.error ? Theme.state-danger
: root.line.level == LogLevel.warn ? Theme.state-warn
: root.line.level == LogLevel.debug ? Theme.fg-disabled
: Theme.fg-primary;
}
}
export component LogsPage inherits Rectangle {
in property <[UiLogSession]> sessions;
in property <[UiLogLine]> lines;
in property <UiDiagnosis> diagnosis;
in property <bool> has-diagnosis: false;
in property <bool> live: false;
in-out property <string> selected: "";
in-out property <string> query: "";
callback select(string);
callback ask-ai(string);
callback apply-fix();
callback query-changed(string);
background: Theme.bg-canvas;
HorizontalLayout {
// ── 左侧会话列表 ─────────────────────────────────────────
Rectangle {
width: 248px;
background: Theme.bg-surface;
VerticalLayout {
Rectangle {
height: 44px;
background: transparent;
HorizontalLayout {
padding-left: Metrics.gap-3;
padding-right: Metrics.gap-2;
spacing: Metrics.gap-2;
UiText {
role: TextRole.bodyStrong;
text: "会话";
horizontal-stretch: 1;
}
if root.live : Rectangle {
width: 6px;
height: 6px;
border-radius: 3px;
background: Theme.state-success;
}
}
}
ListView {
vertical-stretch: 1;
for s in root.sessions : SessionRow {
data: s;
active: root.selected == s.id;
clicked => { root.select(s.id); }
}
}
}
}
Rectangle { width: 1px; background: Theme.stroke; }
// ── 右侧日志流 + 诊断卡片 ────────────────────────────────
VerticalLayout {
vertical-stretch: 1;
Rectangle {
height: 44px;
background: Theme.bg-surface;
HorizontalLayout {
padding-left: Metrics.gap-3;
padding-right: Metrics.gap-3;
spacing: Metrics.gap-2;
UiText {
role: TextRole.bodyStrong;
text: root.selected == "" ? "未选择会话" : root.selected;
horizontal-stretch: 1;
}
SearchField {
width: 200px;
placeholder: "筛选日志行";
text <=> root.query;
edited(t) => { root.query-changed(t); }
}
MetroButton {
kind: ButtonKind.subtle;
text: "打开目录";
button-height: 26px;
}
}
}
Rectangle { height: 1px; background: Theme.stroke; }
// 崩溃诊断卡片(D8)
Rectangle {
height: root.has-diagnosis ? 76px : 0px;
visible: root.has-diagnosis;
background: Theme.state-danger-soft;
HorizontalLayout {
padding: Metrics.gap-3;
spacing: Metrics.gap-3;
AppIcon { kind: IconKind.error; icon-size: 20px; tint: Theme.state-danger; }
VerticalLayout {
spacing: 2px;
vertical-stretch: 1;
HorizontalLayout {
spacing: Metrics.gap-2;
UiText {
role: TextRole.bodyStrong;
text: root.diagnosis.title;
horizontal-stretch: 1;
}
Badge {
text: "置信度 " + root.diagnosis.confidence + "%";
tint: Theme.state-danger;
}
}
UiText {
role: TextRole.caption;
text: root.diagnosis.hint;
horizontal-stretch: 1;
}
}
VerticalLayout {
spacing: Metrics.gap-1;
alignment: center;
if root.diagnosis.has_fix : MetroButton {
kind: ButtonKind.standard;
text: "修复建议";
button-height: 26px;
clicked => { root.apply-fix(); }
}
MetroButton {
kind: ButtonKind.subtle;
text: "让 AI 详解";
button-height: 26px;
clicked => { root.ask-ai(root.selected); }
}
}
}
}
// 日志流(行虚拟化)
Rectangle {
vertical-stretch: 1;
background: Theme.bg-canvas;
ListView {
for l in root.lines : LogRow {
line: l;
width: root.width;
}
}
}
}
}
}
@@ -0,0 +1,146 @@
// 设置页「外观」分组(09 §2 G6 + §113 D17 定案):主题三态 + 「外观(高级)」P1 四件。
//
// 从 pages/settings.slint 拆出来只为守住 400 行门槛;控件语义与设置键一一对应:
// theme-mode → appearance.theme_mode / bg-* → appearance.bg_image* / panel-alpha →
// appearance.panel_alpha / glass → appearance.glass / accent-color → appearance.accent_color。
// 09 §111 硬约束:高级特性全部默认关闭,开启背景图时这里会给出对比度提示(warn 行)。
import { Theme } from "../theme/tokens.slint";
import { ThemeMode, BgFillKind } from "../models.slint";
import { SettingItem, SettingGroup, ControlKind } from "../widgets/setting-item.slint";
export component AppearanceSection inherits VerticalLayout {
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
in-out property <bool> bg-image-enabled: false;
in-out property <string> bg-image: "";
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
in-out property <float> bg-dim: 0.35;
in-out property <float> panel-alpha: 1.0;
in-out property <bool> glass: false;
in-out property <string> accent-color: "";
in property <bool> accent-invalid: false;
callback theme-changed(ThemeMode);
callback bg-image-enabled-changed(bool);
callback bg-image-changed(string);
callback bg-fill-changed(BgFillKind);
callback bg-dim-changed(float);
callback panel-alpha-changed(float);
callback glass-changed(bool);
callback accent-color-changed(string);
callback accent-swatch-picked(int);
// ── 外观(D17:主题三态 + 09 §101-104 高级四件)──────
SettingGroup { title: "主题"; }
SettingItem {
label: "主题模式";
description: "跟随系统(Auto,随 OS 热切)/ 浅色 / 深色";
kind: ControlKind.segmented;
options: ["跟随系统", "浅色", "深色"];
selected: root.theme-mode == ThemeMode.auto ? 0
: root.theme-mode == ThemeMode.light ? 1 : 2;
changed(i) => {
root.theme-mode = i == 0 ? ThemeMode.auto
: i == 1 ? ThemeMode.light : ThemeMode.dark;
root.theme-changed(root.theme-mode);
}
}
SettingGroup {
title: "高级特性(出厂全部关闭,开启后请确认前景可读)";
}
// ① 自定义窗口背景图(09 §101)
SettingItem {
label: "自定义窗口背景图";
description: "PNG 图片铺满窗口;开启后所有面板半透明处都会透出它";
kind: ControlKind.toggle;
checked: root.bg-image-enabled;
toggled(v) => {
root.bg-image-enabled = v;
root.bg-image-enabled-changed(v);
}
}
SettingItem {
label: "背景图路径";
description: root.bg-image == "" ? "尚未选择(绝对路径,例:D:/wall/p.png)" : root.bg-image;
kind: ControlKind.text;
button-text: "D:/wall/p.png";
value <=> root.bg-image;
edited(t) => { root.bg-image-changed(t); }
}
SettingItem {
label: "填充模式";
description: "铺满(裁切)/ 完整(留底色)/ 平铺";
kind: ControlKind.segmented;
options: ["铺满", "完整", "平铺"];
selected: root.bg-fill == BgFillKind.cover ? 0
: root.bg-fill == BgFillKind.contain ? 1 : 2;
changed(i) => {
root.bg-fill = i == 0 ? BgFillKind.cover
: i == 1 ? BgFillKind.contain : BgFillKind.tile;
root.bg-fill-changed(root.bg-fill);
}
}
SettingItem {
label: "暗化层强度";
// 09 §111:开启背景图时自动给对比度提示——暗化太低 + 面板太透会伤可读性
description: (root.bg-image-enabled && (root.bg-dim < 0.25 || root.panel-alpha < 0.8))
? "⚠ 对比度偏低:建议暗化 ≥ 25% 或面板不透明度 ≥ 80%"
: "越大背景越暗、前景越清晰(0% = 不压暗)";
warn: root.bg-image-enabled && (root.bg-dim < 0.25 || root.panel-alpha < 0.8);
kind: ControlKind.slider;
min-value: 0.0;
max-value: 0.9;
slider-value: root.bg-dim;
slid(v) => {
root.bg-dim = v;
root.bg-dim-changed(v);
}
}
// ② 全局面板半透明度(09 §102)
SettingItem {
label: "全局面板半透明度";
description: "卡片 / 导航 / AI 栏统一透明度(100% = 出厂 Metro 纯色)";
kind: ControlKind.slider;
min-value: 0.4;
max-value: 1.0;
slider-value: root.panel-alpha;
slid(v) => {
root.panel-alpha = v;
root.panel-alpha-changed(v);
}
}
// ③ 玻璃拟态卡片(09 §103)
SettingItem {
label: "玻璃拟态卡片";
description: "卡片底铺背景图的预生成模糊层(需先开启背景图)";
kind: ControlKind.toggle;
checked: root.glass;
toggled(v) => {
root.glass = v;
root.glass-changed(v);
}
}
// ④ 自定义强调色(09 §104)
SettingItem {
label: "预设强调色";
description: root.accent-color == "" ? "当前:出厂 Metro 蓝" : "当前:" + root.accent-color;
kind: ControlKind.swatches;
swatch-colors: [
#0078D4, #0F6CBD, #107C10, #9D5D00,
#C42B1C, #8764B8, #C239B3, #00B7C3,
];
swatch-current: root.accent-color == "" ? #0078D4 : Theme.accent;
swatch-picked(i) => { root.accent-swatch-picked(i); }
}
SettingItem {
label: "强调色(十六进制)";
description: root.accent-invalid
? "⚠ 需要 #RRGGBB 形式,留空恢复出厂蓝"
: "留空 = 出厂 #0078D4;影响顶线 / 选中态 / 按钮 / 徽标";
warn: root.accent-invalid;
kind: ControlKind.text;
button-text: "#0078D4";
value <=> root.accent-color;
edited(t) => { root.accent-color-changed(t); }
}
}
+363
View File
@@ -0,0 +1,363 @@
// G6 设置页(09 §2 P0·G6):左子导航 + 右表单 + 搜索框(设置项多,防迷路)。
// 「通用 / 外观(D17 三态 + 09 §101-104 高级四件,实现在 settings-appearance.slint)/ 数据 / AI /
// 关于」是真实控件,Java / 账户 / 代理分组仍是入口按钮(等各自 mission 接实现)。
// 关于页内嵌 AboutSlint —— Slint RF 2.0 许可义务(01c §8:关于页放官方部件)。
import { Theme } from "../theme/tokens.slint";
import { Metrics } from "../theme/metrics.slint";
import { SettingSection, TileSize, ThemeMode, BgFillKind } from "../models.slint";
import { UiText, TextRole } from "../components/label.slint";
import { SettingItem, SettingGroup, ControlKind } from "../widgets/setting-item.slint";
import { AppearanceSection } from "settings-appearance.slint";
import { SearchField } from "../widgets/inputs.slint";
import { AboutSlint, ScrollView } from "std-widgets.slint";
component SectionRow inherits Rectangle {
in property <string> label: "";
in property <SettingSection> section: SettingSection.general;
in property <bool> active: false;
callback clicked();
height: 36px;
background: root.active ? Theme.accent-soft : (row-touch.has-hover ? Theme.bg-hover : transparent);
if root.active : Rectangle {
x: 0;
y: 0;
width: 3px;
height: root.height;
background: Theme.accent;
}
UiText {
x: Metrics.gap-3;
y: 0;
width: root.width - Metrics.gap-3 - Metrics.gap-2;
height: root.height;
role: TextRole.body;
text: root.label;
color: root.active ? Theme.accent : Theme.fg-primary;
}
row-touch := TouchArea {
mouse-cursor: pointer;
clicked => { root.clicked(); }
}
}
export component SettingsPage inherits Rectangle {
in-out property <SettingSection> section: SettingSection.general;
in-out property <string> query: "";
// 外观(D17:主题三态 + 09 §101-104 高级特性四件)
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
in-out property <bool> bg-image-enabled: false;
in-out property <string> bg-image: "";
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
in-out property <float> bg-dim: 0.35;
in-out property <float> panel-alpha: 1.0;
in-out property <bool> glass: false;
in-out property <string> accent-color: "";
in property <bool> accent-invalid: false;
// 通用
in-out property <TileSize> tile-size: TileSize.medium;
in-out property <bool> close-to-tray: true;
// 数据
in-out property <int> data-mode: 0;
in property <string> data-path: "";
// 下载
in-out property <int> download-concurrency: 1;
in property <string> region-label: "未知";
// 账户
in property <string> account-label: "未登录";
// AI
in-out property <int> ai-endpoint: 0;
in-out property <bool> yolo: false;
in-out property <bool> mcp-enabled: false;
// 代理
in-out property <string> proxy: "";
// 关于
in property <string> version: "";
callback section-changed(SettingSection);
callback query-changed(string);
callback theme-changed(ThemeMode);
callback bg-image-enabled-changed(bool);
callback bg-image-changed(string);
callback bg-fill-changed(BgFillKind);
callback bg-dim-changed(float);
callback panel-alpha-changed(float);
callback glass-changed(bool);
callback accent-color-changed(string);
callback accent-swatch-picked(int);
callback tile-size-changed(TileSize);
callback close-to-tray-changed(bool);
callback data-mode-changed(int);
callback download-concurrency-changed(int);
callback ai-endpoint-changed(int);
callback yolo-changed(bool);
callback mcp-changed(bool);
callback proxy-changed(string);
callback migrate-data();
callback login();
callback manage-java();
callback open-audit-log();
callback detect-region();
background: Theme.bg-canvas;
HorizontalLayout {
// ── 左子导航 ──────────────────────────────────────────────
Rectangle {
width: 200px;
background: Theme.bg-surface;
VerticalLayout {
padding-top: Metrics.gap-2;
SectionRow { label: "通用"; section: SettingSection.general; active: root.section == SettingSection.general; clicked => { root.section-changed(SettingSection.general); } }
SectionRow { label: "外观"; section: SettingSection.appearance; active: root.section == SettingSection.appearance; clicked => { root.section-changed(SettingSection.appearance); } }
SectionRow { label: "数据"; section: SettingSection.data; active: root.section == SettingSection.data; clicked => { root.section-changed(SettingSection.data); } }
SectionRow { label: "下载"; section: SettingSection.download; active: root.section == SettingSection.download; clicked => { root.section-changed(SettingSection.download); } }
SectionRow { label: "Java"; section: SettingSection.java; active: root.section == SettingSection.java; clicked => { root.section-changed(SettingSection.java); } }
SectionRow { label: "账户"; section: SettingSection.account; active: root.section == SettingSection.account; clicked => { root.section-changed(SettingSection.account); } }
SectionRow { label: "AI"; section: SettingSection.ai; active: root.section == SettingSection.ai; clicked => { root.section-changed(SettingSection.ai); } }
SectionRow { label: "代理"; section: SettingSection.proxy; active: root.section == SettingSection.proxy; clicked => { root.section-changed(SettingSection.proxy); } }
SectionRow { label: "关于"; section: SettingSection.about; active: root.section == SettingSection.about; clicked => { root.section-changed(SettingSection.about); } }
Rectangle { vertical-stretch: 1; background: transparent; }
}
}
Rectangle { width: 1px; background: Theme.stroke; }
// ── 右表单 ────────────────────────────────────────────────
VerticalLayout {
vertical-stretch: 1;
Rectangle {
height: Metrics.page-header-height;
background: Theme.bg-surface;
HorizontalLayout {
padding-left: Metrics.gap-4;
padding-right: Metrics.gap-4;
spacing: Metrics.gap-3;
UiText {
role: TextRole.subtitle;
text: "设置";
width: 72px;
}
SearchField {
width: 240px;
placeholder: "搜索设置项";
text <=> root.query;
edited(t) => { root.query-changed(t); }
}
Rectangle { horizontal-stretch: 1; background: transparent; }
}
}
Rectangle { height: 1px; background: Theme.stroke; }
ScrollView {
vertical-stretch: 1;
VerticalLayout {
padding-bottom: Metrics.gap-5;
// 外观(D17:主题三态 + 09 §101-104 高级四件;实现在 settings-appearance.slint)
if root.section == SettingSection.appearance : AppearanceSection {
theme-mode: root.theme-mode;
bg-image-enabled: root.bg-image-enabled;
bg-image: root.bg-image;
bg-fill: root.bg-fill;
bg-dim: root.bg-dim;
panel-alpha: root.panel-alpha;
glass: root.glass;
accent-color: root.accent-color;
accent-invalid: root.accent-invalid;
theme-changed(m) => {
root.theme-mode = m;
root.theme-changed(m);
}
bg-image-enabled-changed(v) => {
root.bg-image-enabled = v;
root.bg-image-enabled-changed(v);
}
bg-image-changed(t) => {
root.bg-image = t;
root.bg-image-changed(t);
}
bg-fill-changed(f) => {
root.bg-fill = f;
root.bg-fill-changed(f);
}
bg-dim-changed(v) => {
root.bg-dim = v;
root.bg-dim-changed(v);
}
panel-alpha-changed(v) => {
root.panel-alpha = v;
root.panel-alpha-changed(v);
}
glass-changed(v) => {
root.glass = v;
root.glass-changed(v);
}
accent-color-changed(t) => {
root.accent-color = t;
root.accent-color-changed(t);
}
accent-swatch-picked(i) => { root.accent-swatch-picked(i); }
}
// ── 通用 ────────────────────────────────────────
if root.section == SettingSection.general : SettingGroup { title: "外观"; }
if root.section == SettingSection.general : SettingItem {
label: "磁贴尺寸";
description: "小 6 列 / 中 4 列(默认)/ 大 3 列";
kind: ControlKind.segmented;
options: ["小", "中", "大"];
selected: root.tile-size == TileSize.small ? 0
: root.tile-size == TileSize.large ? 2 : 1;
changed(i) => {
root.tile-size-changed(
i == 0 ? TileSize.small : i == 2 ? TileSize.large : TileSize.medium);
}
}
if root.section == SettingSection.general : SettingItem {
label: "关闭窗口时最小化到托盘";
description: "避免误关正在运行的游戏";
kind: ControlKind.toggle;
checked: root.close-to-tray;
toggled(v) => { root.close-to-tray-changed(v); }
}
// ── 数据 ────────────────────────────────────────
if root.section == SettingSection.data : SettingGroup { title: "数据目录(D6 三模式)"; }
if root.section == SettingSection.data : SettingItem {
label: "存储模式";
description: "便携(运行目录 .ULL/.minecraft)/ 标准(系统应用数据目录)/ 自定义";
kind: ControlKind.segmented;
options: ["便携", "标准", "自定义"];
selected: root.data-mode;
changed(i) => {
root.data-mode = i;
root.data-mode-changed(i);
}
}
if root.section == SettingSection.data : SettingItem {
label: "当前路径";
description: root.data-path;
kind: ControlKind.button;
button-text: "迁移…";
clicked => { root.migrate-data(); }
}
// ── 下载 ────────────────────────────────────────
if root.section == SettingSection.download : SettingGroup { title: "下载(D7)"; }
if root.section == SettingSection.download : SettingItem {
label: "并发数";
kind: ControlKind.segmented;
options: ["4", "8", "16"];
selected: root.download-concurrency;
changed(i) => {
root.download-concurrency = i;
root.download-concurrency-changed(i);
}
}
if root.section == SettingSection.download : SettingItem {
label: "地区判定";
description: "当前:" + root.region-label + "(决定是否走国内镜像)";
kind: ControlKind.button;
button-text: "重新检测";
clicked => { root.detect-region(); }
}
// ── Java ────────────────────────────────────────
if root.section == SettingSection.java : SettingGroup { title: "Java(D13)"; }
if root.section == SettingSection.java : SettingItem {
label: "Java 管理";
description: "基准 JDK17 自动下载 · 多版本可选 · 不匹配时黄条提示";
kind: ControlKind.button;
button-text: "管理多版本";
clicked => { root.manage-java(); }
}
// ── 账户 ────────────────────────────────────────
if root.section == SettingSection.account : SettingGroup { title: "账户(D9)"; }
if root.section == SettingSection.account : SettingItem {
label: "当前账户";
description: root.account-label;
kind: ControlKind.button;
button-text: "登录 / 切换";
clicked => { root.login(); }
}
// ── AI ──────────────────────────────────────────
if root.section == SettingSection.ai : SettingGroup { title: "AI 助手(D4)"; }
if root.section == SettingSection.ai : SettingItem {
label: "模型端点";
description: "OpenAI 兼容 / 本地 llama.cpp / Anthropic / 自定义";
kind: ControlKind.segmented;
options: ["OpenAI", "llama.cpp", "Anthropic", "自定义"];
selected: root.ai-endpoint;
changed(i) => {
root.ai-endpoint = i;
root.ai-endpoint-changed(i);
}
}
if root.section == SettingSection.ai : SettingItem {
label: "YOLO 模式";
description: "跳过全部确认弹窗(审计照记),账户/凭据操作永不 YOLO";
kind: ControlKind.toggle;
checked: root.yolo;
toggled(v) => { root.yolo-changed(v); }
}
if root.section == SettingSection.ai : SettingItem {
label: "MCP server";
description: "允许外部客户端(如 Claude Desktop)调用工具集";
kind: ControlKind.toggle;
checked: root.mcp-enabled;
toggled(v) => { root.mcp-changed(v); }
}
if root.section == SettingSection.ai : SettingItem {
label: "审计日志";
description: "AI 的所有写操作都有记录";
kind: ControlKind.button;
button-text: "查看";
clicked => { root.open-audit-log(); }
}
// ── 代理 ────────────────────────────────────────
if root.section == SettingSection.proxy : SettingGroup { title: "代理"; }
if root.section == SettingSection.proxy : SettingItem {
label: "HTTP 代理";
description: "留空则使用系统代理";
kind: ControlKind.text;
button-text: "http://127.0.0.1:7890";
value <=> root.proxy;
edited(t) => { root.proxy-changed(t); }
}
// ── 关于 ────────────────────────────────────────
if root.section == SettingSection.about : SettingGroup { title: "关于"; }
if root.section == SettingSection.about : SettingItem {
label: "版本";
description: root.version;
}
if root.section == SettingSection.about : SettingItem {
label: "许可";
description: "Apache-2.0(Slint 走 RF 2.0 轨道)";
}
if root.section == SettingSection.about : Rectangle {
height: 120px;
AboutSlint { }
}
}
}
}
}
}
+373
View File
@@ -0,0 +1,373 @@
// 主窗口框架(D16 §1):无边框标题栏 + 左侧可折叠导航 + 内容区路由 + 右侧 AI 常驻栏 + 对话框/Toast 覆盖层。
// 这里只做「组装 + 路由转发」,状态全在 Rust 侧(state.rs),Slint 不持有业务真相。
// main.slint(阶段 B 接线)只负责实例化 AppShell 并把 Window 的窗口事件接上。
import { Theme } from "theme/tokens.slint";
import { Metrics } from "theme/metrics.slint";
import {
RouteKind, TileSize, InstanceView, SettingSection, DownloadCategory, ThemeMode, BgFillKind,
UiTile, UiVersion, UiLogSession, UiLogLine, UiDiagnosis, UiChatMessage, UiDialog, UiToast,
} from "models.slint";
import { TitleBar } from "components/titlebar.slint";
import { Nav } from "components/nav.slint";
import { AiPanel } from "components/ai-panel.slint";
import { UiText, TextRole } from "components/label.slint";
import { MetroButton, ButtonKind } from "widgets/button.slint";
import { DialogHost } from "widgets/dialog.slint";
import { ToastHost } from "widgets/toast.slint";
import { InstancesPage } from "pages/instances.slint";
import { DownloadPage } from "pages/download.slint";
import { LogsPage } from "pages/logs.slint";
import { SettingsPage } from "pages/settings.slint";
export component AppShell inherits Rectangle {
// ── 窗口 ────────────────────────────────────────────────────
in property <string> app-title: "Unlucky Launcher";
in property <bool> maximized: false;
// ── 路由 ────────────────────────────────────────────────────
in property <RouteKind> route: RouteKind.instances;
// ── 导航 / 账户 ──────────────────────────────────────────────
in property <bool> nav-collapsed: false;
in property <string> account-name: "未登录";
in property <string> account-initial: "?";
in property <color> account-hue: #5C2D91;
// ── AI 栏(双形态共享同一份会话)──────────────────────────────
in property <bool> ai-collapsed: false;
in property <[UiChatMessage]> ai-messages;
in property <bool> ai-streaming: false;
in property <bool> yolo: false;
in property <string> ai-endpoint-label: "llama.cpp · 本地";
in-out property <string> ai-draft: "";
// ── 页面数据 ────────────────────────────────────────────────
in property <[UiTile]> tiles;
in property <[UiTile]> running-tiles;
in property <[UiVersion]> versions;
in property <[UiLogSession]> log-sessions;
in property <[UiLogLine]> log-lines;
in property <UiDiagnosis> diagnosis;
in property <bool> has-diagnosis: false;
in property <string> selected-session: "";
// ── 偏好(持久化键见 SubAgentsTalk/app-DTO通道约定.md)──────────
in-out property <TileSize> tile-size: TileSize.medium;
in-out property <InstanceView> instance-view: InstanceView.tiles;
in-out property <string> instance-query: "";
in-out property <SettingSection> settings-section: SettingSection.general;
/// D17 主题三态(auto 跟随系统;light/dark 钉死)。Rust 侧同时写 Theme 全局。
in-out property <ThemeMode> theme-mode: ThemeMode.auto;
/// 外观(高级)四件的 in-out 通道:MainWindow ↔ SettingsPage(图片本身走 `Theme.bg-image`)
in-out property <bool> bg-image-enabled: false;
in-out property <string> bg-image: "";
in-out property <BgFillKind> bg-fill: BgFillKind.cover;
in-out property <float> bg-dim: 0.35;
in-out property <float> panel-alpha: 1.0;
in-out property <bool> glass: false;
/// 设置页编辑的十六进制串(`accent-color` 是解析后的颜色,只给 Theme 用)
in-out property <string> accent-hex: "";
/// 强调色输入是否非法(设置页亮 warn 行)
in-out property <bool> accent-invalid: false;
in-out property <DownloadCategory> download-category: DownloadCategory.release;
in-out property <bool> download-installed-only: false;
/// 下载页版本号筛选词(输入由页面写回,state.download_query 参与过滤)
in-out property <string> download-query: "";
// ── 对话框队列 / Toast ───────────────────────────────────────
in property <UiDialog> dialog;
in property <bool> dialog-open: false;
in property <int> dialog-queued: 0;
in property <[UiToast]> toasts;
// ── 窗口控制(拖拽走 WindowMoveArea,不需要 Rust 参与)────────
callback toggle-maximize();
callback minimize();
callback request-close();
// ── 导航 / AI ───────────────────────────────────────────────
callback navigate(RouteKind);
callback toggle-nav();
callback toggle-ai();
callback expand-ai();
callback dock-ai();
callback toggle-yolo();
callback ai-send(string);
callback ai-stop();
// ── 实例页 ──────────────────────────────────────────────────
callback instance-launch(string);
callback instance-configure(string);
callback instance-stop(string);
callback instance-open(string);
callback new-instance();
callback instance-view-changed(InstanceView);
callback tile-size-changed(TileSize);
callback instance-query-changed(string);
// ── 下载页 ──────────────────────────────────────────────────
callback download-category-changed(DownloadCategory);
callback download-install(string);
callback installed-only-changed(bool);
callback download-query-changed(string);
callback ancient-help();
// ── 日志页 ──────────────────────────────────────────────────
callback log-select(string);
callback log-ask-ai(string);
callback log-apply-fix();
// ── 设置页 ──────────────────────────────────────────────────
callback settings-section-changed(SettingSection);
callback theme-changed(ThemeMode);
callback bg-image-enabled-changed(bool);
callback bg-image-changed(string);
callback bg-fill-changed(BgFillKind);
callback bg-dim-changed(float);
callback panel-alpha-changed(float);
callback glass-changed(bool);
callback accent-color-changed(string);
callback accent-swatch-picked(int);
callback yolo-changed(bool);
callback mcp-changed(bool);
callback ai-endpoint-changed(int);
// ── 对话框 / Toast ──────────────────────────────────────────
callback dialog-primary();
callback dialog-secondary();
callback dialog-dismissed();
callback toast-dismissed(string);
// 窗口底色交给 main.slint 的 Window(不透明 `canvas-solid`),这里只铺背景图层
background: transparent;
// 玻璃拟态的对齐基准:整窗逻辑尺寸(components/glass.slint 反向偏移用)
init => {
Theme.window-width = root.width;
Theme.window-height = root.height;
}
changed width => { Theme.window-width = root.width; }
changed height => { Theme.window-height = root.height; }
// ── ① 自定义窗口背景图(09 §101)────────────────────────────
// 只在「开关打开且图片已加载」时才画:空 image 的 width 为 0,出厂态零开销。
if Theme.bg-image.width > 0 : Rectangle {
x: 0;
y: 0;
width: root.width;
height: root.height;
clip: true;
background: Theme.canvas-solid;
Image {
source: Theme.bg-image;
x: 0;
y: 0;
width: parent.width;
height: parent.height;
// tile 模式由 Rust 预平铺成整窗画布,故这里等同 cover
image-fit: root.bg-fill == BgFillKind.contain ? contain : cover;
}
}
// ── ② 暗化层(09 §111:保证前景可读;0 = 不压暗)─────────────
if Theme.bg-image.width > 0 && Theme.bg-dim > 0 : Rectangle {
x: 0;
y: 0;
width: root.width;
height: root.height;
background: rgba(0, 0, 0, Theme.bg-dim);
}
VerticalLayout {
TitleBar {
title: root.app-title;
subtitle: "P0 骨架 · Metro";
maximized: root.maximized;
toggle-maximize => { root.toggle-maximize(); }
minimize => { root.minimize(); }
request-close => { root.request-close(); }
}
HorizontalLayout {
// 左侧主导航
Nav {
active: root.route;
collapsed: root.nav-collapsed;
account-name: root.account-name;
account-initial: root.account-initial;
account-hue: root.account-hue;
navigate(r) => { root.navigate(r); }
toggle-collapsed => { root.toggle-nav(); }
account-clicked => { root.navigate(RouteKind.settings); root.settings-section-changed(SettingSection.account); }
}
// 内容区(每页独立滚动,路由切换栈语义在 Rust Router)
Rectangle {
horizontal-stretch: 1;
background: Theme.bg-canvas;
if root.route == RouteKind.instances : InstancesPage {
tiles: root.tiles;
running: root.running-tiles;
view: root.instance-view;
tile-size: root.tile-size;
query: root.instance-query;
launch(id) => { root.instance-launch(id); }
configure(id) => { root.instance-configure(id); }
stop(id) => { root.instance-stop(id); }
open(id) => { root.instance-open(id); }
new-instance => { root.new-instance(); }
view-changed(v) => {
root.instance-view = v;
root.instance-view-changed(v);
}
tile-size-changed(s) => {
root.tile-size = s;
root.tile-size-changed(s);
}
query-changed(q) => { root.instance-query-changed(q); }
}
if root.route == RouteKind.download : DownloadPage {
versions: root.versions;
category: root.download-category;
installed-only: root.download-installed-only;
query: root.download-query;
install(id) => { root.download-install(id); }
query-changed(q) => {
root.download-query = q;
root.download-query-changed(q);
}
ancient-help => { root.ancient-help(); }
category-changed(c) => {
root.download-category = c;
root.download-category-changed(c);
}
installed-only-changed(v) => {
root.download-installed-only = v;
root.installed-only-changed(v);
}
}
if root.route == RouteKind.logs : LogsPage {
sessions: root.log-sessions;
lines: root.log-lines;
diagnosis: root.diagnosis;
has-diagnosis: root.has-diagnosis;
selected: root.selected-session;
select(id) => { root.log-select(id); }
ask-ai(id) => { root.log-ask-ai(id); }
apply-fix => { root.log-apply-fix(); }
}
if root.route == RouteKind.settings : SettingsPage {
section: root.settings-section;
theme-mode: root.theme-mode;
bg-image-enabled: root.bg-image-enabled;
bg-image: root.bg-image;
bg-fill: root.bg-fill;
bg-dim: root.bg-dim;
panel-alpha: root.panel-alpha;
glass: root.glass;
accent-color: root.accent-hex;
accent-invalid: root.accent-invalid;
section-changed(s) => {
root.settings-section = s;
root.settings-section-changed(s);
}
theme-changed(mode) => {
root.theme-mode = mode;
root.theme-changed(mode);
}
bg-image-enabled-changed(v) => { root.bg-image-enabled-changed(v); }
bg-image-changed(path) => { root.bg-image-changed(path); }
bg-fill-changed(fill) => { root.bg-fill-changed(fill); }
bg-dim-changed(v) => { root.bg-dim-changed(v); }
panel-alpha-changed(v) => { root.panel-alpha-changed(v); }
glass-changed(v) => { root.glass-changed(v); }
accent-color-changed(text) => {
root.accent-hex = text;
root.accent-color-changed(text);
}
accent-swatch-picked(index) => { root.accent-swatch-picked(index); }
yolo-changed(v) => { root.yolo-changed(v); }
mcp-changed(v) => { root.mcp-changed(v); }
ai-endpoint-changed(i) => { root.ai-endpoint-changed(i); }
}
// AI 拆成独立全宽页:与右侧栏共用同一份 ai-messages(切换无损)
if root.route == RouteKind.agent : AiPanel {
docked: false;
messages: root.ai-messages;
collapsed: false;
yolo: root.yolo;
streaming: root.ai-streaming;
endpoint-label: root.ai-endpoint-label;
draft <=> root.ai-draft;
dock => { root.dock-ai(); }
toggle-yolo => { root.toggle-yolo(); }
send(t) => { root.ai-send(t); }
stop => { root.ai-stop(); }
}
// 实例详情 G4:P0 只留占位(点击磁贴进入)
if root.route == RouteKind.detail : VerticalLayout {
alignment: center;
spacing: Metrics.gap-3;
UiText {
role: TextRole.title;
text: "实例详情(G4)";
horizontal-alignment: center;
}
UiText {
role: TextRole.caption;
text: "P0 骨架未实现:概要与设置 tab 在 G4 补齐";
horizontal-alignment: center;
}
HorizontalLayout {
alignment: center;
MetroButton {
kind: ButtonKind.standard;
text: "返回实例页";
clicked => { root.navigate(RouteKind.instances); }
}
}
}
}
// 右侧 AI 常驻栏(拆成独立页时让位给内容区)
AiPanel {
visible: root.route != RouteKind.agent;
docked: true;
collapsed: root.ai-collapsed;
messages: root.ai-messages;
yolo: root.yolo;
streaming: root.ai-streaming;
endpoint-label: root.ai-endpoint-label;
draft <=> root.ai-draft;
toggle-collapsed => { root.toggle-ai(); }
expand => { root.expand-ai(); }
toggle-yolo => { root.toggle-yolo(); }
send(t) => { root.ai-send(t); }
stop => { root.ai-stop(); }
}
}
}
// 覆盖层:模态队列(一次一条)+ 右下 Toast
DialogHost {
current: root.dialog;
open: root.dialog-open;
queued: root.dialog-queued;
primary => { root.dialog-primary(); }
secondary => { root.dialog-secondary(); }
dismissed => { root.dialog-dismissed(); }
}
ToastHost {
toasts: root.toasts;
dismissed(id) => { root.toast-dismissed(id); }
}
}
+48
View File
@@ -0,0 +1,48 @@
// 布局度量令牌(D16 定稿的尺寸口径集中在此):
// 导航栏折叠宽度、AI 栏宽度、标题栏高度、磁贴三档尺寸与列数。
import { TileSize } from "../models.slint";
export global Metrics {
// 间距刻度(4 的倍数,Metro 栅格)
out property <length> gap-1: 4px;
out property <length> gap-2: 8px;
out property <length> gap-3: 12px;
out property <length> gap-4: 16px;
out property <length> gap-5: 24px;
out property <length> gap-6: 32px;
out property <length> radius-sm: 2px;
out property <length> radius-md: 4px;
out property <length> radius-lg: 8px;
// 主窗口骨架
out property <length> titlebar-height: 40px;
out property <length> titlebar-button-width: 46px;
out property <length> accent-line: 2px;
out property <length> nav-expanded-width: 88px;
out property <length> nav-collapsed-width: 48px;
out property <length> ai-panel-width: 320px;
out property <length> ai-rail-width: 44px;
out property <length> page-header-height: 56px;
out property <length> running-strip-height: 32px;
out property <length> row-height: 44px;
out property <length> control-height: 32px;
out property <length> touch-target: 32px;
// 磁贴三档(Q24-3:默认中磁贴 4 列,设置可调小 6 / 大 3)
in-out property <TileSize> tile-size: TileSize.medium;
out property <int> tile-columns:
tile-size == TileSize.small ? 6
: tile-size == TileSize.large ? 3
: 4;
out property <length> tile-height:
tile-size == TileSize.small ? 104px
: tile-size == TileSize.large ? 176px
: 136px;
out property <length> tile-icon-size:
tile-size == TileSize.small ? 32px
: tile-size == TileSize.large ? 56px
: 44px;
// 小磁贴只留图标+名字+启动键,藏起徽标与最后游玩时间(空间不足)
out property <bool> tile-compact: tile-size == TileSize.small;
}
Loaded 100 of 517 files, more files were not shown because too many files have changed in this diff. Show more