diff --git a/.github/workflows/web-image.yml b/.github/workflows/web-image.yml index 607403f..1af7343 100644 --- a/.github/workflows/web-image.yml +++ b/.github/workflows/web-image.yml @@ -57,8 +57,8 @@ jobs: PY - name: Install Web dependencies only run: python -m pip install -r ranch_web/requirements.txt - - name: Offline updater 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 -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: Build image env: WEB_VERSION: ${{ steps.version.outputs.version }} diff --git a/Dockerfile b/Dockerfile index bcfa91d..c00bc05 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim-bookworm -ARG WEB_VERSION=2.0.1 +ARG WEB_VERSION=2.0.2 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 777538e..df1ad34 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # 牧羊人之心Bot -本轮 Web 发布目标 **2.0.1**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 +本轮 Web 发布目标 **2.0.2**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。 ## 运行指引 -### Web 2.0.1(main) +### Web 2.0.2(main) Windows 使用 Python 3.12+,在项目根目录执行: @@ -19,7 +19,7 @@ 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.1** 支持登录成功后自动执行已勾选策略,由用户手动触发在线更新。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器;私有仓库首次配置见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。 +**2.0.2** 沿用登录成功后自动执行已勾选策略及用户手动触发在线更新。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器。已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面。操作条件见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。 ### 桌面 1.2.0 @@ -36,7 +36,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` | 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 | | --- | --- | --- | -| Web 2.0.1 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | +| Web 2.0.2 | 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,17 +44,21 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` 本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。 -## Web 2.0.1 主要功能与掉线修复 +## Web 2.0.2 主要功能与分类日志 + +2.0.2 新增按功能查看的账号日志,页面范围与操作说明见 [2.0.2 发布说明](analysis/RELEASE_2_0_2.md)。其余功能沿用现有实现。 - **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。 - **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。 - **管理登录与子路径**:独立管理登录页、HttpOnly / SameSite cookie、写请求来源校验;支持 `/ranch` 等反代子路径,游戏凭据保存在服务端。 - **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。 -- **日志与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。 +- **分类日志**:登录、每日事务、牧场、自动孵蛋、自动主线、自动赠礼、自动委托、自动探险和自动扫荡提供当前账号的日志面板,保留底部总日志与调试入口。功能面板支持文字搜索、级别筛选、独立清空显示与下载、隐藏及跟随/暂停滚动;共用同一账号日志拉取,浏览器共享缓存最多 1200 条,每面板最多显示最近 600 条。 +- **分类归属与旧日志**:分类随普通日志记录持久保存;孵蛋/牧场整理策略的自动喂养、出售、收取及暂停记录归入孵蛋,手动牧场操作与自动潜能突破归入牧场。无分类旧记录仅在明确前缀指向同一类别时保守推断,混合或未知记录保留为常规日志,在总日志和登录面板可见。 +- **日志保存与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。 连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。 -战斗模拟仍为近似模型,特殊关卡并非全部支持。已有离线回归和早期部署烟测的阶段、命令及限制见 [Web 验证说明](ranch_web/README.md#离线验证);这些记录不代表 2.0.1 已完成真实游戏 API 或生产升级/回滚验收。 +战斗模拟仍为近似模型,特殊关卡并非全部支持。2.0.2 离线回归:后端 **309 项,306 通过、3 项因 Windows 权限或符号链接限制跳过,0 失败、0 错误**;完整浏览器 **52 项全部通过,0 跳过、0 失败**。本版验证范围见 [发布说明](analysis/RELEASE_2_0_2.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 ## 桌面 1.2.0 功能基线 diff --git a/analysis/RELEASE_2_0_2.md b/analysis/RELEASE_2_0_2.md new file mode 100644 index 0000000..e09db55 --- /dev/null +++ b/analysis/RELEASE_2_0_2.md @@ -0,0 +1,35 @@ +# 2.0.2 + +适配资料基线:《牧羊人之心》Android **1.9.68**。Web 版本为 **2.0.2**,正式标签与镜像目标为 `v2.0.2`;桌面正式版保留 **1.2.0**,沿用现有工作台操作结构。 + +## 分类日志 + +| 项目 | 2.0.2 行为 | +| --- | --- | +| 功能页 | 登录、每日事务、牧场、自动孵蛋、自动主线、自动赠礼、自动委托、自动探险和自动扫荡均提供当前账号的分类日志面板 | +| 总日志与调试 | 保留底部总日志、调试入口及独立清空、下载和跟随控制 | +| 面板筛选与操作 | 文字搜索、级别筛选、独立清空显示与下载、隐藏、跟随最新及暂停跟随;下载遵循当前面板的清空范围与筛选条件 | +| 清空范围 | 仅影响当前账号当前面板的显示,不清空其他面板或删除服务端历史记录 | +| 拉取与显示上限 | 同一账号复用单一日志拉取;浏览器共享缓存最多 1200 条,各面板最多显示最近 600 条 | +| 分类保存 | 分类随普通运行日志记录持久保存;调试详情沿用进程内缓存约束 | + +分类以动作来源上下文为依据:孵蛋/牧场整理策略产生的自动喂养、出售、收取及暂停记录归入自动孵蛋(`hatching`);手动牧场操作和自动潜能突破归入牧场(`ranch`)。来源上下文优先于通用文字前缀,孵蛋策略中的“暂停喂养”仍归入孵蛋日志。完整页面与分类对应表见 [产品说明](../ranch_web/PRODUCT.md#202-分类日志)。 + +没有分类字段的旧记录,仅在各片段均有明确前缀且一致指向同一类别时保守推断归属,不拆分旧记录或根据偶然出现的功能词猜测。混合类别、未知前缀及无法识别的分类保留为常规(`general`)记录,在总日志和登录面板可见;登录面板同时包含登录与常规日志。 + +普通日志的限量持久保存及现有业务能力范围沿用原有约束;浏览器缓存和单面板显示上限不等同于服务端日志保存上限。 + +## 已有部署更新 + +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可直接使用现有宿主机更新器安装 2.0.2,无需重复初始化、替换更新器或上传应用源码;2.0.1 的初始化说明和 Release 信息保留为历史参考。 + +`v2.0.2` 稳定 GitHub Release 及对应正式镜像就绪后,可通过“帮助 → 检查版本更新…”检查并手动升级 2.0.2,升级完成后刷新网页以加载新版界面。Web 提交仍需已启用且心跳有效的宿主机执行器;`pending` 只表示请求已提交,安装结果以宿主机健康检查为准,自动安装默认关闭。详见 [部署说明](../deploy/web/README.md)。 + +## 验证 + +- 后端独立回归:**309 项,306 通过、3 项因 Windows 权限或符号链接限制跳过,0 失败、0 错误**。 +- 完整浏览器回归:**52 项全部通过,0 跳过、0 失败**,包含 9 项分类日志测试及相关 6 项回归方法;功能面板截图与隐藏总日志后切换账号的跟随状态均已复核。 +- 源码哈希一致性检查及差异检查通过。 +- 2.0.2 独立宿主机更新器仅依赖 Python 标准库,版本、dry-run、校验和及发布版本门禁校验通过。 + +分类日志及相关回归方法已计入 52 项浏览器总数,不另行累加;历史 2.0.1 统计不计入本版。以上为离线验证,不代表真实游戏 API 或生产升级/回滚验收。 diff --git a/compose.yaml b/compose.yaml index 9796630..8824bc1 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.1} + image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.2} build: context: . args: - WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.1} + WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.2} user: "10001:10001" init: true restart: unless-stopped diff --git a/deploy/web/README.md b/deploy/web/README.md index 1ebd87c..edc5d76 100644 --- a/deploy/web/README.md +++ b/deploy/web/README.md @@ -1,8 +1,8 @@ # Web 2 Linux Docker 部署与更新 -以下更新示例以 `v2.0.1` 为目标;游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 +当前更新示例以 `v2.0.2` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 -已有部署首次接入私有在线更新时,按下文“已有宿主机首次初始化”操作。旧应用和旧更新器需要先配置私有发布认证,再由新版独立更新器在线拉取 `v2.0.1` 镜像。 +已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 ## 容器与持久化 @@ -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.1`,需确认对应镜像已发布后再 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.2`,需确认对应镜像已发布后再 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`。不要对现有账号目录重新初始化密钥。 @@ -49,6 +49,12 @@ sudo sh deploy/web/compose.sh up -d --no-build --pull never --wait --wait-timeou Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳过草稿、预发布、1.x、3.x 和非法标签。数字不含前导零。`2.0.0.dev1 → v2.0.0` 可升级,`2.0.0 → v2.0.0` 不升级,拒绝降级。网络失败会明确显示检查失败,不使用虚构版本或下载脚本。 +### 已完成 2.0.1 初始化的宿主机 + +`v2.0.2` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.2 后手动提交更新请求。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 + +### 全新宿主机准备 + 全新安装时,先安装 root 持有的配置,并准备独立更新器(示例的自动化开关默认关闭): ```sh @@ -58,10 +64,12 @@ sudo install -m 0644 -o root -g root /tmp/updater.pyz /opt/ranch-web/updater.pyz python3 -B /opt/ranch-web/updater.pyz --version ``` -也可从对应 Release 下载 `updater.pyz` 及 `SHA256SUMS`,核对后安装,宿主机不需要完整 Python 源码或 pip 依赖。构建器只打包 `__main__.py`、`updater.py`、`ranch_web/__init__.py`、`ranch_web/updates.py`,版本取构建时的 `ranch_web.__version__`;维护者升版后需重新生成资产。原有 `python3 -B deploy/web/updater.py ...` CLI 仍可运行,本文的 service 默认使用 `/opt/ranch-web/updater.pyz`。 +也可从对应 Release 下载 `updater.pyz` 及 `SHA256SUMS`,核对后安装,宿主机不需要完整 Python 源码或 pip 依赖。构建器只打包 `__main__.py`、`updater.py`、`ranch_web/__init__.py`、`ranch_web/updates.py`,版本取构建时的 `ranch_web.__version__`;维护者为新 Release 生成对应版本资产,不意味着已安装的宿主机更新器必须随应用版本一起替换。原有 `python3 -B deploy/web/updater.py ...` CLI 仍可运行,本文的 service 默认使用 `/opt/ranch-web/updater.pyz`。 ### 已有宿主机首次初始化(用户自行执行) +以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.2`。 + 前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。 1. 用户登录有私有仓库读取权限的 GitHub 账号,从 [v2.0.1 Release](https://github.com/attilanet/myrzx_bot/releases/tag/v2.0.1) 下载 `updater.pyz` 和 `SHA256SUMS`,放到宿主机临时目录。确认 Release 已发布且镜像可读取,在下载目录执行 `sha256sum -c SHA256SUMS` 后安装: @@ -153,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 的工作流结果为准。 -本机 Windows 没有 Docker,已能执行的验证是离线单元测试、临时数据的备份/回滚测试、启动脚本语法与配置静态核对、更新器 dry-run;不代表 Linux/Docker 实机验证通过。可在无 Docker 的机器上只打印计划(不联网、不写文件): +2.0.2 验证范围与结果统一见 [发布说明](../../analysis/RELEASE_2_0_2.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.1 --dry-run +python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.2 --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 ad91b2f..f63b7bc 100644 --- a/deploy/web/image.env.example +++ b/deploy/web/image.env.example @@ -1,2 +1,2 @@ -# Pull only after the v2.0.1 image publishing workflow succeeds and the image is available. -RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.1 +# Pull only after the v2.0.2 image publishing workflow succeeds and the image is available. +RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.2 diff --git a/ranch_web/PRODUCT.md b/ranch_web/PRODUCT.md index f6ac1dd..061f4a5 100644 --- a/ranch_web/PRODUCT.md +++ b/ranch_web/PRODUCT.md @@ -1,8 +1,8 @@ -# 牧羊人之心牧场助手 · Web 2.0.1 +# 牧羊人之心牧场助手 · Web 2.0.2 ## 产品约束 -把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.1`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 +把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.2`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 @@ -24,7 +24,30 @@ - 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。 - 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。 - 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。 -- 2.0.1 由用户手动触发在线更新,使用稳定 Release、对应正式镜像及完成私有认证的宿主机更新器;安装结果以宿主机健康检查为准。 +- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 + +## 2.0.2 分类日志 + +各功能页提供当前账号的分类日志面板;底部总日志和调试日志入口继续保留,账号之间不混入日志。 + +| 功能页 | 分类 | 日志范围 | +| --- | --- | --- | +| 登录 | `login`、`general` | 登录及常规记录,包括混合或无法归类的旧记录 | +| 每日事务 | `daily` | 每日事务记录 | +| 牧场 | `ranch` | 手动牧场操作、自动潜能突破及对应暂停记录 | +| 自动孵蛋 | `hatching` | 孵蛋与牧场整理策略记录,包括自动喂养、出售、收取及暂停 | +| 自动主线 | `mainline` | 主线推进记录 | +| 自动赠礼 | `gifts` | 赠礼记录 | +| 自动委托 | `commissions` | 委托记录 | +| 自动探险 | `exploration` | 探险记录 | +| 自动扫荡 | `maps` | 扫荡及地图挑战记录 | + +- 同一账号使用单一共享日志拉取,供总日志与分类面板复用;浏览器共享缓存上限 1200 条,每个面板最多显示最近 600 条。 +- 分类面板提供文字搜索、级别筛选、独立清空显示与下载、隐藏、跟随最新及暂停跟随。清空只影响当前账号当前面板,不清空其他面板或服务端历史;下载遵循本面板的清空范围与筛选条件。 +- 分类随普通运行日志记录持久保存。动作来源上下文优先于通用文字前缀;孵蛋/牧场整理策略产生的“暂停喂养”归入 `hatching`,不因文字中包含喂养而改归 `ranch`。 +- 无分类旧记录仅在所有片段的明确前缀一致指向同一类别时保守推断;不拆分或强行重分混合记录。混合、未知或无法识别的类别保留为 `general`,在总日志和登录面板可见。 + +功能与验证范围见 [2.0.2 发布说明](../analysis/RELEASE_2_0_2.md)。 ## 安全与验证 diff --git a/ranch_web/README.md b/ranch_web/README.md index 5644f9a..c333466 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -1,6 +1,6 @@ -# Web 2.0.1 运行说明 +# Web 2.0.2 运行说明 -本轮 Web 发布目标 **2.0.1**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 +本轮 Web 发布目标 **2.0.2**,源码入口 `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)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。 @@ -9,8 +9,9 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或 - [x] 原15页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。 - [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。 -- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;已完成 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测。 -- [x] 本轮发布目标为 `2.0.1`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 +- [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。 +- [x] 本轮发布目标为 `2.0.2`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 +- [x] 2.0.2 提供九个功能页的账号分类日志面板,保留总日志与调试入口;页面和分类对应关系见 [产品说明](PRODUCT.md#202-分类日志),验证范围见 [发布说明](../analysis/RELEASE_2_0_2.md#验证)。 ## Windows 本地运行 @@ -40,6 +41,16 @@ py -3 -m venv .venv-web 服务重启会保留配置与加密会话;未启用自动重登录时,需要手动恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。 +### 分类日志(2.0.2) + +登录、每日事务、牧场、自动孵蛋、自动主线、自动赠礼、自动委托、自动探险和自动扫荡均提供当前账号的分类日志面板,底部总日志与调试入口继续保留。同一账号使用单一共享日志拉取,不为每个功能页另开轮询;浏览器共享缓存最多保留 1200 条,各日志面板最多显示最近 600 条。这些是浏览器缓存与显示上限,不改变普通日志的服务端持久保存范围。 + +面板支持文字搜索和级别筛选,可独立隐藏、清空显示或下载日志;下载遵循当前账号、本页清空范围及筛选条件。清空一个面板不清空总日志或其他面板,也不删除服务端历史记录。阅读历史时可暂停跟随;向上滚动会暂停自动跟随,点击“跟随最新”可回到底部。底部总日志保留独立的清空、下载与跟随控制。 + +分类随普通日志记录持久保存。孵蛋/牧场整理策略中的自动喂养、出售、收取及其暂停记录归入自动孵蛋(`hatching`);手动牧场操作和自动潜能突破归入牧场(`ranch`)。动作来源上下文优先于通用文字前缀,因此源自孵蛋策略的“暂停喂养”仍属于孵蛋日志。 + +没有分类字段的旧记录,仅在各片段均有明确前缀且一致指向同一类别时保守推断归属;不拆分旧记录,也不根据偶然出现的功能词猜测。混合类别、未知前缀及无法识别的分类保留为常规(`general`)记录,可在总日志和登录面板查看;登录面板同时包含登录与常规日志。 + ### 掉线后自动重新登录 在“登录”页开启“掉线后自动重新登录”,设置等待时长,默认 **30 分钟**,修改后自动保存。该开关默认关闭,各账号独立配置。使用前请在游戏登录时勾选“记住账号和密码”,并成功进入目标区服;密码仍由服务端加密保存。 @@ -79,16 +90,22 @@ sh start-web.sh --no-browser ## Docker 与在线更新 -完整步骤及一次性私有更新器初始化见 [Linux Docker 部署与受控在线更新](../deploy/web/README.md)。镜像使用 UID/GID 10001,持久化 `/data`,内置 `/api/health` healthcheck,正常退出宽限 120 秒,不挂载 Docker socket。 +完整步骤、已有部署更新与首次私有更新器初始化见 [Linux Docker 部署与受控在线更新](../deploy/web/README.md)。镜像使用 UID/GID 10001,持久化 `/data`,内置 `/api/health` healthcheck,正常退出宽限 120 秒,不挂载 Docker socket。 -已在 Ubuntu 24.04、Docker 29.8、Compose 5.5、Python 3.12 环境完成镜像构建和部署烟测:UID 10001 数据目录权限为 0700、密钥为 0600,应用根文件系统只读;健康检查及 FRP 转发返回 HTTP 200,Edge 管理登录后可访问 15 个功能页且无 JavaScript 错误,更新定时器已启用并成功完成首次 GitHub 检查。此部署烟测记录对应独立管理登录页调整前的版本;调整后的本地验证见下文,重新部署验收待完成,真实游戏 API 尚未验收。 +历史部署烟测(独立管理登录页调整前):曾在 Ubuntu 24.04、Docker 29.8、Compose 5.5、Python 3.12 环境完成镜像构建和部署烟测,UID 10001 数据目录权限为 0700、密钥为 0600,应用根文件系统只读;健康检查及转发返回 HTTP 200,Edge 管理登录后可访问 15 个功能页且无 JavaScript 错误,更新定时器已启用并成功完成首次 GitHub 检查。当时后续登录页调整仅记录了本地验证,重新部署与真实游戏 API 验收尚未完成;此历史状态及烟测结果均不作为 2.0.2 的验收结论。 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** 的在线更新由用户手动触发,使用稳定 Release、对应正式镜像,以及完成私有仓库认证、心跳有效的宿主机更新器。首次配置和操作步骤见[部署说明](../deploy/web/README.md),安装结果以宿主机健康检查为准。 +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.2**,无需重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 ## 离线验证 +### 2.0.2 发布验证 + +后端独立回归 **309 项:306 通过、3 项因 Windows 权限或符号链接限制跳过,0 失败、0 错误**;完整浏览器回归 **52 项全部通过,0 跳过、0 失败**,包含 9 项分类日志测试及相关 6 项回归方法,不另行累加。源码哈希一致性检查及差异检查通过;2.0.2 独立宿主机更新器仅依赖 Python 标准库,版本、dry-run、校验和及发布版本门禁校验通过。完整范围见 [发布说明](../analysis/RELEASE_2_0_2.md#验证)。 + +### 历史验证记录(不计入 2.0.2) + 2.0.1 发布回归:后端及更新器 **297 项中 294 通过、3 项因 Windows 权限或软链接限制跳过**,浏览器 **43 项全部通过**。更新器专项命令增加 `ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package`;Linux 镜像工作流也执行这两项模块,验证独立包、私有认证与容器健康。 自动重登录功能回归:后端及登录链路 **267 项中 266 通过、1 项因 Windows 符号链接权限跳过**,浏览器 **39 项全部通过**;另以禁止外部网络的合成账号完成 24 项独立审核。后端命令增加 `ranch_web.tests.test_auto_relogin ranch_assistant.tests.test_debug`,浏览器命令增加 `ranch_web.tests.browser.test_auto_relogin_browser.AutoReloginBrowserTests ranch_web.tests.browser.test_auto_relogin_browser.AutoReloginSchemaTests`。 diff --git a/ranch_web/__init__.py b/ranch_web/__init__.py index 3c3090c..a48ffb8 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.1" +__version__ = "2.0.2" GAME_VERSION = "1.9.68" __all__ = ["__version__", "GAME_VERSION"] diff --git a/ranch_web/activity.py b/ranch_web/activity.py index f95b67c..ca20879 100644 --- a/ranch_web/activity.py +++ b/ranch_web/activity.py @@ -26,6 +26,8 @@ from pathlib import Path import tempfile import threading +from .log_categories import legacy_category, normalize_category + MAX_ENTRIES = 2000 MAX_MESSAGE_CHARS = 2048 @@ -92,7 +94,7 @@ class ActivityLog: return [dict(entry) for entry, _ in self._entries] def append(self, entry, *, after_sequence=0): - """Append caller-sanitized fields and return {time,message,debug,level,id,seq}. + """Append sanitized fields; return {time,message,category,debug,level,id,seq}. No seq is returned until its high-water mark is durable. If writing fails the event is not published and the in-memory cursor is unchanged. @@ -126,9 +128,9 @@ class ActivityLog: self._sequence = next_sequence return dict(clean) - def log(self, message, *, debug=False): + def log(self, message, *, debug=False, category="general"): """Convenience helper for an already safe_text-sanitized message; int id.""" - return self.append({"message": message, "debug": debug})["id"] + return self.append({"message": message, "debug": debug, "category": category})["id"] @staticmethod def _clean(entry): @@ -146,7 +148,8 @@ class ActivityLog: stamp = datetime.now(timezone.utc).isoformat(timespec="milliseconds") message = entry["message"][:MAX_MESSAGE_CHARS].replace("\r", " ").replace("\n", " ") message = message.encode("utf-8", errors="replace").decode("utf-8") - return {"time": stamp, "message": message, "debug": debug, "level": level} + category = normalize_category(entry["category"]) if "category" in entry else legacy_category(message) + return {"time": stamp, "message": message, "category": category, "debug": debug, "level": level} def _load(self): if self._loaded: diff --git a/ranch_web/log_categories.py b/ranch_web/log_categories.py new file mode 100644 index 0000000..8930da2 --- /dev/null +++ b/ranch_web/log_categories.py @@ -0,0 +1,131 @@ +"""Conservative page attribution for account activity; no engine dependencies.""" +from __future__ import annotations + +import re + + +CATEGORIES = frozenset("general login hatching mainline gifts commissions exploration maps ranch daily".split()) +MAX_ROUTING_CHARS = 16000 +_SEPARATOR = re.compile(r"[;\r\n]+") +_OPERATIONS = { + **dict.fromkeys(("login", "enter_server", "restore_session", "logout", "forget_login", "auto_relogin", "heartbeat"), "login"), + "hatch": "hatching", "growth_sync": "hatching", "gift": "gifts", + "explore": "exploration", "breakthrough": "ranch", + "claim_daily": "daily", "refresh_maps": "maps", "reset_map_pending": "maps", + "refresh_tasks": "mainline", + **dict.fromkeys(("lock", "unlock", "sell", "feed", "expand", "quote_expansion"), "ranch"), +} +_ENDPOINTS = { + "stackService/stackAddMonster": "hatching", "stackService/stackCheckProcess": "hatching", + "stackService/stackTransferMonster": "hatching", "gachaService/gachaGetEggs": "hatching", + "monsterService/monsterSendGift": "gifts", + "monsterService/monsterPotentialUpgrade": "ranch", "monsterService/monsterPotentialLevelUpgrade": "ranch", + "monsterService/monsterLock": "ranch", "monsterService/monsterSell": "ranch", + "monsterService/monsterIntensify": "ranch", "stackService/stackOpen": "ranch", + "roomService/roomCreateByMoney": "ranch", "roomService/roomCreateByKe": "ranch", + "exploreService/start": "exploration", "exploreService/finish": "exploration", + "heartBeatService/keepAlive": "login", "userServerService/loginUser": "login", + "userServerService/enterGame": "login", "dailyGiftService/dailyGiftSign": "daily", + "dailyGiftService/dailyLoopReward": "daily", "dailyCheckService/dailyCheck": "daily", + "vipService/getReward": "daily", "mailService/mailGetReward": "daily", + "taskService/taskLoopReceive": "commissions", "taskService/taskLoopFlush": "commissions", + "taskService/taskReceive": "mainline", "taskService/taskUpdate": "mainline", +} +_LOGIN_OPERATIONS = frozenset(("渠道账号验证", "获取官方区服", "进入选中区服", "进入参数检查", "保存会话")) +_PREFIXES = { + "general": ("状态已刷新", "状态已读取", "已同步等级 / 体力", "已刷新本地资料 / 预览", "策略暂不可用"), + "login": ("游戏连接", "游戏会话", "游戏网络", "会话心跳", "自动重登", "登录未完成", "服务已启动或重启"), + "maps": ("探索奖励事件已结算", "扫荡", "普通挑战", "已刷新关卡", "已解除旧版对已结算奖励事件的误阻塞"), + "exploration": ("探险", "领取探险队"), + "commissions": ("自动委托", "委托", "刷新跨日委托", "接取城市委托", "接取委托", "领取委托奖励", "推进委托"), + "mainline": ("自动主线", "主线", "支线", "任务规划", "已刷新任务与战斗记录", "领取任务奖励", "任务推进"), + "gifts": ("自动赠礼", "赠礼"), + "ranch": ("突破", "自动突破", "补潜能", "未选择自动突破目标", "喂养", "暂停喂养", "已锁定", "已解锁"), + "daily": ("领取每日签到礼包", "领取七日签到", "领取累计签到", "领取VIP", "领取邮件"), + "hatching": ("装填", "孵化", "等待孵化 / 成长", "已自动同步孵化 / 成长状态", "已请求孵化 / 成长结算", + "成长状态等待服务器确认", "资质未同步", "暂不派遣、喂养或收取", "牧场策略未启用", "请到“背包魔物蛋”", + "有空坑", "可孵蛋库存", "所选市场", "购蛋暂停", "十连等待", "抽蛋完成", "收取", "批量收取", "派遣"), +} +_CONTINUATIONS = ("后台每2分钟", "仍有 ", "每轮仅操作一次", "不消耗tp经验", "自动执行已暂停", "未重复提交") +_REWARD = re.compile(r"^(?:金币|经验|体力|氪金|好感|奖励)\s*[::+]?\s*\d|^[^;\r\n]{1,100}[×x]\s*\d+$") + + +def normalize_category(category): + return category if isinstance(category, str) and category in CATEGORIES else "general" + + +def operation_category(operation, payload=None): + if operation == "refresh": + # These refresh actions call dedicated engine methods. Other pages poll + # several features and must not impose the requesting page on results. + return {"maps": "maps", "mainline": "mainline", "battles": "mainline", "commissions": "commissions"}.get( + (payload or {}).get("page"), "general") + return _OPERATIONS.get(operation, "general") + + +def endpoint_category(operation, *, active="general"): + """Only known endpoints; shared task/battle endpoints need task context.""" + if operation in _LOGIN_OPERATIONS: + return "login" + path = str(operation).split("?", 1)[0].rstrip("/") + path = "/".join(path.split("/")[-2:]) + if path.startswith(("taskService/", "battleService/", "stageService/")) and active in {"mainline", "commissions", "maps"}: + return active + if path in _ENDPOINTS: + return _ENDPOINTS[path] + if path == "stageService/stageStart": + return "maps" + return "general" + + +def message_category(message): + text = message.strip().removeprefix("[演示] ") + for category, prefixes in _PREFIXES.items(): + if text.startswith(prefixes): + return category + return None + + +def legacy_category(message): + """Never rewrite/split old records or guess from incidental feature words.""" + categories = {message_category(part) for part in _SEPARATOR.split(message[:MAX_ROUTING_CHARS]) if part.strip()} + return categories.pop() if len(categories) == 1 and None not in categories else "general" + + +def route_message(message, *, context="general", hints=None): + """At most one capped entry per category, in order of first appearance. + + Input and output work are bounded. Persistence retains its existing 2048 + character cap per entry; hundreds of monster notes never mean hundreds of + snapshot writes. Unknown fragments require explicit execution context. + """ + groups = {} + previous = normalize_category(context) + for part in _SEPARATOR.split(message[:MAX_ROUTING_CHARS]): + part = part.strip() + if not part: + continue + category = (hints or {}).get(part) or message_category(part) + if context in {"hatching", "ranch"} and part.removeprefix("[演示] ").startswith(("派遣", "收取", "批量收取", "喂养", "暂停喂养")): + category = context + if category is None: + continuation = (part.startswith(_CONTINUATIONS) + or previous == "maps" and bool(_REWARD.match(part)) + or previous == "gifts" and part.startswith(("冷却", "好感上限", "已达好感上限", "还需等待", "上限")) + or previous == "hatching" and part.startswith(("今日额度", "十连需", "补货目标", "保留 "))) + category = previous if continuation else context + category = normalize_category(category) + groups.setdefault(category, []).append(part) + previous = category + return [(category, ";".join(parts)) for category, parts in groups.items()] + + +def note_hints(sources): + """Exact planner-owned text provides attribution even without feature names.""" + hints = {} + for category, notes in sources: + for note in notes[:512]: + for part in _SEPARATOR.split(str(note)[:MAX_ROUTING_CHARS]): + if part.strip(): + hints[part.strip()] = category + return hints diff --git a/ranch_web/service.py b/ranch_web/service.py index e5682e6..26c47cc 100644 --- a/ranch_web/service.py +++ b/ranch_web/service.py @@ -36,6 +36,7 @@ from collections import OrderedDict, deque from copy import copy, deepcopy from dataclasses import asdict, dataclass from datetime import datetime, timedelta, timezone +from functools import wraps import json import math import re @@ -52,6 +53,7 @@ from ranch_assistant.login import PasswordLogin from ranch_assistant.model import Catalog 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 @@ -97,6 +99,8 @@ class _Job: error: str = "" internal: bool = False workspace: str = "" + category: str = "general" + due_kind: str | None = None def public(self): operation = {"__config": "set_config", "__view": "view"}.get(self.operation, self.operation) @@ -158,7 +162,7 @@ class AccountWorker: except ActivityLogError: self._activity_warning = True self._log_sequence = 1 - self._logs = deque([{"id": 1, "seq": 1, "debug": False, "level": "warning", + self._logs = deque([{"id": 1, "seq": 1, "debug": False, "level": "warning", "category": "general", "time": datetime.now(timezone.utc).isoformat(timespec="milliseconds"), "message": "首次读取运行日志失败,当前日志暂存内存;后续日志将重试保存"}], maxlen=2000) self._debug_entries = OrderedDict() @@ -227,8 +231,66 @@ class AccountWorker: apply_config(engine, config) engine.auto = False engine.heartbeat_enabled = bool(client) + self._route_engine_tasks(engine) return engine + def _attribute_task(self, category): + # Only the serial account thread owns execution context. HTTP readers, + # stop requests and other accounts cannot inherit an in-flight task. + job = self._execution + if job is not None and threading.current_thread() is getattr(self, "thread", None): + job.category = normalize_category(category) + + def _task_category(self): + if self._execution is not None and threading.current_thread() is getattr(self, "thread", None): + return self._execution.category + return "general" + + def _dispatch_category(self, operation): + active = self._task_category() + category = endpoint_category(operation, active=active) + path = "/".join(str(operation).split("?", 1)[0].split("/")[-2:]) + job = self._execution + if (job is not None and threading.current_thread() is getattr(self, "thread", None) + and job.operation == "__tick" and job.due_kind == "poll" + and active in {"general", "hatching"} + and path in {"monsterService/monsterSell", "monsterService/monsterIntensify", "stackService/stackTransferMonster"}): + return "hatching" + return category + + def _route_engine_tasks(self, engine): + # Observe existing action boundaries on this worker's engine instance. + # Retain context through return/exception until _run publishes the job; + # generic local story results and pre-dispatch errors have no endpoint. + sources = {"_run_progression_intent": "mainline", "_execute_legacy_task": "commissions", + "_run_map_challenge": "maps", "_execute_explore": "exploration", + "_execute_breakthrough": "ranch", "claim_daily_entry": "daily"} + for name, category in sources.items(): + method = getattr(engine, name, None) + if not callable(method): + continue + + @wraps(method) + def routed(*args, _method=method, _name=name, _category=category, **kwargs): + category = _category + if _name == "_run_progression_intent": + try: + intent = args[0] if args else kwargs.get("intent") + if intent is None: + intent = next((item for item in engine._progression_intents + if not (item.get("block_reason") if isinstance(item, dict) else getattr(item, "block_reason", ""))), None) + if engine._is_commission(intent): + category = "commissions" + except CancelledBeforeDispatch: + raise + except Exception: + # Attribution must not prevent an otherwise valid action. + category = "general" + self._attribute_task(category) + return _method(*args, **kwargs) + + setattr(engine, name, routed) + def remember(self, value): with self._secret_lock: if isinstance(value, dict): @@ -276,15 +338,23 @@ class AccountWorker: return result raise ValueError("操作返回了不支持的公开数据类型") - def log(self, message, *, debug=False): + def log(self, message, *, debug=False, category=None, level="info"): + message = self.safe_text(message) + level = level if isinstance(level, str) and level in {"info", "warning", "error", "critical", "debug"} else "info" + debug = bool(debug or level == "debug") + if category is None: + category = self._task_category() + if category == "general": + category = legacy_category(message) entry = {"time": datetime.now(timezone.utc).isoformat(timespec="milliseconds"), - "message": self.safe_text(message), "debug": bool(debug), "level": "debug" if debug else "info"} + "message": message, "category": normalize_category(category), + "debug": debug, "level": "debug" if debug else level} with self.lock: try: if self._activity_warning: # Confirm an actual durable write before declaring recovery; # debug appends within a reserved block alone need no IO. - recovered = self._activity.append({"time": entry["time"], "debug": False, "level": "info", + recovered = self._activity.append({"time": entry["time"], "debug": False, "level": "info", "category": "general", "message": "运行日志持久化已恢复;降级期间的日志仅保留在内存"}, after_sequence=self._log_sequence) self._logs.append(recovered) self._log_sequence = recovered["seq"] @@ -297,13 +367,22 @@ class AccountWorker: self._activity_warning = True self._log_sequence += 1 self._logs.append({"id": self._log_sequence, "seq": self._log_sequence, - "time": entry["time"], "debug": False, "level": "warning", + "time": entry["time"], "debug": False, "level": "warning", "category": "general", "message": "运行日志无法持久保存,当前日志仅保留在内存;请检查 Web 数据目录"}) entry["id"] = entry["seq"] = self._log_sequence + 1 self._log_sequence = entry["seq"] self._logs.append(entry) return entry["id"] + def _log_message(self, message): + sources = [] + for name, category in (("planner", "hatching"), ("hatch_planner", "hatching"), + ("gift_planner", "gifts"), ("breakthrough_planner", "ranch")): + 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) + def _trace_event(self, event): fields = [event.get("operation", "网络"), event.get("kind", "")] if "http_status" in event: @@ -312,7 +391,15 @@ class AccountWorker: fields.append(str(event["elapsed_ms"]) + "ms") if event.get("message"): fields.append(str(event["message"])) - identifier = self.log(";".join(fields), debug=True) + source = self._dispatch_category(event.get("operation", "")) + if source == "general": + source = self._dispatch_category(event.get("url", "")) + if event.get("kind") == "request" and source != "general": + self._attribute_task(source) + category = self._task_category() + if category == "general": + category = source + identifier = self.log(";".join(fields), debug=True, category=category) serialized = json.dumps(event, ensure_ascii=False, allow_nan=False).encode("utf-8") if len(serialized) > 1024 * 1024: event = {"kind": event.get("kind"), "operation": event.get("operation"), @@ -417,7 +504,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.log(self.error) + self.log(self.error, level="error") return self.engine.heartbeat_enabled = False if client is not None: @@ -441,7 +528,7 @@ class AccountWorker: message = "游戏请求失败,已停止策略和游戏请求,请手动恢复会话:" + str(error) self.error = self.connection_message = self.safe_text(message) self._last_game_error_message = self.error - self.log(self.connection_message) + self.log(self.connection_message, category="login", level="error") def _game_succeeded(self, *, activated=False): previous = self.connection_state @@ -460,7 +547,7 @@ class AccountWorker: self.schedule.game_resumed() self.engine.heartbeat_enabled = True if previous != "online" and not activated: - self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止")) + self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"), category="login") def status(self): with self.lock: @@ -568,6 +655,7 @@ class AccountWorker: job.status, job.error, job.payload = "cancelled", "操作尚未开始,已取消", {} continue self._active = self._execution = job + job.category = operation_category(job.operation, job.payload) job.status = "running" final_status, final_error, public_result = "succeeded", "", None failure_sequence = self._game_failure_sequence @@ -589,7 +677,7 @@ class AccountWorker: self.error = message if job.consuming: self.stop() - self.log(message) + self.log(message, category=job.category, level="error") finally: job.payload = {} try: @@ -601,7 +689,7 @@ class AccountWorker: summary = dict(self._summary, error=self.error, running=False) if final_status == "succeeded": final_status, final_error = "failed", self.error - self.log(self.error) + self.log(self.error, category=job.category, level="error") with self.condition: if self._auto_relogin_pending_config and self._auto_relogin_pending_config[0] == job.id: self._auto_relogin_pending_config = None @@ -640,7 +728,7 @@ class AccountWorker: self._mark_disconnected(session, saved) if self.config["auto_relogin"]["enabled"]: self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色,策略保持停止" - self.log(self.connection_message) + self.log(self.connection_message, category="login") if self.demo: self.result(*self.engine.poll()) self.schedule.monitor(True) @@ -687,7 +775,7 @@ class AccountWorker: """Actions may consume an Engine triple without exposing its internals.""" self.engine.snapshot = snapshot if message: - self.log(message) + self._log_message(message) self._invalidate_views() self.schedule.arm(self.engine, self.config, self._running, plans) return {"message": self.safe_text(message)} @@ -776,6 +864,7 @@ class AccountWorker: def _tick(self, job): kind = self.schedule.due(self.engine, self.config, self._running) + job.due_kind, job.category = kind, operation_category(kind) if kind is None: return None if kind == "auto_relogin": @@ -795,6 +884,7 @@ class AccountWorker: return self._auto_relogin() if kind is None: return None + job.due_kind, job.category = kind, operation_category(kind) if not self.demo and self.engine.client is None: return None auto = False @@ -841,7 +931,7 @@ class AccountWorker: self.stop() self.schedule.arm(self.engine, self.config, self._running, value[1], completed=kind) elif isinstance(value, str): - self.log(value) + self._log_message(value) return {"kind": kind} except Exception: self.schedule.maintenance_failed(kind) @@ -935,7 +1025,7 @@ class AccountWorker: self.schedule.auto_relogin_failed() self._auto_relogin_blocked = isinstance(error, AutoReloginBlocked) self._auto_relogin_error = "自动重登未完成:" + self.safe_text(str(error)) - self.log(self._auto_relogin_error) + self.log(self._auto_relogin_error, category="login", level="error") return {"connected": False, "running": False, "message": self._auto_relogin_error} finally: self._auto_relogin_inflight = False @@ -966,6 +1056,10 @@ class AccountWorker: def guarded_call(*args, **kwargs): self.check_intent() + path = args[0] if args else kwargs.get("path", "") + category = self._dispatch_category(path) + if category != "general": + self._attribute_task(category) # This precedes Client.call's wire payload construction. A # saved candidate can lag the still-online client's counters. self._share_session_counters(client.session) @@ -1095,7 +1189,7 @@ class AccountWorker: message = login_message + ";策略已自动开启,仅执行已勾选的规则" result = {"connected": True, "running": self._running, "has_saved_password": self._has_saved_password, "message": message} - self.log(message) + self.log(message, category="login") except Exception: with self.lock: self.engine, self.active_identity, self.demo = old_engine, previous_identity, old_demo @@ -1107,7 +1201,7 @@ class AccountWorker: if mode_saved: self.manager._set_demo(self, old_demo) except (OSError, ValueError): - self.log("登录未完成,原连接保留;保存的会话仍可手动恢复") + self.log("登录未完成,原连接保留;保存的会话仍可手动恢复", category="login") if identity != previous_identity: self.manager._release_identity(self, identity) raise diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index b23728c..7ba2d26 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -3,6 +3,7 @@ import {apiPath, webPath} from './paths.js'; import {el, $, $$, clone, getPath, setPath, pathKey, textValue, number, chinaTime, download, csvBlob, optionsList, detailsList, tabKeys} from './dom.js'; import {PageView, PAGES} from './pages.js'; import {notice, dialog, confirm, filePicker, fileBase64} from './ui.js'; +import {createLogState, mergeLogs, visibleLogs, syncLogLines, logText, attachTaskLog} from './task-logs.js'; const state = {accounts:new Map(),active:null,schema:null,meta:null,ready:false,polling:false,seq:0,redirecting:false,webStatusError:null,statusMessage:'连接中'}; const current = () => state.accounts.get(state.active); @@ -72,7 +73,7 @@ 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:{entries:[],next:0,debug:false,loading:false},loadingConfig:false,transportErrors:new Map()}; + logs:createLogState(),loadingConfig:false,transportErrors:new Map()}; } function setStatus(message) { state.statusMessage=message;renderStatus(); } @@ -270,6 +271,7 @@ function getPage(account,key) { const page=new PageView(account,key,{edit:editConfig,perform,load:loadPage,action:pageAction,command, schema:pageKey=>state.schema?.pages?.find(page=>page.key===pageKey)?.form || []}); account.pages.set(key,page);$('#page-host').append(page.root); + attachTaskLog(page); } return account.pages.get(key); } @@ -294,12 +296,14 @@ function selectPage(key) { account.page=key; state.accounts.forEach(other=>other.pages.forEach(page=>{page.root.hidden=other.id!==account.id||page.key!==key;})); const page=getPage(account,key);page.root.hidden=false; + page.taskLog?.render(); $$('.page-tab').forEach(tab=>{const selected=tab.dataset.page===key;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;}); loadPage(page,true); } async function selectAccount(id) { const previous=current();previous?.pages.get('login')?.login?.clearPassword(); + if(previous && !$('#log-panel').hidden && $('#log-lines').dataset.account===previous.id)previous.logs.total.scrollTop=$('#log-lines').scrollTop; if(previous?.edits.size)flushConfig(previous).catch(error); state.active=id;const account=current();if(!account)return; $('#page-host').querySelector('.initial-state')?.remove(); @@ -374,11 +378,11 @@ 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.1'}`}),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.2'}`}),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('请先新增或选择账号。'); - if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.entries=[];account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);await fetchLogs(account);return;} + if(name==='debug'){account.logs.debug=!account.logs.debug;account.logs.next=0;account.logs.generation=(account.logs.generation || 0)+1;$('#debug-log').checked=account.logs.debug;setLogVisible(true);renderLogs(true);currentPage()?.taskLog?.render();await fetchLogs(account);return;} if(name==='save'){await flushConfig(account);notice('策略已保存。');return;} if(name==='stop'||name==='start')return await perform(account,name); if(name==='start-all'||name==='stop-all'){ @@ -478,8 +482,10 @@ function setLogVisible(visible) { function applyLogLayout(account=current(),visibleOverride) { if(account&&account.id!==state.active)return; const visible=visibleOverride ?? account?.config?.log_visible ?? true; - $('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏日志':'显示日志';$('#log-toggle').setAttribute('aria-expanded',String(visible)); + if(!visible && account && !$('#log-panel').hidden && $('#log-lines').dataset.account===account.id)account.logs.total.scrollTop=$('#log-lines').scrollTop; + $('#log-panel').hidden=!visible;$('#log-resizer').hidden=!visible;$('#log-toggle').textContent=visible?'隐藏总日志':'显示总日志';$('#log-toggle').setAttribute('aria-expanded',String(visible)); const size=account?.config?.log_sizes?.[1];if(size)setLogHeight(size); + if(visible)renderLogs(); } function setLogHeight(height) { @@ -489,29 +495,27 @@ function setLogHeight(height) { function renderLogs(reset=false) { const account=current(),root=$('#log-lines');if(!account){root.replaceChildren();return;} - const log=account.logs; - if(reset){root.replaceChildren();log.rendered=0;} - const follow=$('#log-follow').checked&& (reset || root.scrollHeight-root.scrollTop-root.clientHeight<45); - for(const entry of log.entries.slice(log.rendered || 0)){ - const line=el('div',{class:`log-entry ${entry.level || entry.kind || ''}`,'data-entry-id':entry.id}); - const stamp=entry.time || entry.timestamp || entry.at || ''; - line.append(el('span',{class:'log-time',text:chinaTime(stamp),title:String(stamp)}),document.createTextNode(entry.message || entry.operation || textValue(entry))); - if(entry.details_available || entry.detail_url || entry.debug_url){line.classList.add('inspectable');line.tabIndex=0;line.setAttribute('role','button');line.title='查看脱敏请求 / 响应 JSON';line.addEventListener('click',()=>showDebugEntry(account,entry));line.addEventListener('keydown',event=>{if(event.key==='Enter'||event.key===' '){event.preventDefault();showDebugEntry(account,entry);}});} - root.append(line); - } - log.rendered=log.entries.length; - while(root.childElementCount>600)root.firstElementChild.remove(); - $('#log-count').textContent=`${Math.min(600,log.entries.length)} 条`;$('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'调试日志(已脱敏)':'运行日志'; - if(follow)root.scrollTop=root.scrollHeight; + if($('#log-panel').hidden)return; + const log=account.logs,view=log.total; + const switching=root.dataset.account!==account.id; + const scrollTop=switching?view.scrollTop:root.scrollTop; + reset=reset || switching; + const token=JSON.stringify([log.revision,view.clearedThrough,log.debug]); + if(!reset && view.rendered===token)return; + const entries=visibleLogs(log,view); + syncLogLines(root,entries,{reset,follow:view.follow,scrollTop:reset?scrollTop:undefined,inspect:log.debug?entry=>showDebugEntry(account,entry):null}); + root.dataset.account=account.id;view.rendered=token; + $('#log-follow').checked=view.follow; + const count=`${Math.min(600,entries.length)} 条`; + if($('#log-count').textContent!==count)$('#log-count').textContent=count; + $('#debug-log').checked=log.debug;$('#log-heading').textContent=log.debug?'总日志(调试 / 已脱敏)':'总日志'; } async function fetchLogs(account) { if(account.logs.loading)return;account.logs.loading=true;const generation=account.logs.generation || 0; try{const response=await api.logs(account.id,account.logs.next,account.logs.debug);if(generation!==(account.logs.generation || 0))return; - const seen=new Set(account.logs.entries.map(entry=>entry.id)); - account.logs.entries.push(...(response.entries || []).filter(entry=>entry.id==null||!seen.has(entry.id)));account.logs.next=response.next; - if(account.id===state.active)renderLogs(); - if(account.logs.entries.length>1200){account.logs.entries=account.logs.entries.slice(-600);if(account.id===state.active)renderLogs(true);} + mergeLogs(account.logs,response.entries || [],response.next); + if(account.id===state.active){renderLogs();currentPage()?.taskLog?.render();} transportError(account,'logs','日志',null); }catch(failure){if(generation===(account.logs.generation || 0))transportError(account,'logs','日志',failure);}finally{account.logs.loading=false;} } @@ -577,7 +581,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.1';$('#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.2';$('#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})));} } @@ -595,10 +599,10 @@ $('#refresh-interval').addEventListener('change',event=>{if(current())editConfig $('#save-status').tabIndex=0;$('#save-status').addEventListener('click',()=>command('save'));$('#save-status').addEventListener('keydown',event=>{if(event.key==='Enter')command('save');}); $('#debug-toggle').addEventListener('click',()=>command('debug'));$('#debug-log').addEventListener('change',()=>command('debug')); $('#log-toggle').addEventListener('click',()=>setLogVisible($('#log-panel').hidden)); -$('#clear-log').addEventListener('click',()=>{if(current()){current().logs.entries=[];current().logs.rendered=0;renderLogs(true);}}); -$('#download-log').addEventListener('click',()=>{const account=current();if(account)download(new Blob([account.logs.entries.map(entry=>[entry.time || entry.timestamp || '',entry.message || entry.operation || ''].join(' ')).join('\n')],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');}); -$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines');if(node.scrollHeight-node.scrollTop-node.clientHeight>55)$('#log-follow').checked=false;}); -$('#log-follow').addEventListener('change',()=>{if($('#log-follow').checked)$('#log-lines').scrollTop=$('#log-lines').scrollHeight;}); +$('#clear-log').addEventListener('click',()=>{const log=current()?.logs;if(log){log.total.clearedThrough=log.highWater;renderLogs();}}); +$('#download-log').addEventListener('click',()=>{const log=current()?.logs;if(log)download(new Blob([logText(visibleLogs(log,log.total))],{type:'text/plain;charset=utf-8'}),'牧场日志.txt');}); +$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines'),account=current();if(!account || $('#log-panel').hidden || node.dataset.account!==account.id)return;account.logs.total.scrollTop=node.scrollTop;if(node.scrollHeight-node.scrollTop-node.clientHeight>55){$('#log-follow').checked=false;account.logs.total.follow=false;}}); +$('#log-follow').addEventListener('change',()=>{const account=current(),node=$('#log-lines');if(!account || $('#log-panel').hidden || node.dataset.account!==account.id)return;account.logs.total.follow=$('#log-follow').checked;if($('#log-follow').checked)node.scrollTop=node.scrollHeight;}); let resize; $('#log-resizer').addEventListener('pointerdown',event=>{resize={y:event.clientY,height:$('#log-panel').getBoundingClientRect().height};event.currentTarget.setPointerCapture(event.pointerId);event.preventDefault();}); $('#log-resizer').addEventListener('pointermove',event=>{if(resize)setLogHeight(resize.height+resize.y-event.clientY);}); diff --git a/ranch_web/static/index.html b/ranch_web/static/index.html index 4345683..13465a2 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -26,13 +26,13 @@ - 牧羊人之心牧场助手 2.0.1 + 牧羊人之心牧场助手 2.0.2 正在连接本地服务
未登录—等级 —经验 —金币 —氪金 —体力 —
-
+
等待连接服务配置未载入
@@ -40,7 +40,7 @@
正在载入工作台…
-
运行日志
+
总日志
diff --git a/ranch_web/static/styles.css b/ranch_web/static/styles.css index bd2316e..10fb314 100644 --- a/ranch_web/static/styles.css +++ b/ranch_web/static/styles.css @@ -12,3 +12,19 @@ @media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important}} .page-content{display:flex;flex-direction:column;gap:7px;flex:1;min-height:0}.statistics-table-host{display:flex;flex-direction:column;flex:1;min-height:100px}.count-id{width:100px}.statistics-city>summary,.statistics-stage>summary{cursor:pointer;font-size:12px;padding:6px 7px;line-height:1.5;overflow-wrap:anywhere}.statistics-city>summary{background:#eef1f5;border-bottom:1px solid #d8dee6;font-weight:600}.statistics-stage{margin-left:10px}.statistics-stage>summary:hover{background:#edf3fa}.statistics-levels{padding-left:12px}.statistics-levels button{padding:5px 8px}.debug-json{margin:0;font:12px/1.6 Consolas,monospace;white-space:pre-wrap;overflow-wrap:anywhere}.log-entry.inspectable{cursor:pointer}.log-entry.inspectable:hover{background:#e8f0f9}.member-draft-note{font-size:11px;color:#805300}.counts-lines{display:flex;flex-direction:column;gap:3px;margin-bottom:4px} .chart-axis{font-size:11px;fill:#55616e;font-variant-numeric:tabular-nums} +.task-log-panel{flex:0 0 auto;min-width:0;border:1px solid var(--border);background:#fff;overflow-anchor:none} +.has-task-log>.page-content{flex:1 0 160px;min-height:160px;overflow:auto} +.has-task-log[data-page=login]>.page-content{flex:0 0 auto;overflow:visible} +.task-log-heading{flex-wrap:wrap;gap:6px 12px} +.task-log-heading h3{margin:0;font-size:13px;font-weight:600} +.task-log-status{font-size:12px;overflow-wrap:anywhere} +.task-log-body{position:relative;min-width:0} +.task-log-controls{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;padding:6px 8px;border-bottom:1px solid var(--border);font-size:12px} +.task-log-controls label{display:flex;align-items:center;gap:5px;min-width:0} +.task-log-controls input[type=search]{width:185px;min-width:100px;max-width:100%} +.task-log-lines{height:190px;min-height:120px;max-height:35vh;overflow-anchor:none;overscroll-behavior:contain} +.task-log-viewport{position:relative} +.task-log-empty{position:absolute;top:6px;left:10px;right:10px;margin:0;pointer-events:none;font-size:12px} +.task-log-help{margin:0;padding:4px 8px;border-top:1px solid var(--border);font-size:12px;line-height:1.5} +#log-lines{overflow-anchor:none;overscroll-behavior:contain} +@media(max-width:700px){.task-log-controls button,.task-log-heading button{min-height:32px}.task-log-lines{height:165px}.task-log-status{flex:1 1 180px}} diff --git a/ranch_web/static/task-logs.js b/ranch_web/static/task-logs.js new file mode 100644 index 0000000..d200861 --- /dev/null +++ b/ranch_web/static/task-logs.js @@ -0,0 +1,191 @@ +import {el, chinaTime, textValue, download} from './dom.js'; + +const BUFFER_LIMIT = 1200; +const RENDER_LIMIT = 600; +const categories = new Set(['general', 'login', 'hatching', 'mainline', 'gifts', 'commissions', 'exploration', 'maps', 'ranch', 'daily']); +const titles = {login:'登录日志', daily:'每日事务日志', ranch:'牧场日志', hatching:'孵蛋日志', mainline:'主线日志', gifts:'赠礼日志', commissions:'委托日志', exploration:'探险日志', maps:'扫荡日志'}; +let panelId = 0; + +export function createLogState() { + return {entries:[], next:0, highWater:0, retainedAfter:0, revision:0, debug:false, loading:false, + total:{clearedThrough:0, follow:true, scrollTop:0}}; +} + +const levelOf = entry => String(entry.level || entry.kind || (entry.debug ? 'debug' : 'info')).toLowerCase(); +const messageOf = entry => String(entry.message || entry.operation || textValue(entry)); +const stampOf = entry => entry.time || entry.timestamp || entry.at || ''; +const debugEntry = entry => entry.debug || levelOf(entry) === 'debug'; +const lineSignature = (entry, inspect) => JSON.stringify([stampOf(entry), messageOf(entry), levelOf(entry), + Boolean(inspect && (entry.details_available || entry.detail_url || entry.debug_url))]); + +// All panels share this one bounded history. A cursor rewind for debug must not +// reintroduce evicted records or move any panel's local clear watermark. +export function mergeLogs(log, entries, next) { + const bySequence = new Map(log.entries.map(entry => [entry.seq, entry])); + let changed = false; + for (const source of entries) { + const numeric = Number(source.seq ?? source.id); + const seq = Number.isFinite(numeric) ? numeric : log.highWater + 1; + if (seq <= log.retainedAfter) continue; + const entry = {...source, seq, category:categories.has(source.category) ? source.category : 'general'}; + log.highWater = Math.max(log.highWater, seq); + if (JSON.stringify(bySequence.get(seq)) !== JSON.stringify(entry)) { + bySequence.set(seq, entry); + changed = true; + } + } + if (changed) { + log.entries = [...bySequence.values()].sort((a, b) => a.seq - b.seq); + if (log.entries.length > BUFFER_LIMIT) { + const removed = log.entries.splice(0, log.entries.length - BUFFER_LIMIT); + log.retainedAfter = Math.max(log.retainedAfter, removed.at(-1).seq); + } + log.revision++; + } + log.next = next ?? log.next; + log.highWater = Math.max(log.highWater, Number(log.next) || 0); +} + +export function visibleLogs(log, view, page) { + return log.entries.filter(entry => entry.seq > view.clearedThrough && (log.debug || !debugEntry(entry)) + && (!page || entry.category === page || page === 'login' && entry.category === 'general') + && (!view.level || levelOf(entry) === view.level) + && (!view.search || messageOf(entry).toLocaleLowerCase().includes(view.search.toLocaleLowerCase()))); +} + +export function logLine(entry, inspect) { + const level = levelOf(entry); + const line = el('div', {class:`log-entry ${['error','warning','debug'].includes(level) ? level : ''}`, + 'data-entry-id':entry.id, 'data-sequence':entry.seq}); + line.logSignature = lineSignature(entry, inspect); + const stamp = stampOf(entry); + line.append(el('span', {class:'log-time', text:chinaTime(stamp), title:String(stamp)}), document.createTextNode(messageOf(entry))); + if (inspect && (entry.details_available || entry.detail_url || entry.debug_url)) { + line.classList.add('inspectable'); + line.tabIndex = 0; + line.setAttribute('role', 'button'); + line.title = '查看脱敏请求 / 响应 JSON'; + line.addEventListener('click', () => inspect(entry)); + line.addEventListener('keydown', event => { + if (event.key === 'Enter' || event.key === ' ') {event.preventDefault();inspect(entry);} + }); + } + return line; +} + +// Append/remove keyed rows, retaining both row identity and the visible reading +// anchor. Only the log's own scroll position changes; ancestors are never scrolled. +export function syncLogLines(root, entries, {follow, reset=false, scrollTop, inspect} = {}) { + const previousTop = scrollTop ?? root.scrollTop; + const top = root.getBoundingClientRect().top; + const anchor = follow ? null : [...root.children].find(node => node.getBoundingClientRect().bottom > top); + const anchorTop = anchor?.getBoundingClientRect().top; + if (reset) root.replaceChildren(); + const shown = entries.slice(-RENDER_LIMIT); + const wanted = new Set(shown.map(entry => String(entry.seq))); + for (const node of [...root.children]) if (!wanted.has(node.dataset.sequence)) node.remove(); + const existing = new Map([...root.children].map(node => [node.dataset.sequence, node])); + let previous = null; + for (const entry of shown) { + let node = existing.get(String(entry.seq)); + if (node && node.logSignature !== lineSignature(entry, inspect)) { + const replacement = logLine(entry, inspect); + node.replaceWith(replacement); + node = replacement; + } + if (!node) node = logLine(entry, inspect); + const next = previous ? previous.nextElementSibling : root.firstElementChild; + if (next !== node) root.insertBefore(node, next); + previous = node; + } + if (follow) root.scrollTop = root.scrollHeight; + else if (!reset && anchor?.isConnected) root.scrollTop += anchor.getBoundingClientRect().top - anchorTop; + else root.scrollTop = previousTop; +} + +export function logText(entries) { + return entries.map(entry => [stampOf(entry), messageOf(entry)].join(' ')).join('\n'); +} + +export class TaskLogPanel { + constructor(page) { + this.page = page; + this.log = page.account.logs; + this.title = titles[page.key]; + this.view = {clearedThrough:0, follow:true, search:'', level:'', seenThrough:0}; + const id = `task-log-${++panelId}`; + this.heading = el('h3', {id:`${id}-heading`, text:this.title}); + this.status = el('span', {class:'task-log-status muted', role:'status', 'aria-atomic':'true'}); + this.toggle = el('button', {type:'button', text:'隐藏', 'aria-label':`隐藏${this.title}`, 'aria-expanded':'true', 'aria-controls':`${id}-body`, + onClick:() => this.setHidden(!this.body.hidden)}); + this.follow = el('button', {type:'button', text:'暂停跟随', 'aria-label':`${this.title}:暂停自动滚动`, 'aria-pressed':'true', + onClick:() => this.setFollow(!this.view.follow)}); + this.search = el('input', {type:'search', 'aria-label':`${this.title}搜索`, placeholder:'筛选日志文字', + onInput:() => {this.view.search = this.search.value;this.render();}}); + this.level = el('select', {'aria-label':`${this.title}级别`, onChange:() => {this.view.level = this.level.value;this.render();}}, + ...[['','全部级别'],['info','信息'],['warning','警告'],['error','错误'],['debug','调试']].map(([value,text]) => el('option', {value,text}))); + const clear = el('button', {type:'button', text:'清空显示', 'aria-label':`清空当前账号${this.title}显示`, + title:'只清空本账号本页显示,保留总日志及其他页面记录', onClick:() => { + this.view.clearedThrough = this.log.highWater; + this.view.seenThrough = this.log.highWater; + this.render(); + }}); + const save = el('button', {type:'button', text:'下载日志', 'aria-label':`下载当前账号${this.title}`, title:'下载本页清空后保留、符合当前日志筛选的记录', + onClick:() => download(new Blob([logText(this.entries())], {type:'text/plain;charset=utf-8'}), `${page.account.summary.label || page.account.id}-${this.title}.txt`)}); + this.lines = el('div', {class:'log-lines task-log-lines', role:'log', 'aria-live':'off', 'aria-label':`${this.title}内容`, tabindex:0, + onScroll:() => { + if (this.view.follow && this.lines.scrollHeight - this.lines.scrollTop - this.lines.clientHeight > 24) this.setFollow(false); + }}); + this.empty = el('p', {class:'task-log-empty muted', text:'暂无日志;运行任务后将在此显示。'}); + this.body = el('div', {id:`${id}-body`, class:'task-log-body'}, + el('div', {class:'task-log-controls'}, el('label', {}, el('span', {text:'搜索'}), this.search), + el('label', {}, el('span', {text:'级别'}), this.level), this.follow, save, clear), el('div', {class:'task-log-viewport'}, this.lines, this.empty), + el('p', {class:'task-log-help muted', text:`${page.key === 'login' ? '含登录和常规记录(旧记录、未知分类);' : page.key === 'ranch' ? '含潜能突破和牧场记录;' : ''}仅清空本账号本页显示;下载遵循日志筛选。最多显示最近 600 条。`})); + this.root = el('section', {class:'task-log-panel', 'data-task-log':page.key, 'aria-labelledby':`${id}-heading`}, + el('div', {class:'log-toolbar task-log-heading'}, this.heading, this.status, el('span', {class:'spacer'}), this.toggle), this.body); + page.root.classList.add('has-task-log'); + page.root.append(this.root); + } + + entries() { return visibleLogs(this.log, this.view, this.page.key); } + active() { return !this.page.root.hidden && !this.page.root.closest('[hidden]'); } + + setHidden(hidden) { + this.body.hidden = hidden; + this.toggle.textContent = hidden ? '显示' : '隐藏'; + this.toggle.setAttribute('aria-label', `${hidden ? '显示' : '隐藏'}${this.title}`); + this.toggle.setAttribute('aria-expanded', String(!hidden)); + this.render(); + } + + setFollow(follow) { + this.view.follow = follow; + this.view.seenThrough = this.log.highWater; + this.follow.textContent = follow ? '暂停跟随' : '跟随最新'; + this.follow.setAttribute('aria-label', `${this.title}:${follow ? '暂停自动滚动' : '跟随最新日志'}`); + this.follow.setAttribute('aria-pressed', String(follow)); + this.render(); + if (follow && !this.body.hidden) this.lines.scrollTop = this.lines.scrollHeight; + } + + render() { + if (!this.active()) return; + const entries = this.entries(); + const pending = !this.view.follow ? entries.filter(entry => entry.seq > this.view.seenThrough).length : 0; + const status = `${this.title}:${entries.length} 条${entries.length > RENDER_LIMIT ? '(显示最近 600 条)' : ''};${this.view.follow ? '跟随最新' : '已暂停跟随'}${pending ? `,新增 ${pending} 条` : ''}`; + if (this.status.textContent !== status) this.status.textContent = status; + if (this.body.hidden) return; + const token = JSON.stringify([this.log.revision, this.log.debug, this.view.clearedThrough, this.view.search, this.view.level]); + if (token !== this.rendered) { + syncLogLines(this.lines, entries, {follow:this.view.follow}); + this.rendered = token; + this.empty.hidden = entries.length > 0; + this.empty.textContent = this.view.search || this.view.level ? '没有符合当前筛选的日志。' : '暂无日志;运行任务后将在此显示。'; + } + if (this.view.follow) this.view.seenThrough = this.log.highWater; + } +} + +export function attachTaskLog(page) { + if (Object.hasOwn(titles, page.key)) page.taskLog = new TaskLogPanel(page); +} diff --git a/ranch_web/tests/browser/test_base_path_browser.py b/ranch_web/tests/browser/test_base_path_browser.py index 2a99c74..8f95fbe 100644 --- a/ranch_web/tests/browser/test_base_path_browser.py +++ b/ranch_web/tests/browser/test_base_path_browser.py @@ -131,6 +131,9 @@ class BasePathBrowserTests(unittest.TestCase): panel = page.locator(f'.page-panel[data-page="{key}"]:not([hidden])') expect(panel.locator('.page-loading[data-loading="false"]')).to_have_count(1) self.assertEqual(panel.locator(".page-error:not([hidden])").count(), 0) + if key in "login ranch daily hatching mainline gifts commissions exploration maps".split(): + expect(panel.locator(f'.task-log-panel[data-task-log="{key}"]')).to_have_count(1) + expect(panel.locator('.task-log-lines')).to_have_attribute('aria-live', 'off') # The server redirects an authenticated login URL back to this workbench. page.goto(base + "/login", wait_until="networkidle") @@ -149,6 +152,7 @@ class BasePathBrowserTests(unittest.TestCase): self.assertEqual(escapes, [], "Browser requests escaped the configured prefix or local server") self.assertEqual(errors, [], "JavaScript or CSP errors") self.assertTrue(any(request.url == base + "/static/paths.js" for request in requests)) + self.assertTrue(any(request.url == base + "/static/task-logs.js" for request in requests)) def test_preserved_prefix(self): self.check_deployment("/ranch") diff --git a/ranch_web/tests/browser/test_task_logs_browser.py b/ranch_web/tests/browser/test_task_logs_browser.py new file mode 100644 index 0000000..e258118 --- /dev/null +++ b/ranch_web/tests/browser/test_task_logs_browser.py @@ -0,0 +1,471 @@ +"""Per-page logs use synthetic records, disposable demos and loopback HTTP only. + +Run: python -B -m unittest ranch_web.tests.browser.test_task_logs_browser -v +""" +from __future__ import annotations + +import json +from pathlib import Path +import unittest +from unittest.mock import patch +from urllib.parse import parse_qs, urlsplit + +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 TaskLogsBrowserTests(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): + guard = patch("requests.sessions.Session.request", side_effect=AssertionError("Live HTTP is forbidden")) + guard.start() + self.addCleanup(guard.stop) + fixtures.WorkbenchBrowserTests.setUp(self) + self.escapes = [] + self.requests = [] + self.records = {self.first: [], self.second: []} + self.log_calls = [] + self.page.add_init_script("""(() => { + const original = window.setInterval; + window.setInterval = (callback, delay, ...args) => { + if (callback.name === 'tick') {window.__pollLogs = callback;return -1;} + return original(callback, delay, ...args); + }; + })();""") + + def local_only(route): + if route.request.url.startswith(self.base + "/"): + route.continue_() + else: + self.escapes.append(route.request.url) + route.abort() + + self.context.route("**/*", local_only) + self.page.on("request", lambda request: self.requests.append(request)) + + def logs(route): + url = urlsplit(route.request.url) + account = url.path.split("/")[-2] + query = parse_qs(url.query) + after = int(query["after"][0]) + debug = query["debug"] == ["true"] + self.log_calls.append((account, after, debug, query)) + records = self.records[account] + self.fulfill(route, {"entries": [dict(entry, details_available=debug and entry.get("details_available", False)) + for entry in records if entry["seq"] > after and (debug or not entry.get("debug"))], + "next": records[-1]["seq"] if records else 0}) + + self.page.route("**/api/accounts/*/logs?*", logs) + + def tearDown(self): + try: + self.assertEqual(self.escapes, [], "Browser requests must stay on the disposable local server") + self.assertEqual(self.errors, [], "No browser console or JavaScript errors") + finally: + fixtures.WorkbenchBrowserTests.tearDown(self) + + def add(self, category, message, *, account=None, level="info", **extra): + records = self.records[account or self.first] + seq = records[-1]["seq"] + 1 if records else 1 + entry = {"id": seq, "seq": seq, "time": "2026-11-11T00:12:34Z", "message": message, "level": level, **extra} + if category is not None: + entry["category"] = category + records.append(entry) + return seq + + def poll(self): + before = len(self.log_calls) + with self.page.expect_response(lambda response: "/logs?" in response.url): + self.page.evaluate("async () => {await window.__pollLogs();}") + self.assertEqual(len(self.log_calls), before + 1, "One shared log request per poll, independent of mounted pages") + + def task(self, key): + return self.go(key).locator(f'.task-log-panel[data-task-log="{key}"]') + + def download(self, button): + with self.page.expect_download() as pending: + button.click() + return Path(pending.value.path()).read_text(encoding="utf-8") + + def test_categories_legacy_safety_and_all_fifteen_tabs(self): + categories = "hatching mainline gifts commissions exploration maps ranch daily login general".split() + for key in categories: + self.add(key, f"only-{key}") + self.add(None, "legacy-general") + self.add("future-category", "unknown-general") + unsafe = ' & ' + self.add("hatching", unsafe) + self.open() + expect(self.page.locator(".page-tab")).to_have_count(15) + expect(self.page.locator("#log-heading")).to_have_text("总日志") + expect(self.page.locator("#log-lines .log-entry")).to_have_count(13) + for key in categories[:9]: + panel = self.task(key) + body = panel.locator(".task-log-lines") + expect(body).to_contain_text(f"only-{key}") + expect(body).to_have_attribute("aria-live", "off") + self.assertEqual(panel.evaluate("node => node.closest('.page-panel').dataset.page"), key) + if key == "login": + expect(body).to_contain_text("only-general") + expect(body).to_contain_text("legacy-general") + expect(body).to_contain_text("unknown-general") + else: + expect(body).not_to_contain_text("legacy-general") + expect(body).not_to_contain_text("unknown-general") + self.assertEqual(body.locator(".log-entry").count(), 2 if key == "hatching" else 1) + if key == "hatching": + expect(body).to_contain_text(unsafe) + expect(body.locator("img,script")).to_have_count(0) + self.assertIsNone(self.page.evaluate("window.__unsafeLog")) + expect(self.go("bag").locator(".task-log-panel")).to_have_count(0) + for _, _, _, query in self.log_calls: + self.assertEqual(set(query), {"after", "debug"}) + + def test_clear_and_download_are_scoped_in_both_directions_and_survive_debug_replay(self): + self.add("hatching", "hatch-before") + self.add("gifts", "gift-before") + self.add("hatching", "debug-before", level="debug", debug=True) + self.add("hatching", "second-account", account=self.second) + self.open() + hatch = self.task("hatching") + hatch.get_by_role("button", name="清空当前账号孵蛋日志显示", exact=True).click() + expect(hatch.locator(".log-entry")).to_have_count(0) + expect(self.page.locator("#log-lines")).to_contain_text("hatch-before") + self.assertIn("gift-before", self.download(self.page.locator("#download-log"))) + self.assertEqual(self.download(hatch.get_by_role("button", name="下载当前账号孵蛋日志", exact=True)), "") + expect(self.task("gifts").locator(".task-log-lines")).to_contain_text("gift-before") + self.page.locator("#clear-log").click() + expect(self.page.locator("#log-lines .log-entry")).to_have_count(0) + expect(self.task("gifts").locator(".task-log-lines")).to_contain_text("gift-before") + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + expect(self.task("hatching").locator(".task-log-lines")).to_contain_text("second-account") + self.page.locator(f'.account-tab[data-account="{self.first}"]').click() + hatch = self.task("hatching") + expect(hatch.locator(".log-entry")).to_have_count(0) + with self.page.expect_response(lambda response: "/logs?after=0&debug=true" in response.url): + self.page.locator("#debug-toggle").click() + expect(hatch.locator(".log-entry")).to_have_count(0) + expect(self.page.locator("#log-lines .log-entry")).to_have_count(0) + self.add("hatching", "hatch-after") + self.add("gifts", "gift-after") + self.poll() + expect(hatch.locator(".task-log-lines")).to_contain_text("hatch-after") + downloaded = self.download(hatch.get_by_role("button", name="下载当前账号孵蛋日志", exact=True)) + self.assertIn("hatch-after", downloaded) + for hidden in ("hatch-before", "debug-before", "gift-", "second-account"): + self.assertNotIn(hidden, downloaded) + total = self.download(self.page.locator("#download-log")) + self.assertIn("hatch-after", total) + self.assertIn("gift-after", total) + self.assertNotIn("before", total) + self.page.locator("#clear-log").click() + expect(hatch.locator(".task-log-lines")).to_contain_text("hatch-after") + self.assertTrue(all(request.method == "GET" for request in self.requests if "/logs" in request.url)) + + def test_switches_preserve_filters_inputs_focus_and_only_active_panel_updates(self): + self.add("hatching", "keep-first", level="warning") + self.add("gifts", "gift-initial") + self.add("hatching", "second-keep", account=self.second) + self.open() + hatch = self.task("hatching") + self.page.locator(".page-panel:not([hidden]) .subtab").last.click() + query = hatch.get_by_role("searchbox", name="孵蛋日志搜索", exact=True) + query.fill("keep") + hatch.get_by_role("combobox", name="孵蛋日志级别", exact=True).select_option("warning") + page_panel = self.page.locator('.page-panel[data-page="hatching"]:not([hidden])') + field = page_panel.locator('input[type="checkbox"]').first + self.assertGreater(field.count(), 0) + checked = not field.is_checked() + field.set_checked(checked) + field.evaluate("node => {window.__preservedInput=node;}") + query.focus() + query.evaluate("node => {node.setSelectionRange(1,3);window.__preservedSearch=node;}") + self.add("hatching", "keep-new", level="warning") + self.add("hatching", "excluded-info") + self.poll() + expect(query).to_be_focused() + self.assertEqual(query.evaluate("node => [node.selectionStart,node.selectionEnd]"), [1, 3]) + self.assertTrue(query.evaluate("node => node===window.__preservedSearch")) + expect(hatch.locator(".log-entry")).to_have_count(2) + expect(hatch.locator(".task-log-lines")).not_to_contain_text("excluded-info") + hidden_hatch = self.page.locator('.page-panel[data-page="hatching"] .task-log-panel') + gifts = self.task("gifts") + self.add("hatching", "keep-hidden", level="warning") + self.add("gifts", "gift-new") + self.poll() + expect(gifts.locator(".task-log-lines")).to_contain_text("gift-new") + expect(hidden_hatch.locator(".log-entry")).to_have_count(2) + hatch = self.task("hatching") + expect(hatch.locator(".log-entry")).to_have_count(3) + expect(query).to_have_value("keep") + expect(hatch.get_by_role("combobox", name="孵蛋日志级别", exact=True)).to_have_value("warning") + self.assertEqual(field.is_checked(), checked) + self.assertTrue(field.evaluate("node => node===window.__preservedInput")) + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + second = self.task("hatching") + expect(second.get_by_role("searchbox", name="孵蛋日志搜索", exact=True)).to_have_value("") + expect(second.locator(".task-log-lines")).to_contain_text("second-keep") + expect(second.locator(".task-log-lines")).not_to_contain_text("keep-first") + self.page.locator(f'.account-tab[data-account="{self.first}"]').click() + hatch = self.task("hatching") + expect(hatch.get_by_role("searchbox", name="孵蛋日志搜索", exact=True)).to_have_value("keep") + expect(self.page.locator('.page-panel[data-page="hatching"]:not([hidden]) .subtab[aria-selected="true"]')).to_have_text("喂养策略") + + def test_reading_pause_collapse_and_bounded_append_preserve_scroll_and_nodes(self): + for i in range(650): + self.add("maps", f"map-record-{i:04}") + self.open() + task = self.task("maps") + lines = task.locator(".task-log-lines") + expect(lines.locator(".log-entry")).to_have_count(600) + expect(task.get_by_role("button", name="扫荡日志:暂停自动滚动", exact=True)).to_have_attribute("aria-pressed", "true") + lines.evaluate("node => {node.scrollTop=node.scrollHeight/2;node.dispatchEvent(new Event('scroll'));}") + follow = task.get_by_role("button", name="扫荡日志:跟随最新日志", exact=True) + expect(follow).to_have_attribute("aria-pressed", "false") + position = lines.evaluate("node => {const row=[...node.children].find(row=>row.getBoundingClientRect().top>=node.getBoundingClientRect().top);window.__readingRow=row;return {seq:row.dataset.sequence,offset:row.getBoundingClientRect().top-node.getBoundingClientRect().top,parent:node.closest('.page-panel').scrollTop};}") + self.add("maps", "map-new") + self.poll() + expect(task.locator(".task-log-status")).to_contain_text("新增 1 条") + self.assertTrue(lines.evaluate("node => node.contains(window.__readingRow)")) + updated = lines.evaluate("node => ({offset:window.__readingRow.getBoundingClientRect().top-node.getBoundingClientRect().top,parent:node.closest('.page-panel').scrollTop})") + self.assertAlmostEqual(position["offset"], updated["offset"], delta=1) + self.assertEqual(position["parent"], updated["parent"]) + hide = task.get_by_role("button", name="隐藏扫荡日志", exact=True) + hide.focus() + hide.press("Enter") + expect(task.locator(".task-log-heading button")).to_have_attribute("aria-expanded", "false") + rows_before = lines.text_content() + self.add("maps", "map-while-collapsed") + self.poll() + self.assertEqual(lines.text_content(), rows_before) + task.get_by_role("button", name="显示扫荡日志", exact=True).press("Enter") + expect(lines).to_contain_text("map-while-collapsed") + expect(task.get_by_role("button", name="扫荡日志:跟随最新日志", exact=True)).to_be_visible() + task.get_by_role("button", name="扫荡日志:跟随最新日志", exact=True).click() + self.assertLessEqual(lines.evaluate("node => node.scrollHeight-node.scrollTop-node.clientHeight"), 1) + # Unchanged ticks preserve nodes, filters and both scroll containers. + lines.locator(".log-entry").last.evaluate("node => {window.__lastLogNode=node;}") + self.poll() + self.assertTrue(lines.locator(".log-entry").last.evaluate("node => node===window.__lastLogNode")) + for i in range(900): + self.add("maps", f"bounded-{i:04}") + self.poll() + expect(lines.locator(".log-entry")).to_have_count(600) + text = self.download(task.get_by_role("button", name="下载当前账号扫荡日志", exact=True)) + self.assertEqual(len(text.splitlines()), 1200, "Downloads use the same bounded shared buffer") + self.assertNotIn("map-record-0000", text) + with self.page.expect_response(lambda response: "/logs?after=0&debug=true" in response.url): + self.page.locator("#debug-toggle").click() + self.assertEqual(self.download(task.get_by_role("button", name="下载当前账号扫荡日志", exact=True)), text, + "Rewinding the shared cursor must not replay evicted records") + + def test_total_and_task_reading_positions_and_follow_states_are_independent_per_account(self): + for i in range(85): + self.add("hatching", f"first-{i:03}") + self.add("hatching", f"second-{i:03}", account=self.second) + self.open() + hatch = self.task("hatching") + hatch.get_by_role("button", name="孵蛋日志:暂停自动滚动", exact=True).click() + total = self.page.locator("#log-lines") + total.evaluate("node => {node.scrollTop=140;node.dispatchEvent(new Event('scroll'));}") + expect(self.page.locator("#log-follow")).not_to_be_checked() + position = total.evaluate("node => node.scrollTop") + self.add("hatching", "first-new") + self.poll() + self.assertEqual(total.evaluate("node => node.scrollTop"), position) + expect(hatch.locator(".task-log-status")).to_contain_text("已暂停跟随,新增 1 条") + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + expect(self.page.locator("#log-follow")).to_be_checked() + expect(self.task("hatching").get_by_role("button", name="孵蛋日志:暂停自动滚动", exact=True)).to_be_visible() + self.page.locator(f'.account-tab[data-account="{self.first}"]').click() + expect(self.page.locator("#log-follow")).not_to_be_checked() + self.assertEqual(total.evaluate("node => node.scrollTop"), position) + expect(self.task("hatching").get_by_role("button", name="孵蛋日志:跟随最新日志", exact=True)).to_be_visible() + + def test_hidden_total_switches_preserve_each_accounts_follow_and_scroll(self): + for i in range(85): + self.add("hatching", f"first-hidden-{i:03}") + self.add("hatching", f"second-hidden-{i:03}", account=self.second) + self.open() + total = self.page.locator("#log-lines") + follow = self.page.locator("#log-follow") + + def switch(account): + self.page.locator(f'.account-tab[data-account="{account}"]').click() + expect(self.page.locator(f'.account-tab[data-account="{account}"]')).to_have_attribute("aria-selected", "true") + + def hide(): + self.page.locator("#log-toggle").click() + expect(self.page.locator("#log-panel")).to_be_hidden() + + def show(): + self.page.locator("#log-toggle").click() + expect(self.page.locator("#log-panel")).to_be_visible() + + def read_at(position): + total.evaluate("(node, position) => {node.scrollTop=position;node.dispatchEvent(new Event('scroll'));}", position) + expect(follow).not_to_be_checked() + return total.evaluate("node => node.scrollTop") + + expect(total.locator(".log-entry")).to_have_count(85) + first_position = read_at(140) + hide() + switch(self.second) + expect(total).to_contain_text("second-hidden-084") + expect(follow).to_be_checked() + second_position = total.evaluate("node => node.scrollTop") + self.assertGreater(second_position, first_position) + hide() + for account in (self.first, self.second, self.first): + switch(account) + expect(self.page.locator("#log-panel")).to_be_hidden() + show() + expect(follow).not_to_be_checked() + self.assertEqual(total.evaluate("node => node.scrollTop"), first_position) + hide() + switch(self.second) + show() + expect(follow).to_be_checked() + self.assertEqual(total.evaluate("node => node.scrollTop"), second_position) + + # Repeat with two different paused reading positions, so a hidden DOM's + # zero/stale scrollTop cannot replace either account's saved position. + second_position = read_at(260) + hide() + for account in (self.first, self.second, self.first, self.second): + switch(account) + expect(self.page.locator("#log-panel")).to_be_hidden() + show() + expect(follow).not_to_be_checked() + self.assertEqual(total.evaluate("node => node.scrollTop"), second_position) + hide() + switch(self.first) + show() + expect(follow).not_to_be_checked() + self.assertEqual(total.evaluate("node => node.scrollTop"), first_position) + + def test_login_controls_receive_normal_clicks_with_expanded_logs_at_both_viewports(self): + login = {"account": "offline-layout", "has_saved_password": False, + "servers": [{"id": 7, "name": "合成区服一"}, {"id": 8, "name": "合成区服二"}], + "saved_sessions": [{"id": "layout-session-1", "label": "合成会话一"}, + {"id": "layout-session-2", "label": "合成会话二"}]} + actions = [] + + def login_view(route): + response = route.fetch().json() + if response.get("data"): + response["data"]["login"] = login + self.fulfill(route, response) + + def login_action(route): + operation = urlsplit(route.request.url).path.rsplit("/", 1)[1] + actions.append((operation, route.request.post_data_json)) + self.fulfill(route, {"id": f"layout-{len(actions)}", "operation": operation, + "status": "succeeded", "result": login, "error": None}) + + self.page.route(f"**/api/accounts/{self.first}/views/login?*", login_view) + for operation in ("login", "enter_server", "restore_session"): + self.page.route(f"**/api/accounts/{self.first}/actions/{operation}", login_action) + self.add("login", "合成登录日志:验证表单按钮与日志区域互不覆盖。") + self.open() + for width, height in ((1280, 800), (390, 844)): + with self.subTest(viewport=(width, height)): + self.page.set_viewport_size({"width": width, "height": height}) + panel = self.go("login") + task = panel.locator('.task-log-panel[data-task-log="login"]') + expect(task.locator(".task-log-body")).to_be_visible() + geometry = panel.evaluate("""node => { + const content=node.querySelector('.page-content').getBoundingClientRect(); + const log=node.querySelector('.task-log-panel').getBoundingClientRect(); + const controls=[...node.querySelectorAll('.login-layout button')].filter(button=>!button.hidden); + return {gap:log.top-content.bottom, + overflow:Math.max(...controls.map(button=>button.getBoundingClientRect().bottom))-content.bottom}; + }""") + self.assertGreaterEqual(geometry["gap"], 0, geometry) + self.assertLessEqual(geometry["overflow"], 1, geometry) + panel.get_by_label("游戏账号", exact=True).fill("offline-layout") + panel.get_by_label("游戏密码", exact=True).fill("synthetic-layout-password") + for operation, label in (("login", "账号密码登录 / 获取区服"), + ("enter_server", "进入选中区服"), + ("restore_session", "恢复选中会话(无需重新输密码)")): + if operation == "enter_server": + panel.get_by_label("区服 / 角色", exact=True).select_option("8") + if operation == "restore_session": + panel.get_by_label("已保存的账号 / 区服 / 角色", exact=True).select_option("layout-session-2") + with self.page.expect_response(lambda response: response.url.endswith(f"/actions/{operation}")): + panel.get_by_role("button", name=label, exact=True).click() + self.assertEqual(actions[-1][0], operation) + expect(task.locator(".task-log-body")).to_be_visible() + if operation == "enter_server": + self.assertEqual(actions[-1][1], {"server_id": "8"}) + if operation == "restore_session": + self.assertEqual(actions[-1][1], {"session_id": "layout-session-2"}) + task.get_by_role("searchbox", name="登录日志搜索", exact=True).click() + expect(task.get_by_role("searchbox", name="登录日志搜索", exact=True)).to_be_focused() + + def test_all_page_content_stays_separate_from_logs_and_remains_scroll_reachable(self): + self.open() + for width, height in ((1280, 800), (390, 844)): + self.page.set_viewport_size({"width": width, "height": height}) + for key in "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split(): + with self.subTest(viewport=(width, height), page=key): + panel = self.go(key) + task = panel.locator(".task-log-panel") + if not task.count(): + continue + geometry = panel.evaluate("""node => { + const content=node.querySelector('.page-content').getBoundingClientRect(); + const log=node.querySelector('.task-log-panel').getBoundingClientRect(); + return {height:content.height,gap:log.top-content.bottom}; + }""") + self.assertGreaterEqual(geometry["height"], 160, geometry) + self.assertGreaterEqual(geometry["gap"], 0, geometry) + self.assertGreaterEqual(task.locator(".task-log-lines").bounding_box()["height"], 120) + task.get_by_role("searchbox").click() + expect(task.get_by_role("searchbox")).to_be_focused() + + def test_populated_layout_visual_artifact_and_narrow_viewport(self): + def maps_view(route): + response = route.fetch().json() + data = response.get("data") + if data: + data.update(summary="合成离线关卡:仅用于日志交互与布局验证,不连接游戏。", + groups=[{"id": "demo", "label": "合成测试区域", "collapsed": False}], + columns=[{"key": key, "label": title} for key, title in + [("name", "关卡"), ("level", "难度"), ("cost", "体力"), ("today", "今日次数"), ("state", "状态")]], + rows=[{"id": f"synthetic-{i}", "group": "demo", "name": f"合成关卡 {i + 1}", + "level": 3, "cost": 6, "today": i % 3, "state": "等待下次扫荡"} for i in range(8)]) + self.fulfill(route, response) + + self.page.route(f"**/api/accounts/{self.first}/views/maps?*", maps_view) + for i in range(18): + self.add("maps", f"[扫荡] 合成关卡 {i + 1}:完成结算,获得金币与材料。", level="warning" if i == 12 else "info") + self.open() + task = self.task("maps") + page_panel = self.page.locator('.page-panel[data-page="maps"]:not([hidden])') + expect(page_panel.locator(".table-scroll").first).to_be_visible() + self.assertGreaterEqual(page_panel.locator(".table-scroll").first.bounding_box()["height"], 100) + self.assertGreaterEqual(page_panel.locator(".page-content").bounding_box()["height"], 160) + self.assertGreaterEqual(task.locator(".task-log-lines").bounding_box()["height"], 120) + target = Path(__file__).resolve().parents[3] / "test-artifacts" / "task-log-ui.png" + target.parent.mkdir(exist_ok=True) + task.scroll_into_view_if_needed() + self.page.screenshot(path=str(target)) + self.page.set_viewport_size({"width": 390, "height": 844}) + task.scroll_into_view_if_needed() + self.assertLessEqual(task.evaluate("node => node.scrollWidth-node.clientWidth"), 1) + expect(task.get_by_role("button", name="清空当前账号扫荡日志显示", exact=True)).to_be_visible() + self.page.screenshot(path=str(target.with_name("task-log-ui-narrow.png"))) + + +if __name__ == "__main__": + unittest.main() diff --git a/ranch_web/tests/test_activity.py b/ranch_web/tests/test_activity.py index 0a49e61..3428678 100644 --- a/ranch_web/tests/test_activity.py +++ b/ranch_web/tests/test_activity.py @@ -9,6 +9,7 @@ import unittest from unittest.mock import patch from ranch_web.activity import ActivityLog, ActivityLogError, MAX_MESSAGE_CHARS +from ranch_web.log_categories import CATEGORIES class ActivityTests(unittest.TestCase): @@ -33,6 +34,34 @@ class ActivityTests(unittest.TestCase): fsync.assert_not_called() self.assertFalse(self.path.parent.exists()) + def test_categories_and_error_level_persist_across_restart(self): + log = self.log(sequence_block_size=8) + for category in sorted(CATEGORIES): + self.append(log, "attributed operation", category=category, level="error") + for invalid in ("breakthrough", "unknown", "TOKEN_SECRET", {}, [], None): + self.assertEqual(self.append(log, category=invalid)["category"], "general") + debug = self.append(log, "transient categorized trace", category="gifts", debug=True) + restored = self.log(sequence_block_size=8) + self.assertEqual(restored.load(), log.load()) + self.assertEqual({entry["category"] for entry in restored.load() if entry["level"] == "error"}, CATEGORIES) + self.assertGreater(self.append(restored, category="daily")["seq"], debug["seq"]) + self.assertNotIn("TOKEN_SECRET", self.path.read_text(encoding="utf-8")) + + def test_legacy_categories_are_conservative_and_loading_never_migrates(self): + self.path.parent.mkdir(parents=True) + messages = [("自动赠礼:请先选择物品", "gifts"), ("突破请求待核对", "ranch"), + ("状态已刷新;自动赠礼:冷却中", "general"), ("事件已完成", "general"), + ("已推进普通剧情并保存本地检查点", "general")] + record = {"schema": 1, "sequence": 20, "entries": [ + {"seq": index, "message": message} for index, (message, _) in enumerate(messages, 1)]} + raw = json.dumps(record, ensure_ascii=False) + self.path.write_text(raw, encoding="utf-8") + with patch("ranch_web.activity.os.replace") as replace: + entries = self.log().load() + replace.assert_not_called() + self.assertEqual([entry["category"] for entry in entries], [category for _, category in messages]) + self.assertEqual(self.path.read_text(encoding="utf-8"), raw) + def test_account_isolation_and_persistence(self): log = self.log() first = self.append(log, "account A operation", level="warning") @@ -161,7 +190,7 @@ class ActivityTests(unittest.TestCase): "response": {"raw": secret}, "seq": 90000, "id": 90000} log = self.log() saved = log.append(entry) - self.assertEqual(set(saved), {"time", "message", "debug", "level", "id", "seq"}) + self.assertEqual(set(saved), {"time", "message", "category", "debug", "level", "id", "seq"}) self.assertEqual(saved["seq"], 1) for filename in (self.path, self.watermark): raw = filename.read_text(encoding="utf-8") diff --git a/ranch_web/tests/test_task_logs.py b/ranch_web/tests/test_task_logs.py new file mode 100644 index 0000000..cf2f4a0 --- /dev/null +++ b/ranch_web/tests/test_task_logs.py @@ -0,0 +1,254 @@ +"""Offline task routing, bounded persistence, and lazy debug contract regressions.""" +from copy import deepcopy +import json +import threading +from types import SimpleNamespace +import unittest +from unittest.mock import patch + +from ranch_assistant.battles import CancelledBeforeDispatch +from ranch_assistant.engine import Engine +from ranch_assistant.model import Action +from ranch_web.activity import MAX_MESSAGE_CHARS +from ranch_web.log_categories import CATEGORIES, endpoint_category, legacy_category, route_message +from ranch_web.service import WebManager +from ranch_web.tests import test_service as fixtures + + +class RoutingTests(unittest.TestCase): + def test_reward_cooldown_and_purchase_continuations(self): + for message, category in [ + ("扫荡完成:2-11;金币32;经验64;蓝色黏液×1", "maps"), + ("自动赠礼:魔物还需等待;冷却尚未结束;好感上限100", "gifts"), + ("购蛋暂停:余额需保留100;今日额度剩余0;补货目标至少设为10", "hatching"), + ]: + with self.subTest(category=category): + self.assertEqual(route_message(message), [(category, message)]) + self.assertEqual(route_message("扫荡完成:2-11;金币32;状态已刷新", context="maps"), + [("maps", "扫荡完成:2-11;金币32"), ("general", "状态已刷新")]) + + def test_uncertain_legacy_and_shared_endpoints_stay_general(self): + for message in ("事件已完成", "未知结果", "状态已刷新;自动赠礼:冷却中", "魔物名为探险,普通提示"): + self.assertEqual(legacy_category(message), "general") + self.assertEqual(endpoint_category("taskService/taskCompleteStep"), "general") + self.assertEqual(endpoint_category("taskService/taskCompleteStep", active="commissions"), "commissions") + self.assertEqual(endpoint_category("https://offline.invalid/game/exploreService/finish"), "exploration") + + +class TaskLogTests(unittest.TestCase): + # Reuse the existing real-engine/offline HTTP fixture without inheriting its + # unrelated test cases or adding browser/GUI dependencies to image CI. + setUp = fixtures.ServiceTests.setUp + account = fixtures.ServiceTests.account + idle = fixtures.ServiceTests.idle + job = fixtures.ServiceTests.job + login = fixtures.ServiceTests.login + + def tick(self, identifier, kind, *, status="succeeded"): + worker = self.manager._worker(identifier) + with patch.object(worker.schedule, "due", return_value=kind): + return self.job(identifier, worker.enqueue("__tick"), status=status) + + def entries(self, identifier, after=0, debug=False): + return self.manager.logs(identifier, after=after, debug=debug)["entries"] + + def test_mixed_poll_groups_hundreds_of_notes_into_bounded_writes(self): + identifier = self.account() + worker = self.manager._worker(identifier) + hatch = [f"魔物{index}:资质未同步,等待成长结算;暂不派遣、喂养或收取" for index in range(160)] + gifts = ["自动赠礼:代表还需等待;冷却尚未结束"] + ranch = ["代表:材料不足,保留突破目标"] + worker.engine.planner.notes = hatch + gifts + ranch + worker.engine.gift_planner.notes = gifts + worker.engine.breakthrough_planner.notes = ranch + message = ";".join(["状态已刷新", *hatch, *gifts, *ranch, "探索奖励事件已结算:2-11", "金币32", "经验64", "蓝色黏液×1"]) + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, "poll", return_value=(worker.engine.snapshot, [], message)), \ + patch.object(worker._activity, "_write", wraps=worker._activity._write) as write: + self.tick(identifier, "poll") + entries = self.entries(identifier, after) + by_category = {entry["category"]: entry for entry in entries} + self.assertEqual(set(by_category), {"general", "hatching", "gifts", "ranch", "maps"}) + self.assertEqual(len(entries), len(by_category)) + self.assertEqual(sum(call.args[0] == worker.profile_root / "activity.json" for call in write.call_args_list), len(entries)) + self.assertLessEqual(len(entries), len(CATEGORIES)) + self.assertTrue(all(len(entry["message"]) <= MAX_MESSAGE_CHARS for entry in entries)) + self.assertEqual(by_category["general"]["message"], "状态已刷新") + self.assertIn("蓝色黏液×1", by_category["maps"]["message"]) + self.assertIn("冷却尚未结束", by_category["gifts"]["message"]) + self.assertFalse(any(entry["message"] == message for entry in entries)) + + def test_actual_progression_context_routes_generic_results_and_errors(self): + calls = [] + worker = None + + def action(engine, intent=None): + calls.append(intent) + worker.trace.emit("response", "taskService/taskCompleteStep", body={"accepted": True}) + if intent.get("fail"): + raise OSError("local checkpoint failed") + return engine.snapshot, [], "已推进普通剧情并保存本地检查点" + + with patch.object(Engine, "_run_progression_intent", action): + identifier = self.account() + worker = self.manager._worker(identifier) + for task_type, category in ((1, "mainline"), (4, "commissions")): + for fail in (False, True): + intent = {"kind": "progression_dialogue", "task_type_id": "known-task", "fail": fail} + after = self.manager.logs(identifier, debug=True)["next"] + with patch.object(worker.engine, "game_data", SimpleNamespace(task=lambda _: {"type": task_type})), \ + patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent(intent)): + self.tick(identifier, "poll", status="failed" if fail else "succeeded") + entries = self.entries(identifier, after, debug=True) + self.assertEqual({entry["category"] for entry in entries}, {category}) + self.assertEqual(len(entries), 2) + self.assertEqual(entries[-1]["level"], "error" if fail else "info") + detail = self.manager.debug_entry(identifier, entries[0]["id"]) + self.assertTrue(detail["details"]["body"]["accepted"]) + self.assertEqual(len(calls), 4) + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, "poll", return_value=(worker.engine.snapshot, [], "状态已刷新")): + self.job(identifier, self.manager.submit(identifier, "refresh")) + self.assertEqual(self.entries(identifier, after)[0]["category"], "general") + + def test_attribution_metadata_failure_does_not_fail_or_repeat_action(self): + calls = [] + + def action(engine, intent): + calls.append(intent) + return engine.snapshot, [], "unattributed local result" + + with patch.object(Engine, "_run_progression_intent", action): + identifier = self.account() + worker = self.manager._worker(identifier) + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, "_is_commission", side_effect=ValueError("metadata unavailable")), \ + patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent({"kind": "progression_dialogue"})): + self.tick(identifier, "poll") + self.assertEqual(len(calls), 1) + self.assertEqual(self.entries(identifier, after)[0]["category"], "general") + + def test_fast_and_auth_errors_keep_source_category_and_error_level(self): + identifier = self.account() + worker = self.manager._worker(identifier) + for kind, category in (("hatch", "hatching"), ("gift", "gifts"), ("explore", "exploration"), ("breakthrough", "ranch"), ("auto_relogin", "login")): + with self.subTest(kind=kind): + worker._running = True + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, "poll_automation", side_effect=ValueError("task failed")), \ + patch.object(worker, "_auto_relogin_status", return_value={"state": "waiting"}), \ + patch.object(worker, "_auto_relogin", side_effect=ValueError("task failed")): + self.tick(identifier, kind, status="failed") + entry = self.entries(identifier, after)[-1] + self.assertEqual((entry["category"], entry["level"]), (category, "error")) + self.assertEqual(worker._activity.load()[-1]["category"], category) + self.assertEqual(worker._activity.load()[-1]["level"], "error") + + def test_manual_errors_use_operation_category(self): + identifier = self.account() + worker = self.manager._worker(identifier) + for operation, method, category in (("claim_daily", "claim_daily", "daily"), ("refresh_maps", "refresh_stages", "maps")): + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, method, side_effect=ValueError("manual operation failed")): + self.job(identifier, self.manager.submit(identifier, operation), status="failed") + self.assertEqual([(row["category"], row["level"]) for row in self.entries(identifier, after)], [(category, "error")]) + + def test_real_ordinary_poll_attributes_market_purchase_and_automatic_cleanup(self): + identifier = self.account(False) + self.login(identifier) + worker = self.manager._worker(identifier) + engine = worker.engine + market = next(key for key, row in engine.catalog.data["markets"].items() if row.get("money", 0) > 0) + engine.policy.daily_buy_money = 1000000 + engine.planner.notes = [] + actions = [ + Action("buy", "莉莉托斯市场十连抽蛋 ×10,花费100金币", "gachaService/gachaGetEggs", {"id": market, "num": 1}), + Action("sell", "派遣 测试魔物 #1", "monsterService/monsterSell", {"monsterIds": [1]}), + Action("feed", "喂养 测试魔物 ← 素材", "monsterService/monsterIntensify", {"targetId": 1, "foods": []}), + ] + for action in actions: + with self.subTest(kind=action.kind): + worker._running = True + after = self.manager.logs(identifier, debug=True)["next"] + with patch.object(engine, "plans", return_value=[action]): + self.tick(identifier, "poll") + entries = self.entries(identifier, after, debug=True) + result = [row for row in entries if not row["debug"]] + self.assertEqual({row["category"] for row in result}, {"hatching"}) + self.assertIn(action.description, result[0]["message"]) + debug = [row for row in entries if action.path in row["message"]] + self.assertTrue(debug) + self.assertEqual({row["category"] for row in debug}, {"hatching"}) + # The same endpoint belongs to the explicit manual management operation. + after = self.manager.logs(identifier, debug=True)["next"] + self.job(identifier, self.manager.submit(identifier, "sell", {"monster_ids": [201], "confirm": True}), status="failed") + self.assertEqual(self.entries(identifier, after)[-1]["category"], "ranch") + + def test_redaction_before_splitting_restart_cursor_and_lazy_debug_isolation(self): + identifier, other = self.account(), self.account() + worker = self.manager._worker(identifier) + secrets = ("secret;parts", "line-secret\nline-parts") + worker.remember({"password": secrets[0], "token": secrets[1]}) + after = self.manager.logs(identifier)["next"] + worker.result(worker.engine.snapshot, [], f"状态已刷新;自动赠礼:{secrets[0]};突破:{secrets[1]}") + # A trace is exactly one summary/ID, even with a composite diagnostic. + worker.trace.emit("response", "monsterService/monsterSendGift", message="赠礼;突破;探险", + headers={"Authorization": secrets[0]}, body={"token": secrets[1], "ok": True}) + all_logs = self.manager.logs(identifier, after=after, debug=True) + traces = [entry for entry in all_logs["entries"] if entry["details_available"]] + self.assertEqual(len(traces), 1) + trace = traces[0] + self.assertEqual(trace["category"], "gifts") + self.assertEqual(trace["id"], trace["seq"]) + self.assertTrue(self.manager.debug_entry(identifier, trace["id"])["details"]["body"]["ok"]) + with self.assertRaises(KeyError): + self.manager.debug_entry(other, trace["id"]) + self.assertFalse(any(row["debug"] for row in self.entries(identifier, after))) + self.assertEqual(self.manager.logs(identifier)["next"], all_logs["next"]) + self.assertEqual(self.manager.logs(identifier, after=all_logs["next"], debug=True)["entries"], []) + serialized = json.dumps(all_logs, ensure_ascii=False) + (worker.profile_root / "activity.json").read_text(encoding="utf-8") + for fragment in ("secret", "parts", "line-secret", "line-parts", '"headers"', '"body"'): + self.assertNotIn(fragment, serialized) + durable = deepcopy(worker._activity.load()) + self.manager.close() + self.manager = WebManager(self.root, start_scheduler=False, login_factory=fixtures.FakeLogin) + self.addCleanup(self.manager.close) + self.idle(identifier) + restored = self.entries(identifier, debug=True) + for entry in durable: + self.assertIn(entry | {"details_available": False}, restored) + self.assertTrue(all(not row["debug"] for row in restored)) + self.assertGreater(self.manager._worker(identifier).log("after restart", category="daily"), all_logs["next"]) + self.assertNotIn("自动赠礼:<隐藏>", json.dumps(self.entries(other), ensure_ascii=False)) + + def test_cancelled_action_keeps_external_logs_and_other_accounts_isolated(self): + entered, release = threading.Event(), threading.Event() + self.addCleanup(release.set) + + def action(engine, intent): + entered.set() + if not release.wait(5): + raise AssertionError("test did not release action") + raise CancelledBeforeDispatch() + + with patch.object(Engine, "_run_progression_intent", action): + identifier = self.account() + other = self.account() + worker = self.manager._worker(identifier) + after = self.manager.logs(identifier)["next"] + with patch.object(worker.engine, "poll", side_effect=lambda **_: worker.engine._run_progression_intent({"kind": "progression_loop_accept"})), \ + patch.object(worker.schedule, "due", return_value="poll"): + pending = worker.enqueue("__tick") + self.assertTrue(entered.wait(5)) + worker.log("external notice") + self.manager._worker(other).log("other account notice") + worker.stop() + release.set() + self.job(identifier, pending, status="cancelled") + self.assertEqual([(row["message"], row["category"], row["level"]) for row in self.entries(identifier, after)], + [("external notice", "general", "info")]) + self.assertFalse(any(row["message"] == "other account notice" for row in self.entries(identifier))) + + +if __name__ == "__main__": + unittest.main()