diff --git a/.github/workflows/web-image.yml b/.github/workflows/web-image.yml index f4cb74f..b16d059 100644 --- a/.github/workflows/web-image.yml +++ b/.github/workflows/web-image.yml @@ -64,6 +64,13 @@ jobs: ranch_assistant.tests.test_species_retention_limits \ ranch_assistant.tests.test_primary_cultivation \ ranch_assistant.tests.test_primary_resource_admission -v + - name: Offline commission history and priority regression + run: | + python -B -m unittest \ + ranch_assistant.tests.test_commission_history \ + ranch_assistant.tests.test_commission_history_review \ + ranch_assistant.tests.test_commission_priority \ + ranch_web.tests.test_commission_history -v - name: Offline updater and task log regression run: python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package ranch_web.tests.test_activity ranch_web.tests.test_task_logs -v - name: Offline account recovery regression diff --git a/Dockerfile b/Dockerfile index 956bff9..07d93cb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim-bookworm -ARG WEB_VERSION=2.0.7 +ARG WEB_VERSION=2.0.8 ARG VCS_REF=unknown LABEL org.opencontainers.image.source="https://github.com/attilanet/myrzx_bot" \ org.opencontainers.image.title="myrzx_bot Web" \ diff --git a/README.md b/README.md index 0433093..374826b 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # 牧羊人之心Bot -本轮 Web 发布目标 **2.0.7**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 +Web **2.0.8**,源码发布入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。 ## 运行指引 -### Web 2.0.7(main) +### Web 2.0.8(源码发布入口 main) Windows 使用 Python 3.12+,在项目根目录执行: @@ -19,7 +19,9 @@ py -3 -m venv .venv-web Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。 -**2.0.7** 修复同种重复魔物被继续喂养的问题:主培养固定为已养成的高等级魔物,更优资质只作备用;自动喂养、赠礼、潜能突破仅作用于主培养。已启用孵蛋规则按主培养1只、严格更优备用最多1只整理。通过“帮助 → 检查版本更新…”安装,详见 [发布说明](analysis/RELEASE_2_0_7.md)。 +**2.0.8** 自动委托提供“当前委托 / 每日记录”,跨城市按合格候选的预计氪金 **20→15→10** 排序并说明回退原因;按角色、北京时间自然日持久记录接取、推进和领奖,保留最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,缺失金额保持未确认;旧历史仅从本地任务 journal 可证实的部分回填。详见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。 + +沿用 **2.0.7** 的主培养修复:主培养固定为已养成的高等级魔物,更优资质只作备用;自动喂养、赠礼、潜能突破仅作用于主培养。已启用孵蛋规则按主培养1只、严格更优备用最多1只整理,详见 [2.0.7 发布说明](analysis/RELEASE_2_0_7.md)。 ### 桌面 1.2.0 @@ -36,7 +38,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` | 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 | | --- | --- | --- | -| Web 2.0.7 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | +| Web 2.0.8 | 1.9.68 | 源码发布入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | | 桌面 1.2.0(`v1.2.0`) | 1.9.68 | 当前桌面版本;`Start_Ranch_Helper.cmd` / `python -m ranch_assistant` | | 桌面 1.1.1(`v1.1.1`) | 1.9.68 | 历史正式版本,1.1 系列修复与界面更新 | | 桌面 1.1.0(`v1.1.0`) | 1.9.68 | 历史已发布版本 | @@ -44,23 +46,24 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` 本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。 -## Web 2.0.7 主要功能与分类日志 +## Web 2.0.8 主要功能与分类日志 -2.0.7 保留自 2.0.3 起的单一底部日志区,切换页签只显示当前账号、当前功能的日志,不提供总日志或页内日志框。本版重点修复同种重复培养,详见 [2.0.7 发布说明](analysis/RELEASE_2_0_7.md)。 +2.0.8 沿用 2.0.7 的主培养修复与现有界面,并保留自 2.0.3 起的单一底部日志区,切换页签只显示当前账号、当前功能的日志,不提供总日志或页内日志框。自动委托行为与验证状态见 [2.0.8 发布说明](analysis/RELEASE_2_0_8.md)。 - **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。 - **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。 - **管理登录与子路径**:独立管理登录页、HttpOnly / SameSite cookie、写请求来源校验;支持 `/ranch` 等反代子路径,游戏凭据保存在服务端。 - **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。 +- **自动委托(2.0.8)**:当前委托与每日记录分栏;符合条件的候选跨城市按20→15→10排序,说明高档回退原因,城市锁定候选显示不可接取。历史按角色、北京时间保存,预计奖励与领奖确认金额分开。运行详情使用原单一底部“自动委托”分类日志。 - **底部分类日志**:保留原底部日志区及工具栏,顶部右侧是唯一显示/隐藏入口。整页刷新或重新进入工作台默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。手动显隐按账号保留至刷新,同账号切换功能页保持显隐并更新日志范围。 - **日志操作与隔离**:搜索、清空显示、下载、跟随/暂停及滚动位置按账号与页签隔离;清空不删除服务端历史,下载遵循当前范围与搜索条件,不串入其他账号或功能。日志共用同一账号拉取,浏览器缓存最多 1200 条,底部最多显示最近 600 条。 - **日志归属**:培育室查看孵蛋日志,其他功能页查看对应执行日志;没有匹配记录时为空,不回退到全部日志。登录仅显示登录日志,排除常规、混合旧记录及赠礼日志。已有分类及保守旧记录推断沿用原实现。 - **手动刷新反馈**:刷新成功仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 - **日志保存与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。 -连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。 +连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。未手动停止时,手动选服、恢复会话及自动重登成功后自动执行已勾选功能;已保存的手动暂停继续生效,可在顶部开启。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。 -战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_7.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 +战斗模拟仍为近似模型,特殊关卡并非全部支持。2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](analysis/RELEASE_2_0_8.md#验证);2.0.7 结果保留在 [历史发布说明](analysis/RELEASE_2_0_7.md#验证),其他历史记录见 [Web 验证说明](ranch_web/README.md#离线验证)。历史结果不计入 2.0.8,离线验证不代表真实游戏 API 或生产升级/回滚验收。 ## 桌面 1.2.0 功能基线 diff --git a/analysis/RELEASE_2_0_8.md b/analysis/RELEASE_2_0_8.md new file mode 100644 index 0000000..f19efe4 --- /dev/null +++ b/analysis/RELEASE_2_0_8.md @@ -0,0 +1,46 @@ +# Web 2.0.8 发布说明 + +Web **2.0.8** 以 **2.0.7** 为基线,游戏资料 **1.9.68**,桌面正式版 **1.2.0**。 + +## 自动委托与每日记录 + +- “自动委托”分为**当前委托 / 每日记录**。当前页显示任务、原始候选、标注奖励及选择 / 阻塞原因;城市锁定的原始候选显示为不可接取,不计入可执行候选。 +- 在策略允许、城市已解锁且满足次数、资源和步骤支持条件的候选中,跨城市按静态标注氪金 **20→15→10** 全局排序。选择低档时,日志记录高档缺失或不可执行的实际原因;不保证每次都有可接取的20档。 +- 每日记录按账号、区服和角色隔离,以**北京时间(UTC+8)自然日**归档接取、推进、领奖及结果待核对事件,支持日期查询、刷新和服务重启后查看。每角色保留最近 **90 天、最多 5000 条事件**,任一上限达到即裁剪旧事件。 +- **预计氪金**来自任务静态配置;**已确认氪金**仅取已确认的 `taskComplete` 领奖回包 `response.reward.ke`。缺失或无效金额显示“未确认”,不以预计值、余额变化或旧完成标记补算。接取和推进不计为奖励到账。 +- 旧历史仅从本地任务 journal 中可证实的操作部分回填;仅有当前任务或旧完成标记不足以推定历史接取、领奖时间或金额。无本地记录不表示当天未做过委托。 +- 运行详情沿用原有**单一底部“自动委托”分类日志**;每日记录是业务历史,沿用现有账号隔离、日志显隐与筛选。 + +## 保留的行为 + +沿用 [2.0.7 主培养与资质备用修复](RELEASE_2_0_7.md):已养成的高等级魔物保持主培养,更优资质只作备用;自动经验喂养、同种突破、赠礼及潜能材料仅用于主培养,满级、到上限、冷却或忙碌时等待。已启用种类保留主培养1只与严格更优备用最多1只,锁定、在队、装备、探索、委托等硬保护继续生效。 + +保留15页结构、账号页签、统一启停、居中加载反馈和紧凑表单。登录、恢复会话及重登成功后默认执行已勾选策略;用户手动“停止”跨掉线、重登和服务重启保留,点击“开启”恢复,导入配置保留启停意图。 + +## 验证 + +独立离线验证报告:`test-artifacts/commission-history-review-20261113/final-report.txt`(2026-11-13)。 + +| 范围 | 运行 | 通过 | 跳过 | 失败 / 错误 | +| --- | --- | --- | --- | --- | +| 纯核心 | 215 | 215 | 0 | 0 / 0 | +| 主培养回归 | 87 | 87 | 0 | 0 / 0 | +| Web 非浏览器 | 353 | 350 | 3 | 0 / 0 | +| 独立 Qt 任务状态 | 7 | 7 | 0 | 0 / 0 | +| 非浏览器小计 | 662 | 659 | 3 | 0 / 0 | +| 浏览器独立用例 | 77 | 77 | 0 | 0 / 0 | +| **合计** | **739** | **736** | **3** | **0 / 0** | + +核心215项包含新增历史27项、独立评审23项及优先级7项,均已计入合计。3项跳过源于 Windows 的 POSIX 权限或符号链接限制。独立非浏览器验证前后170个源文件 / 测试 / CI文件哈希一致;纯核心、主培养与 Web 非浏览器组隔离 Qt,游戏操作使用合成客户端或本地 HTTP mock,未访问真实游戏 API。 + +浏览器77个独立用例全部验证通过:全量运行76项通过,加载模块在仅修正测试 fixture 的被动轮询竞态后3/3通过,重叠用例不重复计数。测试修复保留全部原断言,产品源码未变。浏览器证据:`test-artifacts/commission-history/final-browser-20261113T013148Z/loading-fixture-fix.report.json` 与 `fixture-race-proof.json`。 + +离线结果不代表真实账号奖励到账、镜像构建或生产升级 / 回滚验收。历史版本测试不计入本版。 + +## 更新包与发布条件 + +本地更新器由 `tools/build_web_updater.py` 生成:`test-artifacts/releases/v2.0.8/updater.pyz`,同目录 `SHA256SUMS` 使用 LF 换行。包内3份源文件与版本库源文件逐字节一致;构建结果可复现,版本、帮助与离线升级计划检查通过。 + +版本标签 `v2.0.8`,镜像 `ghcr.io/attilanet/myrzx_bot-web:v2.0.8`。在线更新以对应稳定 Release 与镜像均就绪为前提。 + +已有部署须等稳定 Release、正式镜像就绪且宿主机心跳有效后,通过“帮助 → 检查版本更新…”升级,完成后刷新网页;详见 [部署说明](../deploy/web/README.md)。 diff --git a/compose.yaml b/compose.yaml index 504d830..b44f940 100644 --- a/compose.yaml +++ b/compose.yaml @@ -1,11 +1,11 @@ name: ranch-web services: web: - image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.7} + image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.8} build: context: . args: - WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.7} + WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.8} user: "10001:10001" init: true restart: unless-stopped diff --git a/deploy/web/README.md b/deploy/web/README.md index 7f7b083..3920482 100644 --- a/deploy/web/README.md +++ b/deploy/web/README.md @@ -1,8 +1,10 @@ # Web 2 Linux Docker 部署与更新 -当前更新示例以 `v2.0.7` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 +当前应用及更新示例为 `v2.0.8`。下文首次初始化章节保留 2.0.1 流程及历史版本示例。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 -已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 +已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 + +2.0.8 自动委托提供“当前委托 / 每日记录”,合格候选跨城市按20→15→10排序并说明回退原因;历史按角色、北京时间自然日持久保存,最近90天、每角色最多5000条事件。静态预计奖励与领奖回包确认金额分开,旧历史仅回填本地任务 journal 可证实的部分;运行详情使用原单一底部分类日志。2.0.7 高等级主培养与资质备用修复继续生效,详见 [2.0.8 发布说明](../../analysis/RELEASE_2_0_8.md)。 ## 容器与持久化 @@ -19,9 +21,9 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env sudoedit .env .image.env ``` -在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。 +在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 的目标示例为 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.8`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。 -`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。 +`/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、委托历史、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。 正式版本启动: @@ -51,9 +53,9 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳 ### 已完成 2.0.1 初始化的宿主机 -`v2.0.7` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.7 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 +稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.8 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 -### 全新宿主机准备 +### 全新宿主机安装 全新安装时,先安装 root 持有的配置,并准备独立更新器(示例的自动化开关默认关闭): @@ -68,11 +70,11 @@ python3 -B /opt/ranch-web/updater.pyz --version ### 已有宿主机首次初始化(用户自行执行) -以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.7`。 +以下保留 2.0.1 引入私有在线更新时的初始化流程,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。本节的历史资产示例为 `v2.0.7`,第4步的 `v2.0.1` 是首次初始化的历史应用目标。当前应用升级须确认对应发布物就绪,再按上文步骤执行。 前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。 -1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [当前正式 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.7) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装: +1. 用户登录有私有仓库读取权限的 GitHub 账号,历史资产示例从 [2.0.7 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.7) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装: ```sh sudo install -m 0644 -o root -g root updater.pyz /opt/ranch-web/updater.pyz @@ -106,7 +108,7 @@ python3 -B /opt/ranch-web/updater.pyz --version Docker 保存的宿主机登录配置供更新器拉镜像使用;不要复制开发机的 Git/registry 凭据,也不要把 Docker 凭据放进 GitHub Token 文件或 Web 容器。[GHCR 官方认证说明](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry) -4. 使用新包先检查再由用户明确发起在线更新: +4. 使用新包先检查再由用户明确发起在线更新。以下 `--apply v2.0.1` 仅保留首次初始化的历史示例,不是本轮 2.0.8 升级命令: ```sh sudo python3 -B /opt/ranch-web/updater.pyz --config /etc/ranch-web-updater.toml --check @@ -161,12 +163,12 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会 [web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。 -2.0.7 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件: +2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过,详见 [发布说明](../../analysis/RELEASE_2_0_8.md#验证)。2.0.7 结果保留在 [历史发布说明](../../analysis/RELEASE_2_0_7.md#验证)。以下命令可复现本地更新器构建与离线检查;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件: ```sh -python -B tools/build_web_updater.py --output test-artifacts/updater.pyz -python -B test-artifacts/updater.pyz --version -python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.7 --dry-run +python -B tools/build_web_updater.py --output test-artifacts/releases/v2.0.8/updater.pyz +python -B test-artifacts/releases/v2.0.8/updater.pyz --version +python -B test-artifacts/releases/v2.0.8/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.8 --dry-run python -B -m unittest ranch_web.tests.test_updates ranch_web.tests.test_web_updater ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package -v ``` diff --git a/deploy/web/image.env.example b/deploy/web/image.env.example index 9c3ca21..7b7f76e 100644 --- a/deploy/web/image.env.example +++ b/deploy/web/image.env.example @@ -1,2 +1,2 @@ -# Pull only after the v2.0.7 image publishing workflow succeeds and the image is available. -RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.7 +# Pull only after the v2.0.8 image publishing workflow succeeds and the image is available. +RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.8 diff --git a/ranch_assistant/commission_history.py b/ranch_assistant/commission_history.py new file mode 100644 index 0000000..350542c --- /dev/null +++ b/ranch_assistant/commission_history.py @@ -0,0 +1,305 @@ +"""Bounded, per-role commission receipts, independent of rolling activity logs. + +Only journaled operations enter this ledger. A current task or passTask flag +alone proves neither its acceptance date nor that its reward was collected. +""" +from __future__ import annotations + +from copy import deepcopy +from datetime import date, datetime, timedelta +import json +import math +import os +from pathlib import Path +import threading +import time +import uuid + +from .quests import CN, commission_priority + + +def beijing_day(timestamp=None): + return datetime.fromtimestamp(time.time() if timestamp is None else timestamp, CN).date().isoformat() + + +def confirmed_reward(response): + """NetTask.finishTaskHandler -> RewardCenter -> MasterCenter.addKe: delta.""" + reward = response.get("reward") if isinstance(response, dict) else None + value = reward.get("ke") if isinstance(reward, dict) else None + if type(value) not in (int, float) or not math.isfinite(value) or value < 0 or int(value) != value: + return None + return int(value) + + +def positive_id(value): + if isinstance(value, bool): + return None + try: + number = float(value) + return int(number) if math.isfinite(number) and number.is_integer() and number > 0 else None + except (ValueError, TypeError, OverflowError): + return None + + +def valid_stored_event(event): + required = {"id", "journal_id", "time", "date", "kind", "status", "description", "task_id", "task_type_id", + "name", "city", "expected_ke", "confirmed_ke", "selection_code", "selection_reason", "higher_reward_blockers"} + if not isinstance(event, dict) or not required <= event.keys(): + return False + if any(not isinstance(event[key], str) for key in + ("id", "journal_id", "date", "kind", "status", "description", "task_type_id", "name", "selection_code", "selection_reason")): + return False + if (type(event["time"]) not in (int, float) or not math.isfinite(event["time"]) + or event["date"] != beijing_day(event["time"])): + return False + if event["task_id"] is not None and (type(event["task_id"]) is not int or event["task_id"] <= 0): + return False + if type(event["expected_ke"]) is not int or event["expected_ke"] < 0: + return False + if event["confirmed_ke"] is not None and (type(event["confirmed_ke"]) is not int or event["confirmed_ke"] < 0): + return False + return (bool(event["id"]) and bool(event["journal_id"]) and isinstance(event["higher_reward_blockers"], list) + and event["kind"] in ("accept", "complete", "reset", "step", "navigate", "dialogue", "battle", "farm", "local_step") + and event["status"] in ("confirmed", "pending", "unknown", "cancelled", "failed")) + + +def reconciled_accept_task(record, snapshot, today): + """Recheck only a journal-proven acceptance from the current Beijing day.""" + if (snapshot is None or record.get("outcome") != "reconciled" + or not (record.get("path") or "").endswith("taskLoopReceive") + or str(snapshot.raw.get("master", {}).get("id")) != str(record.get("role_id"))): + return None + timestamp = record.get("finished_at") or record.get("updated_at") or record.get("timestamp") + if type(timestamp) not in (int, float) or not math.isfinite(timestamp) or beijing_day(timestamp) != today: + return None + old = {str(task.get("id")) for task in (record.get("baseline") or {}).get("tasks", [])} + expected_id = positive_id(record.get("task_id")) + matches = [task for task in snapshot.raw.get("currentTasks", []) + if str(task.get("typeId")) == str(record.get("task_type_id")) and str(task.get("id")) not in old + and positive_id(task.get("id")) and positive_id(task.get("curStep")) + and (expected_id is None or positive_id(task["id"]) == expected_id)] + return {key: matches[0][key] for key in ("id", "typeId", "curStep")} if len(matches) == 1 else None + + +def journal_event(record, info, snapshot=None): + meta = record.get("commission") or {} + path, original = record.get("path") or "", record.get("kind") or "" + farming = bool(record.get("source_task_type_id")) + type_id = str(record.get("source_task_type_id") or record.get("task_type_id") or "") + if not (meta or (info or {}).get("type") == 4 or original.startswith("quest_") + or original in ("progression_loop_accept", "progression_loop_reset")): + return None + kind = ("farm" if farming else "accept" if path.endswith("taskLoopReceive") else + "complete" if path.endswith("taskComplete") else "reset" if path.endswith("taskLoopFlush") else + "navigate" if original == "progression_navigate" else "dialogue" if original == "progression_dialogue" else + "battle" if original == "progression_battle" else "local_step" if original == "progression_local_step" else "step") + response = record.get("response") + response_ok = isinstance(response, dict) and response.get("resCode", 0) in (0, "0") + action_response = record.get("commission_action_response") + action_receipt = record.get("commission_action_confirmed") is True and isinstance(action_response, dict) and action_response.get("resCode", 0) in (0, "0") + receipt = response_ok and (record.get("response_confirmed") is True or record.get("settlement_confirmed") is True + or record.get("phase") in ("acknowledged", "settlement_acknowledged") + or record.get("phase") == "done" and record.get("outcome") in ("task", "win")) + task_id = record.get("source_task_id") if farming else record.get("task_id") + phase, outcome = record.get("phase"), record.get("outcome") + status = "unknown" if "unknown" in str(phase) or outcome == "reconciled" else "pending" + if kind == "accept": + task = response.get("task") if receipt else None + if not isinstance(task, dict) and outcome == "reconciled": + # Bind only the snapshot that resolved this pending attempt. A + # later currentTasks entry may be another day's same-type task. + task = record.get("commission_task") + if (isinstance(task, dict) and str(task.get("typeId")) == type_id + and positive_id(task.get("id")) and positive_id(task.get("curStep"))): + task_id, status = positive_id(task["id"]), "confirmed" + elif receipt: + status = "unknown" + elif kind == "complete": + # passTask is type-level history: it cannot prove this instance's claim. + if receipt: + status = "confirmed" + elif receipt or action_receipt or phase == "done" and outcome in ("local", "win", "sweep", "event"): + status = "confirmed" + elif outcome == "reconciled" and kind in ("step", "battle", "reset"): + status = "confirmed" + if outcome in ("cancelled", "unsupported"): + status = "cancelled" + elif outcome == "loss": + status = "failed" + timestamp = (record.get("finished_at") or record.get("updated_at") or record.get("timestamp")) if status == "confirmed" else record.get("timestamp") + if type(timestamp) not in (int, float) or not math.isfinite(timestamp): + return None + name = str(meta.get("name") or (info or {}).get("name") or type_id or "每日委托") + expected = meta.get("expected_ke", -commission_priority(info or {})) + actual = confirmed_reward(response) if kind == "complete" and receipt else None + labels = {"accept": "接取委托", "complete": "领取委托奖励", "reset": "刷新每日委托", + "step": "提交委托步骤", "navigate": "委托导航", "dialogue": "委托对话", "battle": "委托战斗", + "farm": "收集委托材料", "local_step": "完成委托步骤本地收尾"} + detail = record.get("description") or "" + description = f"{labels[kind]}:{name}(预计{expected}氪金)" + if kind in ("step", "battle", "local_step") and record.get("step_number"): + description += f",第{record['step_number']}步" + if kind in ("navigate", "dialogue", "farm") and detail: + description += ";" + detail + if status == "confirmed": + if kind in ("step", "battle") and meta.get("operation_detail"): + description += ";" + meta["operation_detail"] + description += ";本地操作已完成" if outcome == "local" else ";快照已核对" if outcome == "reconciled" and not receipt else ";已确认" + if kind == "complete": + description += f",实际获得{actual}氪金" if actual is not None else ",实际氪金奖励未记录" + if kind == "accept" and meta.get("selection_reason"): + description += ";" + meta["selection_reason"] + else: + description += {"pending": ";请求待确认", "unknown": ";结果未知,等待核对,禁止重发", + "cancelled": ";未执行", "failed": ";战斗失败,未推进委托"}[status] + return {"id": str(record["attempt_id"]), "journal_id": str(record["attempt_id"]), + "time": timestamp, "date": beijing_day(timestamp), "kind": kind, "status": status, + "description": description, "task_id": positive_id(task_id), "task_type_id": type_id, + "name": name, "city": meta.get("city", (record.get("payload") or {}).get("city")), + "expected_ke": expected, "confirmed_ke": actual, + "operation_detail": meta.get("operation_detail", ""), + "confirmation": "receipt" if receipt or action_receipt else "local" if outcome == "local" else "snapshot" if outcome == "reconciled" and status == "confirmed" else "", + "selection_code": meta.get("selection_code", "unknown" if kind == "accept" else "already_accepted"), + "selection_reason": meta.get("selection_reason") or (("历史接取已确认,当时选择原因未记录" if status == "confirmed" + else "接取已取消,当时选择原因未记录" if status == "cancelled" else "接取结果待核对,当时选择原因未记录") if kind == "accept" + else "已有委托继续处理,接取时间及当时选择原因未记录"), + "higher_reward_blockers": deepcopy(meta.get("higher_reward_blockers") or [])} + + +class CommissionHistory: + def __init__(self, path=None, *, retention_days=90, max_events=5000, clock=None): + self.path = Path(path) if path else None + self.retention_days, self.max_events = retention_days, max_events + self.clock = clock or time.time + self.lock = threading.RLock() + self.state = {"version": 1, "roles": {}} + self.error = "" + self.warning = "" + self._dirty = False + self._seen = {} + if self.path and self.path.exists(): + try: + state = json.loads(self.path.read_text(encoding="utf-8")) + if state.get("version") != 1 or not isinstance(state.get("roles"), dict): + raise ValueError("unsupported history") + for events in state["roles"].values(): + if not isinstance(events, dict) or any(not valid_stored_event(event) for event in events.values()): + raise ValueError("invalid history") + self.state = state + except (OSError, ValueError, AttributeError, OverflowError) as error: + self.error = "委托历史无法读取,原文件已保留:" + type(error).__name__ + + def _prune(self): + cutoff = (datetime.fromtimestamp(self.clock(), CN).date() - timedelta(days=self.retention_days - 1)).isoformat() + for role, events in self.state["roles"].items(): + keep = sorted((event for event in events.values() if event["date"] >= cutoff), + key=lambda event: (event["time"], event["id"]))[-self.max_events:] + self.state["roles"][role] = {event["id"]: event for event in keep} + + def _save(self): + self._prune() + if self.path: + self.path.parent.mkdir(parents=True, exist_ok=True) + temporary = self.path.with_name(self.path.name + "." + uuid.uuid4().hex + ".tmp") + try: + with temporary.open("w", encoding="utf-8") as stream: + json.dump(self.state, stream, ensure_ascii=False, allow_nan=False) + stream.flush() + os.fsync(stream.fileno()) + temporary.replace(self.path) + finally: + temporary.unlink(missing_ok=True) + + def ingest(self, role_id, records, info_for, snapshot=None): + """Upsert by existing attempt ID; never read traces or dispatch requests.""" + if self.error: + return + with self.lock: + role_id = str(role_id) + events = self.state["roles"].setdefault(role_id, {}) + seen = self._seen.setdefault(role_id, {}) + changed = False + for record in records: + if str(record.get("role_id")) != role_id or not record.get("attempt_id"): + continue + key = str(record["attempt_id"]) + acceptance = reconciled_accept_task(record, snapshot, beijing_day(self.clock())) + revision = (record.get("phase"), record.get("outcome"), record.get("updated_at"), record.get("finished_at"), + json.dumps([record.get("commission") or {}, record.get("commission_task"), acceptance], sort_keys=True, ensure_ascii=False)) + if seen.get(key) == revision: + continue + info = info_for(str(record.get("source_task_type_id") or record.get("task_type_id") or "")) + evidence = record | {"commission_task": acceptance} if acceptance and not record.get("commission_task") else record + event = journal_event(evidence, info, snapshot) + if event: + previous = events.get(key) + # A previously captured receipt stays known after restart, + # even if a reconciled acceptance has left the snapshot. + if previous and previous["status"] == "confirmed" and event["status"] != "confirmed": + event = previous + if previous != event: + events[key] = event + changed = True + seen[key] = revision + current_ids = {str(record.get("attempt_id")) for record in records} + self._seen[role_id] = {key: revision for key, revision in seen.items() if key in current_ids} + self._dirty = self._dirty or changed + if self._dirty: + self._save() + self._dirty = False + self.warning = "" + + def query(self, role_id, day=None): + today = beijing_day(self.clock()) + if day is None: + day = today + if not isinstance(day, str): + raise ValueError("委托历史日期须为 YYYY-MM-DD") + try: + if date.fromisoformat(day).isoformat() != day: + raise ValueError(day) + except ValueError as error: + raise ValueError("委托历史日期须为 YYYY-MM-DD") from error + with self.lock: + events = sorted(self.state["roles"].get(str(role_id), {}).values(), key=lambda event: (event["time"], event["id"])) + dates = sorted({today, day, *(event["date"] for event in events)}, reverse=True) + daily = [event for event in events if event["date"] == day] + groups = {} + for event in events: + if event["date"] > day or not event["task_type_id"]: + continue + identity = f"{role_id}:{event['task_type_id']}:{event['task_id']}" if event["task_id"] else f"{role_id}:attempt:{event['id']}" + groups.setdefault(identity, []).append(event) + rows = [] + for identity, timeline in groups.items(): + selected = [event for event in timeline if event["date"] == day] + if not selected: + continue + accepted = next((event for event in timeline if event["kind"] == "accept" and event["status"] == "confirmed"), None) + completed = next((event for event in timeline if event["kind"] == "complete" and event["status"] == "confirmed"), None) + latest, first = timeline[-1], accepted or timeline[0] + status = (latest["status"] if latest["status"] in ("pending", "unknown", "failed", "cancelled") else "completed" if completed else + "accepted" if latest["kind"] == "accept" and accepted else "in_progress") + rows.append({"id": identity, "task_id": first["task_id"], "task_type_id": first["task_type_id"], + "name": first["name"], "city": first["city"], "status": status, + "accepted_at": accepted["time"] if accepted else None, "completed_at": completed["time"] if completed else None, + "expected_ke": first["expected_ke"], "confirmed_ke": completed["confirmed_ke"] if completed else None, + "selection_reason": first["selection_reason"], "selection_code": first["selection_code"], + "higher_reward_blockers": first["higher_reward_blockers"], "last_action": latest["description"], "events": selected}) + receipts = {"accept": {}, "complete": {}} + for event in events: + if event["kind"] not in receipts or event["status"] != "confirmed": + continue + identity = (event["task_type_id"], event["task_id"]) if event["task_id"] else ("attempt", event["id"]) + receipts[event["kind"]].setdefault(identity, event) + accepts = [event for event in receipts["accept"].values() if event["date"] == day] + completes = [event for event in receipts["complete"].values() if event["date"] == day] + result = {"date": day, "dates": dates, "timezone": "Asia/Shanghai", "role_id": str(role_id), + "summary": {"accepted_count": len(accepts), "completed_count": len(completes), + "pending_count": sum(row["status"] in ("pending", "unknown") for row in rows), + "expected_ke": sum(event["expected_ke"] for event in accepts), + "confirmed_ke": sum(event["confirmed_ke"] for event in completes if event["confirmed_ke"] is not None), + "unknown_reward_count": sum(event["confirmed_ke"] is None for event in completes)}, + "rows": list(reversed(rows)), "events": list(reversed(daily)), "retention_days": self.retention_days, + "notice": "仅展示已记录的委托操作;缺失的旧历史未记录,不补推接取、完成或奖励。", "error": self.error or self.warning} + return deepcopy(result) diff --git a/ranch_assistant/engine.py b/ranch_assistant/engine.py index 2e659bc..6290b86 100644 --- a/ranch_assistant/engine.py +++ b/ranch_assistant/engine.py @@ -12,7 +12,8 @@ from types import SimpleNamespace from .model import Action, Catalog, Planner, Policy, Snapshot, seconds from .daily import DailyLedger, DailyPolicy, selected_entries from .sweeping import SweepPolicy, SweepRunner -from .quests import QuestPolicy, TaskPlanner +from .quests import QuestPolicy, TaskPlanner, commission_priority +from .commission_history import CommissionHistory from .market import PurchaseBudget from .management import expansion_quote, manual_monster_actions from .gifts import GiftPlanner @@ -104,6 +105,10 @@ class Engine: self._progression_state_loaded = False self._battle_catalog_ready = False self.battle_journal = BattleJournal(folder / "progression" / "journal.json" if folder else None) + self._commission_history = CommissionHistory(folder / "progression" / "commission_history.json" if folder else None) + self._commission_history_roles = set() + self._commission_offer_diagnostics = [] + self._commission_diagnostics_key = None self.battles = BattleOrchestrator(catalog, self.battle_journal, battle_runtime, self.sweeper, request_builder=self._battle_request, observer=self._battle_observer) self._progression_cancel = threading.Event() @@ -454,6 +459,10 @@ class Engine: self.battle_journal.save() def _battle_observer(self, event, intent, response): + if event == "started" and self._is_commission(intent): + record = self.battle_journal.pending(self.snapshot) + if record is not None: + self._journal_commission(record, intent) if value(intent, "kind") == "map_battle": stage = SimpleNamespace(stage_id=str(value(intent, "stage_id")), level=str(value(intent, "difficulty"))) key = self.sweeper.key(self.snapshot, stage) @@ -487,6 +496,11 @@ class Engine: if farming: if event == "started": planner.mark_started(self.snapshot, intent) # validates the issued ordinary intent only + elif event in ("settled", "event"): + record = self.battle_journal.pending(self.snapshot) + if record is not None: + self.battle_journal.update(record, record["phase"], + commission_action_response=gameplay_response(response), commission_action_confirmed=True) # Farming is a normal map action. Its journal and fresh server # snapshot govern the result; it never acknowledges a task step. return None @@ -701,6 +715,106 @@ class Engine: info = self.game_data.task(value(intent, "source_task_type_id") or value(intent, "task_type_id")) if self.game_data else None return bool(info and info.get("type") == 4) + def _commission_info(self, type_id): + info = self.game_data.task(type_id) if self.game_data and type_id else None + return info or self.catalog.data.get("task_info", {}).get(str(type_id)) or {} + + def _sync_commission_history(self): + """Use the already loaded, bounded journal; ledger failures never retry a game write.""" + if self.snapshot is None or self.snapshot.raw.get("master", {}).get("id") is None: + return + role = str(self.snapshot.raw["master"]["id"]) + try: + records = self.battle_journal.role(self.snapshot)["records"] + self._commission_history.ingest(role, records, self._commission_info, self.snapshot) + self._commission_history_roles.add(role) + except (OSError, ValueError, TypeError, KeyError, AttributeError): + self._commission_history.warning = "委托历史暂未写入磁盘;任务回包仍保存在原日志,稍后核对导入,请勿重发" + + @account_serial + def commission_history(self, day=None): + """Independent plain DTO; day is YYYY-MM-DD in Beijing, default wall-clock today. + + summary: accepted_count/completed_count/pending_count/expected_ke/ + confirmed_ke/unknown_reward_count. Unknown row rewards are None. + Only events on the selected day contribute to daily counts and rewards. + """ + role = str(self.snapshot.raw.get("master", {}).get("id", "")) if self.snapshot else "" + if role and (role not in self._commission_history_roles or self._commission_history._dirty): + self._sync_commission_history() + return self._commission_history.query(role, day) + + @account_serial + def commission_offer_diagnostics(self): + """Cached offline eligibility; no journal reload, game calls or runtime inspection.""" + if self.snapshot is None: + return [] + self._ensure_commission_diagnostics() + return deepcopy(self._commission_offer_diagnostics) + + def _ensure_commission_diagnostics(self): + key = (id(self.snapshot), digest({"quest": vars(self.quest_policy), "ranch": vars(self.policy), + "progression": vars(self.progression_policy), "checks": self._commission_offer_checks})) + if key == self._commission_diagnostics_key: + return + if self.progression_planner is None: + self._ensure_progression() + # Reuse model checks from the worker's last planning pass. A missing + # check remains explicitly unverified until that worker runs. + self._commission_offer_diagnostics = self.progression_planner.commission_offers( + self.snapshot, self.quest_policy, self.policy, battle_policy=self.progression_policy, + accept_supported=lambda key: self._commission_offer_checks.get(str(key), + (False, "后续步骤或战斗能力尚未验证,等待后台检查"))) + self._commission_diagnostics_key = key + + def _journal_commission(self, record, intent, *, legacy=False): + type_id = str(value(intent, "source_task_type_id") or value(intent, "task_type_id") or "") + info = self._commission_info(type_id) + if info.get("type", 4 if legacy else None) != 4 and value(intent, "kind") not in ("progression_loop_reset", "quest_reset"): + return + selected = getattr(self.tasks if legacy else self.progression_planner, "commission_selection", {}) or {} + accepting = (record.get("path") or "").endswith("taskLoopReceive") + meta = {"name": info.get("name", type_id or "每日委托"), "expected_ke": -commission_priority(info), + "city": (record.get("payload") or {}).get("city")} + number = value(intent, "source_step_number") or value(intent, "step_number") or 0 + steps = info.get("steps") or [] + if 1 <= number <= len(steps): + step = steps[number - 1] + kind, required = step.get("statusType"), step.get("statusValue") or {} + remove = required.get("remove") is True + prefix = "提交" if remove else "核对持有" + type_key, count = str(required.get("type", "")), required.get("num", 0) + if kind == "getMoney": + detail = f"{prefix}金币×{required.get('money', 0)}" + elif kind == "getItem" or kind == "getMonster" and required.get("mode") == 0: + name = self.catalog.monster(type_key).get("name", type_key) + "蛋" if type_key in self.catalog.monsters else self.catalog.data.get("item_names", {}).get(type_key, f"道具#{type_key}") + detail = f"{prefix}{name}×{count}" + elif kind == "getMonster": + detail = f"{prefix}{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}×{count}" + elif kind == "passStage": + stage = self.game_data.stage(required.get("stage")) if self.game_data else None + detail = f"通关{(stage or {}).get('name', required.get('stage', '指定关卡'))},难度{required.get('level', 1)}" + elif kind == "battle": + detail = "完成委托专用战斗" + elif kind == "none": + detail = "完成对话条件" + elif kind == "killMonster": + detail = f"核对{self.catalog.monster(type_key).get('name', '魔物#' + type_key)}累计击杀数量" + elif kind == "passLevel": + detail = f"核对角色等级达到{required.get('level', 0)}级" + else: + detail = str(value(intent, "description", "")) + meta["operation_detail"] = detail + if accepting and selected.get("task_type_id") == type_id: + meta.update(deepcopy(selected)) + self.battle_journal.update(record, record["phase"], commission=meta) + + def _commission_message(self, record, default): + self._sync_commission_history() + role = str(self.snapshot.raw["master"].get("id", "")) + event = self._commission_history.state["roles"].get(role, {}).get(str(record.get("attempt_id"))) + return event["description"] if event else default + @staticmethod def _is_farm(intent): return bool(value(intent, "source_task_type_id")) and not value(intent, "task_id") and bool(value(intent, "stage_id")) @@ -725,18 +839,26 @@ class Engine: "" if supported else self._commission_offer_reason or "委托后续步骤当前无法自动完成") return supported + def _commission_offer_eligibility(self, type_id): + self._check_commission_offer(type_id) + return self._commission_offer_checks[str(type_id)] + def _commission_offer_supported(self, type_id): self._commission_offer_reason = "委托后续条件、剧情或战斗未验证支持,未消耗接取次数" info = self.game_data.task(type_id) if not info or info.get("type") != 4: + self._commission_offer_reason = "委托配置缺失或类型不符" return False for number, step in enumerate(info.get("steps", []), 1): for name in (step.get("story"), step.get("afterStory")): if name and (self.game_data.script(name) or {}).get("supported") is not True: + script = self.game_data.script(name) or {} + self._commission_offer_reason = f"第{number}步剧情 {name} 未验证支持" + (":" + ";".join(script.get("block_reasons") or []) if script.get("block_reasons") else "") return False kind = step.get("statusType") if kind in ("battle", "passStage"): if not self.quest_policy.battle_tasks: + self._commission_offer_reason = "委托战斗开关未启用" return False intent = {"kind": "progression_battle", "task_type_id": str(type_id), "task_id": 0, "step_number": number, "battle_kind": "passStage" if kind == "passStage" else "task", @@ -748,12 +870,24 @@ class Engine: return False else: policy = self._intent_policy({"task_type_id": str(type_id)}) - ready, _, _ = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy) + ready, _, requirement_reason = self.progression_planner.requirement(self.snapshot, step, {}, policy, self.policy) if not ready: sources = self.progression_planner.farming_intents(self.snapshot, step, {"id": 0, "typeId": str(type_id), "curStep": number}, policy, self.policy) - if not any(self._is_sweep_intent(source) or self._battle_capability(source)[0] for source in sources): + source_reasons = [] + feasible = False + for source in sources: + supported, reason = (True, "") if self._is_sweep_intent(source) else self._battle_capability(source) + if supported: + feasible = True + break + if reason: + source_reasons.append(reason) + if not feasible: + self._commission_offer_reason = f"第{number}步:{requirement_reason}" + (";材料来源:" + ";".join(source_reasons) if source_reasons else ";没有当前可用的自动收集来源") return False + if not info.get("steps"): + self._commission_offer_reason = "委托没有有效步骤" return bool(info.get("steps")) def _refresh_progression_cache(self, *, force=False): @@ -770,28 +904,33 @@ class Engine: "snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)}) key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy), "quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot), - "pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)}) + "pending": self._progression_pending(), "runtime": id(self.battles.runtime), + "day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)}) if force or key != self._progression_cache_key: self._commission_offer_checks = {} + self._commission_diagnostics_key = None rows = self.progression_planner.rows(self.snapshot, self.progression_policy, self.policy, quest_policy=self.quest_policy) intents = self.progression_planner.plan(self.snapshot, self.progression_policy, self.policy) commission_plan = getattr(self.progression_planner, "commission_plan", None) self._commission_planner_available = callable(commission_plan) if self._commission_planner_available: intents += commission_plan(self.snapshot, self.quest_policy, self.policy, - battle_policy=self.progression_policy, accept_supported=self._check_commission_offer) + battle_policy=self.progression_policy, accept_supported=self._commission_offer_eligibility) + self._commission_offer_diagnostics = deepcopy(self.progression_planner.commission_offer_rows) intents.sort(key=lambda intent: not self._is_commission(intent)) self._progression_rows, self._progression_intents = self._overlay_battle_capabilities(rows, intents) self._persist_progression() self._progression_cache_key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy), "quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot), - "pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)}) + "pending": self._progression_pending(), "runtime": id(self.battles.runtime), + "day": ProgressionPlanner._loop_day(self.snapshot, self.snapshot.now - 10)}) self._progression_error = "" except (ImportError, OSError, ValueError, TypeError, KeyError, AttributeError) as error: self._progression_error = "任务规划暂不可用:" + str(error) self._progression_rows = [{"state": "unsupported", "supported": False, "blocked_reason": self._progression_error}] self._progression_intents = [] self._progression_records = self.battle_journal.records(self.snapshot) + self._sync_commission_history() @account_serial def refresh_progression(self): @@ -838,9 +977,15 @@ class Engine: try: self.last_executed = True kind = value(intent, "kind") + self._sync_commission_history() if kind in ("progression_battle", "battle", "task_battle", "stage_battle", "map_battle", "sweep") or self._is_farm(intent): + previous_attempts = {record["attempt_id"] for record in self.battle_journal.role(self.snapshot)["records"]} message = self.battles.run(self.client, self.snapshot, intent, effective_policy, cancel=self._progression_cancel, ranch=self.policy) + records = [record for record in self.battle_journal.role(self.snapshot)["records"] + if record["attempt_id"] not in previous_attempts] + if records: + message = self._commission_message(records[-1], message) else: message = self._execute_task_intent(intent) if self.battle_journal.pending(self.snapshot) and kind == "progression_battle": @@ -858,6 +1003,7 @@ class Engine: self._persist_progression() raise finally: + self._sync_commission_history() self._refresh_progression_cache(force=True) def _execute_task_intent(self, intent): @@ -875,12 +1021,14 @@ class Engine: return "任务补链必须提供计算后的三个数组;未发送查询或空补链" if self._progression_cancel.is_set(): return "任务推进已取消" + self._sync_commission_history() record = self.battle_journal.begin(self.snapshot, intent) + self._journal_commission(record, intent) if local: self.progression_planner.acknowledge(self.snapshot, intent) self._persist_progression(save=False) self.battle_journal.finish(self.snapshot, record, "local", "已保存普通剧情的本地检查点") - return "已推进普通剧情并保存本地检查点" + return self._commission_message(record, "已推进普通剧情并保存本地检查点") try: self.progression_planner.mark_started(self.snapshot, intent) self._persist_progression(save=False) @@ -890,7 +1038,7 @@ class Engine: except CancelledBeforeDispatch: self._cancel_unsent_progression(intent) self.battle_journal.finish(self.snapshot, record, "cancelled", "任务请求尚未发送,已取消") - return record["message"] + return self._commission_message(record, record["message"]) self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True) acknowledged = self.progression_planner.acknowledge(self.snapshot, intent, gameplay_response(response)) self._persist_progression(save=False) @@ -898,17 +1046,30 @@ class Engine: self.battle_journal.finish(self.snapshot, record, "task", "服务器已确认任务请求,已保存本地检查点") else: self.battle_journal.update(record, "unknown", message="任务成功回包缺少有效状态,等待核对") - return value(intent, "description", "任务请求已确认") + return self._commission_message(record, value(intent, "description", "任务请求已确认") if acknowledged else "任务成功回包缺少有效状态,等待核对,禁止重发") except Exception as error: self.battle_journal.update(record, "unknown", message="任务请求结果未确认,禁止自动重试", error_type=type(error).__name__) raise + finally: + self._sync_commission_history() @account_serial def read_snapshot(self, *, sync_master=True): if self._progression_pending(): self.last_pending_check = time.monotonic() self.snapshot = self.client.snapshot() - self.battle_journal.reconcile(self.snapshot, trusted=True) + pending = self.battle_journal.pending(self.snapshot) + pending_id = pending.get("attempt_id") if pending else None + if self.battle_journal.reconcile(self.snapshot, trusted=True) and pending_id: + record = next((row for row in self.battle_journal.role(self.snapshot)["records"] + if row["attempt_id"] == pending_id), None) + if record and (record.get("path") or "").endswith("taskLoopReceive"): + old = {str(task.get("id")) for task in record.get("baseline", {}).get("tasks", [])} + task = next((task for task in self.snapshot.raw.get("currentTasks", []) + if str(task.get("typeId")) == str(record.get("task_type_id")) and str(task.get("id")) not in old), None) + if task: + record["commission_task"] = {key: task[key] for key in ("id", "typeId", "curStep") if key in task} + self._sync_commission_history() self.master_sync.apply(self.snapshot) if sync_master and not self._progression_pending(): self.master_sync.settle(self.client, self.snapshot) @@ -1223,15 +1384,20 @@ class Engine: if str(task.get("id")) == str(payload.get("taskId"))), {}) intent = {"kind": action.kind, "description": action.description, "path": action.path, "payload": payload, "task_id": payload.get("taskId"), "task_type_id": payload.get("taskTypeId"), "step_number": task.get("curStep")} + self._sync_commission_history() record = self.battle_journal.begin(self.snapshot, intent) + self._journal_commission(record, intent, legacy=True) try: self.battle_journal.update(record, "request_pending") response = self.battles._call(self.client, action.path, payload) - self.battle_journal.update(record, "acknowledged", response=gameplay_response(response)) + self.battle_journal.update(record, "acknowledged", response=gameplay_response(response), response_confirmed=True) + action.description = self._commission_message(record, action.description) return response except Exception as error: self.battle_journal.update(record, "unknown", message="委托请求结果未确认,禁止自动重试", error_type=type(error).__name__) raise + finally: + self._sync_commission_history() def _map_policy(self): return SimpleNamespace(enabled=self.sweep_policy.enabled and (self.sweep_policy.allow_challenge or self.sweep_policy.allow_special), diff --git a/ranch_assistant/progression.py b/ranch_assistant/progression.py index 4477a46..948e378 100644 --- a/ranch_assistant/progression.py +++ b/ranch_assistant/progression.py @@ -45,7 +45,7 @@ import uuid from .game_data import ProgressionData, load_progression_data from .model import Planner, seconds -from .quests import commission_priority, indexed, stage_has_level +from .quests import commission_priority, commission_selection, indexed, stage_has_level CATEGORIES = {1: ("mainline", "主线"), 2: ("sidequest", "支线"), @@ -184,6 +184,8 @@ class ProgressionPlanner: self._anonymous = uuid.uuid4().hex self._accounts = {} self._issued = {} + self.commission_selection = {} + self.commission_offer_rows = [] def _scope(self, snapshot): raw, master = snapshot.raw, snapshot.raw.get("master") or {} @@ -896,11 +898,16 @@ class ProgressionPlanner: taskLoopReceive:{taskTypeId,city}; quotas decrement only on acceptance acknowledgement. Current battle/passStage never become sweep intents. """ + self.commission_selection = {} + self.commission_offer_rows = [] if not quest_policy.enabled: return [] policy = self._commission_policy(quest_policy, battle_policy) scope, account = self._account(snapshot) self.reconcile(snapshot) + candidates = self.commission_offers(snapshot, quest_policy, ranch_policy, + battle_policy=battle_policy, accept_supported=accept_supported) + self.commission_offer_rows = candidates if account["pending"]: reason = "存在未确认请求,委托等待核对,禁止重发" return [self._intent(scope, {}, 0, {}, "progression_blocked", reason, policy, block_reason=reason)] @@ -925,30 +932,67 @@ class ProgressionPlanner: blocked.append(action) if blocked or not quest_policy.accept or remaining <= 0: return blocked - ranked_offers = sorted(((city, key) for city, values in offers.items() for key in _values(values)), - key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {})) - for city, offered_key in ranked_offers: - city = _integer(city) - if city <= 0 or quest_policy.city and city != quest_policy.city or not snapshot.city_unlocked(city): - continue - key, info = str(offered_key), self.data.task(offered_key) - if key in active or key in finished or not info or info.get("type") != 4: - continue - if not self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info)[0]: - continue - if accept_supported is not None and not accept_supported(key): - blocked.append(self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {}, - "progression_loop_accept", "暂不接取:" + info.get("name", key), policy, - path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today), - block_reason="委托后续战斗或条件当前无法自动完成")) + rejected = [] + for candidate in candidates: + city, key = candidate["city"], candidate["task_type_id"] + info = self.data.task(key) + if not candidate["eligible"]: + rejected.append(candidate) + if candidate["blocked_by_support"]: + blocked.append(self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {}, + "progression_loop_accept", "暂不接取:" + info.get("name", key), policy, + path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today), + block_reason=candidate["reason"])) continue + self.commission_selection = {"task_type_id": key, "city": city, + **commission_selection(info, candidates, rejected)} action = self._intent(scope, {"id": 0, "typeId": key}, 0, info.get("startStep") or {}, - "progression_loop_accept", "接取城市委托:" + info.get("name", key), policy, + "progression_loop_accept", f"接取城市委托:{info.get('name', key)}(预计{candidate['expected_ke']}氪金);" + self.commission_selection["selection_reason"], policy, path="taskService/taskLoopReceive", payload={"taskTypeId": key, "city": city}, phase=str(today)) self._issued[action.token] = action.to_dict() return [action] return blocked + def commission_offers(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None, accept_supported=None): + """Offline eligibility for every offer; raw presence never means receivable.""" + policy = self._commission_policy(quest_policy, battle_policy) + _, account = self._account(snapshot) + today, recorded, remaining, offers = self._loop_view(snapshot, account) + active, _, finished = self._tasks(snapshot, account) + has_active = any((self.data.task(key) or {}).get("type") == 4 and key not in finished for key in active) + rows = [] + ranked = sorted(((city, key) for city, values in offers.items() for key in _values(values)), + key=lambda pair: commission_priority(self.data.task(str(pair[1])) or {})) + for offered_city, offered_key in ranked: + city, key = _integer(offered_city), str(offered_key) + info = self.data.task(key) or {} + if info.get("type") != 4: + continue + support_blocked = False + reason = ("城市编号无效" if city <= 0 else + f"策略限定城市 {quest_policy.city}" if quest_policy.city and city != quest_policy.city else + "城市尚未解锁" if not snapshot.city_unlocked(city) else + "委托列表已跨日,等待刷新确认" if recorded is not None and recorded != today and account["commissions"]["day"] != today else + "当日接取次数已用完" if remaining <= 0 else + "自动委托未启用" if not quest_policy.enabled else "自动接取未启用" if not quest_policy.accept else + "存在未确认请求,等待核对" if account["pending"] else + "该委托已接取或已完成" if key in active or key in finished else + "已有委托优先完成" if has_active else "") + if not reason: + ready, reason = self._commission_offer_ready(snapshot, quest_policy, policy, ranch_policy, info) + if ready: + reason = "" + if accept_supported is not None: + result = accept_supported(key) + supported, detail = result if isinstance(result, tuple) else (result, "") + if not supported: + reason = detail or "委托后续战斗或条件当前无法自动完成" + support_blocked = True + rows.append({"task_type_id": key, "name": info.get("name", key), "city": city, + "expected_ke": -commission_priority(info), "eligible": not reason, "reason": reason or "可接取", + "blocked_by_support": support_blocked}) + return rows + def commission_rows(self, snapshot, quest_policy, ranch_policy, *, battle_policy=None): policy = self._commission_policy(quest_policy, battle_policy) return [row for row in self.rows(snapshot, policy, ranch_policy, quest_policy=quest_policy) diff --git a/ranch_assistant/quests.py b/ranch_assistant/quests.py index 1c44b74..33f8e99 100644 --- a/ranch_assistant/quests.py +++ b/ranch_assistant/quests.py @@ -15,6 +15,24 @@ def commission_priority(info): return -reward +def commission_selection(info, offers, rejected): + """Explain this selection using the offers actually examined, across cities.""" + reward = -commission_priority(info) + higher = [row for row in rejected if row["expected_ke"] > reward] + has_twenty = any(row["expected_ke"] == 20 for row in offers) + if reward >= 20: + code, reason = "highest_reward", f"按氪金奖励优先,选择当前可处理的 {reward} 氪金委托" + elif not has_twenty: + code, reason = "no_20_offered", f"本次候选未提供20氪金委托,按奖励优先选择 {reward} 氪金委托" + if higher: + reason += ";" + ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher) + else: + code = "20_ineligible" + details = ";".join(f"{row['name']}({row['expected_ke']}氪金):{row['reason']}" for row in higher) + reason = f"较高奖励委托当前不可接取,选择 {reward} 氪金委托" + (";" + details if details else "") + return {"selection_code": code, "selection_reason": reason, "higher_reward_blockers": higher} + + def indexed(value, key, default=None): if isinstance(value, dict): return value.get(str(key), value.get(key, default)) @@ -84,6 +102,7 @@ class TaskPlanner: def __init__(self, catalog): self.catalog = catalog self.guard = Planner(catalog) + self.commission_selection = {} def current(self, snapshot): infos = self.catalog.data.get("task_info", {}) @@ -161,6 +180,7 @@ class TaskPlanner: return rows def plan(self, snapshot, policy, ranch, *, include_active=True, accept_supported=None): + self.commission_selection = {} if not policy.enabled: return [] history = snapshot.raw.get("history", {}) @@ -176,31 +196,42 @@ class TaskPlanner: index, steps = int(task.get("curStep", 1)) - 1, info.get("steps", []) payload = {"taskId": int(task["id"]), "taskTypeId": str(task["typeId"])} if steps and index >= len(steps): - return [Action("quest_complete", f"领取委托奖励:{info['name']}", "taskService/taskComplete", payload)] + return [Action("quest_complete", f"领取委托奖励:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskComplete", payload)] if 0 <= index < len(steps): ready, ids, _ = self.requirement(snapshot, steps[index], task, policy, ranch) if ready: - return [Action("quest_step", f"推进委托:{info['name']}", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})] + return [Action("quest_step", f"推进委托:{info['name']}(预计{-commission_priority(info)}氪金)", "taskService/taskCompleteStep", payload | {"removeIds": ids or None})] if current_tasks or not policy.accept or int(history.get("loopTaskNum", 0)) <= 0: return [] current = {str(t["typeId"]) for t in self.current(snapshot)} offers = sorted(self.rows(snapshot, policy, ranch), key=lambda row: commission_priority( self.catalog.data["task_info"][row[0]])) + candidates, rejected = [], [] for type_id, name, state, _, meta in offers: if "city" not in meta or type_id in current: continue city = meta["city"] - if policy.city and city != policy.city or not snapshot.city_unlocked(city): - continue info = self.catalog.data["task_info"][type_id] - if info.get("closed") or not condition_ok((info.get("startStep") or {}).get("condition"), snapshot): + candidate = {"task_type_id": type_id, "name": name, "city": city, "expected_ke": -commission_priority(info)} + candidates.append(candidate) + reason = (f"策略限定城市 {policy.city}" if policy.city and city != policy.city else + "城市尚未解锁" if not snapshot.city_unlocked(city) else "委托已关闭" if info.get("closed") else + "接取前置条件未满足" if not condition_ok((info.get("startStep") or {}).get("condition"), snapshot) else "") + if reason: + rejected.append(candidate | {"reason": reason}) continue steps = info.get("steps", []) supported = accept_supported(type_id) if accept_supported else all( (s.get("statusType") in ("passStage", "battle") and policy.battle_tasks) or self.requirement(snapshot, s, {}, policy, ranch)[0] for s in steps) if supported: - return [Action("quest_accept", f"接取委托:{name}", "taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})] + self.commission_selection = {"task_type_id": type_id, "city": city, + **commission_selection(info, candidates, rejected)} + return [Action("quest_accept", f"接取委托:{name}(预计{-commission_priority(info)}氪金);" + self.commission_selection["selection_reason"], + "taskService/taskLoopReceive", {"taskTypeId": type_id, "city": city})] + reason = next((self.requirement(snapshot, step, {}, policy, ranch)[2] for step in steps + if not self.requirement(snapshot, step, {}, policy, ranch)[0]), "委托后续步骤当前无法自动完成") + rejected.append(candidate | {"reason": reason}) return [] def reservations(self, snapshot): diff --git a/ranch_assistant/tests/test_commission_history.py b/ranch_assistant/tests/test_commission_history.py new file mode 100644 index 0000000..17551a1 --- /dev/null +++ b/ranch_assistant/tests/test_commission_history.py @@ -0,0 +1,405 @@ +"""Offline commission observability; every game transport is a fake.""" +from copy import deepcopy +from datetime import datetime +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +from ranch_assistant.commission_history import CommissionHistory, beijing_day +from ranch_assistant.engine import Engine +from ranch_assistant.game_data import ProgressionData +from ranch_assistant.model import Catalog, Snapshot +from ranch_assistant.quests import CN, QuestPolicy, TaskPlanner +from ranch_assistant.progression import ProgressionPlanner +from ranch_assistant.tests.test_progression import config, snapshot, step, task + + +class CommissionHistoryTests(unittest.TestCase): + def setUp(self): + self.folder = Path(self.enterContext(tempfile.TemporaryDirectory(prefix="commission-offline-"))) + self.catalog = Catalog() + self.tasks = {str(400 + number): task(str(400 + number), type=4, + name=name, reward={"ke": reward}) for number, (name, reward) in + enumerate((("低奖励委托", 10), ("中等奖励委托", 15), ("高奖励委托", 20)))} + self.data = ProgressionData(config(self.tasks)) + self.snapshot = snapshot(currentTasks=[]) + self.snapshot.raw["history"].update(loopTaskTime=self.snapshot.now, loopTaskNum=6, + loopTask={"1": ["400", "401"], "2": ["402"]}, unlockCity={"1": True, "2": True}) + self.client = Mock() + self.client.call.side_effect = AssertionError("unexpected offline game operation") + self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.snapshot.raw), self.snapshot.now) + + def engine(self): + engine = Engine(self.catalog, self.client, self.folder / "purchase.json", game_data=self.data) + engine.snapshot = self.snapshot + engine.quest_policy = QuestPolicy(enabled=True) + return engine + + def record(self, engine, *, kind="progression_complete", path="taskService/taskComplete", + task_id=51, type_id="402", response=None, outcome="task"): + record = engine.battle_journal.begin(engine.snapshot, {"kind": kind, "description": "旧任务操作", + "path": path, "payload": {}, "task_id": task_id, "task_type_id": type_id, "step_number": 1}) + if response is not None: + engine.battle_journal.update(record, "acknowledged", response=response, response_confirmed=True) + if outcome is not None: + engine.battle_journal.finish(engine.snapshot, record, outcome) + return record + + def receipt(self, attempt, *, kind="complete", task_id=51, type_id="402", when=None, role=1, + response=None, outcome="task", phase="done", **extra): + when = self.snapshot.now if when is None else when + paths = {"accept": "taskService/taskLoopReceive", "complete": "taskService/taskComplete", + "step": "taskService/taskCompleteStep", "navigate": "", "dialogue": "", "farm": "battleService/battleEnd"} + originals = {"accept": "progression_loop_accept", "complete": "progression_complete", + "step": "progression_step", "navigate": "progression_navigate", "dialogue": "progression_dialogue", "farm": "map_battle"} + return {"attempt_id": attempt, "role_id": str(role), "kind": originals[kind], "path": paths[kind], + "task_type_id": type_id, "task_id": task_id, "step_number": 1, "phase": phase, "outcome": outcome, + "timestamp": when, "finished_at": when if phase == "done" else None, "updated_at": when, + "response": {"resCode": 0} if response is None else response, + "response_confirmed": phase == "done" and outcome == "task", "payload": {}, + "baseline": {"tasks": []}, **extra} + + def ledger(self, records, *, now=None, role=1, **options): + ledger = CommissionHistory(self.folder / "history.json", clock=lambda: now or self.snapshot.now, **options) + ledger.ingest(role, records, lambda key: self.tasks.get(key), self.snapshot) + return ledger + + def test_early_battle_return_never_relogs_previous_commission_claim(self): + engine = self.engine() + self.record(engine, response={"resCode": 0, "reward": {"ke": 20}}) + engine.battles.run = Mock(return_value="体力不足,未开始战斗") + intent = {"kind": "progression_battle", "task_type_id": "402", "task_id": 52, + "step_number": 1, "description": "下一份委托战斗"} + with patch.object(engine, "read_snapshot"), patch.object(engine, "_refresh_progression_cache"): + _, _, message = engine._run_progression_intent(intent) + self.assertEqual(message, "体力不足,未开始战斗") + self.client.call.assert_not_called() + + def test_receipts_persist_instance_and_expected_reward_separately_from_actual(self): + records = [self.receipt("a", kind="accept", task_id=0, type_id="401", + response={"resCode": 0, "task": {"id": 51, "typeId": "401", "curStep": 1}}), + self.receipt("c", type_id="401", response={"resCode": 0, "reward": {"ke": 7}})] + ledger = self.ledger(records) + dto = ledger.query(1) + self.assertEqual(dto["summary"], {"accepted_count": 1, "completed_count": 1, "pending_count": 0, + "expected_ke": 15, "confirmed_ke": 7, "unknown_reward_count": 0}) + self.assertEqual(len(dto["rows"]), 1) + self.assertEqual((dto["rows"][0]["expected_ke"], dto["rows"][0]["confirmed_ke"]), (15, 7)) + restored = CommissionHistory(self.folder / "history.json") + restored.ingest(1, records, self.tasks.get) + self.assertEqual(restored.query(1)["summary"], dto["summary"]) + self.assertIn("实际获得7氪金", dto["rows"][0]["last_action"]) + + def test_wallet_total_and_missing_reward_never_become_confirmed_delta(self): + self.snapshot.raw["master"]["ke"] = 9000 + records = [self.receipt("c", response={"resCode": 0, "ke": 9000, "master": {"ke": 9000}})] + dto = self.ledger(records).query(1) + self.assertEqual(dto["summary"]["completed_count"], 1) + self.assertEqual(dto["summary"]["confirmed_ke"], 0) + self.assertEqual(dto["summary"]["unknown_reward_count"], 1) + self.assertIsNone(dto["rows"][0]["confirmed_ke"]) + + def test_step_and_farming_loot_never_count_as_final_commission_reward(self): + records = [self.receipt("s", kind="step", response={"resCode": 0, "reward": {"ke": 5}}), + self.receipt("f", kind="farm", task_id=0, type_id="", outcome="win", source_task_id=51, + source_task_type_id="402", settlement_confirmed=True, + response={"resCode": 0, "stageReward": {"ke": 20}, "reward": {"ke": 20}})] + dto = self.ledger(records).query(1) + self.assertEqual(dto["summary"]["completed_count"], 0) + self.assertEqual(dto["summary"]["confirmed_ke"], 0) + self.assertEqual({event["kind"] for event in dto["events"]}, {"step", "farm"}) + self.assertEqual(len(dto["rows"]), 1) + + def test_snapshot_presence_and_pass_task_flag_create_no_history(self): + self.snapshot.raw["currentTasks"] = [{"id": 51, "typeId": "402", "curStep": 2}] + self.snapshot.raw["history"]["passTask"] = {"402": True} + engine = self.engine() + dto = engine.commission_history() + self.assertEqual(dto["rows"], []) + self.assertEqual(dto["summary"]["accepted_count"], 0) + self.assertEqual(dto["summary"]["completed_count"], 0) + self.client.call.assert_not_called() + + def test_reconciled_claim_without_receipt_remains_unknown(self): + self.snapshot.raw["history"]["passTask"] = {"402": True} + dto = self.ledger([self.receipt("c", phase="done", outcome="reconciled", response=None)]).query(1) + self.assertEqual(dto["summary"]["completed_count"], 0) + self.assertEqual(dto["rows"][0]["status"], "unknown") + self.assertIsNone(dto["rows"][0]["confirmed_ke"]) + + def test_reconciled_acceptance_needs_new_instance_and_does_not_invent_reason(self): + self.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "402", "curStep": 1}] + record = self.receipt("a", kind="accept", task_id=0, outcome="reconciled", response=None, + baseline={"tasks": [{"id": 51, "typeId": "402"}]}, + commission_task={"id": 52, "typeId": "402", "curStep": 1}) + ledger = self.ledger([record]) + dto = ledger.query(1) + self.assertEqual(dto["summary"]["accepted_count"], 1) + self.assertEqual(dto["rows"][0]["task_id"], 52) + self.assertEqual(dto["rows"][0]["selection_code"], "unknown") + self.snapshot.raw["currentTasks"] = [] + restored = CommissionHistory(self.folder / "history.json") + restored.ingest(1, [record], self.tasks.get, self.snapshot) + self.assertEqual(restored.query(1)["summary"]["accepted_count"], 1) + + def test_old_reconciled_acceptance_cannot_bind_to_unrelated_current_instance(self): + self.snapshot.raw["currentTasks"] = [{"id": 99, "typeId": "402", "curStep": 1}] + stamp = self.snapshot.now - 2 * 86400 + ledger = self.ledger([self.receipt("old-a", kind="accept", task_id=0, + when=stamp, outcome="reconciled", response=None)]) + dto = ledger.query(1, beijing_day(stamp)) + self.assertIsNone(dto["rows"][0]["task_id"]) + self.assertEqual(dto["summary"]["accepted_count"], 0) + + def test_fresh_snapshot_reconciliation_captures_exact_new_acceptance_instance(self): + engine = self.engine() + record = self.record(engine, kind="progression_loop_accept", path="taskService/taskLoopReceive", + task_id=0, outcome=None) + engine.battle_journal.update(record, "unknown") + self.snapshot.raw["currentTasks"] = [{"id": 52, "typeId": "402", "curStep": 1}] + engine.read_snapshot(sync_master=False) + dto = engine.commission_history() + self.assertEqual(dto["summary"]["accepted_count"], 1) + self.assertEqual(dto["rows"][0]["task_id"], 52) + self.client.call.assert_not_called() + + def test_acceptance_validates_numeric_ids_and_instance_identity(self): + for identifier, valid in (("51", True), (True, False), (51.5, False), ("bad", False)): + with self.subTest(identifier=identifier): + ledger = CommissionHistory() + ledger.ingest(1, [self.receipt(str(identifier), kind="accept", task_id=0, + response={"task": {"id": identifier, "typeId": "402", "curStep": "1"}})], self.tasks.get) + self.assertEqual(ledger.query(1)["summary"]["accepted_count"], int(valid)) + ledger = CommissionHistory() + ledger.ingest(1, [self.receipt("wrong", kind="accept", task_id=0, + response={"resCode": 0, "task": {"id": 52, "typeId": "401", "curStep": 1}})], self.tasks.get) + self.assertEqual(ledger.query(1)["summary"]["accepted_count"], 0) + + def test_duplicate_attempts_and_receipts_deduplicate_daily_counts_by_instance(self): + records = [self.receipt("a1", kind="accept", task_id=0, + response={"task": {"id": 51, "typeId": "402", "curStep": 1}}), + self.receipt("a2", kind="accept", task_id=0, + response={"task": {"id": "51", "typeId": "402", "curStep": 1}}), + self.receipt("c1", response={"reward": {"ke": 20}}), + self.receipt("c2", task_id="51", response={"reward": {"ke": 20}})] + ledger = self.ledger(records) + ledger.ingest(1, records, self.tasks.get) + dto = ledger.query(1) + self.assertEqual(len(dto["events"]), 4) + self.assertEqual(len(dto["rows"]), 1) + self.assertEqual(dto["summary"]["accepted_count"], 1) + self.assertEqual(dto["summary"]["completed_count"], 1) + self.assertEqual(dto["summary"]["expected_ke"], 20) + self.assertEqual(dto["summary"]["confirmed_ke"], 20) + + def test_beijing_midnight_repeat_types_and_cross_day_duplicate_claims(self): + midnight = datetime(2026, 11, 13, tzinfo=CN).timestamp() + records = [self.receipt("old", when=midnight - 1, response={"reward": {"ke": 20}}), + self.receipt("duplicate", when=midnight + 1, response={"reward": {"ke": 20}}), + self.receipt("new", task_id=52, when=midnight + 2, response={"reward": {"ke": 20}})] + ledger = self.ledger(records, now=midnight + 10) + self.assertEqual(beijing_day(midnight - 1), "2026-11-12") + self.assertEqual(ledger.query(1)["date"], "2026-11-13") + self.assertEqual(ledger.query(1, "2026-11-12")["summary"]["confirmed_ke"], 20) + dto = ledger.query(1) + self.assertEqual(len(dto["rows"]), 2) + self.assertEqual(dto["summary"]["completed_count"], 1) + self.assertEqual(dto["summary"]["confirmed_ke"], 20) + self.assertEqual(len({row["id"] for row in dto["rows"]}), 2) + self.assertEqual(dto["dates"], ["2026-11-13", "2026-11-12"]) + + def test_pending_and_failure_states_never_claim_success(self): + for phase, outcome, expected in (("request_pending", "", "pending"), ("unknown", "", "unknown"), + ("done", "cancelled", "cancelled"), ("done", "loss", "failed")): + with self.subTest(expected=expected): + ledger = CommissionHistory() + ledger.ingest(1, [self.receipt(expected, kind="step", phase=phase, outcome=outcome)], self.tasks.get) + dto = ledger.query(1) + self.assertEqual(dto["rows"][0]["status"], expected) + self.assertEqual(dto["summary"]["completed_count"], 0) + self.assertNotIn(";已确认", dto["events"][0]["description"]) + + def test_existing_task_action_is_not_counted_as_accepted_today(self): + dto = self.ledger([self.receipt("s", kind="step")]).query(1) + self.assertEqual(dto["summary"]["accepted_count"], 0) + self.assertIsNone(dto["rows"][0]["accepted_at"]) + self.assertEqual(dto["rows"][0]["selection_code"], "already_accepted") + + def test_role_isolation_and_dto_mutation_cannot_change_history(self): + ledger = self.ledger([self.receipt("c", response={"reward": {"ke": 20}})]) + self.assertEqual(ledger.query(2)["rows"], []) + dto = ledger.query(1) + dto["rows"][0]["events"][0]["description"] = "changed" + dto["summary"]["confirmed_ke"] = 10000 + self.assertEqual(ledger.query(1)["summary"]["confirmed_ke"], 20) + self.assertNotEqual(ledger.query(1)["events"][0]["description"], "changed") + + def test_bounded_retention_and_journal_rollover_preserve_imported_receipts(self): + now = self.snapshot.now + records = [self.receipt(str(number), task_id=number + 1, when=now - number, + response={"reward": {"ke": 20}}) for number in range(8)] + records.append(self.receipt("ancient", task_id=99, when=now - 91 * 86400, response={"reward": {"ke": 20}})) + ledger = self.ledger(records, max_events=4) + self.assertEqual(len(ledger.query(1)["events"]), 4) + ledger.ingest(1, [], self.tasks.get) + restored = CommissionHistory(self.folder / "history.json", max_events=4) + self.assertEqual(restored.query(1)["summary"]["completed_count"], 4) + + def test_history_reads_do_not_reload_journal_or_load_full_progression(self): + engine = self.engine() + engine.game_data = None + self.record(engine, type_id="100", response={"reward": {"ke": 20}}) + with patch("ranch_assistant.game_data.load_progression_data", side_effect=AssertionError("unexpected full load")), \ + patch.object(engine.battle_journal, "records", side_effect=AssertionError("unexpected payload copy")), \ + patch.object(engine.battle_journal, "reload", side_effect=AssertionError("unexpected journal reload")): + engine.commission_history() + engine.commission_history() + self.client.call.assert_not_called() + + def test_history_write_failure_preserves_success_and_recovers_without_game_retry(self): + engine = self.engine() + engine._ensure_progression() + intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0] + self.client.call.side_effect = lambda *args: {"resCode": 0, "task": {"id": 51, "typeId": "402", "curStep": 1}} + with patch.object(engine._commission_history, "_save", side_effect=OSError("fixture disk full")): + message = engine._execute_task_intent(intent) + self.assertIn("已确认", message) + dto = engine.commission_history() + self.assertEqual(dto["summary"]["accepted_count"], 1) + self.assertIn("暂未写入磁盘", dto["error"]) + self.assertEqual(self.client.call.call_count, 1) + self.assertIsNone(engine.battle_journal.pending(self.snapshot)) + recovered = engine.commission_history() + self.assertEqual(recovered["error"], "") + self.assertTrue(engine._commission_history.path.exists()) + self.assertEqual(self.client.call.call_count, 1) + + def test_acceptance_timeout_stays_unknown_and_restart_never_replays(self): + engine = self.engine() + engine._ensure_progression() + intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0] + self.client.call.side_effect = TimeoutError("offline timeout") + with self.assertRaises(TimeoutError): + engine._execute_task_intent(intent) + self.assertEqual(engine.commission_history()["rows"][0]["status"], "unknown") + restored = self.engine() + restored._refresh_progression_cache(force=True) + _, _, message = restored._run_progression_intent() + self.assertIn("待核对", message) + self.assertEqual(self.client.call.call_count, 1) + self.assertEqual(restored.commission_history()["summary"]["accepted_count"], 0) + + def test_accepted_reply_without_task_is_unknown_in_both_log_and_history(self): + engine = self.engine() + engine._ensure_progression() + intent = engine.progression_planner.commission_plan(self.snapshot, engine.quest_policy, engine.policy)[0] + self.client.call.side_effect = lambda *args: {"resCode": 0} + message = engine._execute_task_intent(intent) + self.assertIn("结果未知", message) + self.assertNotIn(";已确认", message) + self.assertEqual(engine.commission_history()["summary"]["accepted_count"], 0) + self.assertIsNotNone(engine.battle_journal.pending(self.snapshot)) + + def test_offer_diagnostics_and_selection_explain_locked_city_and_runtime(self): + engine = self.engine() + self.snapshot.raw["history"]["unlockCity"]["2"] = False + engine._refresh_progression_cache(force=True) + selected = engine.progression_planner.commission_selection + self.assertEqual(selected["task_type_id"], "401") + self.assertEqual(selected["selection_code"], "20_ineligible") + self.assertIn("城市尚未解锁", selected["selection_reason"]) + with patch.object(engine, "_battle_capability", side_effect=AssertionError("UI must not inspect runtime")): + for _ in range(3): + rows = engine.commission_offer_diagnostics() + high = next(row for row in rows if row["task_type_id"] == "402") + self.assertFalse(high["eligible"]) + self.assertEqual(high["reason"], "城市尚未解锁") + self.client.call.assert_not_called() + engine._commission_offer_supported = Mock(side_effect=lambda key: str(key) != "402") + engine._commission_offer_reason = "保护目标规则暂不支持" + self.snapshot.raw["history"]["unlockCity"]["2"] = True + engine._refresh_progression_cache(force=True) + self.assertIn("保护目标规则暂不支持", engine.progression_planner.commission_selection["selection_reason"]) + + def test_quota_and_city_filter_diagnostics_do_not_claim_receivable(self): + engine = self.engine() + engine.quest_policy.city = 1 + engine._refresh_progression_cache(force=True) + high = next(row for row in engine.commission_offer_diagnostics() if row["task_type_id"] == "402") + self.assertFalse(high["eligible"]) + self.assertIn("策略限定城市", high["reason"]) + self.snapshot.raw["history"]["loopTaskNum"] = 0 + engine._refresh_progression_cache(force=True) + rows = engine.commission_offer_diagnostics() + self.assertTrue(all(not row["eligible"] for row in rows)) + self.assertIn("当日接取次数已用完", next(row for row in rows if row["city"] == 1)["reason"]) + + def test_unchanged_snapshot_replans_after_beijing_midnight_grace(self): + engine = self.engine() + before = datetime(2026, 11, 13, 23, 59, 59, tzinfo=CN).timestamp() + self.snapshot.raw["history"].update(loopTaskTime=before, loopTaskNum=0) + original = deepcopy(self.snapshot.raw) + with patch("ranch_assistant.model.time.time", return_value=before): + engine._refresh_progression_cache(force=True) + self.assertFalse(any(intent.kind == "progression_loop_reset" for intent in engine._progression_intents)) + with patch("ranch_assistant.model.time.time", return_value=before + 12): + engine._refresh_progression_cache() + self.assertEqual(self.snapshot.raw, original) + self.assertTrue(any(intent.kind == "progression_loop_reset" for intent in engine._progression_intents)) + + def test_no_twenty_fallback_still_explains_rejected_fifteen(self): + self.snapshot.raw["history"]["loopTask"] = {"1": ["400", "401"]} + self.tasks["401"]["closed"] = True + for planner in (ProgressionPlanner(self.catalog, config(self.tasks)), TaskPlanner(self.catalog)): + self.catalog.data["task_info"] = self.tasks + if isinstance(planner, TaskPlanner): + action = planner.plan(self.snapshot, QuestPolicy(enabled=True), self.engine().policy)[0] + self.assertEqual(action.payload["taskTypeId"], "400") + else: + self.assertEqual(planner.commission_plan(self.snapshot, QuestPolicy(enabled=True), self.engine().policy)[0].task_type_id, "400") + self.assertEqual(planner.commission_selection["selection_code"], "no_20_offered") + self.assertIn("未提供20", planner.commission_selection["selection_reason"]) + self.assertIn("委托已关闭", planner.commission_selection["selection_reason"]) + + def test_step_log_names_consumed_and_only_checked_items(self): + self.catalog.data.setdefault("item_names", {})["30001"] = "石块" + for remove, expected in ((True, "提交石块×5"), (False, "核对持有石块×5")): + with self.subTest(remove=remove): + engine = Engine(self.catalog, self.client, game_data=ProgressionData(config({"402": task("402", type=4, + reward={"ke": 20}, steps=[step("getItem", statusValue={"type": "30001", "num": 5, "remove": remove})])}))) + engine.snapshot = self.snapshot + intent = {"kind": "quest_step", "task_id": 51, "task_type_id": "402", "step_number": 1, + "path": "taskService/taskCompleteStep", "payload": {}, "description": "提交步骤"} + record = engine.battle_journal.begin(self.snapshot, intent) + engine._journal_commission(record, intent, legacy=True) + engine.battle_journal.update(record, "acknowledged", response={"resCode": 0}, response_confirmed=True) + engine.battle_journal.finish(self.snapshot, record, "task") + dto = engine.commission_history() + self.assertIn(expected, dto["events"][0]["description"]) + self.assertIn("20氪金", dto["events"][0]["description"]) + + def test_navigation_and_dialogue_are_local_evidence_with_honest_labels(self): + records = [self.receipt("n", kind="navigate", outcome="local", description="前往王城市场"), + self.receipt("d", kind="dialogue", outcome="local", description="与妮娜对话")] + dto = self.ledger(records).query(1) + self.assertEqual({event["kind"] for event in dto["events"]}, {"navigate", "dialogue"}) + self.assertTrue(all(event["confirmation"] == "local" for event in dto["events"])) + self.assertEqual(dto["summary"]["accepted_count"], 0) + + def test_invalid_day_and_corrupt_history_preserve_file(self): + ledger = self.ledger([]) + for day in ("20261113", "2026-02-30", "2026-1-1", 20261113): + with self.subTest(day=day), self.assertRaises(ValueError): + ledger.query(1, day) + damaged = self.folder / "damaged.json" + damaged.write_text("not-json", encoding="utf-8") + ledger = CommissionHistory(damaged) + ledger.ingest(1, [self.receipt("c", response={"reward": {"ke": 20}})], self.tasks.get) + self.assertIn("无法读取", ledger.query(1)["error"]) + self.assertEqual(damaged.read_text(encoding="utf-8"), "not-json") + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_assistant/tests/test_commission_history_review.py b/ranch_assistant/tests/test_commission_history_review.py new file mode 100644 index 0000000..f9ca32a --- /dev/null +++ b/ranch_assistant/tests/test_commission_history_review.py @@ -0,0 +1,369 @@ +"""Independent offline review repros; all records and accounts are synthetic.""" +from copy import deepcopy +from datetime import datetime, timezone +import json +from pathlib import Path +import tempfile +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from ranch_assistant.battles import BattleJournal +from ranch_assistant.commission_history import CommissionHistory, journal_event +from ranch_assistant.engine import Engine +from ranch_assistant.game_data import ProgressionData +from ranch_assistant.model import Catalog, Policy, Snapshot +from ranch_assistant.progression import ProgressionPlanner +from ranch_assistant.quests import QuestPolicy + + +NOW = datetime(2026, 11, 13, 4, tzinfo=timezone.utc).timestamp() +DAY = "2026-11-13" +INFO = {"id": "review20", "type": 4, "name": "Review commission", "reward": {"ke": 20}, + "startStep": {"condition": {}}, "steps": [{"statusType": "none", "statusValue": {}}]} + + +def review_snapshot(role=71, tasks=()): + return Snapshot({"master": {"id": role, "level": 20, "money": 2000, "ti": 50, "ke": 99999}, + "currentTasks": deepcopy(list(tasks)), "history": {"unlockCity": {"1": True}}, + "items": [], "monsters": [], "stacks": [], "rooms": [], "teams": []}) + + +def review_record(attempt="review-claim", *, kind="complete", task_id=81, timestamp=NOW, **changes): + record = {"attempt_id": attempt, "role_id": "71", "task_id": task_id, "task_type_id": "review20", + "kind": {"accept": "progression_loop_accept", "complete": "progression_reward", + "step": "progression_step", "battle": "progression_battle"}[kind], + "path": {"accept": "taskService/taskLoopReceive", "complete": "taskService/taskComplete", + "step": "taskService/taskCompleteStep", "battle": ""}[kind], + "timestamp": timestamp, "updated_at": timestamp, "finished_at": timestamp, + "phase": "done", "outcome": "task", "payload": {}, + "commission": {"name": INFO["name"], "expected_ke": 20, "city": 1, + "selection_code": "highest_reward", "selection_reason": "review-selected"}, + "baseline": {"tasks": []}, "response_confirmed": True, + "response": {"resCode": 0, "reward": {"ke": 20}}} + if kind == "accept": + record.update(task_id=None, response={"resCode": 0, + "task": {"id": task_id, "typeId": "review20", "curStep": 1}}) + record.update(changes) + return record + + +class CommissionHistoryIndependentReviewTests(unittest.TestCase): + def setUp(self): + self.folder = Path(self.enterContext(tempfile.TemporaryDirectory(prefix="commission-independent-review-"))) + self.enterContext(patch("socket.socket.connect", side_effect=AssertionError("offline review forbids network"))) + self.history = CommissionHistory(self.folder / "history.json", clock=lambda: NOW) + + def ingest(self, records, snapshot=None, history=None, role="71"): + target = history if history is not None else self.history + target.ingest(role, records, lambda key: INFO, snapshot) + return target.query(role, DAY) + + def test_cancelled_accept_with_task_body_is_never_confirmed(self): + record = review_record(kind="accept", outcome="cancelled") + event = journal_event(record, INFO, review_snapshot()) + self.assertEqual(event["status"], "cancelled") + result = self.ingest([record]) + self.assertEqual(result["summary"]["accepted_count"], 0) + self.assertEqual(result["summary"]["expected_ke"], 0) + self.assertIsNone(result["rows"][0]["accepted_at"]) + + def test_pending_receipt_body_does_not_count_as_a_claim(self): + record = review_record(phase="request_pending", outcome="", response_confirmed=False) + result = self.ingest([record]) + self.assertEqual(result["summary"]["completed_count"], 0) + self.assertEqual(result["summary"]["confirmed_ke"], 0) + self.assertEqual(result["summary"]["pending_count"], 1) + self.assertIsNone(result["rows"][0]["confirmed_ke"]) + + def test_cancelled_and_failed_outcomes_stay_terminal_in_aggregate(self): + for outcome, status in (("cancelled", "cancelled"), ("unsupported", "cancelled"), ("loss", "failed")): + with self.subTest(outcome=outcome): + ledger = CommissionHistory(clock=lambda: NOW) + result = self.ingest([review_record(kind="battle", outcome=outcome)], history=ledger) + self.assertEqual(result["events"][0]["status"], status) + self.assertEqual(result["rows"][0]["status"], status) + self.assertEqual(result["summary"]["pending_count"], 0) + self.assertEqual(result["summary"]["completed_count"], 0) + + def test_unknown_result_stays_unknown_and_pending_in_summary(self): + result = self.ingest([review_record(phase="task_unknown", outcome="", response=None, + response_confirmed=False)]) + self.assertEqual(result["rows"][0]["status"], "unknown") + self.assertEqual(result["summary"]["pending_count"], 1) + self.assertEqual(result["summary"]["completed_count"], 0) + + def test_duplicate_claim_attempts_count_one_instance_once(self): + result = self.ingest([review_record("claim-one"), review_record("claim-two", timestamp=NOW + 1)]) + self.assertEqual(len(result["events"]), 2, "retain both attempts as evidence") + self.assertEqual(len(result["rows"]), 1) + self.assertEqual(result["summary"]["completed_count"], 1) + self.assertEqual(result["summary"]["confirmed_ke"], 20) + + def test_duplicate_claim_on_later_day_does_not_create_new_reward(self): + before = datetime(2026, 11, 12, 15, 59, tzinfo=timezone.utc).timestamp() + after = before + 120 + result = self.ingest([review_record("claim-before", timestamp=before), + review_record("claim-after", timestamp=after)]) + self.assertEqual(result["summary"]["completed_count"], 0) + self.assertEqual(result["summary"]["confirmed_ke"], 0) + self.assertEqual(self.history.query("71", "2026-11-12")["summary"]["confirmed_ke"], 20) + + def test_same_type_different_instances_are_counted_separately(self): + result = self.ingest([review_record("claim-one", task_id=81), + review_record("claim-two", task_id=82, timestamp=NOW + 1)]) + self.assertEqual(len(result["rows"]), 2) + self.assertEqual(result["summary"]["completed_count"], 2) + self.assertEqual(result["summary"]["confirmed_ke"], 40) + + def test_reconciled_accept_is_reconsidered_when_snapshot_changes(self): + record = review_record(kind="accept", task_id=81, response=None, + response_confirmed=False, outcome="reconciled") + first = self.ingest([record], review_snapshot()) + self.assertEqual(first["summary"]["accepted_count"], 0) + second = self.ingest([record], review_snapshot(tasks=[{"id": 81, "typeId": "review20", "curStep": 1}])) + self.assertEqual(second["summary"]["accepted_count"], 1) + self.assertEqual(second["rows"][0]["task_id"], 81) + + def test_old_accept_today_claim_uses_beijing_day_for_each_count(self): + before = datetime(2026, 11, 12, 15, 59, tzinfo=timezone.utc).timestamp() + after = before + 120 + today = self.ingest([review_record("accept-old", kind="accept", timestamp=before), + review_record("claim-today", timestamp=after)]) + yesterday = self.history.query("71", "2026-11-12") + self.assertEqual(today["summary"]["accepted_count"], 0) + self.assertEqual(today["summary"]["expected_ke"], 0) + self.assertEqual(today["summary"]["completed_count"], 1) + self.assertEqual(today["summary"]["confirmed_ke"], 20) + self.assertEqual(yesterday["summary"]["accepted_count"], 1) + self.assertEqual(yesterday["summary"]["completed_count"], 0) + self.assertEqual(today["rows"][0]["accepted_at"], before) + + def test_missing_historical_metadata_never_invents_reason_or_reward(self): + record = review_record(commission={}, response={"resCode": 0, "ke": 99999}) + result = self.ingest([record], review_snapshot()) + row = result["rows"][0] + self.assertIsNone(row["accepted_at"]) + self.assertIsNone(row["confirmed_ke"]) + self.assertNotIn("review-selected", row["selection_reason"]) + self.assertEqual(result["summary"]["confirmed_ke"], 0) + self.assertEqual(result["summary"]["unknown_reward_count"], 1) + + def test_unconfirmed_historical_accept_does_not_describe_itself_as_confirmed(self): + result = self.ingest([review_record(kind="accept", commission={}, phase="request_pending", + outcome="", response=None, response_confirmed=False)]) + self.assertEqual(result["summary"]["accepted_count"], 0) + self.assertNotIn("已确认", result["rows"][0]["selection_reason"]) + + def test_invalid_reward_values_are_unknown_not_catalog_or_wallet_amounts(self): + for value in (None, True, "20", -1, 1.5, float("nan"), float("inf")): + with self.subTest(value=value): + ledger = CommissionHistory(clock=lambda: NOW) + result = self.ingest([review_record(response={"resCode": 0, "reward": {"ke": value}})], + history=ledger) + self.assertEqual(result["summary"]["completed_count"], 1) + self.assertEqual(result["summary"]["confirmed_ke"], 0) + self.assertIsNone(result["rows"][0]["confirmed_ke"]) + + def test_read_and_restart_are_idempotent_and_return_detached_data(self): + records = [review_record()] + expected = self.ingest(records) + before = self.history.path.read_bytes() + for _ in range(3): + self.assertEqual(self.ingest(records), expected) + self.assertEqual(self.history.query("71", DAY), expected) + self.assertEqual(self.history.path.read_bytes(), before) + restored = CommissionHistory(self.history.path, clock=lambda: NOW) + self.assertEqual(self.ingest(records, history=restored), expected) + copy = restored.query("71", DAY) + copy["rows"][0]["name"] = "caller mutation" + self.assertEqual(restored.query("71", DAY), expected) + + def test_role_and_separate_account_paths_are_isolated(self): + self.ingest([review_record()]) + other = review_record(role_id="72", response={"resCode": 0, "reward": {"ke": 15}}) + self.ingest([other], role="72") + self.assertEqual(self.history.query("71", DAY)["summary"]["confirmed_ke"], 20) + self.assertEqual(self.history.query("72", DAY)["summary"]["confirmed_ke"], 15) + separate = CommissionHistory(self.folder / "other-account" / "history.json", clock=lambda: NOW) + self.assertEqual(separate.query("71", DAY)["events"], []) + + def test_ledger_survives_rolling_journal_eviction_and_restart(self): + snapshot = review_snapshot() + journal = BattleJournal(self.folder / "journal.json") + journal.role(snapshot)["records"].append(review_record()) + journal.save() + self.ingest(journal.role(snapshot)["records"]) + journal.role(snapshot)["records"].extend({"attempt_id": f"other-{i}", "role_id": "71"} + for i in range(501)) + journal.save() + self.assertEqual(len(journal.role(snapshot)["records"]), 500) + self.assertNotIn("review-claim", {r["attempt_id"] for r in journal.role(snapshot)["records"]}) + self.ingest(journal.role(snapshot)["records"]) + restored = CommissionHistory(self.history.path, clock=lambda: NOW) + result = restored.query("71", DAY) + self.assertEqual(result["summary"]["completed_count"], 1) + self.assertEqual(result["summary"]["confirmed_ke"], 20) + + def test_event_cap_and_retention_preserve_newest_events_on_restart(self): + ledger = CommissionHistory(self.folder / "bounded.json", max_events=2, retention_days=2, clock=lambda: NOW) + self.ingest([review_record(f"event-{i}", task_id=81 + i, timestamp=NOW + i) + for i in (-3 * 86400, 0, 1, 2)], history=ledger) + restored = CommissionHistory(ledger.path, max_events=2, retention_days=2, clock=lambda: NOW) + result = restored.query("71", DAY) + self.assertEqual({e["id"] for e in result["events"]}, {"event-1", "event-2"}) + + def test_corrupt_history_is_reported_and_original_bytes_preserved(self): + path = self.folder / "corrupt.json" + path.write_text('{"broken":', encoding="utf-8") + before = path.read_bytes() + ledger = CommissionHistory(path, clock=lambda: NOW) + result = self.ingest([review_record()], history=ledger) + self.assertTrue(result["error"]) + self.assertEqual(result["events"], []) + self.assertEqual(path.read_bytes(), before) + + def test_incomplete_persisted_event_reports_error_instead_of_crashing_read(self): + path = self.folder / "incomplete-event.json" + path.write_text(json.dumps({"version": 1, "roles": {"71": {"bad-event": { + "id": "bad-event", "time": NOW, "date": DAY, "kind": "complete", "status": "confirmed"}}}}), + encoding="utf-8") + before = path.read_bytes() + ledger = CommissionHistory(path, clock=lambda: NOW) + result = ledger.query("71", DAY) + self.assertTrue(result["error"]) + self.assertEqual(path.read_bytes(), before) + + def test_cancelled_history_row_is_labelled_cancelled_by_web(self): + from ranch_web.policies import default_config + from ranch_web.views import build_view + + history = self.ingest([review_record(kind="accept", outcome="cancelled")]) + engine = Engine(Catalog()) + engine.snapshot = review_snapshot() + engine.commission_history = Mock(return_value=history) + dto = build_view(engine, "commissions", default_config(), {"tab": "history", "date": DAY}) + self.assertEqual(dto["rows"][0]["status_label"], "已取消") + self.assertIn("已取消", dto["details"][dto["rows"][0]["id"]]["行动记录"]) + + +class CommissionRunMessageIndependentReviewTests(unittest.TestCase): + def test_uncertain_accept_is_not_resent_after_engine_restart(self): + with tempfile.TemporaryDirectory(prefix="commission-uncertain-review-") as directory: + client = Mock() + client.call.side_effect = TimeoutError("synthetic uncertain write") + path = Path(directory) / "budget.json" + data = ProgressionData({"task_info": {"review20": deepcopy(INFO)}, "scripts": {}, + "stage_info": {}, "game_setting": {"cityInfo": {"1": {}}}}) + engine = Engine(Catalog(), client, path, game_data=data) + engine.snapshot = review_snapshot() + engine.snapshot.raw["history"].update(loopTaskTime=engine.snapshot.now, loopTaskNum=6, + loopTask={"1": ["review20"]}) + engine.quest_policy.enabled = True + engine._refresh_progression_cache(force=True) + intent = next(i for i in engine._progression_intents if not i.blocked) + self.assertEqual(intent.kind, "progression_loop_accept") + with self.assertRaises(TimeoutError): + engine._run_progression_intent(intent) + self.assertEqual(client.call.call_count, 1) + self.assertIsNotNone(engine.battle_journal.pending(engine.snapshot)) + restored = Engine(Catalog(), client, path, game_data=data) + restored.snapshot = review_snapshot() + restored.quest_policy.enabled = True + for _ in range(3): + _, _, message = restored._run_progression_intent(intent) + self.assertIn("核对", message) + self.assertEqual(restored.commission_history()["summary"]["accepted_count"], 0) + self.assertEqual(restored.commission_history()["summary"]["completed_count"], 0) + self.assertEqual(client.call.call_count, 1) + + def test_history_save_failure_recovers_without_replaying_game_request(self): + with tempfile.TemporaryDirectory(prefix="commission-storage-review-") as directory: + client = Mock() + client.call.side_effect = AssertionError("history must never replay a game write") + engine = Engine(Catalog(), client, Path(directory) / "budget.json", + game_data=ProgressionData({"task_info": {"review20": deepcopy(INFO)}})) + engine.snapshot = review_snapshot() + engine._commission_history.clock = lambda: NOW + engine.battle_journal.role(engine.snapshot)["records"].append(review_record()) + engine.battle_journal.save() + with patch.object(engine._commission_history, "_save", side_effect=PermissionError("synthetic disk error")): + engine._sync_commission_history() + result = engine.commission_history(DAY) + self.assertTrue(result["error"]) + self.assertEqual(result["summary"]["completed_count"], 1) + engine._sync_commission_history() + self.assertFalse(engine.commission_history(DAY)["error"]) + restored = CommissionHistory(engine._commission_history.path, clock=lambda: NOW) + self.assertEqual(restored.query("71", DAY)["summary"]["completed_count"], 1) + client.call.assert_not_called() + + def test_battle_early_return_cannot_replay_old_commission_success(self): + for early_return in ("resources", "cancelled", "lock"): + with self.subTest(early_return=early_return), tempfile.TemporaryDirectory( + prefix="commission-message-review-") as directory: + client = Mock() + client.call.side_effect = AssertionError("offline review forbids game writes") + client.snapshot.side_effect = AssertionError("offline review forbids game reads") + engine = Engine(Catalog(), client, Path(directory) / "budget.json", + game_data=ProgressionData({"task_info": {"review20": deepcopy(INFO)}})) + engine.snapshot = review_snapshot() + engine.quest_policy.enabled = True + engine._commission_history.clock = lambda: NOW + state = engine.battle_journal.role(engine.snapshot) + state["records"].append(review_record()) + engine.battle_journal.save() + engine._sync_commission_history() + history_before = engine.commission_history(DAY) + journal_before = deepcopy(state["records"]) + engine.plans = Mock(return_value=[]) + engine.read_snapshot = Mock(return_value=engine.snapshot) + engine._refresh_progression_cache = Mock() + engine._intent_policy = Mock(return_value=SimpleNamespace(enabled=True, team="teamA")) + intent = {"kind": "progression_battle", "task_id": 82, "task_type_id": "review20", + "step_number": 1, "block_reason": ""} + if early_return == "resources": + expected = "review-resource-shortage" + engine.battles.resource_reason = Mock(return_value=expected) + elif early_return == "cancelled": + expected = "任务 / 战斗已取消,未开始" + def cancel_during_preflight(*args): + engine._progression_cancel.set() + return "" + engine.battles.resource_reason = Mock(side_effect=cancel_during_preflight) + else: + expected = "同账号已有任务 / 战斗正在执行" + engine.battles.run = Mock(return_value=expected) + with patch.object(engine.battle_journal, "begin", wraps=engine.battle_journal.begin) as begin: + _, _, message = engine._run_progression_intent(intent) + begin.assert_not_called() + client.call.assert_not_called() + client.snapshot.assert_not_called() + self.assertEqual(state["records"], journal_before) + self.assertEqual(engine.commission_history(DAY), history_before) + self.assertEqual(message, expected, "a previous confirmed claim must not replace the new blocked message") + + +class CommissionSelectionIndependentReviewTests(unittest.TestCase): + def test_fallback_to_ten_explains_rejected_fifteen_when_twenty_absent(self): + tasks = {} + for amount in (10, 15): + tasks[str(amount)] = deepcopy(INFO) | {"id": str(amount), "name": f"review-{amount}", + "closed": amount == 15, "reward": {"ke": amount}} + data = {"task_info": tasks, "scripts": {}, "stage_info": {}, + "game_setting": {"cityInfo": {"1": {}, "2": {}}}} + snapshot = review_snapshot() + snapshot.raw["history"].update(loopTaskTime=snapshot.now, loopTaskNum=6, + loopTask={"1": ["10"], "2": ["15"]}, unlockCity={"1": True, "2": True}) + planner = ProgressionPlanner(Catalog(), data) + actions = planner.commission_plan(snapshot, QuestPolicy(enabled=True), Policy()) + self.assertEqual(actions[0].task_type_id, "10") + self.assertEqual([b["task_type_id"] for b in planner.commission_selection["higher_reward_blockers"]], ["15"]) + reason = planner.commission_selection["selection_reason"] + self.assertIn("review-15", reason) + self.assertIn("关闭", reason) + self.assertIn("20", reason) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_web/PRODUCT.md b/ranch_web/PRODUCT.md index 5e00658..99baeb9 100644 --- a/ranch_web/PRODUCT.md +++ b/ranch_web/PRODUCT.md @@ -1,8 +1,8 @@ -# 牧羊人之心牧场助手 · Web 2.0.7 +# 牧羊人之心牧场助手 · Web 2.0.8 ## 产品约束 -把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.7`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 +把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。Web `2.0.8`,源码发布入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md),功能与验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 @@ -17,19 +17,29 @@ ## 核心操作 - 账号密码登录后选择区服进入;恢复已保存会话;退出与清除登录记录。游戏凭据仅交给同源服务端,不进入浏览器持久存储或 URL。 -- 手动选服、恢复会话和自动重登成功读取角色后,均默认开启策略,自动执行已配置且已勾选的功能,可在顶部停止;不改变各子功能的勾选。获取区服候选及失败候选不视为登录成功,界面以服务端在线与运行状态为准。导入配置只替换规则并停止执行,下次成功登录仍自动开启;服务重启后未成功登录时不直接执行。 +- 手动选服、恢复会话和自动重登成功读取角色后,默认执行已配置且已勾选的功能,不改变各子功能勾选。用户手动“停止”跨掉线、重登和服务重启保留,点击“开启”恢复;导入配置只替换规则,保留用户启停意图。获取区服候选及失败候选不视为登录成功,服务重启后未成功登录时不执行策略,界面以服务端状态为准。 - 配置通过中文 schema 生成原生控件;逐蛋孵化/补货规则、物品赠礼保留量、逐魔物培养目标、关卡规则等直接在对应页面编辑。自动保存显示待保存、保存中、失败与已保存状态。 - 培育室扩建、牧场锁定/解锁、批量派遣/喂养、上下文菜单和费用二次确认沿用核心行为。切换功能页只读取视图,不触发游戏写操作。 - 主线默认当前主线,可切换筛选。地图按地区默认折叠,展示普通关卡、矿洞、难度、次数和工具库存。探险支持队员手选/自动与完成后自动领奖说明。 - 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。 - 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。 - 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。 -- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 +- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,稳定 Release 与正式镜像发布后,可直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 + +## 2.0.8 自动委托与每日历史 + +- 自动委托包含“当前委托 / 每日记录”。当前页展示原始候选、任务状态、标注奖励及选择 / 回退原因;城市锁定候选显示不可接取。 +- 策略允许且满足城市、次数、资源与步骤支持条件的候选,跨城市按静态预计氪金20→15→10全局排序。高档不可用时日志说明原因,再选择可执行的低档,不保证全部接取20档。 +- 每日记录按账号、区服、角色隔离,以北京时间(UTC+8)自然日查询接取、推进、领奖和待核对事件,刷新和服务重启后可查。每角色保留最近90天、最多5000条事件。 +- 预计奖励与已确认实际奖励分别展示;实际氪金仅来自确认成功的 `taskComplete` 领奖回包 `response.reward.ke`,缺失金额显示“未确认”。接取、推进、预计奖励及旧完成标记不作为到账证据。 +- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失记录。每日历史用于业务进度,运行详情继续使用原单一底部“自动委托”分类日志。 ## 2.0.7 主培养与资质备用 同种只自动培养已养成的高等级主培养;新资质更好的魔物只作为备用保留,不分配经验、礼物或潜能材料。已启用种类按主培养1只、更优备用最多1只整理,新备用严格更优才替换,同分保留已有备用。主培养到上限或冷却时等待,不向同种备用转移资源。硬保护保留,未勾选种类不扩大自动整理范围。 +2.0.8 沿用上述修复及现有界面,历史功能与验证记录见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。 + ## 表单布局(2.0.6 起) 勾选框与右侧文字组成一组;数字、文本与下拉框采用标签在上、控件在下的布局。设置区限定合理宽度,并按可用空间排为多列,每日领取项目在单独分组中排列。界面尺寸变化不改变配置路径、自动保存或策略执行规则。 @@ -69,6 +79,8 @@ ## 安全与验证 +2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。证据与发布门禁见 [发布说明](../analysis/RELEASE_2_0_8.md#验证);历史版本结果不计入本版。 + 不发真实游戏 API 测试,不读取或更改私人 `local_state` 账号。浏览器测试仅使用临时目录、fake 后端或服务端离线演示。所有游戏文本用 `textContent` 呈现;日志使用服务端脱敏数据。管理登录、同源校验与 cookie 由 API 负责。 ## 技术默认假设 diff --git a/ranch_web/README.md b/ranch_web/README.md index 548293d..88a63e6 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -1,19 +1,26 @@ -# Web 2.0.7 运行说明 +# Web 2.0.8 运行说明 -本轮 Web 发布目标 **2.0.7**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 +Web **2.0.8**,源码发布入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。自动委托提供当前委托与每日记录,功能和验证状态见 [2.0.8 发布说明](../analysis/RELEASE_2_0_8.md)。 Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。 ## 迁移清单 - [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。 -- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。 +- [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,未手动停止时,成功登录后自动执行已配置且已勾选的功能;手动暂停跨重登保留,可在顶部开启。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。 - [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。 -- [x] 本轮发布目标为 `2.0.7`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 -- 2.0.7 修复同种重复培养:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [本版发布说明](../analysis/RELEASE_2_0_7.md)。 +- [x] `2.0.8` 自动委托当前 / 每日记录、持久化历史及奖励证据区分;739项独立测试中736通过、3项 Windows 跳过,浏览器77项全部验证通过。战斗模拟仍为近似模型,特殊关卡并非全部支持。 +- 沿用 2.0.7 的同种重复培养修复:主培养与资质备用分离,自动喂养、赠礼和潜能突破仅作用于主培养,启用种类固定主培养1只与更优备用最多1只。详见 [2.0.7 发布说明](../analysis/RELEASE_2_0_7.md)。 - 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。 +## 自动委托(2.0.8) + +- “当前委托”查看任务、原始候选和选择 / 回退原因;城市锁定候选显示不可接取。策略允许且满足城市、次数、资源和步骤条件的候选,跨城市按预计氪金20→15→10排序,日志说明高档不可用的原因。 +- “每日记录”按账号、区服、角色及北京时间(UTC+8)自然日查询接取、推进、领奖与待核对事件。历史持久保存,刷新或重启后可查;每角色保留最近90天、最多5000条事件。 +- 预计氪金来自静态任务配置,已确认氪金仅取确认成功的领奖回包 `response.reward.ke`;金额缺失显示“未确认”。接取、推进、旧完成标记和预计数额不作为实际奖励证据。 +- 旧历史仅从本地任务 journal 可证实的操作部分回填,不推造缺失的过去。业务历史之外的运行详情继续使用原单一底部“自动委托”分类日志。完整行为见 [发布说明](../analysis/RELEASE_2_0_8.md)。 + ## Windows 本地运行 使用 Python 3.12+,在项目根目录执行(本机已安装 3.13): @@ -32,7 +39,7 @@ py -3 -m venv .venv-web .\Start_Ranch_Web.cmd --demo --data-dir "$env:TEMP\ranch-web-demo-new" --no-browser ``` -健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,均默认开启策略,只执行已勾选的功能,子功能不会全选。顶部“停止”暂停策略,仍保留状态监控;可用“开启”继续。登录后默认执行已勾选策略;只有手动“停止”才暂停,手动“开启”恢复。启停选择跨掉线、重新登录和服务重启保存,导入策略不会改变这个选择。 +健康检查 `GET /api/health` 不访问游戏 API。关闭终端时使用 Ctrl+C,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,默认执行已勾选功能,子功能不会全选;用户手动“停止”则继续保持暂停,点击“开启”恢复。启停选择跨掉线、重登和服务重启保存,导入策略保留该选择;停止策略后仍保留状态监控。 ### 后台运行与断线处理 @@ -97,13 +104,13 @@ sh start-web.sh --no-browser Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。 -已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.7 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.7**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,稳定 Release 和正式镜像就绪、宿主机心跳有效后,可直接通过“帮助 → 检查版本更新…”升级 **2.0.8**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 ## 离线验证 -2.0.7 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录不计入本版验收。 +2.0.8 共验证739项独立测试:736通过、3项 Windows 跳过;其中非浏览器662项(659通过、3跳过),浏览器77项全部验证通过。分组结果与证据见 [发布说明](../analysis/RELEASE_2_0_8.md#验证)。2.0.7 的结果保留在 [历史发布说明](../analysis/RELEASE_2_0_7.md#验证),以下历史记录也不计入本版验收。 -### 历史验证记录(不计入 2.0.7) +### 历史验证记录(不计入 2.0.8) 2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。 diff --git a/ranch_web/__init__.py b/ranch_web/__init__.py index 6a852f9..12e3857 100644 --- a/ranch_web/__init__.py +++ b/ranch_web/__init__.py @@ -1,6 +1,6 @@ """Headless Web workspace for the ranch assistant.""" -__version__ = "2.0.7" +__version__ = "2.0.8" GAME_VERSION = "1.9.68" __all__ = ["__version__", "GAME_VERSION"] diff --git a/ranch_web/service.py b/ranch_web/service.py index 4746dbd..c0eff90 100644 --- a/ranch_web/service.py +++ b/ranch_web/service.py @@ -101,6 +101,7 @@ class _Job: workspace: str = "" category: str = "general" due_kind: str | None = None + commission_failure: str = "" def public(self): operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation) @@ -450,10 +451,41 @@ class AccountWorker: # Attribution must not prevent an otherwise valid action. category = "general" self._attribute_task(category) - return _method(*args, **kwargs) + try: + return _method(*args, **kwargs) + except CancelledBeforeDispatch: + raise + except Exception: + if category == "commissions": + # Enrich the existing error entry, preserving the original + # exception and its one-time reporting on the worker. + try: + source = args[0] if args else kwargs.get("intent", kwargs.get("action")) + if source is None and _name == "_run_progression_intent": + source = intent + self._commission_failure_context(engine, source) + except Exception: + pass + raise setattr(engine, name, routed) + def _commission_failure_context(self, engine, source): + if self._execution is None or threading.current_thread() is not getattr(self, "thread", None): + return + field = lambda key, default=None: source.get(key, default) if isinstance(source, dict) else getattr(source, key, default) + payload = field("payload") or {} + type_id = field("source_task_type_id") or field("task_type_id") or payload.get("taskTypeId") + info = engine._commission_info(type_id) + name = info.get("name") or type_id or "名称未记录" + reward = (info.get("reward") or {}).get("ke") + expected = f"标注{reward}氪金" if type(reward) in (int, float) else "标注氪金未记录" + path = field("path", "") or "" + kind = field("kind", "") + action = "接取" if path.endswith("taskLoopReceive") or kind in {"quest_accept", "progression_loop_accept"} else ( + "领奖" if path.endswith("taskComplete") or kind in {"quest_complete", "progression_complete"} else "推进") + self._execution.commission_failure = f"委托「{name}」({expected}){action}异常,结果待核对" + def remember(self, value): with self._secret_lock: if isinstance(value, dict): @@ -544,7 +576,13 @@ class AccountWorker: notes = getattr(getattr(self.engine, name, None), "notes", ()) sources.append((category, [self.safe_text(note) for note in notes[:512]])) for category, text in route_message(self.safe_text(message), context=self._task_category(), hints=note_hints(sources)): - self.log(text, category=category) + level = "info" + if category == "commissions": + if "战斗失败" in text: + level = "error" + elif any(marker in text for marker in ("结果未知", "未确认", "待确认", "等待核对", "奖励未记录")): + level = "warning" + self.log(text, category=category, level=level) def _trace_event(self, event): fields = [event.get("operation", "网络"), event.get("kind", "")] @@ -844,7 +882,7 @@ class AccountWorker: if (job.consuming and job.operation != "start" and failure_sequence == self._game_failure_sequence): self._execution_failed(error) - self.log(message, category=job.category, level="error") + self.log((job.commission_failure + ";" if job.commission_failure else "") + message, category=job.category, level="error") finally: job.payload = {} try: diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index d130235..b954e9b 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -415,7 +415,7 @@ async function exportYields(account=current()) { async function command(name,account=current()) { try { if(name==='add-account'||name==='add-demo')return await addAccount(name==='add-demo'); - if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.7'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true}); + if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.8'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`})),{info:true}); if(name==='updates')return await showUpdates(); if(name==='admin-logout'){hideWorkbench();try{await api.logout();}finally{requireAuth();}return;} if(!account)throw new Error('请先新增或选择账号。'); @@ -640,7 +640,7 @@ async function bootstrap() { $('#app').hidden=false; const [meta,schema]=await Promise.all([api.meta(),api.schema()]);state.meta=meta;state.schema=schema; if(state.redirecting)return; - $('#app-version').textContent=meta.version || '2.0.7';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台'; + $('#app-version').textContent=meta.version || '2.0.8';$('#game-version').textContent=meta.gameVersion || '1.9.68';$('#access-mode').textContent=auth.access_mode==='local'||auth.access_mode==='loopback'?'本机工作台':auth.required?'管理工作台':'本机工作台'; await syncAccounts();if(state.redirecting)return;state.ready=true;setStatus('工作台已连接'); }catch(failure){if(failure.status===401||$('#app').hidden){requireAuth();return;}if(state.redirecting)return;setStatus(failure.message);$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:failure.message}),el('button',{text:'重新连接',onClick:bootstrap})));} } diff --git a/ranch_web/static/index.html b/ranch_web/static/index.html index 07e55cc..6d33606 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -26,7 +26,7 @@ - 牧羊人之心牧场助手 2.0.7 + 牧羊人之心牧场助手 2.0.8
diff --git a/ranch_web/static/pages.js b/ranch_web/static/pages.js index 833d187..bbb5793 100644 --- a/ranch_web/static/pages.js +++ b/ranch_web/static/pages.js @@ -9,7 +9,7 @@ export const PAGES = [ ['commissions', '自动委托'], ['exploration', '自动探险'], ['maps', '自动扫荡'], ['statistics', '数据分析'], ['plans', '执行计划'], ['yields', '收益资料'], ]; -export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {}; +export const initialQuery = page => page === 'bag' ? {category: 'eggs'} : page === 'mainline' ? {category: 'mainline', state: 'current'} : page === 'commissions' ? {tab: 'current'} : page === 'ranch' ? {grouped: false} : page === 'maps' ? {category: 'all', only_unlocked: true} : {}; class LoginPage { constructor(host, page) { @@ -161,7 +161,7 @@ export class PageView { filters.forEach(field => { if (this.key === 'bag' && field.key === 'category') return; included.add(field.key); - if (!Object.hasOwn(this.query, field.key)) this.query[field.key] = field.value; + if (!Object.hasOwn(this.query, field.key) || field.type === 'date' && !this.query[field.key]) this.query[field.key] = field.value; let item = this.filters.get(field.key); const signature = JSON.stringify({...field, value: undefined}); if (!item || item.signature !== signature && !item.root.contains(document.activeElement)) { @@ -170,6 +170,7 @@ export class PageView { set: (_, value) => this.setQuery(field.key, value), onError: this.error, }); if (field.key === 'search') { entry.root.type = 'search'; entry.root.placeholder = this.key === 'maps' ? '关卡、名称或掉落物品' : '按名称或编号筛选'; } + if (field.type === 'date') entry.root.type = 'date'; const root = el('label', {}, el('span', {text: field.label}), entry.root); item?.root.remove(); item = {root, entry, signature}; @@ -187,11 +188,17 @@ export class PageView { if (this.key === 'bag') tabs = [{key:'eggs',title:'魔物蛋'}, {key:'usable',title:'可使用'}, {key:'consumables',title:'消耗品'}, {key:'materials',title:'材料'}, {key:'other',title:'其他'}, {key:'equipment',title:'装备'}]; if (!tabs.length && this.key === 'hatching') tabs = ['孵蛋策略','牧场策略','喂养策略'].map(title => ({key:title,title})); if (!tabs.length && this.key === 'mainline') tabs = [{key:'tasks',title:'任务状态'}, {key:'policy',title:'推进策略'}]; + if (this.key === 'commissions') this.activeSubtab = this.query.tab || 'current'; const signature = JSON.stringify(tabs); if (this.tabSignature !== signature) { if (!this.activeSubtab || !tabs.some(tab => tab.key === this.activeSubtab)) this.activeSubtab = this.key === 'bag' ? this.query.category || tabs[0]?.key : tabs[0]?.key; this.subtabs.replaceChildren(...tabs.map(tab => el('button', {type: 'button', class: 'subtab', role: 'tab', 'data-key': tab.key, text: tab.title || tab.label, - onClick: () => { this.activeSubtab = tab.key; if (this.key === 'bag') this.setQuery('category', tab.key); this.render(this.data || data); }}))); + onClick: () => { + this.activeSubtab = tab.key; + if (this.key === 'commissions') { this.setQuery('tab', tab.key); this.updateSubtabs(data); return; } + if (this.key === 'bag') this.setQuery('category', tab.key); + this.render(this.data || data); + }}))); this.tabSignature = signature; } $$('.subtab', this.subtabs).forEach(button => { const selected = button.dataset.key === this.activeSubtab; button.setAttribute('aria-selected', selected); button.tabIndex = selected ? 0 : -1; }); @@ -220,7 +227,7 @@ export class PageView { const currencies = action.currencies ? optionsList(action.currencies) : [null]; currencies.forEach(currency => { const button = el('button', {type: 'button', text: `${action.label}${currency ? `(${currency.label})` : ''}`, 'data-operation': action.operation, - 'data-selection': action.selection, onClick: () => this.options.action(this, action, currency?.value).catch(this.error)}); + 'data-selection': action.selection, onClick: () => action.operation === 'reload_view' ? this.options.load(this, true).catch(this.error) : this.options.action(this, action, currency?.value).catch(this.error)}); this.actionsHost.append(button); }); }); @@ -296,12 +303,12 @@ export class PageView { const data = this.data.details?.[row.id] || row.details; if (!data) return; const labels = {name:'名称',species:'种类',id:'魔物ID',level:'等级 / 当前上限',quality:'资质 攻/防/血/敏',reference_stats:'参考攻击 / 防御 / 生命 / 敏捷',growth:'成长数值',likes:'喜欢的物品',feel:'好感 / 上限',feed_exp:'喂养经验',scope:'管理范围'}; - const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':'详情'; + const title=this.key==='ranch'?'魔物详情':this.key==='mainline'?'任务详情':this.key==='battles'?'战斗详情':this.key==='commissions'?'委托详情':'详情'; dialog(title, el('div', {class:'detail-sections'}, detailsList(data, labels)), {info:true}); } openContext(event, selected, row) { - const items = [{label:'刷新本页',run:()=>this.perform('refresh',{page:this.key})}]; + const items = [{label:'刷新本页',run:()=>this.key === 'commissions' && this.query.tab === 'history' ? this.options.load(this, true) : this.perform('refresh',{page:this.key})}]; if (this.key === 'ranch') { items.push({label:'查看魔物详情',run:()=>this.showDetail(row)}); (this.data.actions || []).filter(action => ['lock','unlock','sell','feed'].includes(action.operation)).forEach(action => items.push({label:action.label,disabled:!selected.length,run:()=>this.options.action(this,action)})); diff --git a/ranch_web/tests/browser/test_commission_history_browser.py b/ranch_web/tests/browser/test_commission_history_browser.py new file mode 100644 index 0000000..f66282a --- /dev/null +++ b/ranch_web/tests/browser/test_commission_history_browser.py @@ -0,0 +1,218 @@ +"""Commission subtabs, local reads and the original log region over loopback only.""" +from datetime import datetime, timedelta, timezone +import json +from pathlib import Path +import time +import unittest +from unittest.mock import Mock, patch +from urllib.parse import parse_qs, urlsplit + +from ranch_assistant.engine import Engine, demo_snapshot +from ranch_assistant.model import Catalog +from ranch_web.tests.test_commission_history import history_fixture +from ranch_web.views import build_view +from . import test_workbench_browser as fixtures + +if fixtures.AVAILABLE: + from playwright.sync_api import expect + + +@unittest.skipUnless(fixtures.AVAILABLE, "Python Playwright and a system Chromium browser are required") +class CommissionHistoryBrowserTests(unittest.TestCase): + setUpClass = classmethod(fixtures.WorkbenchBrowserTests.setUpClass.__func__) + tearDownClass = classmethod(fixtures.WorkbenchBrowserTests.tearDownClass.__func__) + await_job = fixtures.WorkbenchBrowserTests.await_job + open = fixtures.WorkbenchBrowserTests.open + go = fixtures.WorkbenchBrowserTests.go + fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill) + + def setUp(self): + self.enterContext(patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP forbidden"))) + fixtures.WorkbenchBrowserTests.setUp(self) + self.context.set_default_timeout(6000) + self.today = datetime.now(timezone(timedelta(hours=8))).date() + self.external, self.writes, self.reads, self.pending = [], [], [], [] + self.hold = self.fail_reads = False + self.engines = {} + for identifier, label in ((self.first, "账号一"), (self.second, "账号二")): + engine = Engine(Catalog(), budget_path=Path(self.temp.name) / identifier / "fixture-budget.json") + engine.snapshot = demo_snapshot(engine.catalog) + engine.catalog.data["task_info"] = {"test20": {"name": label + "高额候选", "reward": {"money": 123, "ke": 20}}, + "test15": {"name": label + "回退候选", "reward": {"money": 456, "ke": 15}}} + engine.tasks.rows = Mock(return_value=[("test20", label + "高额候选", "城市 4 可接", "", {"city": 4}), + ("test15", label + "回退候选", "城市 1 可接", "", {"city": 1})]) + engine.tasks.current = Mock(return_value=[]) + engine.commission_offer_diagnostics = Mock(return_value=[]) + engine.progression_rows = Mock(return_value=[{"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"}, + {"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}]) + engine.commission_history = lambda day=None, label=label: self.history(day, label) + engine.client = Mock() + self.engines[identifier] = engine + + def local_only(route): + if route.request.url.startswith(self.base + "/"): + route.continue_() + else: + self.external.append(route.request.url) + route.abort() + + self.context.route("**/*", local_only) + self.page.on("request", lambda request: self.writes.append(request) if request.method in ("POST", "PUT", "PATCH", "DELETE") else None) + + def view(route): + parsed = urlsplit(route.request.url) + identifier = parsed.path.split("/")[-3] + params = parse_qs(parsed.query) + query = json.loads(params["query"][0]) if "query" in params else {key: value[0] for key, value in params.items()} + self.reads.append((identifier, query)) + dto = build_view(self.engines[identifier], "commissions", self.manager.get_config(identifier)["config"], query) + if self.hold: + self.pending.append((route, dto)) + elif self.fail_reads: + route.fulfill(status=503, content_type="application/json", body='{"detail":"本地记录读取失败"}') + else: + self.fulfill(route, {"loading": False, "data": dto}) + + self.page.route("**/api/accounts/*/views/commissions?*", view) + + def history(self, day, label): + fixture = history_fixture(day) + fixture["rows"][0]["name"] = label + day + "提交魔物与道具" + return fixture + + def tearDown(self): + try: + self.assertEqual(self.external, []) + self.assertEqual(self.errors, []) + for engine in self.engines.values(): + engine.client.call.assert_not_called() + finally: + self.context.unroute_all(behavior="ignoreErrors") + self.context.close() + + def records(self): + panel = self.go("commissions") + panel.get_by_role("tab", name="每日记录", exact=True).click() + expect(panel.locator('input[type="date"]')).to_have_value(self.today.isoformat()) + expect(panel.locator("tbody tr")).to_have_count(2) + expect(panel).to_have_attribute("aria-busy", "false") + return panel + + def test_history_refresh_is_get_only_and_original_single_log_stays_collapsed(self): + self.open() + expect(self.page.locator("#page-tabs [role=tab]")).to_have_count(15) + panel = self.records() + expect(panel.get_by_role("tab", name="每日记录")).to_have_attribute("aria-selected", "true") + expect(panel.locator(".policy-form")).to_be_hidden() + expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("已记录接取 2 · 已记录完成 1") + expect(panel.locator(".page-surface > p.page-summary")).to_contain_text("当日领奖确认氪金 15 · 当日接取标注氪金 35") + expect(panel.locator('td[data-column="confirmed_ke"]')).to_have_text(["15", "未确认"]) + expect(self.page.locator("#log-panel")).to_have_count(1) + expect(self.page.locator("#log-panel")).to_be_hidden() + before = len(self.writes) + with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen: + panel.get_by_role("button", name="刷新记录", exact=True).click() + self.assertEqual(seen.value.method, "GET") + expect(panel).to_have_attribute("aria-busy", "false") + self.assertEqual(len(self.writes), before) + expect(self.page.locator("#log-panel")).to_be_hidden() + self.assertEqual(self.page.locator('[role="log"]').count(), 1) + + panel.locator("tbody tr").first.click(button="right") + with self.page.expect_request(lambda request: "/views/commissions?" in request.url) as seen: + self.page.get_by_role("menuitem", name="刷新本页", exact=True).click() + self.assertEqual(seen.value.method, "GET") + expect(panel).to_have_attribute("aria-busy", "false") + self.assertEqual(len(self.writes), before) + artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history" + artifact.mkdir(parents=True, exist_ok=True) + self.page.screenshot(path=str(artifact / "desktop-daily-records.png")) + + panel.locator("tbody tr").first.dblclick() + detail = self.page.get_by_role("dialog") + expect(detail).to_contain_text("委托详情") + for value in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "回退15氪金"): + expect(detail).to_contain_text(value) + expect(self.page.locator("#log-panel")).to_be_hidden() + + def test_current_policy_autosave_and_original_log_filters_commissions_in_both_subtabs(self): + worker = self.manager._worker(self.first) + worker.log("接取委托:仅委托可见(预计20氪金);已确认", category="commissions") + worker.log("其他分类不可见", category="login") + self.open() + panel = self.go("commissions") + with self.page.expect_request(lambda request: request.method == "PUT" and "/config" in request.url): + panel.get_by_role("checkbox", name="允许提交道具(遵守保留数量)", exact=True).check() + expect(self.page.locator("#save-status")).to_have_text("策略已自动保存") + self.assertTrue(self.manager.get_config(self.first)["config"]["quest_policy"]["allow_items"]) + expect(self.page.locator("#log-panel")).to_be_hidden() + self.page.locator("#log-toggle").click() + expect(self.page.locator("#log-heading")).to_have_text("自动委托日志") + expect(self.page.locator("#log-lines")).to_contain_text("仅委托可见") + expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见") + panel.get_by_role("tab", name="每日记录").click() + expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible() + expect(self.page.locator("#log-panel")).to_be_visible() + expect(self.page.locator("#log-panel")).to_have_count(1) + expect(self.page.locator("#log-heading")).to_have_text("自动委托日志") + expect(self.page.locator("#log-lines")).not_to_contain_text("其他分类不可见") + + def test_date_account_isolation_and_keyboard_subtabs(self): + self.open() + panel = self.records() + yesterday = (self.today - timedelta(days=1)).isoformat() + panel.get_by_label("记录日期(北京时间)").fill(yesterday) + expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday) + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + panel = self.records() + expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(self.today.isoformat()) + expect(panel.locator("tbody tr").first).to_contain_text("账号二" + self.today.isoformat()) + self.page.locator(f'.account-tab[data-account="{self.first}"]').click() + panel = self.page.locator('.page-panel[data-page="commissions"]:not([hidden])') + expect(panel.get_by_label("记录日期(北京时间)")).to_have_value(yesterday) + expect(panel.locator("tbody tr").first).to_contain_text("账号一" + yesterday) + current = panel.get_by_role("tab", name="每日记录") + current.focus() + current.press("Home") + expect(panel.get_by_role("tab", name="当前委托")).to_have_attribute("aria-selected", "true") + expect(panel.locator('th[data-column="reward_ke"]')).to_have_text("标注氪金") + expect(panel.locator("tbody tr").first).to_contain_text("城市尚未解锁") + expect(panel.locator('td[data-column="status"]')).to_have_text(["暂不接取", "候选 / 条件待核对"]) + expect(self.page.locator("#log-panel")).to_be_hidden() + + def test_loading_error_and_mobile_history_keep_original_layout(self): + self.open() + panel = self.records() + self.hold = True + panel.get_by_label("记录日期(北京时间)").fill((self.today - timedelta(days=2)).isoformat()) + expect(panel).to_have_attribute("aria-busy", "true") + expect(panel.locator(".page-loading")).to_be_visible() + expect(self.page.locator("#log-panel")).to_be_hidden() + deadline = time.monotonic() + 5 + while not self.pending and time.monotonic() < deadline: + self.page.wait_for_timeout(30) + self.assertTrue(self.pending) + self.hold = False + route, dto = self.pending.pop(0) + self.fulfill(route, {"loading": False, "data": dto}) + expect(panel).to_have_attribute("aria-busy", "false") + expect(panel.locator(".page-loading")).to_be_hidden() + self.fail_reads = True + panel.get_by_role("button", name="刷新记录").click() + expect(panel.locator(".page-error")).to_be_visible() + expect(panel).to_have_attribute("aria-busy", "false") + expect(self.page.locator("#log-panel")).to_be_hidden() + self.fail_reads = False + self.errors[:] = [error for error in self.errors if "503 (Service Unavailable)" not in error] + panel.get_by_role("button", name="重新读取").click() + expect(panel.locator(".page-error")).to_be_hidden() + self.page.set_viewport_size({"width": 390, "height": 844}) + expect(panel.get_by_label("记录日期(北京时间)")).to_be_visible() + self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), 391) + artifact = Path(__file__).resolve().parents[3] / "test-artifacts" / "commission-history" + artifact.mkdir(parents=True, exist_ok=True) + self.page.screenshot(path=str(artifact / "mobile-daily-records.png")) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_web/tests/browser/test_page_loading_browser.py b/ranch_web/tests/browser/test_page_loading_browser.py index 77fb7a0..98931d1 100644 --- a/ranch_web/tests/browser/test_page_loading_browser.py +++ b/ranch_web/tests/browser/test_page_loading_browser.py @@ -51,8 +51,22 @@ class PageLoadingBrowserTests(unittest.TestCase): "details": {"help": "STATIC_HELP_SENTINEL", "note": "STATIC_NOTE_SENTINEL", "notes": ["金币不足,等待补货"]}}} self.hold, self.fail = False, False + self.hold_after_real_retry_click = False + self.page.add_init_script("""(() => { + window.__loadingRetryClicked = false; + document.addEventListener('click', event => { + if (event.target instanceof Element && event.target.closest('.page-panel[data-page="bag"] .page-error button')) { + window.__loadingRetryClicked = true; + } + }, true); + })();""") def view(route): + if self.hold_after_real_retry_click: + if not self.page.evaluate("window.__loadingRetryClicked"): + route.fulfill(status=503, content_type="application/json", body='{"detail":"读取失败"}') + return + self.hold_after_real_retry_click = False if self.hold: self.pending.append(route) elif self.fail: @@ -156,8 +170,16 @@ class PageLoadingBrowserTests(unittest.TestCase): expect(panel.locator(".page-error")).to_be_visible() expect(panel).to_have_attribute("aria-busy", "false") expect(panel.locator(".page-loading")).to_be_hidden() + # Passive polling must keep returning the error until the native click. + # Holding a passive request here would hide the button before it can click. + self.hold_after_real_retry_click = True self.hold, self.fail = True, False + with self.page.expect_response(lambda response: "/views/bag?" in response.url and response.status == 503): + pass # Exercise a real passive refresh during this transition. + expect(panel.locator(".page-error")).to_be_visible() + self.assertEqual(self.pending, [], "Passive errors must not park a request before the retry click") panel.get_by_role("button", name="重新读取").click() + self.assertTrue(self.page.evaluate("window.__loadingRetryClicked")) route = self.wait_request() self.assert_centered(panel) self.summary.update(connection_state="offline", connected=False, connection_message="连接已中断") diff --git a/ranch_web/tests/test_commission_history.py b/ranch_web/tests/test_commission_history.py new file mode 100644 index 0000000..9e78406 --- /dev/null +++ b/ranch_web/tests/test_commission_history.py @@ -0,0 +1,196 @@ +"""Commission DTO regressions with temporary engines and synthetic local history.""" +from datetime import datetime, timezone +import json +from pathlib import Path +import tempfile +import unittest +from unittest.mock import Mock, patch + +from ranch_assistant.engine import Engine, demo_snapshot +from ranch_assistant.model import Catalog +from ranch_web.policies import default_config +from ranch_web.views import build_view + + +def history_fixture(day): + return {"date": day, "dates": [day], "summary": { + "accepted_count": 2, "completed_count": 1, "expected_ke": 35, "confirmed_ke": 15, "pending_count": 1, "unknown_reward_count": 0}, + "rows": [{"id": "local-15", "task_id": 71, "task_type_id": "test15", "name": "提交魔物与道具", + "status": "completed", "accepted_at": day + "T01:02:03+00:00", "completed_at": day + "T02:03:04+00:00", + "expected_ke": 15, "confirmed_ke": 15, "selection_reason": "20氪金候选城市尚未解锁,回退15氪金", + "last_action": "服务器已确认领取15氪金", "events": [ + {"time": day + "T01:02:03+00:00", "kind": "accept", "status": "confirmed", "description": "接取委托,预计15氪金"}, + {"time": day + "T01:03:03+00:00", "kind": "handin_items", "status": "confirmed", "description": "已提交铁矿石 ×2"}, + {"time": day + "T01:04:03+00:00", "kind": "handin_monsters", "status": "confirmed", "description": "已提交1级史莱姆 ×1"}, + {"time": day + "T01:05:03+00:00", "kind": "dialogue", "status": "confirmed", "description": "已与城镇守卫对话"}, + {"time": day + "T01:06:03+00:00", "kind": "battle", "status": "confirmed", "description": "委托战斗胜利,推进第4步"}, + {"time": day + "T02:03:04+00:00", "kind": "claim", "status": "confirmed", "description": "服务器奖励回包确认氪金15"}]}, + {"id": "local-20", "task_id": 72, "task_type_id": "test20", "name": "奖励待核对的委托", + "status": "unknown", "accepted_at": day + "T03:02:03+08:00", "completed_at": None, + "expected_ke": 20, "confirmed_ke": None, "last_action": "领奖请求超时,等待核对", + "events": [{"time": day + "T03:03:04+08:00", "kind": "claim", "status": "unknown", "description": "领奖回包未知"}]}]} + + +class CommissionHistoryViewTests(unittest.TestCase): + def setUp(self): + root = self.enterContext(tempfile.TemporaryDirectory(prefix="commission-web-history-")) + self.engine = Engine(Catalog(), budget_path=Path(root) / "budget.json") + self.engine.snapshot = demo_snapshot(self.engine.catalog) + self.engine.demo = False + self.engine.client = Mock() + self.engine.client.call.side_effect = AssertionError("Game calls forbidden in history views") + self.config = default_config() + self.history = history_fixture("2026-11-12") + self.engine.commission_history = Mock(return_value=self.history) + self.engine.commission_offer_diagnostics = Mock(return_value=[]) + + def view(self, **query): + return build_view(self.engine, "commissions", self.config, {"tab": "history", **query}) + + def test_history_reads_only_local_helper_and_separates_confirmed_rewards(self): + self.engine.tasks.rows = Mock(side_effect=AssertionError("Current tasks are not history")) + self.engine.progression_rows = Mock(side_effect=AssertionError("Do not plan game actions in history")) + self.engine.commission_offer_diagnostics.side_effect = AssertionError("History must not inspect current offers") + self.engine.plans = Mock(side_effect=AssertionError("Do not plan in history")) + dto = self.view(date="2026-11-12") + self.engine.commission_history.assert_called_once_with(day="2026-11-12") + self.engine.client.call.assert_not_called() + self.assertEqual([tab["title"] for tab in dto["tabs"]], ["当前委托", "每日记录"]) + self.assertEqual(dto["form"], []) + self.assertEqual(dto["actions"], [{"operation": "reload_view", "label": "刷新记录"}]) + self.assertIn("已记录接取 2", dto["summary"]) + self.assertIn("已记录完成 1", dto["summary"]) + self.assertIn("仅有本地已保存记录", dto["summary"]) + self.assertIn("当日领奖确认氪金 15", dto["summary"]) + self.assertIn("当日接取标注氪金 35", dto["summary"]) + self.assertIn("操作待核对 1", dto["summary"]) + self.assertIn("领奖金额未记录 0", dto["summary"]) + self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认") + self.assertEqual(dto["rows"][1]["status_label"], "结果待核对") + self.assertEqual(dto["rows"][0]["accepted_at"], "2026-11-12 09:02:03") + self.assertEqual(dto["rows"][1]["completed_at"], "—") + json.dumps(dto, ensure_ascii=False, allow_nan=False) + + def test_details_show_actual_handins_dialogue_battle_and_claim_evidence(self): + dto = self.view(date="2026-11-12") + detail = dto["details"]["local-15"] + for text in ("铁矿石 ×2", "1级史莱姆 ×1", "城镇守卫", "战斗胜利", "氪金15"): + self.assertIn(text, detail["行动记录"]) + self.assertIn("回退15氪金", detail["选择 / 回退原因"]) + self.assertIn("结果待核对", dto["details"]["local-20"]["行动记录"]) + self.assertNotIn("已确认", dto["details"]["local-20"]["行动记录"]) + + def test_search_can_find_action_details_without_changing_daily_totals(self): + dto = self.view(date="2026-11-12", search="铁矿石") + self.assertEqual([row["id"] for row in dto["rows"]], ["local-15"]) + self.assertIn("已记录接取 2", dto["summary"]) + self.assertEqual(set(dto["details"]), {"local-15"}) + + def test_empty_history_does_not_invent_old_acceptance_from_current_tasks(self): + self.engine.snapshot.raw["currentTasks"] = [{"id": 3, "typeId": "test20", "curStep": 1}] + self.engine.commission_history.return_value = {"date": "2026-11-11", "summary": {}, "rows": []} + dto = self.view(date="2026-11-11") + self.assertEqual(dto["rows"], []) + self.assertIn("已记录接取 0", dto["summary"]) + self.assertIn("历史接取与奖励未追溯", dto["summary"]) + + def test_history_available_without_snapshot(self): + self.engine.snapshot = None + dto = self.view(date="2026-11-12") + self.assertEqual(len(dto["rows"]), 2) + self.engine.client.call.assert_not_called() + current = build_view(self.engine, "commissions", self.config) + self.assertIn("请先登录", current["summary"]) + self.assertEqual(len(current["tabs"]), 2) + + def test_default_date_is_beijing_today_at_utc_day_boundary(self): + class FixedDatetime(datetime): + @classmethod + def now(cls, tz=None): + return cls(2026, 11, 12, 17, tzinfo=timezone.utc).astimezone(tz) + + with patch("ranch_web.views.datetime", FixedDatetime): + dto = self.view() + self.engine.commission_history.assert_called_once_with(day="2026-11-13") + self.assertEqual(dto["filters"][0]["value"], "2026-11-13") + self.assertEqual(dto["filters"][0]["type"], "date") + + def test_invalid_date_never_calls_history_helper(self): + for day in ("2026-11-31", "2026-1-1", "../2026-11-12", ["2026-11-12"]): + with self.subTest(day=day), self.assertRaisesRegex(ValueError, "记录日期"): + self.view(date=day) + self.engine.commission_history.assert_not_called() + + def test_raw_history_fields_never_reach_public_view(self): + row = self.history["rows"][0] + row["raw_response"] = {"token": "private-response"} + row["events"][0].update(raw={"password": "private-event"}, payload={"removeIds": [1234567]}) + wire = json.dumps(self.view(date="2026-11-12"), ensure_ascii=False) + for value in ("private-response", "private-event", "1234567", "raw_response", "removeIds"): + self.assertNotIn(value, wire) + + def test_current_offer_presence_never_implies_receivable(self): + self.engine.catalog.data["task_info"] = { + "test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}}, + "test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}} + self.engine.tasks.rows = Mock(return_value=[ + ("test20", "高额候选", "城市 4 可接", "提交物品", {"city": 4}), + ("test15", "回退候选", "城市 1 可接", "提交金币", {"city": 1})]) + self.engine.tasks.current = Mock(return_value=[]) + self.engine.progression_rows = Mock(return_value=[ + {"category": "commission", "task_type_id": "test20", "block_reason": "城市尚未解锁"}, + {"category": "commission", "task_type_id": "test15", "selection_reason": "20氪金候选未解锁,回退15氪金"}]) + dto = build_view(self.engine, "commissions", self.config) + high, fallback = dto["rows"] + self.assertEqual(high["reward_ke"], 20) + self.assertEqual(high["reward_money"], 123) + self.assertEqual(high["status"], "暂不接取") + self.assertEqual(high["reason"], "城市尚未解锁") + self.assertNotIn("可接", fallback["status"]) + self.assertIn("回退15氪金", fallback["selection_reason"]) + self.assertIn("20 → 15 → 10", dto["details"][fallback["id"]]["接取优先级"]) + + def test_authoritative_offer_diagnostics_match_city_and_explain_fallback(self): + self.engine.catalog.data["task_info"] = { + "test20": {"name": "高额候选", "reward": {"money": 123, "ke": 20}}, + "test15": {"name": "回退候选", "reward": {"money": 456, "ke": 15}}} + self.engine.tasks.rows = Mock(return_value=[ + ("test20", "高额候选", "城市 4 可接", "", {"city": 4}), + ("test15", "回退候选", "城市 1 可接", "", {"city": 1}), + ("test15", "回退候选", "城市 9 可接", "", {"city": 9})]) + self.engine.tasks.current = Mock(return_value=[]) + self.engine.progression_rows = Mock(return_value=[ + {"category": "commission", "task_type_id": "test15", "block_reason": "错误城市的阻塞原因"}]) + self.engine.commission_offer_diagnostics.return_value = [ + {"task_type_id": "test20", "name": "高额候选", "city": 4, "expected_ke": 20, "eligible": False, "reason": "城市尚未解锁"}, + {"task_type_id": "test15", "name": "回退候选", "city": 1, "expected_ke": 15, "eligible": True, "reason": "可接取"}, + {"task_type_id": "test15", "name": "回退候选", "city": 9, "expected_ke": 15, "eligible": False, "reason": "提交魔物受保留保护"}] + dto = build_view(self.engine, "commissions", self.config) + self.assertEqual([row["status"] for row in dto["rows"]], ["暂不接取", "可接取", "暂不接取"]) + self.assertIn("选择 15 氪金", dto["rows"][1]["selection_reason"]) + self.assertIn("城市尚未解锁", dto["rows"][1]["selection_reason"]) + self.assertNotIn("错误城市", dto["rows"][1]["reason"]) + self.assertEqual(dto["rows"][2]["reason"], "提交魔物受保留保护") + self.engine.client.call.assert_not_called() + + def test_pending_zero_reward_and_cross_day_totals_remain_distinct(self): + self.history["rows"][0].update(expected_ke=20, confirmed_ke=0, accepted_at="2026-11-11T01:02:03+08:00") + self.history["rows"][1]["status"] = "pending" + self.history["summary"].update(accepted_count=0, expected_ke=0, confirmed_ke=0) + dto = self.view(date="2026-11-12") + self.assertEqual(dto["rows"][0]["confirmed_ke"], 0) + self.assertEqual(dto["rows"][0]["expected_ke"], 20) + self.assertEqual(dto["rows"][1]["confirmed_ke"], "未确认") + self.assertEqual(dto["rows"][1]["status_label"], "等待核对") + self.assertIn("当日接取标注氪金 0", dto["summary"]) + self.assertNotIn("损失", dto["summary"]) + + def test_backend_read_error_visible_without_exposing_private_fields(self): + self.history.update(error="委托历史无法读取,原文件已保留", notice="仅展示本地已保存记录") + dto = self.view(date="2026-11-12") + self.assertIn("委托历史无法读取,原文件已保留", dto["summary"]) + self.assertIn("仅有本地已保存记录", dto["summary"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_web/tests/test_commission_history_service.py b/ranch_web/tests/test_commission_history_service.py new file mode 100644 index 0000000..30d8f95 --- /dev/null +++ b/ranch_web/tests/test_commission_history_service.py @@ -0,0 +1,113 @@ +"""Real worker/local ledger integration; game transports are always offline fakes.""" +from copy import deepcopy +from datetime import datetime, timedelta, timezone +from types import SimpleNamespace +import unittest +from unittest.mock import Mock, patch + +from ranch_assistant.engine import Engine +from ranch_web.tests import test_service as fixtures + + +class CommissionHistoryServiceTests(unittest.TestCase): + setUp = fixtures.ServiceTests.setUp + account = fixtures.ServiceTests.account + idle = fixtures.ServiceTests.idle + job = fixtures.ServiceTests.job + + def view(self, identifier, day): + response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day}) + if response["loading"]: + self.job(identifier, {"id": response["job_id"]}) + response = self.manager.view(identifier, "commissions", {"tab": "history", "date": day}) + self.assertFalse(response["loading"]) + return response["data"] + + def tick(self, identifier, *, failed=False): + worker = self.manager._worker(identifier) + with patch.object(worker.schedule, "due", return_value="poll"): + self.job(identifier, worker.enqueue("__tick"), status="failed" if failed else "succeeded") + + def test_real_local_ledger_history_is_account_role_day_isolated_without_game_calls(self): + first, second = self.account(), self.account() + worker = self.manager._worker(first) + engine = worker.engine + role = str(engine.snapshot.raw["master"]["id"]) + today = datetime.now(timezone(timedelta(hours=8))).date() + stamp = datetime.combine(today, datetime.min.time(), timezone(timedelta(hours=8))).timestamp() + 3600 + info = {"type": 4, "name": "已保存的20氪金委托", "reward": {"ke": 20}} + record = {"attempt_id": "synthetic-accept", "role_id": role, "task_type_id": "test20", "task_id": 71, + "kind": "quest_accept", "path": "taskService/taskLoopReceive", "timestamp": stamp, + "finished_at": stamp, "phase": "done", "outcome": "task", "response_confirmed": True, + "response": {"resCode": 0, "task": {"id": 71, "typeId": "test20", "curStep": 1}}, + "commission": {"name": info["name"], "expected_ke": 20}} + engine._commission_history.ingest(role, [record], lambda _: info, engine.snapshot) + after = self.manager.logs(first)["next"] + with patch.object(engine, "read_snapshot", side_effect=AssertionError("history must stay local")), \ + patch.object(engine, "poll", side_effect=AssertionError("history must not poll")): + dto = self.view(first, today.isoformat()) + self.assertIn("已记录接取 1", dto["summary"]) + self.assertEqual(dto["rows"][0]["confirmed_ke"], "未确认") + self.assertEqual(self.view(second, today.isoformat())["rows"], []) + self.assertEqual(self.view(first, (today - timedelta(days=1)).isoformat())["rows"], []) + original = engine.snapshot + engine.snapshot = deepcopy(original) + engine.snapshot.raw["master"]["id"] = "other-local-role" + worker._invalidate_views() + self.assertEqual(self.view(first, today.isoformat())["rows"], []) + engine.snapshot = original + worker._invalidate_views() + self.assertEqual(len(self.view(first, today.isoformat())["rows"]), 1) + self.assertEqual(fixtures.FakeClient.calls, []) + self.assertEqual(self.manager.logs(first, after=after)["entries"], [], "Reading history must not create activity logs") + + def test_accept_step_claim_and_unknown_messages_are_chinese_categorized_and_redacted(self): + def action(engine, intent): + return engine.snapshot, [], intent["message"] + + with patch.object(Engine, "_run_progression_intent", action): + identifier = self.account() + worker = self.manager._worker(identifier) + worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4}) + messages = [ + ("接取委托:本地测试(预计20氪金);已确认", "info"), + ("提交委托步骤:本地测试(预计20氪金);已提交铁矿石 ×2", "info"), + ("领取委托奖励:本地测试(预计20氪金);已确认,实际获得20氪金", "info"), + ("领取委托奖励:本地测试(预计20氪金);结果未知,等待核对,禁止重发", "warning"), + ("委托战斗:本地测试(预计20氪金);战斗失败,未推进委托", "error")] + for message, level in messages: + with self.subTest(message=message): + before = self.manager.logs(identifier)["next"] + intent = {"kind": "progression_complete", "task_type_id": "test20", "message": message + ";password=synthetic-password"} + with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)): + self.tick(identifier) + entries = self.manager.logs(identifier, after=before)["entries"] + self.assertEqual(len(entries), 1) + self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", level)) + self.assertIn("本地测试", entries[0]["message"]) + self.assertIn("20氪金", entries[0]["message"]) + self.assertNotIn("synthetic-password", entries[0]["message"]) + + def test_failed_commission_keeps_one_error_with_name_reward_and_no_success(self): + def action(engine, intent): + raise TimeoutError("token=synthetic-token 请求超时") + + with patch.object(Engine, "_run_progression_intent", action): + identifier = self.account() + worker = self.manager._worker(identifier) + worker.engine.game_data = SimpleNamespace(task=lambda _: {"type": 4, "name": "受保护的提交委托", "reward": {"ke": 20}}) + before = self.manager.logs(identifier)["next"] + intent = {"kind": "progression_loop_accept", "task_type_id": "test20"} + with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)): + self.tick(identifier, failed=True) + entries = self.manager.logs(identifier, after=before)["entries"] + self.assertEqual(len(entries), 1) + self.assertEqual((entries[0]["category"], entries[0]["level"]), ("commissions", "error")) + for value in ("受保护的提交委托", "标注20氪金", "接取异常", "结果待核对"): + self.assertIn(value, entries[0]["message"]) + self.assertNotIn("synthetic-token", entries[0]["message"]) + self.assertNotIn("已确认", entries[0]["message"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_web/views.py b/ranch_web/views.py index 4c304fc..42e0b50 100644 --- a/ranch_web/views.py +++ b/ranch_web/views.py @@ -13,6 +13,7 @@ from ranch_assistant.drop_statistics import analyze from ranch_assistant.presentation import monster_rows from ranch_assistant.battle_messages import battle_message from ranch_assistant.resource_stages import available_item_count, item_requirements, with_resource_data +from ranch_assistant.quests import commission_priority, commission_selection from .policies import default_config, validate_config @@ -126,7 +127,10 @@ def build_view(engine, page, config, query=None): "form": [field | {"value": _value(config, field["path"])} for field in fields], "filters": [], "details": {}, "actions": [{"operation": "refresh", "label": "刷新本页", "payload": {"page": page}}]} builder = _BUILDERS.get(page) - if engine.snapshot is None and page not in ("login", "yields", "statistics"): + if page == "commissions": + dto["tabs"] = [{"key": "current", "title": "当前委托"}, {"key": "history", "title": "每日记录"}] + local_history = page == "commissions" and (query or {}).get("tab") == "history" + if engine.snapshot is None and page not in ("login", "yields", "statistics") and not local_history: dto["summary"] = "请先登录或打开离线演示" return dto if builder is not None: @@ -562,33 +566,121 @@ def _battles(dto, engine, config, query): dto["actions"] = [{"operation": "refresh_tasks", "label": "刷新战斗记录", "payload": {}}] +COMMISSION_STATES = {"accepted": "已接取", "active": "进行中", "in_progress": "进行中", "completed": "已完成", "pending": "等待核对", + "claimed": "已领奖", "confirmed": "已确认", "unknown": "结果待核对", "failed": "失败", "cancelled": "已取消", "observed": "仅观察到任务", "blocked": "等待条件"} +COMMISSION_EVENTS = {"accept": "接取", "step": "推进步骤", "claim": "领取奖励", "complete": "领取奖励", "dialogue": "对话", "battle": "战斗", + "navigate": "前往任务地点", "farm": "收集委托材料", "local_step": "步骤收尾", "reset": "刷新每日委托", + "handin": "交付", "handin_items": "提交道具", "handin_monsters": "提交魔物", "handin_money": "提交金币", + "quest_accept": "接取", "quest_step": "推进步骤", "quest_complete": "领取奖励", "observe": "观察到任务"} + + +def _commission_time(value): + if value is None or value == "": + return "—" + try: + if type(value) in (int, float): + stamp = datetime.fromtimestamp(value / 1000 if value >= 1e12 else value, CHINA_TIME) + elif isinstance(value, str): + stamp = datetime.fromisoformat(value.replace("Z", "+00:00")) + if stamp.tzinfo is None: + stamp = stamp.replace(tzinfo=CHINA_TIME) + else: + return "—" + return stamp.astimezone(CHINA_TIME).strftime("%Y-%m-%d %H:%M:%S") + except (ValueError, OverflowError, OSError): + return "时间未确认" + + +def _commission_history(dto, engine, query): + selected = query.get("date") or datetime.now(CHINA_TIME).date().isoformat() + try: + if not isinstance(selected, str) or datetime.strptime(selected, "%Y-%m-%d").date().isoformat() != selected: + raise ValueError + except (TypeError, ValueError): + raise ValueError("记录日期须为 YYYY-MM-DD") from None + history = engine.commission_history(day=selected) + totals = history.get("summary") or {} + dto["form"] = [] + dto["actions"] = [{"operation": "reload_view", "label": "刷新记录"}] + dto["filters"] = [_filter("date", "记录日期(北京时间)", selected, kind="date")] + search = _search(dto, query) + dto["columns"] = [_column(key, label) for key, label in (("name", "委托"), ("status_label", "状态"), + ("expected_ke", "预计氪金"), ("confirmed_ke", "已确认氪金"), ("accepted_at", "接取时间(北京时间)"), + ("completed_at", "完成时间(北京时间)"), ("last_action", "最近行动"))] + sources = history.get("rows") or [] + for index, source in enumerate(sources): + status = _text(source.get("status"), "unknown") + row = {"id": _text(source.get("id"), str(index)), "task_type_id": _text(source.get("task_type_id")), + "name": _text(source.get("name")), "status_label": COMMISSION_STATES.get(status, "结果待核对"), + "expected_ke": source.get("expected_ke") if type(source.get("expected_ke")) in (int, float) else "未记录", + "confirmed_ke": source.get("confirmed_ke") if type(source.get("confirmed_ke")) in (int, float) else "未确认", + "accepted_at": _commission_time(source.get("accepted_at")), "completed_at": _commission_time(source.get("completed_at")), + "last_action": _text(source.get("last_action"), "暂无行动记录")} + events = [] + for event in source.get("events") or []: + kind, outcome = _text(event.get("kind"), "unknown"), _text(event.get("status"), "unknown") + label = {"success": "已确认", "succeeded": "已确认", "confirmed": "已确认", "completed": "已确认", + "failed": "失败", "unknown": "结果待核对", "pending": "等待核对", "cancelled": "已取消"}.get(outcome, "结果待核对") + events.append(f"{_commission_time(event.get('time'))} · {COMMISSION_EVENTS.get(kind, '委托行动')} · {label} · {_text(event.get('description'))}") + detail = {"委托": row["name"], "任务编号": row["task_type_id"], "状态": row["status_label"], + "预计氪金": row["expected_ke"], "已确认氪金": row["confirmed_ke"], "接取时间(北京时间)": row["accepted_at"], + "完成时间(北京时间)": row["completed_at"], "选择 / 回退原因": _text(source.get("selection_reason"), "未记录"), + "行动记录": "\n".join(events) or "暂无行动记录"} + if search and search not in " ".join(map(str, [*row.values(), *detail.values()])).casefold(): + continue + dto["rows"].append(row) + dto["details"][row["id"]] = detail + dto["summary"] = (f"{selected} · 已记录接取 {totals.get('accepted_count', 0)} · 已记录完成 {totals.get('completed_count', 0)}" + f" · 当日领奖确认氪金 {totals.get('confirmed_ke', 0)} · 当日接取标注氪金 {totals.get('expected_ke', 0)}" + f" · 操作待核对 {totals.get('pending_count', 0)} · 领奖金额未记录 {totals.get('unknown_reward_count', 0)}") + dto["summary"] += ";仅有本地已保存记录" if sources else ";当日暂无本地记录,历史接取与奖励未追溯" + if history.get("error"): + dto["summary"] += ";" + _text(history["error"]) + + def _commissions(dto, engine, config, query): + if query.get("tab") == "history": + _commission_history(dto, engine, query) + return snapshot, catalog = engine.snapshot, engine.catalog search = _search(dto, query) - dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("status", "状态"), - ("reward_money", "金币奖励"), ("reward_ke", "氪金奖励"), ("reason", "需求 / 下一步 / 阻塞原因"))] + dto["columns"] = [_column(key, label) for key, label in (("task_type_id", "编号"), ("name", "委托"), ("city", "城市"), ("status", "状态"), + ("reward_money", "标注金币"), ("reward_ke", "标注氪金"), ("selection_reason", "选择 / 回退原因"), ("reason", "需求 / 下一步 / 阻塞原因"))] diagnostics = {str(row.get("task_type_id")): row for row in engine.progression_rows() if _category(row.get("category")) == "commission"} - source = engine.tasks.rows(snapshot, engine.quest_policy, engine.policy) + offer_rows = engine.commission_offer_diagnostics() + offers = {(str(row.get("task_type_id")), str(row.get("city"))): row for row in offer_rows} + selected = next((row for row in offer_rows if row.get("eligible") is True), {}) + selection = commission_selection({"reward": {"ke": selected.get("expected_ke", 0)}}, offer_rows, + [row for row in offer_rows if row.get("eligible") is False]) if selected else {} + source = sorted(engine.tasks.rows(snapshot, engine.quest_policy, engine.policy), key=lambda row: ( + "city" in row[4], commission_priority(catalog.data.get("task_info", {}).get(str(row[0]), {})))) for index, (key, name, status, text, meta) in enumerate(source): diagnostic = diagnostics.get(str(key), {}) - reason = diagnostic.get("block_reason") or diagnostic.get("blocked_reason") + offer = offers.get((str(key), str(meta.get("city"))), {}) if "city" in meta else {} + if "city" in meta: + status = "可接取" if offer.get("eligible") is True else "候选 / 条件待核对" + reason = (offer.get("reason") if offer.get("eligible") is False else None) if offer else diagnostic.get("block_reason") or diagnostic.get("blocked_reason") if reason: status = "暂不接取" if "city" in meta else "等待条件" text = reason - elif diagnostic.get("next_action"): + elif not offer and diagnostic.get("next_action"): text = diagnostic["next_action"] info = catalog.data.get("task_info", {}).get(str(key), {}) reward = info.get("reward") or {} row = {"id": f"{key}:{index}", "task_type_id": str(key), "name": name, "status": status, "reward_money": reward.get("money", 0), "reward_ke": reward.get("ke", 0), "reason": battle_message(text), - "city": meta.get("city"), "active": "city" not in meta} + "city": meta.get("city"), "active": "city" not in meta, + "selection_reason": _text(offer.get("selection_reason") or (selection.get("selection_reason") if offer and offer == selected else None) + or diagnostic.get("selection_reason") or meta.get("selection_reason") or (reason if "city" in meta else None), + "较高氪金的可执行委托优先" if offer.get("eligible") is True else "接取条件待核对" if "city" in meta else "已接取,优先推进当前委托")} if search and search not in " ".join(map(str, row.values())).casefold(): continue dto["rows"].append(row) - dto["details"][row["id"]] = {"描述": info.get("des", ""), "需求 / 下一步": row["reason"], + dto["details"][row["id"]] = {"描述": info.get("des", ""), "标注奖励": reward_summary(catalog, reward), + "城市": _text(meta.get("city")), "选择 / 回退原因": row["selection_reason"], "需求 / 下一步": row["reason"], "交付限制": {"允许物品": engine.quest_policy.allow_items, "允许魔物": engine.quest_policy.allow_monsters, "单次金币上限": engine.quest_policy.max_money, "允许已支持战斗": engine.quest_policy.battle_tasks}, - "接取优先级": "氪金奖励较高的委托优先;仅接取原规划器确认可支持的委托"} + "接取优先级": "跨城市按标注氪金 20 → 15 → 10 优先;20 氪金均不可用时回退到可执行的 15 / 10 氪金委托"} dto["summary"] = f"今日剩余可接次数:{snapshot.raw.get('history', {}).get('loopTaskNum', '未知')};当前委托:{len(engine.tasks.current(snapshot))}"