diff --git a/Dockerfile b/Dockerfile index c00bc05..a356f88 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,6 @@ FROM python:3.12-slim-bookworm -ARG WEB_VERSION=2.0.2 +ARG WEB_VERSION=2.0.3 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 df1ad34..0000680 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@ # 牧羊人之心Bot -本轮 Web 发布目标 **2.0.2**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 +本轮 Web 发布目标 **2.0.3**,源码入口为 `main`;原生 PySide6 桌面正式版本保留 **1.2.0**(`v1.2.0`)。两者的适配资料基线均为《牧羊人之心》Android **1.9.68**。 支持多账号独立运行、牧场培养、每日事务、主线与委托推进、近似战斗模拟、探险、扫荡及本地掉落分析,能力与验证限制见下文。 ## 运行指引 -### Web 2.0.2(main) +### Web 2.0.3(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.2** 沿用登录成功后自动执行已勾选策略及用户手动触发在线更新。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器。已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面。操作条件见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。 +**2.0.3** 修复 2.0.2 的日志布局,游戏策略沿用现有实现。在线更新使用稳定 GitHub Release、对应正式镜像及心跳有效的宿主机受控更新器。已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面。操作条件见[部署说明](deploy/web/README.md),更新结果以宿主机健康检查为准。 ### 桌面 1.2.0 @@ -36,7 +36,7 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` | 组件与版本 | 《牧羊人之心》Android 基线 | 入口与状态 | | --- | --- | --- | -| Web 2.0.2 | 1.9.68 | 本轮发布目标;源码入口 `main`,`Start_Ranch_Web.cmd` / `sh start-web.sh` | +| Web 2.0.3 | 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,21 +44,23 @@ Web 无需 Node/npm 或 PySide6,数据独立保存在 `local_state/ranch_web` 本表记录适配资料基线,不代表其他客户端版本兼容或全部功能已完成实机验收。Docker 镜像以标签流水线成功结果为准,在线更新依赖对应 GitHub Release 条目;详见 [部署说明](deploy/web/README.md)。 -## Web 2.0.2 主要功能与分类日志 +## Web 2.0.3 主要功能与分类日志 -2.0.2 新增按功能查看的账号日志,页面范围与操作说明见 [2.0.2 发布说明](analysis/RELEASE_2_0_2.md)。其余功能沿用现有实现。 +2.0.3 将 2.0.2 的日志界面改为所有功能页共用原有底部日志区,切换页签只显示当前账号、当前功能的日志;取消总日志/全部模式及页内日志框。操作说明见 [2.0.3 发布说明](analysis/RELEASE_2_0_3.md)。其余功能沿用现有实现。 - **原布局与15页**:沿用桌面页面顺序、账号页签、顶部玩家数值与统一启停、可调整日志区。 - **多账号与独立后台**:各账号隔离并行、同账号请求串行;关闭网页或退出管理登录后,服务端继续监控及已开启的策略。 - **管理登录与子路径**:独立管理登录页、HttpOnly / SameSite cookie、写请求来源校验;支持 `/ranch` 等反代子路径,游戏凭据保存在服务端。 - **策略与数据**:复用孵蛋、牧场、喂养、突破、赠礼、每日、主线、委托、探险和扫荡策略,支持自动保存、导入导出、执行计划及掉落分析。 -- **分类日志**:登录、每日事务、牧场、自动孵蛋、自动主线、自动赠礼、自动委托、自动探险和自动扫荡提供当前账号的日志面板,保留底部总日志与调试入口。功能面板支持文字搜索、级别筛选、独立清空显示与下载、隐藏及跟随/暂停滚动;共用同一账号日志拉取,浏览器共享缓存最多 1200 条,每面板最多显示最近 600 条。 -- **分类归属与旧日志**:分类随普通日志记录持久保存;孵蛋/牧场整理策略的自动喂养、出售、收取及暂停记录归入孵蛋,手动牧场操作与自动潜能突破归入牧场。无分类旧记录仅在明确前缀指向同一类别时保守推断,混合或未知记录保留为常规日志,在总日志和登录面板可见。 +- **底部分类日志**:保留原底部日志区及工具栏,顶部右侧是唯一显示/隐藏入口。整页刷新或重新进入工作台默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。手动显隐按账号保留至刷新,同账号切换功能页保持显隐并更新日志范围。 +- **日志操作与隔离**:搜索、清空显示、下载、跟随/暂停及滚动位置按账号与页签隔离;清空不删除服务端历史,下载遵循当前范围与搜索条件,不串入其他账号或功能。日志共用同一账号拉取,浏览器缓存最多 1200 条,底部最多显示最近 600 条。 +- **日志归属**:培育室查看孵蛋日志,其他功能页查看对应执行日志;没有匹配记录时为空,不回退到全部日志。登录仅显示登录日志,排除常规、混合旧记录及赠礼日志。已有分类及保守旧记录推断沿用原实现。 +- **手动刷新反馈**:刷新成功仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 - **日志保存与更新**:普通日志按账号限量持久保存,调试详情按进程缓存;仅检查官方稳定 2.x Release,未配置执行器时仅检查,受控安装与备份/回滚由宿主机执行,自动安装默认关闭。 连接状态区分在线、临时故障重试、游戏会话失效与未连接,显示最后成功通信及下次重试时间,旧快照标注为缓存。临时故障先停止策略,再退避执行只读探测;会话失效时停止游戏轮询,按自动重登设置等待,或手动恢复、重新登录。手动选服、恢复会话及自动重登成功后,均自动执行已勾选功能,可在顶部停止。获取区服候选或登录失败不视为成功;未确认的写操作不自动重发,页面轮询不会清除游戏连接错误。 -战斗模拟仍为近似模型,特殊关卡并非全部支持。2.0.2 离线回归:后端 **309 项,306 通过、3 项因 Windows 权限或符号链接限制跳过,0 失败、0 错误**;完整浏览器 **52 项全部通过,0 跳过、0 失败**。本版验证范围见 [发布说明](analysis/RELEASE_2_0_2.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 +战斗模拟仍为近似模型,特殊关卡并非全部支持。本版验证结果统一见 [发布说明](analysis/RELEASE_2_0_3.md#验证),历史记录见 [Web 验证说明](ranch_web/README.md#离线验证);离线验证不代表真实游戏 API 或生产升级/回滚验收。 ## 桌面 1.2.0 功能基线 diff --git a/analysis/RELEASE_2_0_3.md b/analysis/RELEASE_2_0_3.md new file mode 100644 index 0000000..a64ee15 --- /dev/null +++ b/analysis/RELEASE_2_0_3.md @@ -0,0 +1,27 @@ +# Web 2.0.3 发布说明 + +Web **2.0.3** 是修复 2.0.2 日志布局的补丁,随正式版本提供在线更新。桌面版保持 **1.2.0**,游戏资料基线保持 **1.9.68**;游戏玩法、自动策略及后端日志分类/持久化沿用现有实现。 + +## 底部日志修复 + +- 所有功能页只复用原有可调高度的底部日志区及工具栏,切换页签后显示当前账号、当前功能的日志。取消页内日志框和总日志/全部模式,调试入口保留。 +- 顶部右侧是唯一显示/隐藏入口。每次整页刷新(F5)或重新进入工作台均默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。同一浏览器会话内显隐按账号保留,手动展开后切换功能页保持展开,隐藏后切页仍保持隐藏。 +- 搜索、清空显示、下载、跟随/暂停及滚动位置按账号、页签隔离。清空不删除服务端历史,下载遵循当前范围与搜索条件;账号切换不串用日志或操作状态。 +- 登录仅显示登录日志,排除常规、混合旧记录及赠礼日志。培育室查看孵蛋日志,其余功能页查看对应执行日志;只读页没有对应日志时显示为空,不补入无关日志。 +- 手动刷新成功时仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 + +功能对应关系与操作说明见 [产品说明](../ranch_web/PRODUCT.md#203-底部分类日志)。 + +## 安装与升级 + +发布目标为 `v2.0.3`,正式镜像为 `ghcr.io/attilanet/myrzx_bot-web:v2.0.3`;对应稳定 Release 与正式镜像均就绪后才可在线安装。 + +已完成 2.0.1 在线更新初始化的宿主机,可通过现有更新器直接安装 2.0.3,无需先安装 2.0.2、重复初始化或替换更新器。“帮助 → 检查版本更新…”仍需有效宿主机心跳并已启用 Web 更新请求;安装结果以宿主机健康检查为准,自动安装默认关闭。升级后刷新网页加载新版界面,底部日志默认收起。操作条件见 [部署说明](../deploy/web/README.md)。 + +## 验证 + +- 独立完整浏览器回归:全新 Edge 会话中 **52/52 项通过**。 +- 离线更新器与独立包回归:**64 项,62 通过、2 项因预期的 Windows 权限/符号链接限制跳过,0 失败、0 错误**。 +- 最终刷新反馈保护仅作用于成功路径;已有刷新用例已在旧日志显示配置为 `true`、`false` 两种情况下复验通过,**复验不重复计数**。 + +后端业务源码未改,本轮未重跑历史 309 项后端回归,也不将其计入本版结果。以上离线验证不代表真实游戏 API 或生产升级/回滚验收。 diff --git a/compose.yaml b/compose.yaml index 8824bc1..330cfa5 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.2} + image: ${RANCH_WEB_IMAGE:-ghcr.io/attilanet/myrzx_bot-web:v2.0.3} build: context: . args: - WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.2} + WEB_VERSION: ${RANCH_WEB_BUILD_VERSION:-2.0.3} user: "10001:10001" init: true restart: unless-stopped diff --git a/deploy/web/README.md b/deploy/web/README.md index edc5d76..14a7ed8 100644 --- a/deploy/web/README.md +++ b/deploy/web/README.md @@ -1,8 +1,8 @@ # Web 2 Linux Docker 部署与更新 -当前更新示例以 `v2.0.2` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 +当前更新示例以 `v2.0.3` 为目标;下文 2.0.1 首次初始化步骤保留历史版本。游戏资料基线为 `1.9.68`,桌面版保留 `1.2.0`。镜像流水线成功、Git tag 与 GitHub Release 是不同的发布步骤:在线更新必须等对应镜像及非草稿、非预发布的 Release 均发布后才能使用。私有仓库未获授权返回 404 属于访问失败,不代表没有版本;只有成功读取列表且没有稳定 2.x 时才显示“暂无正式版”。 -已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 +已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 稳定 Release 与正式镜像就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器。尚未接入私有在线更新的宿主机才需参考下文“已有宿主机首次初始化”。 ## 容器与持久化 @@ -19,7 +19,7 @@ sudo install -m 0600 -o root -g root deploy/web/image.env.example .image.env sudoedit .env .image.env ``` -在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.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,写请求依赖来源校验。 +在 `.env` 填入独立的 `RANCH_WEB_PASSWORD`,这是 Web 管理密码,不是游戏密码;`.image.env` 选择 `RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.3`,需确认对应镜像已发布后再 pull。Compose 默认只发布到宿主机 `127.0.0.1:8765`,容器内监听 `0.0.0.0:8765` 并强制管理密码。使用域名反代时,同时配置 `RANCH_WEB_ALLOWED_HOSTS` 与 `RANCH_WEB_ALLOWED_ORIGINS`;TLS 入口设置 `RANCH_WEB_SECURE_COOKIE=true`。代理保留正确的 Host,写请求依赖来源校验。 `/opt/ranch-web/data` 挂到容器 `/data`,包括账号、加密会话与密钥、配置、SQLite 统计和更新请求;独立于桌面数据。心跳控制目录独立只读挂到 `/run/ranch-updater`。使用 bind mount 的目录必须预先创建,Compose 不会悄悄创建 root 所有、容器无法写入的目录。默认容器用户 `10001:10001`,根文件系统只读,临时文件写到 `/tmp`。不要对现有账号目录重新初始化密钥。 @@ -51,7 +51,7 @@ Web 只读检查官方 GitHub Releases;默认只接受 `v2.MINOR.PATCH`,跳 ### 已完成 2.0.1 初始化的宿主机 -`v2.0.2` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.2 后手动提交更新请求。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 +`v2.0.3` 稳定 Release 与正式镜像发布后,用户打开“帮助 → 检查版本更新…”,检查到 2.0.3 后手动提交更新请求,可从 2.0.1 直接安装。现有私有仓库认证、GHCR 登录与宿主机更新器继续使用;Web 按钮仍要求有效心跳及 `accept_web_requests=true`。请求显示 `pending` 只表示已提交,宿主机完成备份、安装及健康检查后才确认成功;升级完成后刷新网页以加载新版界面,底部日志默认收起。Windows 或未启用执行器时仍仅可检查版本。自动安装默认关闭。 ### 全新宿主机准备 @@ -68,7 +68,7 @@ python3 -B /opt/ranch-web/updater.pyz --version ### 已有宿主机首次初始化(用户自行执行) -以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.2`。 +以下保留 2.0.1 引入私有在线更新时的初始化步骤与 Release 链接,仅供尚未初始化的宿主机参考;已完成私有仓库和 GHCR 认证的部署无需重做。步骤中的 `v2.0.1` 是首次初始化的历史目标,当前应用更新目标为 `v2.0.3`。 前提是原有 `/opt/ranch-web` Compose 部署、数据目录及 `/etc/ranch-web-updater.toml` 均已存在,配置仍由 root 持有。保留原有数据和配置,不重新初始化密钥;数据目录由 `10001:10001` 持有。以下仅初始化在线更新器,不需要复制项目源码或 Compose。 @@ -161,12 +161,12 @@ Windows 或未安装执行器的 Docker 部署仍能检查版本,但按钮会 [web-image.yml](../../.github/workflows/web-image.yml) 仅对官方仓库的严格稳定 `v2.x.y` tag 推送 `ghcr.io/attilanet/myrzx_bot-web:v2.x.y`;校验 `ranch_web.__version__` 必须与 tag 一致,不能只改变镜像 label。PR 与手动运行只测试、构建,不推送。开发分支 push 不触发正式镜像发布,也没有 `latest` 滚动升级通道。CI 执行更新器、私有凭据和独立包回归,并在无外网容器中检查 healthcheck、非 root 数据写权限、无 Qt 和正常停止;镜像发布状态以对应 tag 的工作流结果为准。 -2.0.2 验证范围与结果统一见 [发布说明](../../analysis/RELEASE_2_0_2.md#验证)。以下命令用于更新器离线验证;历史 Windows 离线验证与 Linux 部署烟测见 [Web 运行说明](../../ranch_web/README.md#离线验证),不计入本版验收。可在无 Docker 的机器上构建临时更新器资产并打印计划;`--dry-run` 不联网、不读取凭据、不调用 Docker,也不写文件: +2.0.3 验证结果统一见 [发布说明](../../analysis/RELEASE_2_0_3.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.2 --dry-run +python -B test-artifacts/updater.pyz --config deploy/web/updater.example.toml --apply v2.0.3 --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 f63b7bc..4b53235 100644 --- a/deploy/web/image.env.example +++ b/deploy/web/image.env.example @@ -1,2 +1,2 @@ -# 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 +# Pull only after the v2.0.3 image publishing workflow succeeds and the image is available. +RANCH_WEB_IMAGE=ghcr.io/attilanet/myrzx_bot-web:v2.0.3 diff --git a/ranch_web/PRODUCT.md b/ranch_web/PRODUCT.md index 061f4a5..19ebaef 100644 --- a/ranch_web/PRODUCT.md +++ b/ranch_web/PRODUCT.md @@ -1,8 +1,8 @@ -# 牧羊人之心牧场助手 · Web 2.0.2 +# 牧羊人之心牧场助手 · Web 2.0.3 ## 产品约束 -把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.2`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 +把现有桌面助手的功能和操作结构迁移至单管理员 Web 工作台。桌面版是页面顺序、信息密度、业务名称、保护条件与交互的依据,保留桌面兼容。本轮 Web 发布目标为 `2.0.3`,源码入口 `main`,游戏数据版本 `1.9.68`;桌面正式版保留 `1.2.0`。启动与配置见 [运行说明](README.md),Docker 与更新条件见 [部署说明](../deploy/web/README.md)。 使用者在 Windows 本机配置、验证,随后可在 Linux Docker 常驻运行。多个浏览器访问同一个管理员工作台;账号互相隔离,各账号串行执行,账号之间可以并行。 @@ -10,9 +10,9 @@ 1. 顶部原生风格菜单:账号、策略、配置、帮助。 2. 多账号页签,支持新增、切换、移除。 -3. 当前角色昵称、等级、经验、金币、氪金、体力;随机刷新间隔、绿色开启/红色停止、刷新/预览、调试、日志显隐。 +3. 当前角色昵称、等级、经验、金币、氪金、体力;随机刷新间隔、绿色开启/红色停止、刷新/预览、调试,右上角唯一的日志显示/隐藏按钮。 4. 同桌面顺序的功能页:登录、培育室、背包、牧场、每日事务、自动孵蛋、自动主线、战斗记录、自动赠礼、自动委托、自动探险、自动扫荡、数据分析、执行计划、收益资料。 -5. 可拖动高度、可隐藏的底部日志和常驻状态栏。 +5. 所有功能页共用原有可拖动高度的底部日志区及工具栏,保留常驻状态栏;日志按当前功能筛选,整页刷新或重新进入工作台默认收起。 ## 核心操作 @@ -24,30 +24,30 @@ - 数据分析用真实 DTO 绘制 SVG 条形图,保留来源筛选、体力效率、样本和不确定性说明。没有样本时明确说明。 - 策略统一导入导出;收益 CSV/XLSX 导入与可用数据下载。错误展示具体原因,不把不支持的任务伪装成可执行任务。 - 帮助可检查 GitHub 正式版本并提交受控更新请求。未配置部署器时明确显示原因,更新提交不表示更新成功。 -- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 +- 已在 2.0.1 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 发布就绪后直接通过“帮助 → 检查版本更新…”升级,无需先安装 2.0.2、重复初始化或替换宿主机更新器;升级完成后刷新网页以加载新版界面,安装结果以宿主机健康检查为准。 -## 2.0.2 分类日志 +## 2.0.3 底部分类日志 -各功能页提供当前账号的分类日志面板;底部总日志和调试日志入口继续保留,账号之间不混入日志。 +2.0.3 修复 2.0.2 的日志布局。所有功能页只复用原有底部日志区,切换页签即按当前账号、当前功能过滤;取消总日志/全部模式及页内日志框,调试入口保留。没有对应执行日志的只读页显示为空,不补入无关日志。 -| 功能页 | 分类 | 日志范围 | -| --- | --- | --- | -| 登录 | `login`、`general` | 登录及常规记录,包括混合或无法归类的旧记录 | -| 每日事务 | `daily` | 每日事务记录 | -| 牧场 | `ranch` | 手动牧场操作、自动潜能突破及对应暂停记录 | -| 自动孵蛋 | `hatching` | 孵蛋与牧场整理策略记录,包括自动喂养、出售、收取及暂停 | -| 自动主线 | `mainline` | 主线推进记录 | -| 自动赠礼 | `gifts` | 赠礼记录 | -| 自动委托 | `commissions` | 委托记录 | -| 自动探险 | `exploration` | 探险记录 | -| 自动扫荡 | `maps` | 扫荡及地图挑战记录 | +| 功能页 | 日志范围 | +| --- | --- | +| 登录 | 仅登录记录,排除常规、混合旧记录及赠礼日志 | +| 每日事务 | 每日事务记录 | +| 牧场 | 手动牧场操作、自动潜能突破及对应暂停记录 | +| 自动孵蛋、培育室 | 孵蛋与牧场整理策略记录,包括自动喂养、出售、收取及暂停 | +| 自动主线 | 主线推进记录 | +| 自动赠礼 | 赠礼记录 | +| 自动委托 | 委托记录 | +| 自动探险 | 探险记录 | +| 自动扫荡 | 扫荡及地图挑战记录 | -- 同一账号使用单一共享日志拉取,供总日志与分类面板复用;浏览器共享缓存上限 1200 条,每个面板最多显示最近 600 条。 -- 分类面板提供文字搜索、级别筛选、独立清空显示与下载、隐藏、跟随最新及暂停跟随。清空只影响当前账号当前面板,不清空其他面板或服务端历史;下载遵循本面板的清空范围与筛选条件。 -- 分类随普通运行日志记录持久保存。动作来源上下文优先于通用文字前缀;孵蛋/牧场整理策略产生的“暂停喂养”归入 `hatching`,不因文字中包含喂养而改归 `ranch`。 -- 无分类旧记录仅在所有片段的明确前缀一致指向同一类别时保守推断;不拆分或强行重分混合记录。混合、未知或无法识别的类别保留为 `general`,在总日志和登录面板可见。 +- 顶部右侧是唯一显示/隐藏入口。每次整页刷新(F5)或重新进入工作台默认收起,不沿用旧配置自动展开;配置/状态刷新及调试模式不展开日志。同一浏览器会话内显隐按账号保留,手动展开或隐藏后,切换功能页保持该选择。 +- 原底部工具栏保留。搜索、清空显示、下载、跟随/暂停及滚动位置按账号、页签隔离;清空不删除服务端历史,下载遵循当前范围与搜索条件,账号切换不串用内容或操作状态。 +- 同一账号共用日志拉取;浏览器缓存最多 1200 条,底部最多显示最近 600 条。已有分类与保守旧记录推断沿用原实现,无法明确归属的记录不补入登录或其他功能日志。 +- 手动刷新成功时仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 -功能与验证范围见 [2.0.2 发布说明](../analysis/RELEASE_2_0_2.md)。 +本补丁只调整日志展示与 Web 版本元数据,游戏玩法、策略及后端日志分类/持久化沿用现有实现。功能与验证范围见 [2.0.3 发布说明](../analysis/RELEASE_2_0_3.md)。 ## 安全与验证 diff --git a/ranch_web/README.md b/ranch_web/README.md index c333466..9412cd3 100644 --- a/ranch_web/README.md +++ b/ranch_web/README.md @@ -1,6 +1,6 @@ -# Web 2.0.2 运行说明 +# Web 2.0.3 运行说明 -本轮 Web 发布目标 **2.0.2**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 +本轮 Web 发布目标 **2.0.3**,源码入口 `main`,游戏资料基线 **1.9.68**。桌面正式版保留 **1.2.0**,入口为 `python -m ranch_assistant`;Web 使用独立依赖与数据根。 Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或前端编译步骤,不安装 PySide6。页面和策略能力沿用现有核心,详细业务范围与原有限制见 [桌面使用说明](../ranch_assistant/README.md)。多浏览器连接同一个管理员工作台;一个服务实例内,各账号独立线程并行,同一账号操作串行。 @@ -10,8 +10,8 @@ Web 采用 FastAPI / Uvicorn 和原生 HTML/CSS/ES 模块,无 Node、npm 或 - [x] 保留账号页签、顶部数值与统一启停、可调日志;规则自动保存,配置与统计按账号/角色隔离,每次成功登录后自动执行已配置且已勾选的功能,可在顶部停止。 - [x] Windows Python 启动与离线演示;Web 导入链和依赖不使用 Qt,无 Node 构建步骤。 - [x] 提供 Linux Docker 与稳定 2.x 受控更新、停机备份及失败回滚脚本;历史 Linux Docker 部署、持久化权限、健康检查和定时更新检查烟测见下文。 -- [x] 本轮发布目标为 `2.0.2`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 -- [x] 2.0.2 提供九个功能页的账号分类日志面板,保留总日志与调试入口;页面和分类对应关系见 [产品说明](PRODUCT.md#202-分类日志),验证范围见 [发布说明](../analysis/RELEASE_2_0_2.md#验证)。 +- [x] 本轮发布目标为 `2.0.3`,保留桌面兼容;战斗模拟为近似模型,特殊关卡并非全部支持,真实游戏 API 验收范围不因版本号变更而扩大。 +- 2.0.3 修复 2.0.2 日志布局:所有页签复用原有底部日志区,按当前账号与功能筛选,默认收起;操作约定见 [产品说明](PRODUCT.md#203-底部分类日志),验收结果见 [发布说明](../analysis/RELEASE_2_0_3.md#验证)。 ## Windows 本地运行 @@ -41,15 +41,17 @@ py -3 -m venv .venv-web 服务重启会保留配置与加密会话;未启用自动重登录时,需要手动恢复会话。普通运行日志在各账号目录中限量持久保存,服务重启后仍可查看;调试请求详情仅在当前进程中按原有上限缓存。页面展示旧角色数据时会标注缓存状态,不把页面刷新视作游戏连接成功。 -### 分类日志(2.0.2) +### 底部分类日志(2.0.3) -登录、每日事务、牧场、自动孵蛋、自动主线、自动赠礼、自动委托、自动探险和自动扫荡均提供当前账号的分类日志面板,底部总日志与调试入口继续保留。同一账号使用单一共享日志拉取,不为每个功能页另开轮询;浏览器共享缓存最多保留 1200 条,各日志面板最多显示最近 600 条。这些是浏览器缓存与显示上限,不改变普通日志的服务端持久保存范围。 +所有功能页只复用原有可调高度的底部日志区及工具栏,切换页签后按当前账号、当前功能筛选。取消总日志/全部模式及功能页内嵌日志框,调试入口保留。培育室查看孵蛋日志;其他只读页无对应执行日志时显示为空,不补入无关日志。功能对应关系见 [产品说明](PRODUCT.md#203-底部分类日志)。 -面板支持文字搜索和级别筛选,可独立隐藏、清空显示或下载日志;下载遵循当前账号、本页清空范围及筛选条件。清空一个面板不清空总日志或其他面板,也不删除服务端历史记录。阅读历史时可暂停跟随;向上滚动会暂停自动跟随,点击“跟随最新”可回到底部。底部总日志保留独立的清空、下载与跟随控制。 +顶部右侧是唯一的日志显示/隐藏入口。每次整页刷新(F5)或重新进入工作台均默认收起,即使旧配置为显示也不自动展开;配置/状态刷新及调试模式不展开日志。同一浏览器会话内,显隐按账号保留,手动展开后切换功能页保持展开,隐藏后切页仍保持隐藏。 -分类随普通日志记录持久保存。孵蛋/牧场整理策略中的自动喂养、出售、收取及其暂停记录归入自动孵蛋(`hatching`);手动牧场操作和自动潜能突破归入牧场(`ranch`)。动作来源上下文优先于通用文字前缀,因此源自孵蛋策略的“暂停喂养”仍属于孵蛋日志。 +搜索、清空显示、下载、跟随/暂停及滚动位置按账号、页签隔离。清空只影响当前范围的显示,不删除服务端历史;下载遵循相同的清空范围与搜索条件。向上滚动可暂停跟随,点击“跟随最新”回到底部;切换账号或功能页不会串用其他上下文的日志或操作状态。同一账号共用日志拉取,浏览器缓存最多 1200 条,底部最多显示最近 600 条。 -没有分类字段的旧记录,仅在各片段均有明确前缀且一致指向同一类别时保守推断归属;不拆分旧记录,也不根据偶然出现的功能词猜测。混合类别、未知前缀及无法识别的分类保留为常规(`general`)记录,可在总日志和登录面板查看;登录面板同时包含登录与常规日志。 +已有分类与保守旧记录推断沿用原实现。孵蛋/牧场整理策略中的自动喂养、出售、收取及暂停归入孵蛋;手动牧场操作与自动潜能突破归入牧场。登录仅显示登录日志,排除常规、混合旧记录及赠礼日志;无法明确归属当前功能的记录不回退为全部显示。 + +手动刷新成功时仅显示简短状态,详细日志只在原底部日志区查看,不弹出诊断提示或大段浮动消息,也不自动展开日志;错误与登录认证反馈沿用原有行为。 ### 掉线后自动重新登录 @@ -92,19 +94,19 @@ sh start-web.sh --no-browser 完整步骤、已有部署更新与首次私有更新器初始化见 [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,应用根文件系统只读;健康检查及转发返回 HTTP 200,Edge 管理登录后可访问 15 个功能页且无 JavaScript 错误,更新定时器已启用并成功完成首次 GitHub 检查。当时后续登录页调整仅记录了本地验证,重新部署与真实游戏 API 验收尚未完成;此历史状态及烟测结果均不作为 2.0.2 的验收结论。 +历史部署烟测(独立管理登录页调整前):曾在 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.3 的验收结论。 Web 检查固定官方 GitHub Releases 的稳定 `v2.x.y`,跳过桌面 1.x、未来 3.x、草稿和预发布。开发版本 `2.0.0.dev1` 可升级至同数字的正式 `v2.0.0`;没有正式 Web 2 发布时明确显示暂无更新。Windows 默认仅检查;Web “更新”按钮仅在宿主机显式启用并有有效只读心跳时可提交 `pending` 请求,安装、备份和回滚由宿主机执行。默认定时检查只通知,自动安装需操作者 opt-in。 -已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.2 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.2**,无需重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 +已在 **2.0.1** 完成私有仓库和 GHCR 认证的部署,可在 2.0.3 稳定 Release 和正式镜像就绪、宿主机心跳有效后,直接通过“帮助 → 检查版本更新…”升级 **2.0.3**,无需先安装 2.0.2、重复初始化或替换宿主机更新器。升级完成后刷新网页以加载新版界面,底部日志默认收起。安装结果以宿主机健康检查为准;首次配置仅供尚未初始化的宿主机参考。 ## 离线验证 -### 2.0.2 发布验证 +2.0.3 验证结果统一见 [发布说明](../analysis/RELEASE_2_0_3.md#验证),以下历史记录不计入本版验收。 -后端独立回归 **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.3) -### 历史验证记录(不计入 2.0.2) +2.0.2 验证记录见 [历史发布说明](../analysis/RELEASE_2_0_2.md#验证)。 2.0.1 发布回归:后端及更新器 **297 项中 294 通过、3 项因 Windows 权限或软链接限制跳过**,浏览器 **43 项全部通过**。更新器专项命令增加 `ranch_web.tests.test_private_updates ranch_web.tests.test_web_updater_package`;Linux 镜像工作流也执行这两项模块,验证独立包、私有认证与容器健康。 diff --git a/ranch_web/__init__.py b/ranch_web/__init__.py index a48ffb8..46ce062 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.2" +__version__ = "2.0.3" GAME_VERSION = "1.9.68" __all__ = ["__version__", "GAME_VERSION"] diff --git a/ranch_web/static/app.js b/ranch_web/static/app.js index 7ba2d26..2362d23 100644 --- a/ranch_web/static/app.js +++ b/ranch_web/static/app.js @@ -3,7 +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'; +import {createLogState, logView, mergeLogs, visibleLogs, syncLogLines, logText} 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); @@ -174,7 +174,7 @@ function editConfig(account,path,value,field={},row) { syncSaveStatus(account); // Update other controls, while every control protects its own focused input. account.pages.forEach(page=>page.data&&page.render(page.data)); - if (path[0]==='log_visible'||path[0]==='log_sizes') applyLogLayout(account); + if (path[0]==='log_sizes') applyLogLayout(account); } async function flushConfig(account=current()) { @@ -261,8 +261,8 @@ async function perform(account,operation,payload={},options={}) { const page=options.page || account.pages.get(account.page);if(page)await loadPage(page,true); if(operation==='login'&&result)account.pages.get('login')?.login?.update(result); const message=loginOperations.has(operation)?account.summary.running?'已读取角色,已自动开启策略,执行已配置且已勾选的功能;可在顶部“停止”。':'已读取角色。策略已停止,可在顶部“开启”继续执行已勾选功能。':result?.message; - if(message)notice(message); - setStatus(message || `${operationLabels[operation] || '操作'}已完成`); + if(message && operation!=='refresh')notice(message); + setStatus(operation==='refresh'?'状态已刷新':message || `${operationLabels[operation] || '操作'}已完成`); return result; } @@ -271,7 +271,6 @@ 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); } @@ -292,18 +291,19 @@ async function loadPage(page,force=false) { function selectPage(key) { const account=current();if(!account)return; + saveLogScroll(account); if(account.page!==key)account.pages.get(account.page)?.login?.clearPassword(); 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(); + renderLogs(); $$('.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; + saveLogScroll(previous); if(previous?.edits.size)flushConfig(previous).catch(error); state.active=id;const account=current();if(!account)return; $('#page-host').querySelector('.initial-state')?.remove(); @@ -378,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.2'}`}),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.3'}`}),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.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==='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;renderLogs(true);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'){ @@ -475,17 +475,24 @@ async function showUpdates() { } function setLogVisible(visible) { - const account=current();if(account?.config)editConfig(account,['log_visible'],visible); - else applyLogLayout(null,visible); + const account=current();if(!account)return; + saveLogScroll(account); + account.logs.visible=Boolean(visible); + applyLogLayout(account); } -function applyLogLayout(account=current(),visibleOverride) { +function saveLogScroll(account=current()) { + const root=$('#log-lines'); + if(account && !$('#log-panel').hidden && root.dataset.account===account.id && root.dataset.page===account.page) + logView(account.logs,account.page).scrollTop=root.scrollTop; +} + +function applyLogLayout(account=current()) { if(account&&account.id!==state.active)return; - const visible=visibleOverride ?? account?.config?.log_visible ?? true; - 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 visible=Boolean(account?.logs.visible); + $('#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(); + renderLogs(); } function setLogHeight(height) { @@ -494,28 +501,32 @@ function setLogHeight(height) { } function renderLogs(reset=false) { - const account=current(),root=$('#log-lines');if(!account){root.replaceChildren();return;} + const account=current(),root=$('#log-lines'); + const title=`${PAGES.find(([key])=>key===account?.page)?.[1] || ''}日志`; + $('#log-heading').textContent=title;$('#log-panel').setAttribute('aria-label',title);root.setAttribute('aria-label',`${title}内容`); + $('#log-search').setAttribute('aria-label',`${title}搜索`); + if(!account){root.replaceChildren();delete root.dataset.account;delete root.dataset.page;$('#log-count').textContent='';return;} + const log=account.logs,view=logView(log,account.page); + $('#log-follow').checked=view.follow;$('#debug-log').checked=log.debug; + if($('#log-search').value!==view.search)$('#log-search').value=view.search; if($('#log-panel').hidden)return; - const log=account.logs,view=log.total; - const switching=root.dataset.account!==account.id; + const switching=root.dataset.account!==account.id || root.dataset.page!==account.page; const scrollTop=switching?view.scrollTop:root.scrollTop; reset=reset || switching; - const token=JSON.stringify([log.revision,view.clearedThrough,log.debug]); + const token=JSON.stringify([log.revision,view.clearedThrough,log.debug,view.search]); if(!reset && view.rendered===token)return; - const entries=visibleLogs(log,view); + const entries=visibleLogs(log,view,account.page); 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; + root.dataset.account=account.id;root.dataset.page=account.page;view.rendered=token; 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; mergeLogs(account.logs,response.entries || [],response.next); - if(account.id===state.active){renderLogs();currentPage()?.taskLog?.render();} + if(account.id===state.active)renderLogs(); transportError(account,'logs','日志',null); }catch(failure){if(generation===(account.logs.generation || 0))transportError(account,'logs','日志',failure);}finally{account.logs.loading=false;} } @@ -533,7 +544,7 @@ async function showDebugEntry(account,entry) { function showNoAccounts() { state.active=null;$('#page-host').replaceChildren(el('div',{class:'initial-state'},el('p',{text:'尚未添加账号。新增账号后登录游戏,或使用离线演示查看工作台。'}),el('div',{class:'page-toolbar'},el('button',{text:'新增账号…',onClick:()=>command('add-account')}),el('button',{text:'新增离线演示账号',onClick:()=>command('add-demo')})))); - renderAccountTabs();renderSummary();renderLogs(true);setStatus('等待新增账号'); + renderAccountTabs();renderSummary();applyLogLayout();setStatus('等待新增账号'); } async function syncAccounts() { @@ -562,6 +573,9 @@ async function tick() { } function hideWorkbench() { + saveLogScroll(); + state.accounts.forEach(account=>account.logs.visible=false); + applyLogLayout(); state.ready=false; $('#app').hidden=true;$('#notice').hidden=true; $$('dialog[open]').forEach(root=>root.close()); @@ -581,7 +595,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.2';$('#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.3';$('#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})));} } @@ -599,10 +613,11 @@ $('#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',()=>{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;}); +$('#clear-log').addEventListener('click',()=>{const account=current();if(account){logView(account.logs,account.page).clearedThrough=account.logs.highWater;renderLogs();}}); +$('#download-log').addEventListener('click',()=>{const account=current();if(account)download(new Blob([logText(visibleLogs(account.logs,logView(account.logs,account.page),account.page))],{type:'text/plain;charset=utf-8'}),`${$('#log-heading').textContent}.txt`);}); +$('#log-search').addEventListener('input',event=>{const account=current();if(account){logView(account.logs,account.page).search=event.target.value;renderLogs();}}); +$('#log-lines').addEventListener('scroll',()=>{const node=$('#log-lines'),account=current();if(!account || $('#log-panel').hidden || node.dataset.account!==account.id || node.dataset.page!==account.page)return;const view=logView(account.logs,account.page);view.scrollTop=node.scrollTop;if(node.scrollHeight-node.scrollTop-node.clientHeight>55){$('#log-follow').checked=false;view.follow=false;}}); +$('#log-follow').addEventListener('change',()=>{const account=current(),node=$('#log-lines');if(!account || $('#log-panel').hidden || node.dataset.account!==account.id || node.dataset.page!==account.page)return;const view=logView(account.logs,account.page);view.follow=$('#log-follow').checked;if(view.follow)node.scrollTop=node.scrollHeight;view.scrollTop=node.scrollTop;}); 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 13465a2..9c90493 100644 --- a/ranch_web/static/index.html +++ b/ranch_web/static/index.html @@ -26,21 +26,21 @@ - 牧羊人之心牧场助手 2.0.2 + 牧羊人之心牧场助手 2.0.3 正在连接本地服务
未登录—等级 —经验 —金币 —氪金 —体力 —
-
+
等待连接服务配置未载入
正在载入工作台…
- -
总日志
+ + diff --git a/ranch_web/static/styles.css b/ranch_web/static/styles.css index 10fb314..e20f9eb 100644 --- a/ranch_web/static/styles.css +++ b/ranch_web/static/styles.css @@ -10,21 +10,7 @@ @media(max-width:1000px){.window-title{display:none}.toolbar{gap:5px}.run-controls{width:100%}.player-line{gap:10px}.page-tab{padding-left:8px;padding-right:8px}.form-grid{grid-template-columns:repeat(2,minmax(240px,1fr))}.statistics-picker{width:220px}} @media(max-width:650px){:root{--log-height:120px}.workbench{min-width:340px}.window-header{gap:5px}.menu>summary{padding:5px 7px}.access-key{display:none}#access-mode{font-size:11px}.toolbar{padding:6px}.player-line{gap:7px 10px}.player-line>strong{max-width:135px}.experience progress{display:none}.run-controls{gap:4px}.run-controls>button{padding-left:7px;padding-right:7px;font-size:12px}.form-grid{grid-template-columns:1fr}.field>.field-label{min-width:120px}.field-wide{grid-column:auto}.login-layout{padding:3px}.login-layout .field{align-items:stretch;flex-direction:column;gap:4px}.login-layout .field>.field-label{flex-basis:auto;min-width:0}.login-layout input[type=text],.login-layout input[type=password]{width:100%}.login-options,.login-actions{margin-left:0}.server-row{flex-wrap:wrap}.statistics-layout{flex-direction:column}.statistics-picker{width:100%;max-height:130px}.log-toolbar{gap:7px}#download-log{display:none}.status-bar{gap:8px}.status-bar #game-version{display:none}dialog .field{flex-direction:column;align-items:stretch}dialog .field-label{flex-basis:auto}#save-status{max-width:160px;overflow:hidden;text-overflow:ellipsis}} @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} +.page-content{display:flex;flex-direction:column;gap:7px;flex:1;min-height:160px;overflow:auto}.page-panel[data-page=login]>.page-content{flex:0 0 auto;min-height:0;overflow:visible}.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}} +.log-toolbar{flex-wrap:wrap;gap:5px 13px}.log-toolbar input[type=search]{width:170px;min-width:100px;max-width:100%} diff --git a/ranch_web/static/task-logs.js b/ranch_web/static/task-logs.js index d200861..a06386f4 100644 --- a/ranch_web/static/task-logs.js +++ b/ranch_web/static/task-logs.js @@ -1,14 +1,18 @@ -import {el, chinaTime, textValue, download} from './dom.js'; +import {el, chinaTime, textValue} 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; +const pageCategories = {login:'login', daily:'daily', ranch:'ranch', hatching:'hatching', mainline:'mainline', gifts:'gifts', commissions:'commissions', exploration:'exploration', maps:'maps', incubator:'hatching'}; export function createLogState() { return {entries:[], next:0, highWater:0, retainedAfter:0, revision:0, debug:false, loading:false, - total:{clearedThrough:0, follow:true, scrollTop:0}}; + visible:false, views:new Map()}; +} + +export function logView(log, page) { + if (!log.views.has(page)) log.views.set(page, {clearedThrough:0, follow:true, scrollTop:0, search:''}); + return log.views.get(page); } const levelOf = entry => String(entry.level || entry.kind || (entry.debug ? 'debug' : 'info')).toLowerCase(); @@ -18,8 +22,8 @@ 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. +// Each account keeps one bounded history. A cursor rewind for debug must not +// reintroduce evicted records or move any tab's local clear watermark. export function mergeLogs(log, entries, next) { const bySequence = new Map(log.entries.map(entry => [entry.seq, entry])); let changed = false; @@ -47,8 +51,9 @@ export function mergeLogs(log, entries, next) { } export function visibleLogs(log, view, page) { + const category = Object.hasOwn(pageCategories, page) ? pageCategories[page] : null; return log.entries.filter(entry => entry.seq > view.clearedThrough && (log.debug || !debugEntry(entry)) - && (!page || entry.category === page || page === 'login' && entry.category === 'general') + && entry.category === category && (!view.level || levelOf(entry) === view.level) && (!view.search || messageOf(entry).toLocaleLowerCase().includes(view.search.toLocaleLowerCase()))); } @@ -106,86 +111,3 @@ export function syncLogLines(root, entries, {follow, reset=false, scrollTop, ins 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 8f95fbe..81c666a 100644 --- a/ranch_web/tests/browser/test_base_path_browser.py +++ b/ranch_web/tests/browser/test_base_path_browser.py @@ -126,14 +126,17 @@ class BasePathBrowserTests(unittest.TestCase): self.assertEqual(context.cookies()[0]["path"], prefix or "/") self.assertEqual(page.evaluate("localStorage.length + sessionStorage.length"), 0) + page.locator("#log-panel").evaluate("node => {window.__originalLogPanel=node;}") for key in "login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split(): page.locator(f'.page-tab[data-page="{key}"]').click() 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') + expect(page.locator('[data-task-log], .task-log-panel')).to_have_count(0) + expect(page.locator('#log-panel')).to_be_hidden() + expect(page.locator('#log-lines')).to_have_attribute('role', 'log') + expect(page.locator('#log-lines')).to_have_attribute('aria-live', 'off') + self.assertTrue(page.locator('#log-panel').evaluate("node => node===window.__originalLogPanel && node.parentElement===document.querySelector('#workspace').parentElement && !document.querySelector('#workspace').contains(node)")) # The server redirects an authenticated login URL back to this workbench. page.goto(base + "/login", wait_until="networkidle") diff --git a/ranch_web/tests/browser/test_task_logs_browser.py b/ranch_web/tests/browser/test_task_logs_browser.py index e258118..9966d3c 100644 --- a/ranch_web/tests/browser/test_task_logs_browser.py +++ b/ranch_web/tests/browser/test_task_logs_browser.py @@ -1,11 +1,12 @@ -"""Per-page logs use synthetic records, disposable demos and loopback HTTP only. +"""The original bottom log region, with synthetic records 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 re +import time import unittest from unittest.mock import patch from urllib.parse import parse_qs, urlsplit @@ -24,23 +25,23 @@ class TaskLogsBrowserTests(unittest.TestCase): open = fixtures.WorkbenchBrowserTests.open go = fixtures.WorkbenchBrowserTests.go fulfill = staticmethod(fixtures.WorkbenchBrowserTests.fulfill) + viewports = ((1920, 860), (1280, 800), (390, 844)) 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.escapes, self.requests, self.log_calls = [], [], [] self.records = {self.first: [], self.second: []} - self.log_calls = [] - self.page.add_init_script("""(() => { + self.poll_script = """(() => { const original = window.setInterval; window.setInterval = (callback, delay, ...args) => { if (callback.name === 'tick') {window.__pollLogs = callback;return -1;} return original(callback, delay, ...args); }; - })();""") + })();""" + self.page.add_init_script(self.poll_script) def local_only(route): if route.request.url.startswith(self.base + "/"): @@ -49,6 +50,7 @@ class TaskLogsBrowserTests(unittest.TestCase): self.escapes.append(route.request.url) route.abort() + self.local_only = local_only self.context.route("**/*", local_only) self.page.on("request", lambda request: self.requests.append(request)) @@ -64,6 +66,7 @@ class TaskLogsBrowserTests(unittest.TestCase): for entry in records if entry["seq"] > after and (debug or not entry.get("debug"))], "next": records[-1]["seq"] if records else 0}) + self.serve_logs = logs self.page.route("**/api/accounts/*/logs?*", logs) def tearDown(self): @@ -83,110 +86,360 @@ class TaskLogsBrowserTests(unittest.TestCase): return seq def poll(self): + self.page.wait_for_load_state("networkidle") before = len(self.log_calls) - with self.page.expect_response(lambda response: "/logs?" in response.url): + account = self.page.locator('.account-tab[aria-selected="true"]').get_attribute("data-account") + with self.page.expect_request(lambda request: f"/accounts/{account}/logs?" in request.url) as pending: 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") + pending.value.response().finished() + self.assertEqual(len(self.log_calls), before + 1, "One shared log request per poll, regardless of visited pages") + + def wait_saved(self): + # The fixture parks tick() to count shared fetches; keep its job polling + # moving while the real debounced configuration save is in flight. + deadline = time.monotonic() + 10 + while self.page.locator("#save-status").inner_text() != "策略已自动保存" and time.monotonic() < deadline: + self.page.evaluate("async () => {await window.__pollLogs();}") + self.page.wait_for_timeout(50) + fixtures.WorkbenchBrowserTests.wait_saved(self) + + def original_region(self): + panel = self.page.locator("#log-panel") + expect(panel).to_have_count(1) + expect(self.page.locator("#log-resizer")).to_have_count(1) + expect(self.page.locator("[data-task-log], .task-log-panel, .task-log-lines, .has-task-log, iframe")).to_have_count(0) + expect(self.page.locator('[role="log"]')).to_have_count(1) + expect(self.page.locator("#log-lines")).to_have_attribute("aria-live", "off") + expect(self.page.locator('[aria-controls="log-panel"]')).to_have_count(1) + self.assertTrue(panel.evaluate("""node => { + const workspace=document.querySelector('#workspace'), resizer=document.querySelector('#log-resizer'); + window.__originalLogPanel ??= node; + window.__originalLogResizer ??= resizer; + return node===window.__originalLogPanel && resizer===window.__originalLogResizer + && node.parentElement===workspace.parentElement && resizer.parentElement===workspace.parentElement + && workspace.nextElementSibling===resizer && resizer.nextElementSibling===node + && !workspace.contains(node) && !workspace.contains(resizer); + }"""), "Tabs and accounts must reuse the original siblings after #workspace") + self.assertNotRegex(panel.inner_text(), r"总日志|全部日志") + return panel def task(self, key): - return self.go(key).locator(f'.task-log-panel[data-task-log="{key}"]') + self.go(key) + panel = self.original_region() + label = self.page.locator(f'.page-tab[data-page="{key}"]').inner_text() + expect(self.page.locator("#log-heading")).to_have_text(label + "日志") + return panel - def download(self, button): + def toggle(self, visible): + panel = self.page.locator("#log-panel") + (expect(panel).to_be_hidden if visible else expect(panel).to_be_visible)() + self.page.locator("#log-toggle").click() + (expect(panel).to_be_visible if visible else expect(panel).to_be_hidden)() + expect(self.page.locator("#log-toggle")).to_have_attribute("aria-expanded", str(visible).lower()) + (expect(self.page.locator("#log-resizer")).to_be_visible if visible + else expect(self.page.locator("#log-resizer")).to_be_hidden)() + + def download(self): with self.page.expect_download() as pending: - button.click() + self.page.locator("#download-log").click() return Path(pending.value.path()).read_text(encoding="utf-8") - def test_categories_legacy_safety_and_all_fifteen_tabs(self): + def refresh_config(self, visible): + config = self.manager.get_config(self.first)["config"] + config.update(log_visible=visible, interval=60 if config["interval"] != 60 else 120) + response = self.manager.set_config(self.first, config) + self.await_job(self.first, response["job_id"]) + with self.page.expect_response(self.base + f"/api/accounts/{self.first}/config"): + self.poll() + self.wait_saved() + + def refresh_job(self): + with self.page.expect_response(self.base + f"/api/accounts/{self.first}/status"): + with self.page.expect_response(self.base + f"/api/accounts/{self.first}/actions/refresh") as pending: + self.page.locator("#refresh").click() + self.await_job(self.first, pending.value.json()["id"]) + self.poll() + + def click_unobscured(self, control): + expect(control).to_be_visible() + expect(control).to_be_enabled() + control.evaluate("""node => { + window.__logControlClick=null; + node.addEventListener('click', event => {window.__logControlClick=[event.isTrusted && event.detail>0, + node.contains(document.elementFromPoint(event.clientX,event.clientY)), + !document.querySelector('#log-panel').hidden];}, {once:true}); + }""") + control.click(timeout=5000) + self.assertEqual(self.page.evaluate("window.__logControlClick"), [True, True, True], + "A normal pointer click must hit the original control with logs still open") + expect(self.page.locator("#log-panel")).to_be_visible() + + def layout_artifact(self, key): + panel = self.original_region() + geometry = panel.evaluate("""node => { + const log=node.getBoundingClientRect(), workspace=document.querySelector('#workspace').getBoundingClientRect(); + const resizer=document.querySelector('#log-resizer').getBoundingClientRect(); + const content=document.querySelector('.page-panel:not([hidden])').getBoundingClientRect(); + return {gap:log.top-workspace.bottom, splitterGap:resizer.top-workspace.bottom, + logGap:log.top-resizer.bottom, content:content.height, lines:document.querySelector('#log-lines').clientHeight, + overflow:document.documentElement.scrollWidth-innerWidth, right:log.right-innerWidth}; + }""") + for gap in ("gap", "splitterGap", "logGap"): + self.assertGreaterEqual(geometry[gap], -1, geometry) + self.assertGreaterEqual(geometry["content"], 120, geometry) + self.assertGreaterEqual(geometry["lines"], 60, geometry) + self.assertLessEqual(geometry["overflow"], 1, geometry) + self.assertLessEqual(geometry["right"], 1, geometry) + viewport = self.page.viewport_size + target = Path(__file__).resolve().parents[3] / "test-artifacts" / "logfix" + target.mkdir(parents=True, exist_ok=True) + self.page.screenshot(path=str(target / f"{key}-{viewport['width']}x{viewport['height']}.png")) + + def dense_fixture(self): + categories = ("general", "gifts", "maps", "login", "gifts", None, "gifts", "maps") + for i in range(1120): + category = categories[i % len(categories)] + message = f"synthetic-{category}-{i:04} 合成离线记录:" + "长文本赠礼与区服结算数据" * 20 + if i % 3 == 0: + message += "\n多行明细:合成道具 × 3\n仅供布局回归,不连接游戏。" + self.add(category, message, level="warning" if i % 7 == 0 else "info") + login = {"account": "offline-layout-" + "synthetic" * 8, "has_saved_password": False, + "servers": [{"id": i, "name": f"合成区服 {i} " + "长区服名称" * 12, + "role_name": "离线角色" * 12} for i in range(1, 37)], + "saved_sessions": [{"id": f"layout-session-{i}", "label": f"合成会话 {i} " + "长账号区服角色说明" * 12} + for i in range(1, 37)]} + + def view(route): + response = route.fetch().json() + data = response.get("data") + key = urlsplit(route.request.url).path.rsplit("/", 1)[1] + if data and key == "login": + data["login"] = login + for field in data["form"]: + field["help"] = field.get("help", "") + " 合成长表单说明:记住账号后,选择原区服角色并等待服务端状态。" * 5 + elif data and key == "maps": + data["summary"] = "合成离线关卡:显示 48 关;仅供布局回归,不连接游戏。" + data["groups"] = [{"id": "demo", "label": "合成测试区域", "collapsed": False}] + data["rows"] = [{"id": f"synthetic{i}", "group": "demo", "number": f"1-{i + 1}", + "name": f"合成关卡 {i + 1}", "enabled": False, "level": "3", "limit": 3, + "stars_text": "★★★", "status": "等待下次扫荡", "used": i % 3, + "cost_text": "体力 单次 6 / 可用 100 / 保留 0", "drops": "合成金币与材料", + "rule_path": ["sweep_policy", "rules", f"synthetic{i}"], + "rule_defaults": {"enabled": False, "level": "3", "limit": 3}} for i in range(48)] + elif data and key == "gifts": + data["rows"] = [{"id": str(i), "species": f"合成魔物 {i + 1}", "monster_id": i + 1, + "level": 30, "feel_text": "60 / 100", "quality": "S / A / A / S", + "likes": "合成礼物", "cooldown": "可赠礼"} for i in range(48)] + self.fulfill(route, response) + + for key in ("login", "maps", "gifts"): + self.page.route(f"**/api/accounts/{self.first}/views/{key}?*", view) + return login + + def test_single_original_region_strict_categories_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") + self.add(None, "legacy-mixed-gift") + self.add("future-category", "unknown-mixed-gift") 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) + self.original_region() + expect(self.page.locator("#log-panel")).to_be_hidden() + self.toggle(True) 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) + with self.subTest(category=key): + panel = self.task(key) + expect(panel).to_be_visible() + body = panel.locator("#log-lines") + expect(body).to_contain_text(f"only-{key}") + expect(body.locator(".log-entry")).to_have_count(2 if key == "hatching" else 1) + for excluded in ("legacy-mixed-gift", "unknown-mixed-gift", *(f"only-{other}" for other in categories if other != key)): + expect(body).not_to_contain_text(excluded) + if key == "hatching": + expect(body).to_contain_text(unsafe) + expect(body.locator("img,script")).to_have_count(0) + self.task("incubator") + expect(self.page.locator("#log-lines")).to_contain_text("only-hatching") + expect(self.page.locator("#log-lines .log-entry")).to_have_count(2) + for key in "bag battles statistics plans yields".split(): + self.task(key) + expect(self.page.locator("#log-lines .log-entry")).to_have_count(0) + self.assertEqual(self.download(), "", "Read-only pages have no invented all-category mode") 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) + def test_first_paint_both_legacy_configs_debug_and_passive_refreshes_stay_collapsed(self): + self.add("login", "login-before-config") + detail_marker = "LOGFIX_REFRESH_DETAIL_ONLY_IN_ORIGINAL_LOG_REGION_7c91" + self.page.route(self.base + f"/api/accounts/{self.first}/actions/refresh", lambda route: self.fulfill(route, { + "id": "logfix-refresh", "operation": "refresh", "status": "succeeded", + "result": {"message": detail_marker + "\nEngine diagnostic: synthetic mixed gift/login log details."}, + "error": None, + })) + config_url = self.base + f"/api/accounts/{self.first}/config" + for legacy_visible in (True, False): + with self.subTest(legacy_log_visible=legacy_visible): + config = self.manager.get_config(self.first)["config"] + config["log_visible"] = legacy_visible + pending = self.manager.set_config(self.first, config) + self.await_job(self.first, pending["job_id"]) + held = [] + self.page.route(config_url, lambda route: held.append(route)) + with self.page.expect_request(config_url): + response = self.page.goto(self.base, wait_until="domcontentloaded") + for identifier in ("log-panel", "log-resizer"): + tag = re.search(r'<[^>]+\bid="' + identifier + r'"[^>]*>', response.text()) + self.assertIsNotNone(tag, f"Original #{identifier} must exist in the HTML") + self.assertRegex(tag.group(), r"\bhidden(?:\s|=|>)", "The HTML itself must be collapsed before config loads") + expect(self.page.locator("#" + identifier)).to_be_hidden() + self.original_region() + expect(self.page.locator("#log-toggle")).to_have_attribute("aria-expanded", "false") + self.assertEqual(len(held), 1) + self.page.unroute(config_url) + self.fulfill(held[0], self.manager.get_config(self.first)) + self.wait_saved() + self.poll() + expect(self.page.locator("#log-panel")).to_be_hidden() + for debug in ("true", "false"): + with self.page.expect_response(lambda response: f"/logs?after=0&debug={debug}" in response.url): + self.page.locator("#debug-toggle").click() + expect(self.page.locator("#log-panel")).to_be_hidden() + self.refresh_config(not legacy_visible) + with self.page.expect_response(self.base + f"/api/accounts/{self.first}/status"): + self.page.locator("#refresh").click() + expect(self.page.locator("#status-text")).to_have_text("状态已刷新") + expect(self.page.locator("#log-panel")).to_be_hidden() + expect(self.page.locator("#notice")).not_to_contain_text(detail_marker) + outside_logs = self.page.locator("body").evaluate("""node => { + const copy=node.cloneNode(true);copy.querySelector('#log-panel')?.remove();return copy.textContent; + }""") + self.assertNotIn(detail_marker, outside_logs, "Refresh diagnostics belong only in the original log region") + for account in (self.second, self.first): + self.page.locator(f'.account-tab[data-account="{account}"]').click() + self.wait_saved() + expect(self.original_region()).to_be_hidden() + + def test_explicit_toggle_tabs_close_reopen_bfcache_reload_reentry_and_new_context(self): + for key in ("login", "gifts", "maps"): + self.add(key, f"visible-{key}") 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.toggle(True) + for key in ("login", "gifts", "maps", "login"): + expect(self.task(key)).to_be_visible() + expect(self.page.locator("#log-lines")).to_contain_text(f"visible-{key}") + self.refresh_config(False) + self.refresh_job() + expect(self.original_region()).to_be_visible() + self.page.locator("#log-search").fill("visible") + self.page.locator("#log-follow").uncheck() + self.toggle(False) + rows = self.page.locator("#log-lines").text_content() + self.add("login", "visible-arrived-while-closed") + self.poll() + self.refresh_config(True) + self.refresh_job() + expect(self.original_region()).to_be_hidden() + self.assertEqual(self.page.locator("#log-lines").text_content(), rows, "Closed regions do not update row DOM") + self.toggle(True) + expect(self.page.locator("#log-search")).to_have_value("visible") + expect(self.page.locator("#log-follow")).not_to_be_checked() + expect(self.page.locator("#log-lines")).to_contain_text("visible-arrived-while-closed") + # Exercise persisted lifecycle handlers even when instrumented Chromium does not use BFCache. + with self.page.expect_response(self.base + "/api/auth/status"): + self.page.evaluate("""() => { + window.dispatchEvent(new PageTransitionEvent('pagehide', {persisted:true})); + window.dispatchEvent(new PageTransitionEvent('pageshow', {persisted:true})); + }""") + expect(self.page.locator("#app")).to_be_visible() + expect(self.original_region()).to_be_hidden() + self.toggle(True) + self.wait_saved() + self.page.reload(wait_until="networkidle") + expect(self.original_region()).to_be_hidden() + self.toggle(True) + self.wait_saved() + self.page.goto(self.base + "/login", wait_until="networkidle") + expect(self.page).to_have_url(self.base + "/") + expect(self.original_region()).to_be_hidden() + self.toggle(True) + self.wait_saved() + fresh = self.browser.new_context(viewport={"width": 1280, "height": 800}) + self.addCleanup(fresh.close) + fresh.route("**/*", self.local_only) + other = fresh.new_page() + other.add_init_script(self.poll_script) + other.route("**/api/accounts/*/logs?*", self.serve_logs) + other.on("pageerror", lambda failure: self.errors.append(str(failure))) + other.on("console", lambda message: self.errors.append(message.text) if message.type == "error" else None) + self.open(other) + expect(other.locator("#log-panel")).to_be_hidden() + expect(other.locator("#log-resizer")).to_be_hidden() + expect(other.locator("#log-toggle")).to_have_attribute("aria-expanded", "false") + expect(self.page.locator("#log-panel")).to_be_visible() + + def test_clears_downloads_and_debug_replay_are_scoped_to_context_and_account(self): + for key in ("login", "gifts", "maps"): + self.add(key, f"{key}-before") + self.add("login", "debug-before", level="debug", debug=True) + self.add("general", "mixed-old-gift") + self.add("login", "second-login", account=self.second) + self.open() + self.task("login") + self.toggle(True) + self.assertIn("login-before", self.download()) + self.assertNotIn("gift", self.download()) 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.assertEqual(self.download(), "") + for key in ("gifts", "maps"): + self.task(key) + self.assertIn(f"{key}-before", self.download()) + self.page.locator("#clear-log").click() + self.assertEqual(self.download(), "") 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.task("login") + if self.page.locator("#log-panel").is_hidden(): + self.toggle(True) + expect(self.page.locator("#log-lines")).to_contain_text("second-login") + self.assertNotIn("before", self.download()) self.page.locator(f'.account-tab[data-account="{self.first}"]').click() - hatch = self.task("hatching") - expect(hatch.locator(".log-entry")).to_have_count(0) + self.task("login") + if self.page.locator("#log-panel").is_hidden(): + self.toggle(True) 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") + for key in ("login", "gifts", "maps"): + self.add(key, f"{key}-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") + for key in ("login", "gifts", "maps"): + self.task(key) + text = self.download() + self.assertIn(f"{key}-after", text) + for excluded in ("before", "second-login", "mixed-old", *(f"{other}-after" for other in ("login", "gifts", "maps") if other != key)): + self.assertNotIn(excluded, text) 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): + def test_context_filters_inputs_focus_and_single_active_dom_survive_switches(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") + panel = self.task("hatching") + self.toggle(True) page_panel = self.page.locator('.page-panel[data-page="hatching"]:not([hidden])') + page_panel.locator(".subtab").last.click() field = page_panel.locator('input[type="checkbox"]').first - self.assertGreater(field.count(), 0) checked = not field.is_checked() field.set_checked(checked) + self.wait_saved() field.evaluate("node => {window.__preservedInput=node;}") + query = panel.get_by_role("searchbox") + query.fill("keep") query.focus() query.evaluate("node => {node.setSelectionRange(1,3);window.__preservedSearch=node;}") self.add("hatching", "keep-new", level="warning") @@ -195,276 +448,250 @@ class TaskLogsBrowserTests(unittest.TestCase): 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') + expect(panel.locator(".log-entry")).to_have_count(2) + self.assertNotIn("excluded-info", self.download()) gifts = self.task("gifts") + expect(query).to_have_value("") + gifts.get_by_role("searchbox").fill("gift") 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(gifts.locator("#log-lines")).to_contain_text("gift-new") + expect(self.page.locator(".page-panel .log-entry")).to_have_count(0) + expect(self.page.locator(".log-entry")).to_have_count(2) + self.task("hatching") expect(query).to_have_value("keep") - expect(hatch.get_by_role("combobox", name="孵蛋日志级别", exact=True)).to_have_value("warning") + expect(panel.locator(".log-entry")).to_have_count(3) 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.task("hatching") + if panel.is_hidden(): + self.toggle(True) + expect(query).to_have_value("") + expect(panel.locator("#log-lines")).to_contain_text("second-keep") + expect(panel.locator("#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("喂养策略") + self.task("hatching") + if panel.is_hidden(): + self.toggle(True) + expect(query).to_have_value("keep") + expect(page_panel.locator('.subtab[aria-selected="true"]')).to_have_text("喂养策略") + self.task("gifts") + expect(query).to_have_value("gift") - def test_reading_pause_collapse_and_bounded_append_preserve_scroll_and_nodes(self): + def test_reading_follow_collapse_bounded_append_and_original_resizer(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") + self.task("maps") + self.toggle(True) + lines, follow = self.page.locator("#log-lines"), self.page.locator("#log-follow") expect(lines.locator(".log-entry")).to_have_count(600) - expect(task.get_by_role("button", name="扫荡日志:暂停自动滚动", exact=True)).to_have_attribute("aria-pressed", "true") + expect(follow).to_be_checked() 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};}") + expect(follow).not_to_be_checked() + position = lines.evaluate("""node => { + window.__readingRow=[...node.children].find(row=>row.getBoundingClientRect().top>=node.getBoundingClientRect().top); + return {scroll:node.scrollTop, offset:window.__readingRow.getBoundingClientRect().top-node.getBoundingClientRect().top, + parent:document.querySelector('.page-panel:not([hidden])').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.assertAlmostEqual(position["offset"], lines.evaluate("node => window.__readingRow.getBoundingClientRect().top-node.getBoundingClientRect().top"), delta=1) + self.assertEqual(position["parent"], self.page.locator('.page-panel:not([hidden])').evaluate("node => node.scrollTop")) + self.page.locator("#log-search").fill("map-") + paused = lines.evaluate("node => node.scrollTop") + self.toggle(False) + self.toggle(True) + self.assertEqual(lines.evaluate("node => node.scrollTop"), paused, "Unchanged close/reopen restores reading position") + expect(follow).not_to_be_checked() + expect(self.page.locator("#log-search")).to_have_value("map-") + self.toggle(False) + previous = 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") + self.assertEqual(lines.text_content(), previous) + self.toggle(True) 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() + expect(follow).not_to_be_checked() + self.page.locator("#log-search").fill("") + follow.check() 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") + expect(self.page.locator(".log-entry")).to_have_count(600) + text = self.download() + self.assertEqual(len(text.splitlines()), 1200, "Downloads use the shared buffer, not only the 600 DOM rows") 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") + self.assertEqual(self.download(), text, "Debug cursor rewinds cannot resurrect evicted records") + splitter = self.page.locator("#log-resizer") + old_height = int(splitter.get_attribute("aria-valuenow")) + box = splitter.bounding_box() + self.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) + self.page.mouse.down() + self.page.mouse.move(box["x"] + box["width"] / 2, box["y"] - 36, steps=5) + self.page.mouse.up() + self.assertGreater(int(splitter.get_attribute("aria-valuenow")), old_height) + splitter.focus() + resized = int(splitter.get_attribute("aria-valuenow")) + splitter.press("ArrowDown") + self.assertEqual(int(splitter.get_attribute("aria-valuenow")), resized - 16) + self.wait_saved() + self.assertEqual(self.manager.get_config(self.first)["config"]["log_sizes"][1], resized - 16) + self.original_region() - def test_total_and_task_reading_positions_and_follow_states_are_independent_per_account(self): + def test_hidden_account_context_switches_keep_reading_state_and_reject_late_other_account_logs(self): for i in range(85): - self.add("hatching", f"first-{i:03}") - self.add("hatching", f"second-{i:03}", account=self.second) + self.add("maps", f"first-{i:03}") + self.add("gifts", f"gift-{i:03}") + self.add("maps", 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() + self.task("maps") + self.toggle(True) + lines, follow = self.page.locator("#log-lines"), self.page.locator("#log-follow") def read_at(position): - total.evaluate("(node, position) => {node.scrollTop=position;node.dispatchEvent(new Event('scroll'));}", position) + lines.evaluate("(node, position) => {node.scrollTop=position;node.dispatchEvent(new Event('scroll'));}", position) expect(follow).not_to_be_checked() - return total.evaluate("node => node.scrollTop") + return lines.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") + self.task("gifts") 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() + gift_position = read_at(280) + self.task("maps") expect(follow).not_to_be_checked() - self.assertEqual(total.evaluate("node => node.scrollTop"), first_position) - hide() - switch(self.second) - show() + self.assertEqual(lines.evaluate("node => node.scrollTop"), first_position) + self.toggle(False) + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + self.task("maps") + expect(self.original_region()).to_be_hidden() + self.toggle(True) 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() + self.toggle(False) + self.page.locator(f'.account-tab[data-account="{self.first}"]').click() + self.task("maps") + expect(self.original_region()).to_be_hidden() + self.toggle(True) expect(follow).not_to_be_checked() - self.assertEqual(total.evaluate("node => node.scrollTop"), second_position) - hide() - switch(self.first) - show() + self.assertEqual(lines.evaluate("node => node.scrollTop"), first_position) + self.task("gifts") + self.assertEqual(lines.evaluate("node => node.scrollTop"), gift_position) + self.task("maps") + held = [] + self.add("maps", "late-first-account") + self.page.route(f"**/api/accounts/{self.first}/logs?*", lambda route: held.append(route)) + with self.page.expect_request(lambda request: f"/accounts/{self.first}/logs?" in request.url): + self.page.evaluate("async () => {await window.__pollLogs();}") + self.add("maps", "second-after-switch", account=self.second) + self.page.locator(f'.account-tab[data-account="{self.second}"]').click() + self.task("maps") + if self.page.locator("#log-panel").is_hidden(): + self.toggle(True) + expect(lines).to_contain_text("second-084") + expect(lines).to_contain_text("second-after-switch") + self.assertEqual(len(held), 1) + self.serve_logs(held[0]) + self.poll() + expect(lines).not_to_contain_text("late-first-account") + expect(lines).not_to_contain_text("first-") expect(follow).not_to_be_checked() - self.assertEqual(total.evaluate("node => node.scrollTop"), first_position) + self.assertEqual(lines.evaluate("node => node.scrollTop"), second_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": "合成会话二"}]} + def test_dense_login_form_and_server_choices_receive_normal_clicks_at_three_viewports(self): + login = self.dense_fixture() 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)): + self.task("login") + self.toggle(True) + for width, height in self.viewports: 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") + self.task("login") + panel = self.page.locator('.page-panel[data-page="login"]:not([hidden])') + expect(self.page.locator("#log-lines .log-entry")).to_have_count(140) + expect(self.page.locator("#log-lines")).not_to_contain_text("synthetic-gifts-") + expect(self.page.locator("#log-lines")).not_to_contain_text("synthetic-general-") + account, password = panel.get_by_label("游戏账号", exact=True), panel.get_by_label("游戏密码", exact=True) + self.click_unobscured(account) + account.fill("offline-layout") + self.click_unobscured(password) + password.fill("synthetic-layout-password") + self.layout_artifact("login-form") 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") + if operation != "login": + choice = panel.get_by_label("区服 / 角色" if operation == "enter_server" else "已保存的账号 / 区服 / 角色", exact=True) + self.click_unobscured(choice) + choice.press("Escape") + choice.select_option("36" if operation == "enter_server" else "layout-session-36") with self.page.expect_response(lambda response: response.url.endswith(f"/actions/{operation}")): - panel.get_by_role("button", name=label, exact=True).click() + self.click_unobscured(panel.get_by_role("button", name=label, exact=True)) 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() + if operation == "login": + self.assertEqual(actions[-1][1], {"account": "offline-layout", "password": "synthetic-layout-password", "remember": True}) + expect(password).to_have_value("") + else: + self.assertEqual(actions[-1][1], {"server_id": "36"} if operation == "enter_server" else {"session_id": "layout-session-36"}) + self.layout_artifact("login-sessions") + self.assertEqual(self.page.evaluate("localStorage.length + sessionStorage.length"), 0) + self.assertNotIn("synthetic-layout-password", self.page.url) - def test_all_page_content_stays_separate_from_logs_and_remains_scroll_reachable(self): + def test_dense_maps_and_gifts_keep_original_workbench_controls_reachable_at_three_viewports(self): + self.dense_fixture() self.open() - for width, height in ((1280, 800), (390, 844)): + self.toggle(True) + for width, height in self.viewports: 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(): + for key, label in (("maps", "启用勾选关卡自动刷图"), ("gifts", "启用自动赠礼")): 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"))) + self.task(key) + panel = self.page.locator(f'.page-panel[data-page="{key}"]:not([hidden])') + checkbox = panel.get_by_label(label, exact=True) + previous = checkbox.is_checked() + self.click_unobscured(checkbox) + self.assertEqual(checkbox.is_checked(), not previous) + self.wait_saved() + rows = panel.locator("tbody tr[data-row-id]") + expect(rows).to_have_count(48) + rows.last.scroll_into_view_if_needed() + self.assertTrue(rows.last.evaluate("""node => { + const r=node.getBoundingClientRect(), content=node.closest('.page-panel').getBoundingClientRect(); + return r.top>=content.top-1 && r.bottom<=content.bottom+1; + }"""), "The final original table row must remain reachable above the bottom logs") + if key == "maps": + limit = rows.last.locator('td[data-column="limit"] input') + self.layout_artifact("maps-controls") + self.click_unobscured(limit) + limit.fill("7") + limit.press("Tab") + self.wait_saved() + self.assertEqual(self.manager.get_config(self.first)["config"]["sweep_policy"]["rules"]["synthetic47"]["limit"], 7) + body = self.page.locator("#log-lines") + expect(body).to_contain_text(f"synthetic-{key}-") + expect(body).not_to_contain_text("synthetic-login-") + expect(self.page.locator(".page-panel .log-entry")).to_have_count(0) + self.assertLessEqual(self.page.locator(".log-entry").count(), 600) + self.layout_artifact(key) if __name__ == "__main__": diff --git a/ranch_web/tests/browser/test_workbench_browser.py b/ranch_web/tests/browser/test_workbench_browser.py index 2451ad5..ba1f4c5 100644 --- a/ranch_web/tests/browser/test_workbench_browser.py +++ b/ranch_web/tests/browser/test_workbench_browser.py @@ -264,14 +264,17 @@ class WorkbenchBrowserTests(unittest.TestCase): def route_logs(route): query = parse_qs(urlsplit(route.request.url).query) debug = query.get("debug") == ["true"] - self.fulfill(route, {"entries": [{"id": 51, "seq": 51, "time":"2026-11-10T07:08:09Z", "message": "离线请求响应", "details_available": debug}], "next": 51}) + self.fulfill(route, {"entries": [{"id": 51, "seq": 51, "category": "login", "time":"2026-11-10T07:08:09Z", "message": "离线请求响应", "details_available": debug}], "next": 51}) def route_detail(route): detail_requests.append(route.request.url) self.fulfill(route, {"id": 51, "details": {"operation": "离线测试", "body": {"master": {"name": "演示"}, "token": "<隐藏>"}}}) self.page.route(f"**/api/accounts/{self.first}/logs?*", route_logs) self.page.route(f"**/api/accounts/{self.first}/debug/51", route_detail) self.open() + expect(self.page.locator("#log-panel")).to_be_hidden() self.page.locator("#debug-toggle").click() + expect(self.page.locator("#log-panel")).to_be_hidden() + self.page.locator("#log-toggle").click() self.page.wait_for_selector(".log-entry.inspectable") expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_text('15:08:09') expect(self.page.locator('.log-entry.inspectable .log-time')).to_have_attribute('title','2026-11-10T07:08:09Z')