diff --git a/.github/workflows/web-image.yml b/.github/workflows/web-image.yml index 1af7343..f7a9f54 100644 --- a/.github/workflows/web-image.yml +++ b/.github/workflows/web-image.yml @@ -59,6 +59,8 @@ jobs: run: python -m pip install -r ranch_web/requirements.txt - 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 + run: python -B -m unittest ranch_web.tests.test_run_intent ranch_web.tests.test_scheduler_recovery ranch_web.tests.test_auto_relogin ranch_web.tests.test_connection_state -v - name: Build image env: WEB_VERSION: ${{ steps.version.outputs.version }} diff --git a/Dockerfile b/Dockerfile index a356f88..665ce9f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim-bookworm -ARG WEB_VERSION=2.0.3 +ARG WEB_VERSION=2.0.4 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 0000680..cf6881b 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # 牧羊人之心Bot -本轮 Web 发布目标 **2.0.3**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 +本轮 Web 发布目标 **2.0.4**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。 ## 运行指引 -### Web 2.0.3(main) +### Web 2.0.4(main) Windows 使用 Python 3.12+,在项目根目录执行: @@ -15,11 +15,11 @@ py -3 -m venv .venv-web .\Start_Ranch_Web.cmd ``` -访问 `http://127.0.0.1:8765`。配置管理密码后先在独立 `/login` 页面登录,再添加游戏账号、选择区服或恢复保存的会话;本机 loopback 未设置管理密码时可直接访问。手动选服、恢复会话及自动重登成功读取角色后,默认开启策略,自动执行已配置且已勾选的功能,可用顶部“停止”暂停;各子功能仍按原有勾选生效,不会全选。导入配置只替换规则并停止执行,下次成功登录仍会自动开启;服务重启后未成功登录时不直接执行。 +访问 `http://127.0.0.1:8765`。配置管理密码后先在独立 `/login` 页面登录,再添加游戏账号、选择区服或恢复保存的会话;本机 loopback 未设置管理密码时可直接访问。账号登录后默认执行已配置且已勾选的策略,不会全选子功能。只有手动点击“停止”才暂停,点击“开启”恢复;这个选择跨断线、重新登录和服务重启保留,导入配置不会改变它。保存登录记录的账号会在服务重启后自动恢复登录,掉线后按登录页设置的等待时长重登。 Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web`。Linux Python 启动、离线演示与环境配置见 [Web 运行说明](ranch_web/README.md);单服务 Docker、`/data` 持久化、子路径反代与宿主机受控更新见 [Web 部署说明](deploy/web/README.md)。 -**2.0.3** 修复 2.0.2 的日志布局,游戏策略沿用现有实现。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器。已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面。操作条件见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。 +**2.0.4** 修复“网络超时恢复后已登录但策略停止”的问题,持久保存策略启停意图并恢复后台自动登录,保留 2.0.3 的原底部分类日志。已接入私有在线更新的部署可通过“帮助 → 检查版本更新…”安装,镜像和稳定 Release 均发布后可用;无需手动部署。详见 [发布说明](analysis/RELEASE_2_0_4.md)。 ### 桌面 1.2.0 @@ -36,7 +36,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` | 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 | | --- | --- | --- | -| Web 2.0.3 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | +| Web 2.0.4 | 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,9 +44,9 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` 本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。 -## Web 2.0.3 主要功能与分类日志 +## Web 2.0.4 主要功能与分类日志 -2.0.3 将 2.0.2 的日志界面改为所有功能页共用原有底部日志区,切换页签只显示当前账号、当前功能的日志;取消总日志/全部模式及页内日志框。操作说明见 [2.0.3 发布说明](analysis/RELEASE_2_0_3.md)。其余功能沿用现有实现。 +2.0.4 将 2.0.2 的日志界面改为所有功能页共用原有底部日志区,切换页签只显示当前账号、当前功能的日志;取消总日志/全部模式及页内日志框。操作说明见 [2.0.4 发布说明](analysis/RELEASE_2_0_4.md)。其余功能沿用现有实现。 - **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。 - **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。 @@ -60,7 +60,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` 连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。 -战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_3.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 +战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_4.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 ## 桌面 1.2.0 功能基线 diff --git a/analysis/RELEASE_2_0_4.md b/analysis/RELEASE_2_0_4.md new file mode 100644 index 0000000..45ac471 --- /dev/null +++ b/analysis/RELEASE_2_0_4.md @@ -0,0 +1,28 @@ +# Web 2.0.4 发布说明 + +Web **2.0.4** 修复网络超时后“已登录,但策略一直停止”的问题。桌面版保持 **1.2.0**,游戏资料基线保持 **1.9.68**。 + +## 持续运行与恢复 + +- 已登录账号默认执行原有已勾选策略,不会自动勾选其他功能。只有用户点击“停止”才暂停,点击“开启”恢复;这个选择跨掉线、重新登录和服务重启保存。 +- 临时网络故障先退避并只读验证连接,恢复成功后自动继续策略,不再需要手动点击“开启”。失败原因、恢复状态与重试安排分别显示。 +- 保存过登录记录的账号在服务重启后自动恢复登录。掉线按登录页设置的分钟数重登,默认 30 分钟,可设为 10 分钟;失败后继续按该间隔尝试。停止策略不取消连接监控与重登;清除登录记录或删除账号才取消持续登录。 +- 重试不会重放结果未知的消耗请求,已有战斗、探险、突破等核对记录继续保留;存在阻塞时显示原因并继续核对。 +- 修复调度中的监控饥饿及错误隔离,单账号调度异常不再中断其他账号。 +- 沿用 2.0.3 原底部分类日志:仅一个日志区域,按当前账号和页签筛选,每次刷新页面默认收起。 + +需要服务器保存账号密码、原区服与角色。缺少凭据时显示具体原因,不尝试猜测角色或登录其他区服。旧版未持久保存手动停止意图,升级后有保存登录记录的账号会默认恢复自动运行;如需暂停,请在新版点击“停止”。 + +## 安装与升级 + +正式发布目标 `v2.0.4`,镜像 `ghcr.io/attilanet/myrzx_bot-web:v2.0.4`。已接入私有在线更新的部署通过“帮助 → 检查版本更新…”手动安装;沿用现有凭据、持久化数据及宿主机更新器,无需手动部署 X99。稳定 Release 和镜像均就绪后才可在线安装,安装结果以宿主机健康检查为准。 + +升级完成后刷新网页。自动化由服务端运行,关闭浏览器或退出管理控制台不影响账号监控。 + +## 验证 + +- 后端完整回归 **338 项:335 通过,3 项因预期的 Windows 权限/符号链接限制跳过,0 失败、0 错误**。 +- Edge 浏览器完整回归 **58/58 通过**,包括恢复状态、停止按钮、自动重登配置、多账号隔离及原底部分类日志。 +- 覆盖首次掉线计时、10 分钟边界、失败后再次重登、服务重启、手动停止与开启竞态、恢复检查只读、待核对请求不重放及确认后自动恢复。 + +测试使用临时目录、合成账号、离线传输与本机浏览器,不向真实游戏接口提交操作。本次仅只读核对生产状态及历史错误,未手动部署或操作 X99 游戏账号;真实游戏在线运行效果由升级后观察确认。 diff --git a/compose.yaml b/compose.yaml index 330cfa5..e7c17ef 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.3} + image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.4} build: context: . args: - WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.3} + WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.4} user: "10001:10001" init: true restart: unless-stopped diff --git a/deploy/web/README.md b/deploy/web/README.md index 14a7ed8..10a9558 100644 --- a/deploy/web/README.md +++ b/deploy/web/README.md @@ -1,8 +1,8 @@ # Web 2 Linux Docker 部署与更新 -当前更新示例以 `v2.0.3` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 +当前更新示例以 `v2.0.4` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 -已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 +已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.4 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 ## 容器与持久化 @@ -19,7 +19,7 @@ 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.3`,需确认对应镜像已发布后再 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.4`,需确认对应镜像已发布后再 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`。不要对现有账号目录重新初始化密钥。 @@ -51,7 +51,7 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳 ### 已完成 2.0.1 初始化的宿主机 -`v2.0.3` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.3 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 +`v2.0.4` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.4 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 ### 全新宿主机准备 @@ -68,7 +68,7 @@ python3 -B /opt/ranch-web/updater.pyz --version ### 已有宿主机首次初始化(用户自行执行) -以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.3`。 +以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.4`。 前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。 @@ -161,12 +161,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.3 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_3.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件: +2.0.4 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_4.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.3 --dry-run +python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.4 --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 4b53235..35f604b 100644 --- a/deploy/web/image.env.example +++ b/deploy/web/image.env.example @@ -1,2 +1,2 @@ -# Pull only after the v2.0.3 image publishing workflow succeeds and the image is available. -RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.3 +# Pull only after the v2.0.4 image publishing workflow succeeds and the image is available. +RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.4 diff --git a/ranch_web/PRODUCT.md b/ranch_web/PRODUCT.md index 19ebaef..f393213 100644 --- a/ranch_web/PRODUCT.md +++ b/ranch_web/PRODUCT.md @@ -1,8 +1,8 @@ -# 牧羊人之心牧场助手 · Web 2.0.3 +# 牧羊人之心牧场助手 · Web 2.0.4 ## 产品约束 -把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.3`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 +把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.4`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 @@ -24,7 +24,13 @@ - 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。 - 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。 - 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。 -- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 +- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.4 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 + +## 2.0.4 持续运行与自动恢复 + +账号登录后默认执行已勾选策略,只有用户点击“停止”才暂停;点击“开启”恢复。启停选择由服务端持久保存,掉线、重新登录、关闭网页或服务重启不会误改。停止策略不停止连接监控与自动重登。 + +网络超时先进行只读恢复检查,成功后继续策略;会话失效按登录页等待分钟数重新登录,失败继续等待重试。保存过登录记录的账号在服务启动时自动恢复;只有清除登录记录或删除账号才取消。原有未确认请求核对与禁止重放规则保留。 ## 2.0.3 底部分类日志 @@ -47,7 +53,7 @@ - 同一账号共用日志拉取;浏览器缓存最多 1200 条,底部最多显示最近 600 条。已有分类与保守旧记录推断沿用原实现,无法明确归属的记录不补入登录或其他功能日志。 - 手动刷新成功时仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 -本补丁只调整日志展示与 Web 版本元数据,游戏玩法、策略及后端日志分类/持久化沿用现有实现。功能与验证范围见 [2.0.3 发布说明](../analysis/RELEASE_2_0_3.md)。 +2.0.3 补丁只调整日志展示与 Web 版本元数据,游戏玩法、策略及后端日志分类/持久化沿用现有实现。功能与验证范围见 [2.0.3 发布说明](../analysis/RELEASE_2_0_3.md)。 ## 安全与验证 diff --git a/ranch_web/README.md b/ranch_web/README.md index 9412cd3..a4e3b46 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -1,6 +1,6 @@ -# Web 2.0.3 运行说明 +# Web 2.0.4 运行说明 -本轮 Web 发布目标 **2.0.3**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 +本轮 Web 发布目标 **2.0.4**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。 @@ -10,7 +10,8 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或 - [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。 - [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。 -- [x] 本轮发布目标为 `2.0.3`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 +- [x] 本轮发布目标为 `2.0.4`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 +- 2.0.4 修复掉线恢复后策略意外停止,启停选择跨重登与重启保留;登录记录存在即持续自动重登。详见 [本版发布说明](../analysis/RELEASE_2_0_4.md)。 - 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。 ## Windows 本地运行 @@ -31,15 +32,15 @@ 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,让应用正常关闭账号队列。手动选服、恢复会话及自动重登成功读取角色后,均默认开启策略,只执行已勾选的功能,子功能不会全选。顶部“停止”暂停策略,仍保留状态监控;可用“开启”继续。登录后默认执行已勾选策略;只有手动“停止”才暂停,手动“开启”恢复。启停选择跨掉线、重新登录和服务重启保存,导入策略不会改变这个选择。 ### 后台运行与断线处理 -关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控和策略执行由服务端管理;“停止”策略后仍保留状态监控,退出游戏账号或停止服务后结束监控。 +关闭网页或退出 Web 管理登录不会停止服务器上的账号监控和已开启策略。账号监控、重登及策略执行都由服务端管理。手动“停止”只暂停策略,连接监控与掉线重登继续;该暂停在重新登录和服务重启后仍保留,点击“开启”恢复。 -账号状态区分游戏在线、临时故障重试、游戏登录过期和未连接,显示最后成功通信时间及具体原因。临时网络故障采用退避后的只读状态检查;无法确认的操作保留核对记录,不自动重复提交。游戏会话失效后停止策略和游戏轮询,按自动重登录设置等待处理,或在登录页手动恢复;成功登录后自动执行已配置且已勾选的功能,可在顶部停止。仅获取区服候选、候选角色验证失败或会话恢复失败,均不显示为登录成功。 +临时网络故障采用退避后的只读状态检查,确认角色连接恢复后自动继续原先启用的策略。会话失效时按登录页等待时长自动重新登录。账号状态区分用户暂停、临时恢复和请求待核对,心跳成功不等于策略已经运行;日志保留失败原因及恢复结果。未确认的消耗请求仍保留核对记录,不自动重复提交。 -服务重启会保留配置与加密会话;未启用自动重登录时,需要手动恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。 +服务重启会保留配置、加密会话及启停选择,并自动恢复有登录记录的账号。只有清除登录记录或移除账号才取消持续自动登录;缺少密码、区服或原角色信息时显示具体原因。运行日志按账号限量持久保存,旧角色数据会标注缓存状态。 ### 底部分类日志(2.0.3) @@ -55,13 +56,11 @@ py -3 -m venv .venv-web ### 掉线后自动重新登录 -在“登录”页开启“掉线后自动重新登录”,设置等待时长,默认 **30 分钟**,修改后自动保存。该开关默认关闭,各账号独立配置。使用前请在游戏登录时勾选“记住账号和密码”,并成功进入目标区服;密码仍由服务端加密保存。 +登录成功并保存原区服、原角色后,自动保持登录;“登录”页只需设置重登等待时长,默认 **30 分钟**,可改为 **10 分钟**,每账号独立保存。请勾选“记住账号和密码”,密码由服务端加密保存。旧版关闭的自动重登开关不再阻止已保存账号恢复登录。 -登录偏好保存在本账号中,进入其他区服或退出登录后仍保留设置;便携策略导入导出不携带、也不覆盖该登录偏好。 +掉线后从首次失败开始计时;普通只读重试不会延后重登时间。密码重登失败后按同一时长继续尝试,登录成功后仅执行原有已勾选功能;如果你手动停止过策略,则继续保持暂停。关闭浏览器不影响计时,退出游戏连接仍会安排恢复;彻底取消请清除登录记录或删除账号。 -检测到掉线后,服务端按等待时长重新进行账号密码登录,回到原区服、原角色。登录页显示安排时间及执行结果,关闭浏览器不影响计时。临时网络故障的只读恢复检查继续运行,连接提前恢复后会取消重登录计划。重登录失败后按配置时长等待下一次尝试;缺少保存的密码或目标角色时会显示具体原因。 - -开启此功能且保留有效登录记录时,服务重启也会先等待所设时长,再尝试重登录;等待及失败阶段不执行策略。主动退出、清除登录记录或移除账号会取消自动计划。重登录成功读取原区服、原角色后,恢复状态监控并默认开启策略,自动执行已勾选功能,可点击顶部“停止”暂停。 +登录偏好与策略启停不随便携策略导入导出,避免在其他账号误用。后台保留未确认请求证据,恢复连接不会重放这些请求。 ## Linux Python 与环境变量 @@ -98,13 +97,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.3 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.3**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.4 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.4**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 ## 离线验证 -2.0.3 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_3.md#验证),以下历史记录不计入本版验收。 +2.0.4 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_4.md#验证),以下历史记录不计入本版验收。 -### 历史验证记录(不计入 2.0.3) +### 历史验证记录(不计入 2.0.4) 2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。 diff --git a/ranch_web/__init__.py b/ranch_web/__init__.py index 46ce062..49bb892 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.3" +__version__ = "2.0.4" GAME_VERSION = "1.9.68" __all__ = ["__version__", "GAME_VERSION"] diff --git a/ranch_web/scheduler.py b/ranch_web/scheduler.py index 944e8a6..891bd82 100644 --- a/ranch_web/scheduler.py +++ b/ranch_web/scheduler.py @@ -1,6 +1,7 @@ """Desktop scheduling semantics without Qt timers or concurrent Engine access.""" from __future__ import annotations +import logging import math import random import threading @@ -8,6 +9,7 @@ import time FAST_KINDS = ("hatch", "gift", "explore", "breakthrough") +logger = logging.getLogger(__name__) class AccountSchedule: @@ -17,6 +19,7 @@ class AccountSchedule: self.clock, self.uniform = clock, uniform self.wall_clock = wall_clock self.next_poll = math.inf + self._poll_deferred = False self.next_fast = {kind: math.inf for kind in FAST_KINDS} self.monitoring = False self.last_maintenance_error = {} @@ -43,7 +46,7 @@ class AccountSchedule: return None origin = max(self.disconnected_at, self.auto_relogin_failed_at if self.auto_relogin_failed_at is not None else self.disconnected_at) - return origin + preference["delay_minutes"] * 60 + return origin + preference.get("delay_minutes", 30) * 60 def auto_relogin_failed(self): # Back off from completion, including time spent authenticating. @@ -59,15 +62,21 @@ class AccountSchedule: self.retry_deadline = self.clock() + delay return delay - def game_resumed(self): + def game_resumed(self, *, clear_disconnection=True): + """Resume monitored reads; the service decides if outage evidence clears.""" + was_paused = self.game_paused self.game_paused = False self.retry_deadline = None self.retry_attempt = 0 - self.clear_disconnection() + if clear_disconnection: + self.clear_disconnection() + if self.monitoring and (was_paused or self.next_poll == math.inf): + self.next_poll = min(self.next_poll, self.clock()) def monitor(self, enabled=True): self.monitoring = bool(enabled) self.next_poll = self.clock() if enabled else math.inf + self._poll_deferred = False def stop(self): for kind in FAST_KINDS: @@ -75,6 +84,7 @@ class AccountSchedule: def poll_finished(self, config): self.next_poll = self.clock() + self.uniform(0, config.get("interval", 30)) + self._poll_deferred = False def maintenance_failed(self, kind): self.last_maintenance_error[kind] = self.clock() @@ -83,7 +93,7 @@ class AccountSchedule: if completed in self.next_fast: self.next_fast[completed] = math.inf snapshot = engine.snapshot - if not self.monitoring or not running or snapshot is None: + if not self.monitoring or self.game_paused or not running or snapshot is None: self.stop() return now = self.clock() @@ -123,22 +133,35 @@ class AccountSchedule: def allowed(kind): return now - self.last_maintenance_error.get(kind, -math.inf) >= 30 + poll_due = self.monitoring and now >= self.next_poll and allowed("poll") + if not poll_due: + self._poll_deferred = False + elif self._poll_deferred: + return "poll" + + def before_poll(kind): + # Preserve maintenance/hatch priority once, then give an overdue + # snapshot its turn even if the preceding work remains due. + if poll_due: + self._poll_deferred = True + return kind + connected = not engine.demo and engine.client is not None and engine.snapshot is not None if connected and engine.heartbeat_enabled and now - engine.last_heartbeat >= 240 and allowed("heartbeat"): - return "heartbeat" + return before_poll("heartbeat") if connected and self.monitoring and engine.pending_recovery_due() and allowed("reconcile"): - return "reconcile" + return before_poll("reconcile") if connected and engine.heartbeat_enabled and engine.master_sync_due() and allowed("master_sync"): - return "master_sync" + return before_poll("master_sync") if connected and engine.heartbeat_enabled and engine.growth_sync_due() and allowed("growth_sync"): - return "growth_sync" - if self.monitoring and running and now >= self.next_fast["hatch"]: - return "hatch" - if self.monitoring and now >= self.next_poll: + return before_poll("growth_sync") + if self.monitoring and running and now >= self.next_fast["hatch"] and allowed("hatch"): + return before_poll("hatch") + if poll_due: return "poll" if self.monitoring and running: for kind in ("gift", "explore", "breakthrough"): - if now >= self.next_fast[kind]: + if now >= self.next_fast[kind] and allowed(kind): return kind return None @@ -155,8 +178,14 @@ class Scheduler: def _run(self): while not self.closed.wait(self.interval): - for worker in self.workers(): - worker.request_tick() + try: + for worker in self.workers(): + try: + worker.request_tick() + except Exception: + logger.exception("Unable to request account tick; continuing other accounts") + except Exception: + logger.exception("Unable to enumerate account workers; retrying next scheduler pass") def close(self): self.closed.set() diff --git a/ranch_web/service.py b/ranch_web/service.py index 26c47cc..4746dbd 100644 --- a/ranch_web/service.py +++ b/ranch_web/service.py @@ -50,13 +50,13 @@ from ranch_assistant.battles import CancelledBeforeDispatch from ranch_assistant.debug import TraceLog, sensitive from ranch_assistant.engine import Engine from ranch_assistant.login import PasswordLogin -from ranch_assistant.model import Catalog +from ranch_assistant.model import Catalog, seconds from .activity import ActivityLog, ActivityLogError from .log_categories import endpoint_category, legacy_category, normalize_category, note_hints, operation_category, route_message from .policies import apply_config, default_config, validate_config from .scheduler import AccountSchedule, FAST_KINDS, Scheduler -from .store import WebStore, session_identity +from .store import WebStore, _unlinked, atomic_json, session_identity PAGES = frozenset("login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split()) @@ -172,6 +172,14 @@ class AccountWorker: self._view_epoch = 0 self._generation = 0 self._running = False + self._intent_error = "" + self._legacy_pending = {} + self._run_intents = self._load_run_intents() + self._execution_retry_deadline = None + self._execution_retry_at = None + self._execution_retry_attempt = 0 + self._execution_error = "" + self._execution_block = "" self._closing = False self._active = None self._execution = None @@ -222,8 +230,163 @@ class AccountWorker: login = self.manager.store.load_config(self._login_settings_root) if login: value["auto_relogin"] = validate_config(login["config"])["auto_relogin"] + # A saved role is durable keep-login authorization. Old releases used + # enabled=False as their default; it was never an explicit account clear. + if re.fullmatch(r"[a-f0-9]{64}", folder.name): + value["auto_relogin"]["enabled"] = True return value, revision + def _load_run_intents(self): + try: + path = _unlinked(self.profile_root / "run_intent.json") + if not path.exists(): + return {} + value = json.loads(path.read_text(encoding="utf-8")) + if (not isinstance(value, dict) or value.get("schema") != 1 + or not isinstance(value.get("roles"), dict) + or any(not isinstance(scope, str) or not re.fullmatch(r"[a-f0-9]{64}|demo|disconnected", scope) + or type(requested) is not bool for scope, requested in value["roles"].items())): + raise ValueError("invalid run intent") + pending = value.get("legacy_pending", {}) + if (not isinstance(pending, dict) or any(not re.fullmatch(r"[a-f0-9]{64}", scope) + or not isinstance(record, dict) or record.get("kind") not in {"gift", "hatch", "feed"} + or not isinstance(record.get("evidence"), dict) for scope, record in pending.items())): + raise ValueError("invalid pending evidence") + self._legacy_pending = pending + return value["roles"] + except (OSError, ValueError, TypeError): + self._intent_error = "运行意愿记录无法读取;已保留原文件,请检查 Web 数据目录后重试" + return {} + + @property + def strategy_requested(self): + # Missing records migrate to enabled. Transient running=False from an + # old process is not evidence that the user pressed Stop. + if self.demo: + return self._run_intents.get("demo", False) + return self._run_intents.get(self._workspace(), self._run_intents.get("disconnected", True)) + + def _set_strategy_requested(self, requested): + """Only the explicit manager Stop and Start paths may call this.""" + with self.lock: + if requested: + # The Start may have waited behind persistence while a later + # synchronous Stop revoked its generation. + self.check_intent() + if self._intent_error: + raise OSError(self._intent_error) + self._run_intents[self._workspace()] = bool(requested) + self._save_run_intents() + + def _save_run_intents(self): + try: + atomic_json(self.profile_root / "run_intent.json", {"schema": 1, "roles": self._run_intents, + "legacy_pending": self._legacy_pending}) + except (OSError, ValueError): + self._intent_error = "运行意愿或待核对记录无法持久保存;请检查 Web 数据目录" + raise OSError(self._intent_error) from None + + def _legacy_write(self, path, payload): + """Fence only three legacy writes lacking Engine's durable journals.""" + if path not in {"monsterService/monsterSendGift", "stackService/stackAddMonster", "monsterService/monsterIntensify"}: + return None + if not self.active_identity or self.engine.snapshot is None: + return None + if self.active_identity in self._legacy_pending: + raise ValueError("上次赠礼、装填或喂养请求待核对,禁止自动重发") + payload = payload or {} + if path == "monsterService/monsterSendGift": + mid = int(payload["monsterId"]) + evidence = {"monster": mid, "gift_time": seconds(self.engine.snapshot.monsters[mid].get("giftTime"))} + kind = "gift" + elif path == "stackService/stackAddMonster": + stacks = {int(row["id"]): int(row.get("monsterId") or 0) for row in self.engine.snapshot.raw.get("stacks", [])} + evidence = {str(egg["stackId"]): stacks[int(egg["stackId"])] for egg in payload["eggs"]} + kind = "hatch" + elif path == "monsterService/monsterIntensify" and payload.get("foods"): + evidence = {"foods": list(payload["foods"])} + kind = "feed" + else: + return None + with self.lock: + self._legacy_pending[self.active_identity] = {"kind": kind, "evidence": evidence} + self._save_run_intents() # A failure here prevents sending the write. + return self.active_identity + + def _reconcile_legacy_write(self, snapshot, identity): + # Raw server snapshots precede Engine's local optimistic gift/growth + # overlays. An unchanged read, heartbeat or elapsed time is not proof. + with self.lock: + record = self._legacy_pending.get(identity) + if not record: + return + evidence, kind = record["evidence"], record["kind"] + if kind == "gift": + mon = snapshot.monsters.get(int(evidence["monster"])) + confirmed = mon is None or seconds(mon.get("giftTime")) > seconds(evidence["gift_time"]) + elif kind == "feed": + confirmed = all(int(mid) not in snapshot.monsters for mid in evidence["foods"]) + else: + stacks = {str(row["id"]): int(row.get("monsterId") or 0) for row in snapshot.raw.get("stacks", [])} + confirmed = bool(evidence) and all(stacks.get(slot, 0) > 0 and stacks[slot] != previous + for slot, previous in evidence.items()) + if confirmed: + self._legacy_pending.pop(identity) + self._save_run_intents() + + def _pending_execution_reason(self): + if self.active_identity in self._legacy_pending: + return "赠礼、装填或喂养请求结果待核对,禁止自动重发;后台继续读取游戏状态,确认后自动恢复已勾选策略" + if self.engine.snapshot is not None and (self.engine._progression_pending() + or self.engine.explore_planner.pending(self.engine.snapshot) or self.engine._breakthrough_pending): + return "存在未确认的任务、战斗、探险或突破请求,禁止自动重发;后台继续核对,核对完成后恢复已勾选策略" + return "" + + def _refresh_execution(self): + """Rearm desired execution, never grant writes to a read-only callback.""" + with self.lock: + self._execution_block = self._intent_error or self._pending_execution_reason() + ready = self.demo or self.connection_state == "online" and self.engine.client is not None + if ready and self.engine.snapshot is not None and not self.schedule.monitoring: + self.schedule.monitor(True) + if self._execution_retry_deadline is not None and self.schedule.clock() >= self._execution_retry_deadline: + self._execution_retry_deadline = self._execution_retry_at = None + self._running = bool(self.strategy_requested and ready and self.engine.snapshot is not None + and not self._execution_block and self._execution_retry_deadline is None + and not self._closing and not self.manager._closing and not getattr(self, "_session_write_error", "")) + if not self._running: + self.engine.auto = False + self.schedule.stop() + return self._running + + def _strategy_status(self): + requested = self.strategy_requested + if not requested: + state, message = "stopped", "已按用户选择停止策略;离线后仍按配置间隔重登,点击开始可恢复策略" + elif self._execution_block: + state, message = "blocked", self._execution_block + elif self._execution_retry_deadline is not None: + state, message = "recovering", self._execution_error + ";等待退避后自动恢复已勾选策略" + elif self.connection_state == "retrying": + state, message = "recovering", self.connection_message + elif not self._running: + state, message = "offline", self.connection_message + else: + state, message = "running", "已勾选的策略将自动执行" + return {"strategy_requested": requested, "manual_stop": not requested, + "strategy_state": state, "strategy_message": self.safe_text(message), + "strategy_retry_at": self._execution_retry_at or (self.next_retry_at if requested else None)} + + def _execution_failed(self, error): + self.stop() + if self._pending_execution_reason(): + return + self._execution_retry_attempt += 1 + delay = min(5 * 2 ** min(self._execution_retry_attempt - 1, 4), 60) + self._execution_retry_deadline = self.schedule.clock() + delay + self._execution_retry_at = (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat(timespec="milliseconds") + self._execution_error = self.safe_text(str(error)) or type(error).__name__ + def _engine(self, client=None, *, state_root=None, config=None): state_root = self.state_root if state_root is None else state_root config = self.config if config is None else config @@ -425,7 +588,7 @@ class AccountWorker: "demo": self.demo, "running": self._running, "busy": False, "player": player, "revision": self.revision, "error": self.error, "connection_state": self.connection_state, "connection_message": self.connection_message, "last_game_success_at": self.last_game_success_at, - "next_retry_at": self.next_retry_at, "auto_relogin_status": self._auto_relogin_status()}) + "next_retry_at": self.next_retry_at, "auto_relogin_status": self._auto_relogin_status(), **self._strategy_status()}) def _auto_relogin_status(self): with self.lock: @@ -504,6 +667,7 @@ class AccountWorker: # A decoded business rejection proves neither disconnection nor # expiry. Keep monitoring, but never retry its rejected write. self.error = self._last_game_error_message = self.safe_text(str(error)) + self._execution_failed(error) self.log(self.error, level="error") return self.engine.heartbeat_enabled = False @@ -514,11 +678,11 @@ class AccountWorker: self.next_retry_at = None if expired: self.connection_state = "expired" - message = "游戏会话已失效(408);策略已停止,游戏请求已暂停,请手动恢复会话或重新登录" + message = "游戏会话已失效(408);游戏请求已暂停,将按配置间隔重新登录,策略运行意愿已保留" elif temporary and client is not None: self.connection_state = "retrying" reason = "游戏网络请求超时" if isinstance(error, requests.Timeout) or isinstance(cause, requests.Timeout) else "游戏网络暂时不可用" - message = f"{reason};策略已停止,{delay} 秒后只读重试,未确认记录保留" + message = f"{reason};{delay} 秒后只读重试,连接恢复后自动继续已勾选策略,未确认记录保留" self.next_retry_at = (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat(timespec="milliseconds") elif temporary: self.connection_state = "offline" @@ -546,6 +710,7 @@ class AccountWorker: self._auto_relogin_blocked = False self.schedule.game_resumed() self.engine.heartbeat_enabled = True + self._refresh_execution() if previous != "online" and not activated: self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"), category="login") @@ -554,6 +719,7 @@ class AccountWorker: result = deepcopy(self._summary) result.update(running=self._running, busy=bool(self._active or self._pending)) result["auto_relogin_status"] = self._auto_relogin_status() + result.update(self._strategy_status()) return result @property @@ -675,13 +841,15 @@ class AccountWorker: if self.connection_state not in {"expired", "retrying"} and not ( self.engine.client is not None and job.operation in {"login", "enter_server", "restore_session"}): self.error = message - if job.consuming: - self.stop() + 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") finally: job.payload = {} try: self._persist_session() + self._refresh_execution() summary = self._make_summary() except Exception as error: self.stop() @@ -722,12 +890,12 @@ class AccountWorker: self.config, self.revision = self._load_config(self.state_root) self.active_identity = saved self.engine = self._engine() - self.connection_message = "服务已启动或重启;已保留保存的会话,请手动恢复会话或重新登录,策略保持停止" + self.connection_message = "服务已启动或重启;已保留会话与策略运行意愿,将等待配置分钟后重新登录原区服、原角色" # Opt-in only: retain the known startup offline origin even # while disabled, so enabling later can reuse that timestamp. self._mark_disconnected(session, saved) if self.config["auto_relogin"]["enabled"]: - self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色,策略保持停止" + self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色" self.log(self.connection_message, category="login") if self.demo: self.result(*self.engine.poll()) @@ -791,6 +959,8 @@ class AccountWorker: # login authorization. Never erase or enable this preference. source["auto_relogin"] = deepcopy(self.config["auto_relogin"]) value = validate_config(source) + if self.active_identity and not self.demo: + value["auto_relogin"]["enabled"] = True new_revision = self.revision + 1 self.manager.store.save_config(self.state_root, value, new_revision) if self.state_root != self._login_settings_root: @@ -802,8 +972,9 @@ class AccountWorker: with self.lock: self.config, self.revision = value, new_revision # A policy job never clears cancellation or resurrects a stopped start. - self.engine.auto = bool(self._running and not self._closing and self._execution - and self._execution.generation == self._generation) + if not (self._running and not self._closing and self._execution + and self._execution.generation == self._generation): + self.engine.auto = False self.schedule.poll_finished(value) self.schedule.arm(self.engine, value, self._running, self.engine.plans() if self.engine.snapshot else ()) self._invalidate_views() @@ -863,6 +1034,7 @@ class AccountWorker: return active def _tick(self, job): + self._refresh_execution() kind = self.schedule.due(self.engine, self.config, self._running) job.due_kind, job.category = kind, operation_category(kind) if kind is None: @@ -897,6 +1069,7 @@ class AccountWorker: self.engine.snapshot = self.engine.client.snapshot() finally: self._retry_probe = False + self._refresh_execution() self.schedule.poll_finished(self.config) self._invalidate_views() return {"kind": kind} @@ -928,7 +1101,13 @@ class AccountWorker: # while preserving the user's running switch. Only a pause # by the current Engine generation turns that switch off. if auto and job.generation == self._generation and not self.engine.auto: - self.stop() + if self._pending_execution_reason(): + self.stop() + else: + self._execution_failed(ValueError(value[2] or "策略暂不可用")) + elif auto and job.generation == self._generation: + self._execution_retry_attempt = 0 + self._execution_error = "" self.schedule.arm(self.engine, self.config, self._running, value[1], completed=kind) elif isinstance(value, str): self._log_message(value) @@ -1069,11 +1248,32 @@ class AccountWorker: # A repaired directory may be retried. Client.persist_session # sets this before Trace.begin blocks an unsafe dispatch. self._session_write_error = "" + legacy = self._legacy_write(path, args[1] if len(args) > 1 else kwargs.get("payload")) if active else None try: response = original(*args, **kwargs) except Exception as error: + if legacy is not None and (isinstance(error, CancelledBeforeDispatch) + or isinstance(error, ApiError) and error.code is not None): + # A decoded rejection did not apply the write; it needs + # bounded backoff and fresh planning, not uncertainty. + with self.lock: + self._legacy_pending.pop(legacy, None) + self._save_run_intents() self._game_failed(error, client) raise + if legacy is not None and path == "monsterService/monsterSendGift": + try: + feel, gifted_at = float(response["feel"]), seconds(response["giftDate"]) + before = self._legacy_pending[legacy]["evidence"]["gift_time"] + confirmed = math.isfinite(feel) and feel >= 0 and math.isfinite(gifted_at) and gifted_at > before + except (KeyError, TypeError, ValueError): + confirmed = False + if confirmed: + # The same authoritative response used by GiftPlanner's + # cooldown is sufficient even if role reads lag behind. + with self.lock: + self._legacy_pending.pop(legacy, None) + self._save_run_intents() path = args[0] if args else kwargs.get("path") if active and path == "heartBeatService/keepAlive": self._game_succeeded() @@ -1091,6 +1291,7 @@ class AccountWorker: except Exception as error: self._game_failed(error, client) raise + self._reconcile_legacy_write(snapshot, session_identity(client.session)) if client is self.engine.client: self._game_succeeded() return snapshot @@ -1178,15 +1379,10 @@ class AccountWorker: self.schedule.poll_finished(self.config) self._game_succeeded(activated=True) self._invalidate_views(clear=True) - # Activation and its new start authorization share the final - # generation check/lock. Never queue a start that could outlive - # a stop, logout or policy replacement during persistence. - try: - self._start({}, require_selection=False) - except ValueError as error: - message = login_message + ";策略保持停止:" + self.safe_text(str(error)) - else: - message = login_message + ";策略已自动开启,仅执行已勾选的规则" + # A verified connection never changes durable user intent or + # grants writes to this authentication/read-only operation. + self._refresh_execution() + message = login_message + ";" + self._strategy_status()["strategy_message"] result = {"connected": True, "running": self._running, "has_saved_password": self._has_saved_password, "message": message} self.log(message, category="login") @@ -1312,20 +1508,19 @@ class AccountWorker: client.close() def _logout(self, payload): + identity = self.active_identity + session = (self.engine.client.session if self.engine.client is not None else + self.securestore.load(identity) if identity else None) self._release_clients() - self.manager._release_identity(self) - self.active_identity = None - self.securestore.set_active(None) - self.state_root = self.state = self.manager.store.role_root(self.id, demo=self.demo) - config, revision = self._load_config(self.state_root) - self.config, self.revision = config, max(self.revision, revision) + 1 self.engine = self._engine() with self.lock: self._servers = [] self.schedule.monitor(False) self.schedule.game_failed() + if session is not None: + self._mark_disconnected(session, identity) self.connection_state = "offline" - self.connection_message = "已手动退出游戏;请登录或手动恢复保存的会话,策略保持停止" + self.connection_message = "已退出当前游戏连接;会话、密码与策略运行意愿已保留,将按配置间隔重新登录" self.next_retry_at = None self.error = "" self._refresh_login_metadata() @@ -1335,12 +1530,20 @@ class AccountWorker: def _forget_login(self, payload): self._logout(payload) self.securestore.forget() + self.manager._release_identity(self) + self.active_identity = None + self.state_root = self.state = self.manager.store.role_root(self.id, demo=self.demo) + config, revision = self._load_config(self.state_root) + self.config, self.revision = config, max(self.revision, revision) + 1 + self.engine = self._engine() + self.connection_message = "已清空保存的登录,不再自动重登;请重新登录并选择区服" self._refresh_login_metadata() self._invalidate_views() return {"connected": False, "running": False, "has_saved_password": False} def _start(self, payload, *, require_selection=True): self.check_intent() + self._set_strategy_requested(True) if not self.demo: self._require_game() if self.engine.snapshot is None or not (self.demo or self.engine.client): @@ -1354,16 +1557,19 @@ class AccountWorker: raise ValueError("请先勾选至少一项功能,并启用对应策略") if require_selection and ranch and not other and not any(rule["enabled"] for rule in policy["egg_rules"].values()): raise ValueError("请先在背包魔物蛋勾选要孵化的蛋,并设置优先级和孵出后的去向") - if (self.engine._progression_pending() or self.engine.explore_planner.pending(self.engine.snapshot) - or self.engine._breakthrough_pending): - raise ValueError("存在未确认的任务、战斗、探险或突破请求,禁止自动重发;请先核对") + reason = self._pending_execution_reason() + if reason: + raise ValueError(reason) with self.lock: self.check_intent() - self._running = self.engine.auto = True + self._execution_retry_deadline = self._execution_retry_at = None + self._execution_retry_attempt = 0 + self._execution_error = "" + self._refresh_execution() self.engine.heartbeat_enabled = True self.schedule.monitor(True) self._invalidate_views() - return {"running": True} + return {"running": self._running, **self._strategy_status()} def _stop(self, payload): # submit('stop') already made cancellation effective synchronously. @@ -1513,12 +1719,14 @@ class WebManager: with worker.condition: if operation == "stop": worker.stop() + worker._set_strategy_requested(False) # Stop is complete before returning; it never waits behind a model. - job = _Job(uuid.uuid4().hex, operation, {}, worker._generation, status="succeeded", result={"running": False}) + job = _Job(uuid.uuid4().hex, operation, {}, worker._generation, status="succeeded", + result={"running": False, **worker._strategy_status()}) worker._jobs[job.id] = job return job.public() if operation in STOP_ACTIONS or operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}: - if operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}: + if operation == "forget_login": worker.suspend_auto_relogin() worker.stop() consuming = operation not in READ_ACTIONS and operation not in LOCAL_ACTIONS and operation not in {"logout", "forget_login"} diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index 2362d23..1b6b28d 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -22,6 +22,35 @@ function connectionState(summary) { function gameAvailable(account) { return Boolean(account && !state.webStatusError && !account.transportErrors.has('status') && connectionState(account.summary)==='online'); } +function strategyRequested(summary) { return typeof summary?.strategy_requested==='boolean'?summary.strategy_requested:Boolean(summary?.running); } + +function strategyDetails(account) { + if(!account)return ''; + const summary=account.summary,requested=strategyRequested(summary); + if(!requested)return summary.strategy_requested===false?'策略已停止(用户暂停);暂停会保留到再次“开启”,账号仍会按设定时长自动重登。':'策略已停止,可在顶部“开启”继续执行已勾选功能。'; + if(summary.strategy_state==='blocked')return `策略等待处理:${summary.strategy_message || '请检查执行结果,确认后再继续。'}`; + if(summary.running && gameAvailable(account))return '角色状态自动刷新,正在自动执行已配置且已勾选的功能;可在顶部“停止”。'; + const parts=['已请求自动执行已勾选功能,等待恢复;可在顶部“停止”暂停执行。']; + if(summary.strategy_message)parts.push(summary.strategy_message); + const value=summary.strategy_retry_at; + const retryAt=typeof value==='number'?(value<1e12?value*1000:value):Date.parse(value); + if(value!=null && Number.isFinite(retryAt)){ + const seconds=Math.max(0,Math.ceil((retryAt-Date.now())/1000)); + parts.push(seconds?`${seconds} 秒后检查策略恢复`:'等待策略恢复检查结果'); + } + return parts.join(';'); +} + +function acceptSummary(account,summary) { + account.summary=summary; + // Keep the last observed failure separate from current connection health. + const kind=connectionState(summary); + const failure=summary.error || (['retrying','expired'].includes(kind)?summary.connection_message:''); + if(failure)account.lastFailure=failure; +} + +function failureHistory(account) { return account?.lastFailure && connectionState(account.summary)==='online'?`上次失败:${account.lastFailure}`:''; } + function connectionReason(summary) { return summary?.connection_message || summary?.error || {retrying:'游戏请求暂时失败,等待重试。',expired:'游戏登录状态已失效,请在登录页重新登录或恢复会话。',offline:'尚未连接游戏,请在登录页登录或恢复已保存会话。'}[connectionState(summary)] || ''; } @@ -46,7 +75,8 @@ function connectionDetails(account) { function transportMessages(account=current()) { return [...(account?.transportErrors.values() || [])]; } function renderStatus() { - const message=[connectionDetails(current()),...transportMessages()].filter(Boolean).join(';') || state.statusMessage; + const account=current(); + const message=[connectionDetails(account),typeof account?.summary.strategy_requested==='boolean'?strategyDetails(account):'',failureHistory(account),...transportMessages()].filter(Boolean).join(';') || state.statusMessage; const node=$('#status-text');if(node.textContent!==message)node.textContent=message;node.title=message; } @@ -72,8 +102,9 @@ function renderPageConnection(page) { } function makeAccount(summary) { - return {id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null, - logs:createLogState(),loadingConfig:false,transportErrors:new Map()}; + const account={id:summary.id,summary,config:null,revision:null,edits:new Map(),pages:new Map(),page:'login',jobs:new Map(),savePromise:null,saveError:null, + logs:createLogState(),loadingConfig:false,transportErrors:new Map(),lastFailure:''}; + acceptSummary(account,summary);return account; } function setStatus(message) { state.statusMessage=message;renderStatus(); } @@ -90,9 +121,9 @@ function renderAccountTabs() { } const summary=account.summary,selected=state.active===account.id,kind=connectionState(summary); $('.account-label',button).textContent=summary.label || summary.player?.name || '账号'; - $('.account-dot',button).className=`account-dot${summary.error || kind!=='online'?' error':summary.running?' running':''}`; + $('.account-dot',button).className=`account-dot${kind!=='online' || summary.strategy_state==='blocked'?' error':summary.running?' running':''}`; button.setAttribute('aria-selected',String(selected));button.tabIndex=selected?0:-1; - button.title=[summary.label || '账号',summary.demo?'离线演示':connectionLabels[kind],summary.running?'策略运行中':'',kind==='online'?summary.error:connectionReason(summary)].filter(Boolean).join(' · '); + button.title=[summary.label || '账号',summary.demo?'离线演示':connectionLabels[kind],strategyDetails(account),kind==='online'?failureHistory(account):connectionReason(summary)].filter(Boolean).join(' · '); }); } @@ -113,9 +144,9 @@ function renderSummary() { for (const [id,key] of [['player-level','level'],['player-money','money'],['player-ke','ke'],['player-ti','ti']]) $('#'+id).textContent=number(player[key]); $('#player-exp').textContent=player.exp==null?'—':`${number(player.exp)} / ${number(player.next_exp)}`; $('#experience-progress').max=Math.max(1,Number(player.next_exp)||1);$('#experience-progress').value=Number(player.exp)||0; - const run=$('#strategy-toggle');run.textContent=summary?.running?'停止':'开启';run.classList.toggle('running',Boolean(summary?.running));run.disabled=!account || !summary?.running && (!account.config || !connected); - run.setAttribute('aria-pressed',String(Boolean(summary?.running))); - run.title=summary?.running?'停止自动执行已勾选功能;取消尚未发送的请求':!connected?details:'开启后自动执行各页面已勾选功能'; + const requested=strategyRequested(summary),run=$('#strategy-toggle');run.textContent=requested?'停止':'开启';run.classList.toggle('running',requested);run.disabled=!account || !requested && (!account.config || !connected); + run.setAttribute('aria-pressed',String(requested)); + run.title=requested?'暂停自动执行已勾选功能,取消尚未发送的请求;掉线、重新登录和服务重启后仍保持暂停,直到再次“开启”;账号仍会自动重登。':!connected?details:'开启后自动执行各页面已勾选功能,连接恢复后继续执行'; $('[data-command="start"]').disabled=!account?.config || !connected; $('[data-command="start-all"]').disabled=![...state.accounts.values()].some(gameAvailable); if (account?.config && document.activeElement!==$('#refresh-interval')) $('#refresh-interval').value=String(account.config.interval); @@ -123,7 +154,7 @@ function renderSummary() { $('#refresh').disabled=!connected;$('#refresh').title=connected?'读取游戏状态并预览策略':details; const task=account?[...account.jobs.values()].at(-1)?.job:null; $('#job-status').textContent=task?`${operationLabels[task.operation] || task.operation} · ${jobLabels[task.status]}`:summary?.busy?'后台任务执行中':''; - const message=[details || summary?.error || (demo?'当前为离线演示,不连接游戏服务器。':connected?summary.running?'角色状态自动刷新,正在自动执行已配置且已勾选的功能;可在顶部“停止”。':'角色状态自动刷新;策略已停止,可在顶部“开启”继续执行已勾选功能。':'请在登录页输入账号密码,或恢复已保存会话。'),...transportMessages(account)].filter(Boolean).join(';'); + const message=[demo?'当前为离线演示,不连接游戏服务器。':'',strategyDetails(account),details,failureHistory(account),...transportMessages(account)].filter(Boolean).join(';'); $('#data-summary').textContent=message;$('#data-summary').title=message; account?.pages.forEach(renderPageConnection);renderStatus(); syncSaveStatus(account); @@ -254,13 +285,14 @@ async function perform(account,operation,payload={},options={}) { if(!state.accounts.has(account.id))return result; if(result?.config){account.config=clone(result.config);account.revision=result.revision;} if(['enter_server','restore_session','logout','forget_login','import_config','import_yields'].includes(operation))await refreshConfig(account); - try{account.summary=await api.status(account.id);account.transportErrors.delete('status');} + try{acceptSummary(account,await api.status(account.id));account.transportErrors.delete('status');} catch(failure){transportError(account,'status','Web 账号状态',failure);failure.connection=true;throw failure;} renderAccountTabs();renderSummary(); if((gameRefreshOperations.has(operation)||loginOperations.has(operation)) && !gameAvailable(account)){setStatus('工作台状态已更新');throw connectionError(account);} const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true); if(operation==='login'&&result)account.pages.get('login')?.login?.update(result); - const message=loginOperations.has(operation)?account.summary.running?'已读取角色,已自动开启策略,执行已配置且已勾选的功能;可在顶部“停止”。':'已读取角色。策略已停止,可在顶部“开启”继续执行已勾选功能。':result?.message; + if(operation==='forget_login')account.lastFailure=''; + const message=loginOperations.has(operation)?account.summary.running && strategyRequested(account.summary)?'已读取角色,已自动开启策略,执行已配置且已勾选的功能;可在顶部“停止”。':`已读取角色。${strategyDetails(account)}`:result?.message; if(message && operation!=='refresh')notice(message); setStatus(operation==='refresh'?'状态已刷新':message || `${operationLabels[operation] || '操作'}已完成`); return result; @@ -325,10 +357,9 @@ async function pageAction(page,action,currency) { if(operation==='reveal_breakthrough'){page.root.querySelector('th[data-column=breakthrough_selected]')?.scrollIntoView({block:'nearest',inline:'center'});return;} if(operation==='apply_preset'){ const preset=page.data.details.preset; - if(account.summary.running)await perform(account,'stop'); Object.entries(preset.patch || {}).forEach(([section,fields])=>Object.entries(fields).forEach(([key,value])=>editConfig(account,[section,key],value))); editConfig(account,['policy','egg_rules'],preset.egg_rules); - await flushConfig(account);notice('预设已保存。开启顶部策略后运行。');return; + await flushConfig(account);notice(`预设已保存;${strategyDetails(account)}`);return; } if(operation==='expand_regions'||operation==='collapse_regions'){page.table?.expand(operation==='expand_regions');return;} if(operation==='import_yields'){return importYields(account);} @@ -378,7 +409,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.3'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;每次成功登录后自动执行已勾选功能,可在顶部“停止”。服务重启后须先成功登录才执行。'})),{info:true}); + if(name==='about')return dialog('关于牧场助手',el('div',{},el('p',{text:`牧羊人之心牧场助手 Web ${state.meta?.version || '2.0.4'}`}),el('p',{text:`游戏数据版本 ${state.meta?.gameVersion || '1.9.68'}`}),el('p',{class:'info-note',text:'与桌面助手共用核心策略。配置在服务端自动保存;在线时默认自动执行已勾选功能,连接恢复后继续执行。顶部“停止”仅暂停执行,暂停在重新登录和服务重启后仍保留,直到再次“开启”。已保存的账号按设定时长自动重登,退出登录不取消;只有清除登录记录或删除账号才取消。'})),{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('请先新增或选择账号。'); @@ -394,7 +425,7 @@ async function command(name,account=current()) { } if(name==='logout')return await perform(account,'logout'); if(name==='forget-login'){ - if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return; + if(await confirm('退出并清除登录记录','将退出当前角色,删除当前账号保存的登录会话和账号密码,并取消该账号的自动重登。培养策略和其他账号不受影响。',{confirm:'清除登录记录',danger:true}))await perform(account,'forget_login');return; } if(name==='remove-account'){ if(!await confirm('移除当前账号',`移除“${account.summary.label || '当前账号'}”及其保存的会话和策略?此操作无法撤销。`,{confirm:'移除账号',danger:true}))return; @@ -408,8 +439,8 @@ async function command(name,account=current()) { if(name==='import-config'){ const file=await filePicker('.json');if(!file)return;if(file.size>1024*1024)throw new Error('策略文件过大。'); let config;try{config=JSON.parse(await file.text());}catch{throw new Error('策略文件不是有效的 JSON。');} - if(!await confirm('导入当前账号策略','将替换当前账号策略并停止执行;下次成功登录会自动执行已勾选功能。',{confirm:'导入策略'}))return; - await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入,执行已停止;下次成功登录会自动执行已勾选功能。');await loadPage(getPage(account,account.page),true);return result; + if(!await confirm('导入当前账号策略','将替换当前账号策略配置;自动执行仍遵循当前开启 / 停止设置。',{confirm:'导入策略'}))return; + await flushConfig(account);const result=await trackJob(account,await api.importConfig(account.id,config));await refreshConfig(account);notice('策略已导入;自动执行仍遵循当前开启 / 停止设置。');await loadPage(getPage(account,account.page),true);return result; } if(name==='import-yields')return await importYields(account); if(name==='export-yields')return await exportYields(account); @@ -555,7 +586,7 @@ async function syncAccounts() { const ids=new Set(summaries.map(summary=>summary.id)); for(const [id,account]of state.accounts)if(!ids.has(id)){account.pages.forEach(page=>{clearTimeout(page.loadTimer);page.root.remove();});state.accounts.delete(id);} summaries.forEach(summary=>{ - const account=state.accounts.get(summary.id);if(account){account.summary=summary;account.transportErrors.delete('status');if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);} + const account=state.accounts.get(summary.id);if(account){acceptSummary(account,summary);account.transportErrors.delete('status');if(account.config&&account.revision!==summary.revision&&!account.edits.size&&!account.savePromise)refreshConfig(account).catch(error);} else state.accounts.set(summary.id,makeAccount(summary)); }); renderAccountTabs();renderSummary(); @@ -595,7 +626,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.3';$('#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.4';$('#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})));} } @@ -607,7 +638,7 @@ document.addEventListener('click',event=>{if(!event.target.closest('.menu'))$$(' document.addEventListener('keydown',event=>{if(event.key==='Escape')$$('.menu[open]').forEach(menu=>menu.open=false);}); $$('.menu').forEach(menu=>menu.addEventListener('toggle',()=>{if(menu.open)$$('.menu').filter(other=>other!==menu).forEach(other=>other.open=false);})); $('#add-account').addEventListener('click',()=>command('add-account')); -$('#strategy-toggle').addEventListener('click',()=>command(current()?.summary.running?'stop':'start')); +$('#strategy-toggle').addEventListener('click',()=>command(strategyRequested(current()?.summary)?'stop':'start')); $('#refresh').addEventListener('click',()=>{const account=current();if(account)perform(account,'refresh',{page:account.page}).catch(error);}); $('#refresh-interval').addEventListener('change',event=>{if(current())editConfig(current(),['interval'],Number(event.target.value));}); $('#save-status').tabIndex=0;$('#save-status').addEventListener('click',()=>command('save'));$('#save-status').addEventListener('keydown',event=>{if(event.key==='Enter')command('save');}); diff --git a/ranch_web/static/index.html b/ranch_web/static/index.html index 9c90493..b412f98 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -26,7 +26,7 @@ - 牧羊人之心牧场助手 2.0.3 + 牧羊人之心牧场助手 2.0.4 正在连接本地服务
diff --git a/ranch_web/static/pages.js b/ranch_web/static/pages.js index 49ed964..a9330ab 100644 --- a/ranch_web/static/pages.js +++ b/ranch_web/static/pages.js @@ -48,11 +48,11 @@ class LoginPage { this.restore = el('button', {type: 'button', text: '恢复选中会话(无需重新输密码)', disabled: true, onClick: () => page.perform('restore_session', {session_id: this.saved.value}).catch(page.error)}); this.root.append(form, field('第二步:区服 / 角色', el('div', {class: 'server-row'}, this.servers, this.enter)), - el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。成功登录后自动刷新状态并执行已配置且已勾选的功能,可在顶部“停止”。'}), + el('p', {class: 'info-note', text: '账号验证 → 获取官方区服 → 选择区服 → 进入区服 → 读取角色。在线时默认自动刷新状态并自动执行已勾选功能;顶部“停止”仅暂停执行,重新登录和服务重启后仍保持暂停,直到再次“开启”。'}), el('div', {class: 'session-block policy-form'}, field('已保存账号 / 区服 / 角色', this.saved), el('div', {class: 'login-actions'}, this.restore)), el('div', {class: 'page-toolbar'}, el('button', {type: 'button', text: '退出登录', onClick: () => page.perform('logout').catch(page.error)}), el('button', {type: 'button', text: '退出并清除登录记录…', onClick: () => page.options.command('forget-login', page.account)})), - el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。手动选服、恢复会话和自动重登成功后,均自动执行已勾选功能;退出登录后停止执行。'})); + el('p', {class: 'info-note', text: '记住的账号密码和登录会话由服务端加密保存。浏览器不会保存游戏凭据。账号登录并保存原区服、原角色后会持续保持登录:掉线、退出登录或服务重启,均按设定时长自动重登并恢复监控;默认等待 30 分钟,可修改为 10 分钟等时长。关闭页面不影响自动重登。只有“退出并清除登录记录”或删除账号才取消自动重登;手动停止的执行仍保持暂停。'})); host.append(this.autoReloginStatus, this.root); } @@ -71,13 +71,12 @@ class LoginPage { } updateStatus() { - const enabled = this.page.account.config?.auto_relogin?.enabled === true; const status = this.page.account.summary?.auto_relogin_status; - const message = status?.message || (enabled ? '自动重登已开启,等待服务端状态。' : '自动重登未开启。'); + const message = status?.message || '已保存的账号会持续自动重登,等待服务端状态;可设置重登等待时长。'; if (this.autoReloginMessage.textContent !== message) this.autoReloginMessage.textContent = message; - this.autoReloginCredentials.hidden = !enabled || this.hasSavedPassword !== false; + this.autoReloginCredentials.hidden = this.hasSavedPassword !== false; const attemptAt = typeof status?.next_attempt_at === 'string' ? Date.parse(status.next_attempt_at) : NaN; - this.autoReloginCountdown.hidden = !enabled || !Number.isFinite(attemptAt); + this.autoReloginCountdown.hidden = !Number.isFinite(attemptAt); if (!this.autoReloginCountdown.hidden) { const remaining = Math.max(0, Math.ceil((attemptAt - Date.now()) / 1000)); const countdown = remaining ? `${remaining} 秒后自动重新登录(${chinaTime(status.next_attempt_at, {date: true})},北京时间)` : '等待服务端执行自动重登'; @@ -230,6 +229,7 @@ export class PageView { this.summary.textContent = typeof data.summary === 'string' ? data.summary : textValue(data.summary || ''); this.updateRuntimeStatus(data.details || {}); let fields = data.form || this.options.schema(this.key); + if (this.key === 'login') fields = fields.filter(field => !(field.path?.[0] === 'auto_relogin' && field.path[1] === 'enabled')); fields=fields.map(field=>field.path?.[0]==='policy'&&field.path[1]==='buy_ten'?{...field,disabled:!this.account.config?.policy?.allow_single_draw}:field); if (this.key === 'hatching' && this.activeSubtab) fields = fields.filter(field => !field.group || field.group === this.activeSubtab); const policyTab = this.key === 'mainline' && ['policy', 'settings', '推进策略'].includes(this.activeSubtab); diff --git a/ranch_web/tests/browser/test_auto_relogin_browser.py b/ranch_web/tests/browser/test_auto_relogin_browser.py index 7ff7f72..5d4cee3 100644 --- a/ranch_web/tests/browser/test_auto_relogin_browser.py +++ b/ranch_web/tests/browser/test_auto_relogin_browser.py @@ -27,16 +27,14 @@ class AutoReloginSchemaTests(unittest.TestCase): catalog = Catalog() fields = next(page["form"] for page in schema(catalog)["pages"] if page["key"] == "login") fields = {tuple(field["path"]): field for field in fields} - enabled = fields[("auto_relogin", "enabled")] delay = fields[("auto_relogin", "delay_minutes")] - self.assertEqual(enabled["label"], "掉线后自动重新登录") - self.assertEqual(enabled["type"], "boolean") - self.assertIs(enabled["value"], False) + self.assertNotIn(("auto_relogin", "enabled"), fields) + self.assertIsInstance(default_config()["auto_relogin"]["enabled"], bool) self.assertEqual((delay["type"], delay["min"], delay["max"], delay["value"]), ("integer", 1, 10080, 30)) engine = SimpleNamespace(catalog=catalog, snapshot=None, demo=False) view = build_view(engine, "login", default_config()) values = {tuple(field["path"]): field["value"] for field in view["form"]} - self.assertIs(values[("auto_relogin", "enabled")], False) + self.assertNotIn(("auto_relogin", "enabled"), values) self.assertEqual(values[("auto_relogin", "delay_minutes")], 30) @@ -77,8 +75,9 @@ class AutoReloginBrowserTests(unittest.TestCase): self.configs[identifier]["auto_relogin"] = {"enabled": False, "delay_minutes": 30} summary = copy.deepcopy(self.manager.status(identifier)) summary.update(demo=False, connected=False, running=False, connection_state="offline", - connection_message="尚未连接游戏", error="", revision=9000) - summary["auto_relogin_status"] = {"state": "disabled", "message": "自动重登未开启", "next_attempt_at": None} + connection_message="尚未连接游戏", error="", revision=9000, + strategy_requested=False, strategy_state="stopped", strategy_message="", strategy_retry_at=None) + summary["auto_relogin_status"] = {"state": "missing_identity", "message": "尚未保存登录角色", "next_attempt_at": None} self.summaries[identifier] = summary self.login_data[identifier] = build_view(engine, "login", default_config()) self.login_data[identifier].update(account="offline-fixture", has_saved_password=True) @@ -122,9 +121,10 @@ class AutoReloginBrowserTests(unittest.TestCase): route.abort() return self.summaries[identifier].update(connected=False, running=False, connection_state="offline") - self.set_status(identifier, "cancelled", "手动退出登录,已取消本次自动重登") + self.waiting(identifier, message="退出登录后仍按设定时长自动重登", + requested=self.summaries[identifier]["strategy_requested"]) self.fulfill(route, {"id": "mock-logout", "operation": operation, "status": "succeeded", - "result": {"message": "已退出登录并取消自动重登"}}) + "result": {"message": "已退出当前连接,仍会自动重登"}}) return if request.method in ("POST", "PUT", "DELETE", "PATCH"): self.unexpected_actions.append(path) @@ -146,15 +146,21 @@ class AutoReloginBrowserTests(unittest.TestCase): self.summaries[identifier]["auto_relogin_status"] = { "state": state, "message": message, "next_attempt_at": next_attempt_at} - def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登"): + def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登", requested=True): identifier = identifier or self.first - self.configs[identifier]["auto_relogin"]["enabled"] = True + summary = self.summaries[identifier] + summary["strategy_requested"] = requested + if not requested: + summary["strategy_state"] = "stopped" + elif summary["strategy_state"] == "stopped": + summary["strategy_state"] = "offline" target = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat().replace("+00:00", "Z") self.set_status(identifier, "waiting", message, target) return target - def controls(self, panel): - return panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True), panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True) + def delay_control(self, panel): + expect(panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True)).to_have_count(0) + return panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True) def saved(self, identifier, enabled, minutes): self.page.wait_for_function("() => document.querySelector('#save-status').textContent === '策略已自动保存'") @@ -162,27 +168,27 @@ class AutoReloginBrowserTests(unittest.TestCase): def complete_login(self, operation, *, running=True): self.summaries[self.first].update(connected=True, connection_state="online", - connection_message="游戏连接正常", error="", running=running) + connection_message="游戏连接正常", error="", running=running, + strategy_requested=running, strategy_state="running" if running else "stopped") return {"id": "mock-" + operation, "operation": operation, "status": "succeeded", "result": {}} def test_defaults_visible_explanations_and_existing_layout(self): self.open() panel = self.go("login") - enabled, delay = self.controls(panel) - expect(enabled).to_be_visible() - expect(enabled).not_to_be_checked() + delay = self.delay_control(panel) + expect(delay).to_be_visible() expect(delay).to_have_value("30") for attribute, value in (("min", "1"), ("max", "10080"), ("step", "1")): expect(delay).to_have_attribute(attribute, value) - for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启"): + for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启", "退出登录", "只有", "清除登录记录", "暂停"): expect(panel).to_contain_text(text) - self.assertTrue(enabled.evaluate("node => Boolean(node.closest('.policy-form'))")) - self.assertTrue(enabled.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)")) + self.assertTrue(delay.evaluate("node => Boolean(node.closest('.policy-form'))")) + self.assertTrue(delay.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)")) expect(panel.get_by_role("button", name="保存", exact=True)).to_have_count(0) for width, height in ((1280, 800), (390, 844)): self.page.set_viewport_size({"width": width, "height": height}) self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width) - expect(enabled).to_be_visible() + expect(delay).to_be_visible() self.assertEqual(self.writes, []) self.assertEqual(self.actions, []) @@ -196,7 +202,7 @@ class AutoReloginBrowserTests(unittest.TestCase): return {"id": "mock-login", "operation": "login", "status": "succeeded", "result": candidates} def stop(payload): - self.summaries[self.first]["running"] = False + self.summaries[self.first].update(running=False, strategy_requested=False, strategy_state="stopped") return {"id": "mock-stop", "operation": "stop", "status": "succeeded", "result": {"message": "策略已停止"}} self.action_handlers.update({(self.first, "login"): login, @@ -230,13 +236,13 @@ class AutoReloginBrowserTests(unittest.TestCase): self.assertEqual(self.configs[self.first], original) self.assertEqual(self.writes, []) - def test_import_stays_stopped_and_next_restored_session_runs_imported_selection(self): + def test_import_and_restored_session_preserve_explicit_pause_and_imported_selection(self): imported = copy.deepcopy(default_config()) imported["daily_policy"].update(enabled=True, selected=["gift"]) portable = export_config(imported) imports = [] self.login_data[self.first]["saved_sessions"] = [{"id": "offline-session", "label": "离线区服 / 原角色"}] - self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session") + self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session", running=False) def import_config(route): imports.append(route.request.post_data_json) @@ -253,15 +259,15 @@ class AutoReloginBrowserTests(unittest.TestCase): self.page.locator('[data-command="import-config"]').click() chooser.value.set_files({"name": "offline-policy.json", "mimeType": "application/json", "buffer": json.dumps(portable).encode("utf-8")}) - expect(self.page.locator("#dialog-content")).to_contain_text("下次成功登录会自动执行已勾选功能") + expect(self.page.locator("#dialog-content")).to_contain_text("仍遵循当前开启 / 停止设置") self.page.locator("#dialog-confirm").click() - expect(self.page.locator("#notice")).to_contain_text("策略已导入,执行已停止") + expect(self.page.locator("#notice")).to_contain_text("策略已导入") expect(self.page.locator("#strategy-toggle")).to_be_disabled() self.assertEqual(imports, [portable]) self.assertEqual(self.actions, []) panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True).click() - expect(self.page.locator("#strategy-toggle")).to_have_text("停止") - expect(self.page.locator("#notice")).to_contain_text("已自动开启策略") + expect(self.page.locator("#strategy-toggle")).to_have_text("开启") + expect(self.page.locator("#notice")).to_contain_text("用户暂停") self.assertEqual(self.actions, [(self.first, "restore_session", {"session_id": "offline-session"})]) self.assertEqual(self.configs[self.first], imported, "Restoring must preserve imported selections") self.assertEqual(self.writes, []) @@ -314,17 +320,12 @@ class AutoReloginBrowserTests(unittest.TestCase): def test_native_autosave_range_validation_refresh_and_focus(self): self.open() panel = self.go("login") - enabled, delay = self.controls(panel) - enabled.check() - checkbox = enabled.element_handle() - self.page.wait_for_timeout(850) - self.saved(self.first, True, 30) - self.assertTrue(enabled.evaluate("(node, original) => node === original && node === document.activeElement", checkbox)) + delay = self.delay_control(panel) delay.fill("47") original = delay.element_handle() before = self.view_calls self.page.wait_for_timeout(5200) - self.saved(self.first, True, 47) + self.saved(self.first, False, 47) self.assertGreater(self.view_calls, before, "Offline login DTOs must keep refreshing") self.assertTrue(delay.evaluate("(node, original) => node === original && node === document.activeElement", original)) for invalid in ("0", "10081", "1.5", ""): @@ -336,9 +337,7 @@ class AutoReloginBrowserTests(unittest.TestCase): for valid in (1, 10080): delay.fill(str(valid)) self.page.wait_for_timeout(850) - self.saved(self.first, True, valid) - enabled.uncheck() - self.page.wait_for_timeout(850) + self.saved(self.first, False, valid) self.saved(self.first, False, 10080) self.assertEqual(self.actions, []) @@ -350,14 +349,13 @@ class AutoReloginBrowserTests(unittest.TestCase): remember = panel.get_by_role("checkbox", name="记住账号和密码", exact=True) remember.uncheck() panel.get_by_role("textbox", name="游戏密码", exact=True).fill("mock-secret-never-send") - enabled, _ = self.controls(panel) - enabled.check() + self.delay_control(panel).fill("10") hint = panel.locator("[data-auto-relogin-credentials]") expect(hint).to_be_visible() expect(hint).to_contain_text("缺少") expect(hint).to_contain_text("记住账号和密码") self.page.wait_for_timeout(1000) - self.saved(self.first, True, 30) + self.saved(self.first, False, 10) expect(remember).not_to_be_checked() self.assertTrue(self.writes) payloads = json.dumps(self.writes, ensure_ascii=False) @@ -370,26 +368,24 @@ class AutoReloginBrowserTests(unittest.TestCase): def test_account_switch_isolates_pending_edits_status_and_minutes(self): self.waiting(message="账号一正在等待自动重登") - self.set_status(self.second, "disabled", "账号二未开启自动重登") + self.set_status(self.second, "missing_identity", "账号二尚未保存登录角色") self.open() panel = self.go("login") - _, delay = self.controls(panel) + delay = self.delay_control(panel) delay.fill("17") self.page.locator(f'.account-tab[data-account="{self.second}"]').click() panel = self.go("login") - enabled, second_delay = self.controls(panel) - expect(enabled).not_to_be_checked() + second_delay = self.delay_control(panel) expect(second_delay).to_have_value("30") - expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二未开启") + expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二尚未保存") expect(panel).not_to_contain_text("账号一正在等待") - enabled.check() second_delay.fill("9") self.page.wait_for_timeout(1000) - self.saved(self.second, True, 9) - self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": True, "delay_minutes": 17}) + self.saved(self.second, False, 9) + self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": False, "delay_minutes": 17}) self.page.locator(f'.account-tab[data-account="{self.first}"]').click() panel = self.go("login") - expect(self.controls(panel)[1]).to_have_value("17") + expect(self.delay_control(panel)).to_have_value("17") expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号一正在等待") self.assertEqual({identifier for identifier, _ in self.writes}, {self.first, self.second}) self.assertEqual(self.actions, []) @@ -404,8 +400,8 @@ class AutoReloginBrowserTests(unittest.TestCase): expect(status).to_contain_text("掉线后等待自动重登") expect(countdown).to_contain_text("秒后自动重新登录") expect(countdown).to_contain_text("北京时间") - expect(self.controls(panel)[0]).to_be_enabled() - delay = self.controls(panel)[1] + delay = self.delay_control(panel) + expect(delay).to_be_enabled() delay.focus() original = delay.element_handle() before = countdown.inner_text() @@ -421,10 +417,12 @@ class AutoReloginBrowserTests(unittest.TestCase): self.set_status(self.first, "failed", reason) expect(status).to_contain_text(reason) expect(status.locator("img")).to_have_count(0) - expect(self.page.locator("#strategy-toggle")).to_be_disabled() + expect(self.page.locator("#strategy-toggle")).to_have_text("停止") + expect(self.page.locator("#strategy-toggle")).to_be_enabled() original = copy.deepcopy(self.configs[self.first]) self.set_status(self.first, "monitoring", "重登成功,已恢复监控并自动执行已勾选功能,可在顶部停止") - self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", running=True) + self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", + running=True, strategy_requested=True, strategy_state="running") expect(status).to_contain_text("已恢复监控并自动执行已勾选功能") expect(self.page.locator("#strategy-toggle")).to_have_text("停止") expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行已配置且已勾选的功能") @@ -436,31 +434,35 @@ class AutoReloginBrowserTests(unittest.TestCase): self.open() panel = self.go("login") expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("服务重启") - expect(self.page.locator("#strategy-toggle")).to_be_disabled() + expect(self.page.locator("#strategy-toggle")).to_have_text("停止") + expect(self.page.locator("#strategy-toggle")).to_be_enabled() before = len(self.writes) self.page.reload(wait_until="networkidle") panel = self.go("login") - expect(self.controls(panel)[0]).to_be_checked() - expect(self.controls(panel)[1]).to_have_value("30") + expect(self.delay_control(panel)).to_have_value("30") expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录") - expect(self.page.locator("#strategy-toggle")).to_have_text("开启") - expect(self.page.locator("#strategy-toggle")).to_be_disabled() + expect(self.page.locator("#strategy-toggle")).to_have_text("停止") + expect(self.page.locator("#strategy-toggle")).to_be_enabled() self.page.goto("about:blank") self.page.close() self.assertEqual(len(self.writes), before) self.assertEqual(self.summaries[self.first]["auto_relogin_status"]["next_attempt_at"], target) self.assertEqual(self.actions, []) - def test_manual_logout_cancels_countdown_without_disabling_account_setting(self): + def test_manual_logout_keeps_countdown_and_preserves_strategy_pause(self): self.waiting() + self.summaries[self.first].update(strategy_requested=False, strategy_state="stopped") self.open() panel = self.go("login") expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录") panel.get_by_role("button", name="退出登录", exact=True).click() - expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("已取消本次自动重登") - expect(panel.locator("[data-auto-relogin-countdown]")).to_be_hidden() - expect(self.controls(panel)[0]).to_be_checked() + expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("仍按设定时长自动重登") + expect(panel.locator("[data-auto-relogin-countdown]")).to_be_visible() + expect(self.page.locator("#strategy-toggle")).to_have_text("开启") + expect(self.page.locator("#data-summary")).to_contain_text("用户暂停") + expect(self.delay_control(panel)).to_have_value("30") self.assertEqual(self.actions, [(self.first, "logout", {})]) + self.assertEqual(self.writes, []) if __name__ == "__main__": diff --git a/ranch_web/tests/browser/test_connection_browser.py b/ranch_web/tests/browser/test_connection_browser.py index e49a565..71fcd06 100644 --- a/ranch_web/tests/browser/test_connection_browser.py +++ b/ranch_web/tests/browser/test_connection_browser.py @@ -72,7 +72,8 @@ class ConnectionBrowserTests(unittest.TestCase): panel = self.go("ranch") expect(panel.locator("tbody tr").first).to_be_visible() row_count = panel.locator("tbody tr").count() - self.summary.update(connection_state="expired", connection_message="登录凭据已失效,请重新登录。") + failure_reason = "登录凭据已失效,请重新登录。" + self.summary.update(connection_state="expired", connection_message=failure_reason, error=failure_reason) expect(self.page.locator("#connection")).to_have_text("登录已过期") expect(self.page.locator("#data-summary")).to_contain_text(self.summary["connection_message"]) expect(panel.locator(".page-loading")).to_contain_text("缓存") @@ -89,10 +90,14 @@ class ConnectionBrowserTests(unittest.TestCase): self.assertTrue(panel.locator("input[data-config-path]").first.is_enabled()) self.summary.update(connection_state="online", connection_message="游戏连接正常", error="", last_game_success_at="2026-11-11T00:01:00Z") expect(self.page.locator("#connection")).to_have_text("已登录") + expect(self.page.locator("#connection")).to_have_attribute("title", "游戏连接正常") expect(self.page.locator("#strategy-toggle")).to_be_enabled() expect(panel.locator("[data-connection-status]")).to_be_hidden() - expect(self.page.locator("#data-summary")).not_to_contain_text("凭据已失效") - expect(self.page.locator("#status-text")).not_to_contain_text("凭据已失效") + expect(panel.locator("[data-connection-status]")).to_have_text("") + for selector in ("#data-summary", "#status-text"): + expect(self.page.locator(selector)).to_be_visible() + expect(self.page.locator(selector)).to_contain_text(f"上次失败:{failure_reason}") + expect(self.page.locator(f'.account-tab[data-account="{self.first}"] .account-dot')).not_to_have_class("account-dot error") expect(panel.locator(".page-loading")).not_to_contain_text("缓存") self.assertEqual(self.page.locator("#page-tabs [role=tab]").count(), 15) self.assertEqual(self.external_requests, []) diff --git a/ranch_web/tests/browser/test_run_intent_browser.py b/ranch_web/tests/browser/test_run_intent_browser.py new file mode 100644 index 0000000..3bd36a3 --- /dev/null +++ b/ranch_web/tests/browser/test_run_intent_browser.py @@ -0,0 +1,214 @@ +"""Durable execution intent with synthetic API responses and loopback HTTP only.""" +from __future__ import annotations + +import unittest + +from . import test_auto_relogin_browser as relogin +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 RunIntentBrowserTests(unittest.TestCase): + setUpClass = classmethod(relogin.AutoReloginBrowserTests.setUpClass.__func__) + tearDownClass = classmethod(relogin.AutoReloginBrowserTests.tearDownClass.__func__) + tearDown = relogin.AutoReloginBrowserTests.tearDown + await_job = fixtures.WorkbenchBrowserTests.await_job + open = fixtures.WorkbenchBrowserTests.open + go = fixtures.WorkbenchBrowserTests.go + fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill) + set_status = relogin.AutoReloginBrowserTests.set_status + waiting = relogin.AutoReloginBrowserTests.waiting + + def setUp(self): + relogin.AutoReloginBrowserTests.setUp(self) + for summary in self.summaries.values(): + summary.update(strategy_requested=False, strategy_state="stopped", + strategy_message="", strategy_retry_at=None) + self.summary = self.summaries[self.first] + self.online() + self.page.add_init_script("""(() => { + const original = window.setInterval; + window.setInterval = (callback, delay, ...args) => { + if (callback.name === 'tick') {window.__pollIntent = callback;return -1;} + return original(callback, delay, ...args); + }; + })();""") + + def poll(self): + self.page.evaluate("async () => {await window.__pollIntent();}") + self.page.wait_for_load_state("networkidle") + + def online(self, *, running=True): + self.summary.update(connected=True, connection_state="online", connection_message="游戏连接正常", + error="", running=running, strategy_requested=True, + strategy_state="running" if running else "recovering", strategy_message="", + strategy_retry_at=None, next_retry_at=None) + + def recovering(self): + self.summary.update(running=False, strategy_requested=True, connection_state="retrying", + connection_message="游戏请求超时,正在恢复连接。", error="游戏请求超时", + strategy_state="recovering", strategy_message="网络超时,等待只读检查后恢复策略。") + self.summary["strategy_retry_at"] = self.page.evaluate("new Date(Date.now()+30000).toISOString()") + self.summary["next_retry_at"] = self.summary["strategy_retry_at"] + self.waiting(seconds=600) + + def test_timeout_heartbeat_only_and_recovery_preserve_stop_and_failure_history(self): + self.open() + toggle = self.page.locator("#strategy-toggle") + expect(toggle).to_have_text("停止") + expect(self.page.locator("#log-panel")).to_be_hidden() + self.recovering() + self.poll() + expect(toggle).to_have_text("停止") + expect(toggle).to_be_enabled() + expect(toggle).to_have_class("run-button running") + expect(toggle).to_have_attribute("aria-pressed", "true") + expect(self.page.locator("#data-summary")).to_contain_text("等待") + expect(self.page.locator("#data-summary")).not_to_contain_text("用户暂停") + expect(self.page.locator("#connection")).to_have_text("正在重试") + expect(self.page.locator("#refresh")).to_be_disabled() + self.online(running=False) + self.poll() + expect(self.page.locator("#connection")).to_have_text("已登录") + expect(self.page.locator("#refresh")).to_be_enabled() + expect(self.page.locator("#data-summary")).to_contain_text("等待恢复") + expect(self.page.locator("#data-summary")).to_contain_text("上次失败") + expect(self.page.locator("#data-summary")).to_contain_text("游戏请求超时") + expect(toggle).to_have_text("停止") + expect(self.page.locator(f'.account-tab[data-account="{self.first}"] .account-dot')).not_to_have_class("account-dot error") + self.online() + self.poll() + expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行") + expect(self.page.locator("#data-summary")).to_contain_text("上次失败") + expect(self.page.locator("#connection")).to_have_text("已登录") + expect(self.page.locator("#log-panel")).to_be_hidden() + self.assertEqual(self.actions, []) + self.assertEqual(self.writes, []) + + def test_stop_during_recovery_persists_pause_while_relogin_continues(self): + self.open() + self.recovering() + self.poll() + + def stop(payload): + self.summary.update(strategy_requested=False, running=False, strategy_state="stopped", + strategy_message="用户已停止策略,仍会保持登录。") + return {"id": "intent-stop", "operation": "stop", "status": "succeeded", "result": {}} + + def start(payload): + self.online() + return {"id": "intent-start", "operation": "start", "status": "succeeded", "result": {}} + + self.action_handlers[(self.first, "stop")] = stop + self.action_handlers[(self.first, "start")] = start + toggle = self.page.locator("#strategy-toggle") + toggle.click() + expect(toggle).to_have_text("开启") + expect(toggle).to_have_attribute("aria-pressed", "false") + expect(toggle).to_be_disabled() + expect(self.page.locator("#data-summary")).to_contain_text("用户暂停") + expect(self.page.locator('[data-auto-relogin-countdown]')).to_be_visible() + self.summary.update(connected=True, connection_state="online", connection_message="游戏连接正常", error="", + next_retry_at=None, strategy_retry_at=None) + self.poll() + expect(self.page.locator("#connection")).to_have_text("已登录") + expect(toggle).to_be_enabled() + expect(self.page.locator("#data-summary")).to_contain_text("用户暂停") + self.page.reload(wait_until="networkidle") + expect(toggle).to_have_text("开启") + expect(self.page.locator("#data-summary")).to_contain_text("用户暂停") + toggle.click() + expect(toggle).to_have_text("停止") + expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行") + self.assertEqual([(account, operation) for account, operation, _ in self.actions], + [(self.first, "stop"), (self.first, "start")]) + self.assertEqual(self.writes, []) + + def test_online_execution_block_is_distinct_from_connection_health_and_can_be_stopped(self): + self.online(running=False) + reason = '交付结果待确认