fix: preserve strategy intent and recover accounts automatically

This commit is contained in:
AttilaNet
2026-11-11 19:37:15 +08:00
parent ccb945631d
commit 5c253d5cf9
26 changed files with 1628 additions and 236 deletions
@@ -27,16 +27,14 @@ class AutoReloginSchemaTests(unittest.TestCase):
catalog = Catalog()
fields = next(page["form"] for page in schema(catalog)["pages"] if page["key"] == "login")
fields = {tuple(field["path"]): field for field in fields}
enabled = fields[("auto_relogin", "enabled")]
delay = fields[("auto_relogin", "delay_minutes")]
self.assertEqual(enabled["label"], "掉线后自动重新登录")
self.assertEqual(enabled["type"], "boolean")
self.assertIs(enabled["value"], False)
self.assertNotIn(("auto_relogin", "enabled"), fields)
self.assertIsInstance(default_config()["auto_relogin"]["enabled"], bool)
self.assertEqual((delay["type"], delay["min"], delay["max"], delay["value"]), ("integer", 1, 10080, 30))
engine = SimpleNamespace(catalog=catalog, snapshot=None, demo=False)
view = build_view(engine, "login", default_config())
values = {tuple(field["path"]): field["value"] for field in view["form"]}
self.assertIs(values[("auto_relogin", "enabled")], False)
self.assertNotIn(("auto_relogin", "enabled"), values)
self.assertEqual(values[("auto_relogin", "delay_minutes")], 30)
@@ -77,8 +75,9 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.configs[identifier]["auto_relogin"] = {"enabled": False, "delay_minutes": 30}
summary = copy.deepcopy(self.manager.status(identifier))
summary.update(demo=False, connected=False, running=False, connection_state="offline",
connection_message="尚未连接游戏", error="", revision=9000)
summary["auto_relogin_status"] = {"state": "disabled", "message": "自动重登未开启", "next_attempt_at": None}
connection_message="尚未连接游戏", error="", revision=9000,
strategy_requested=False, strategy_state="stopped", strategy_message="", strategy_retry_at=None)
summary["auto_relogin_status"] = {"state": "missing_identity", "message": "尚未保存登录角色", "next_attempt_at": None}
self.summaries[identifier] = summary
self.login_data[identifier] = build_view(engine, "login", default_config())
self.login_data[identifier].update(account="offline-fixture", has_saved_password=True)
@@ -122,9 +121,10 @@ class AutoReloginBrowserTests(unittest.TestCase):
route.abort()
return
self.summaries[identifier].update(connected=False, running=False, connection_state="offline")
self.set_status(identifier, "cancelled", "手动退出登录,已取消本次自动重登")
self.waiting(identifier, message="退出登录后仍按设定时长自动重登",
requested=self.summaries[identifier]["strategy_requested"])
self.fulfill(route, {"id": "mock-logout", "operation": operation, "status": "succeeded",
"result": {"message": "已退出登录并取消自动重登"}})
"result": {"message": "已退出当前连接,仍会自动重登"}})
return
if request.method in ("POST", "PUT", "DELETE", "PATCH"):
self.unexpected_actions.append(path)
@@ -146,15 +146,21 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.summaries[identifier]["auto_relogin_status"] = {
"state": state, "message": message, "next_attempt_at": next_attempt_at}
def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登"):
def waiting(self, identifier=None, *, seconds=45, message="掉线后等待自动重登", requested=True):
identifier = identifier or self.first
self.configs[identifier]["auto_relogin"]["enabled"] = True
summary = self.summaries[identifier]
summary["strategy_requested"] = requested
if not requested:
summary["strategy_state"] = "stopped"
elif summary["strategy_state"] == "stopped":
summary["strategy_state"] = "offline"
target = (datetime.now(timezone.utc) + timedelta(seconds=seconds)).isoformat().replace("+00:00", "Z")
self.set_status(identifier, "waiting", message, target)
return target
def controls(self, panel):
return panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True), panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True)
def delay_control(self, panel):
expect(panel.get_by_role("checkbox", name="掉线后自动重新登录", exact=True)).to_have_count(0)
return panel.get_by_role("spinbutton", name="重登等待时长(分钟)", exact=True)
def saved(self, identifier, enabled, minutes):
self.page.wait_for_function("() => document.querySelector('#save-status').textContent === '策略已自动保存'")
@@ -162,27 +168,27 @@ class AutoReloginBrowserTests(unittest.TestCase):
def complete_login(self, operation, *, running=True):
self.summaries[self.first].update(connected=True, connection_state="online",
connection_message="游戏连接正常", error="", running=running)
connection_message="游戏连接正常", error="", running=running,
strategy_requested=running, strategy_state="running" if running else "stopped")
return {"id": "mock-" + operation, "operation": operation, "status": "succeeded", "result": {}}
def test_defaults_visible_explanations_and_existing_layout(self):
self.open()
panel = self.go("login")
enabled, delay = self.controls(panel)
expect(enabled).to_be_visible()
expect(enabled).not_to_be_checked()
delay = self.delay_control(panel)
expect(delay).to_be_visible()
expect(delay).to_have_value("30")
for attribute, value in (("min", "1"), ("max", "10080"), ("step", "1")):
expect(delay).to_have_attribute(attribute, value)
for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启"):
for text in ("服务端", "记住账号和密码", "原区服", "角色", "恢复监控", "自动执行已勾选功能", "顶部“停止”", "关闭页面", "服务重启", "退出登录", "只有", "清除登录记录", "暂停"):
expect(panel).to_contain_text(text)
self.assertTrue(enabled.evaluate("node => Boolean(node.closest('.policy-form'))"))
self.assertTrue(enabled.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)"))
self.assertTrue(delay.evaluate("node => Boolean(node.closest('.policy-form'))"))
self.assertTrue(delay.evaluate("node => Boolean(node.compareDocumentPosition(document.querySelector('.login-layout')) & Node.DOCUMENT_POSITION_FOLLOWING)"))
expect(panel.get_by_role("button", name="保存", exact=True)).to_have_count(0)
for width, height in ((1280, 800), (390, 844)):
self.page.set_viewport_size({"width": width, "height": height})
self.assertLessEqual(self.page.evaluate("document.documentElement.scrollWidth"), width)
expect(enabled).to_be_visible()
expect(delay).to_be_visible()
self.assertEqual(self.writes, [])
self.assertEqual(self.actions, [])
@@ -196,7 +202,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
return {"id": "mock-login", "operation": "login", "status": "succeeded", "result": candidates}
def stop(payload):
self.summaries[self.first]["running"] = False
self.summaries[self.first].update(running=False, strategy_requested=False, strategy_state="stopped")
return {"id": "mock-stop", "operation": "stop", "status": "succeeded", "result": {"message": "策略已停止"}}
self.action_handlers.update({(self.first, "login"): login,
@@ -230,13 +236,13 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.assertEqual(self.configs[self.first], original)
self.assertEqual(self.writes, [])
def test_import_stays_stopped_and_next_restored_session_runs_imported_selection(self):
def test_import_and_restored_session_preserve_explicit_pause_and_imported_selection(self):
imported = copy.deepcopy(default_config())
imported["daily_policy"].update(enabled=True, selected=["gift"])
portable = export_config(imported)
imports = []
self.login_data[self.first]["saved_sessions"] = [{"id": "offline-session", "label": "离线区服 / 原角色"}]
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session")
self.action_handlers[(self.first, "restore_session")] = lambda payload: self.complete_login("restore_session", running=False)
def import_config(route):
imports.append(route.request.post_data_json)
@@ -253,15 +259,15 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.page.locator('[data-command="import-config"]').click()
chooser.value.set_files({"name": "offline-policy.json", "mimeType": "application/json",
"buffer": json.dumps(portable).encode("utf-8")})
expect(self.page.locator("#dialog-content")).to_contain_text("下次成功登录会自动执行已勾选功能")
expect(self.page.locator("#dialog-content")).to_contain_text("仍遵循当前开启 / 停止设置")
self.page.locator("#dialog-confirm").click()
expect(self.page.locator("#notice")).to_contain_text("策略已导入,执行已停止")
expect(self.page.locator("#notice")).to_contain_text("策略已导入")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
self.assertEqual(imports, [portable])
self.assertEqual(self.actions, [])
panel.get_by_role("button", name="恢复选中会话(无需重新输密码)", exact=True).click()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#notice")).to_contain_text("已自动开启策略")
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#notice")).to_contain_text("用户暂停")
self.assertEqual(self.actions, [(self.first, "restore_session", {"session_id": "offline-session"})])
self.assertEqual(self.configs[self.first], imported, "Restoring must preserve imported selections")
self.assertEqual(self.writes, [])
@@ -314,17 +320,12 @@ class AutoReloginBrowserTests(unittest.TestCase):
def test_native_autosave_range_validation_refresh_and_focus(self):
self.open()
panel = self.go("login")
enabled, delay = self.controls(panel)
enabled.check()
checkbox = enabled.element_handle()
self.page.wait_for_timeout(850)
self.saved(self.first, True, 30)
self.assertTrue(enabled.evaluate("(node, original) => node === original && node === document.activeElement", checkbox))
delay = self.delay_control(panel)
delay.fill("47")
original = delay.element_handle()
before = self.view_calls
self.page.wait_for_timeout(5200)
self.saved(self.first, True, 47)
self.saved(self.first, False, 47)
self.assertGreater(self.view_calls, before, "Offline login DTOs must keep refreshing")
self.assertTrue(delay.evaluate("(node, original) => node === original && node === document.activeElement", original))
for invalid in ("0", "10081", "1.5", ""):
@@ -336,9 +337,7 @@ class AutoReloginBrowserTests(unittest.TestCase):
for valid in (1, 10080):
delay.fill(str(valid))
self.page.wait_for_timeout(850)
self.saved(self.first, True, valid)
enabled.uncheck()
self.page.wait_for_timeout(850)
self.saved(self.first, False, valid)
self.saved(self.first, False, 10080)
self.assertEqual(self.actions, [])
@@ -350,14 +349,13 @@ class AutoReloginBrowserTests(unittest.TestCase):
remember = panel.get_by_role("checkbox", name="记住账号和密码", exact=True)
remember.uncheck()
panel.get_by_role("textbox", name="游戏密码", exact=True).fill("mock-secret-never-send")
enabled, _ = self.controls(panel)
enabled.check()
self.delay_control(panel).fill("10")
hint = panel.locator("[data-auto-relogin-credentials]")
expect(hint).to_be_visible()
expect(hint).to_contain_text("缺少")
expect(hint).to_contain_text("记住账号和密码")
self.page.wait_for_timeout(1000)
self.saved(self.first, True, 30)
self.saved(self.first, False, 10)
expect(remember).not_to_be_checked()
self.assertTrue(self.writes)
payloads = json.dumps(self.writes, ensure_ascii=False)
@@ -370,26 +368,24 @@ class AutoReloginBrowserTests(unittest.TestCase):
def test_account_switch_isolates_pending_edits_status_and_minutes(self):
self.waiting(message="账号一正在等待自动重登")
self.set_status(self.second, "disabled", "账号二未开启自动重登")
self.set_status(self.second, "missing_identity", "账号二尚未保存登录角色")
self.open()
panel = self.go("login")
_, delay = self.controls(panel)
delay = self.delay_control(panel)
delay.fill("17")
self.page.locator(f'.account-tab[data-account="{self.second}"]').click()
panel = self.go("login")
enabled, second_delay = self.controls(panel)
expect(enabled).not_to_be_checked()
second_delay = self.delay_control(panel)
expect(second_delay).to_have_value("30")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二未开启")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号二尚未保存")
expect(panel).not_to_contain_text("账号一正在等待")
enabled.check()
second_delay.fill("9")
self.page.wait_for_timeout(1000)
self.saved(self.second, True, 9)
self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": True, "delay_minutes": 17})
self.saved(self.second, False, 9)
self.assertEqual(self.configs[self.first]["auto_relogin"], {"enabled": False, "delay_minutes": 17})
self.page.locator(f'.account-tab[data-account="{self.first}"]').click()
panel = self.go("login")
expect(self.controls(panel)[1]).to_have_value("17")
expect(self.delay_control(panel)).to_have_value("17")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("账号一正在等待")
self.assertEqual({identifier for identifier, _ in self.writes}, {self.first, self.second})
self.assertEqual(self.actions, [])
@@ -404,8 +400,8 @@ class AutoReloginBrowserTests(unittest.TestCase):
expect(status).to_contain_text("掉线后等待自动重登")
expect(countdown).to_contain_text("秒后自动重新登录")
expect(countdown).to_contain_text("北京时间")
expect(self.controls(panel)[0]).to_be_enabled()
delay = self.controls(panel)[1]
delay = self.delay_control(panel)
expect(delay).to_be_enabled()
delay.focus()
original = delay.element_handle()
before = countdown.inner_text()
@@ -421,10 +417,12 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.set_status(self.first, "failed", reason)
expect(status).to_contain_text(reason)
expect(status.locator("img")).to_have_count(0)
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
original = copy.deepcopy(self.configs[self.first])
self.set_status(self.first, "monitoring", "重登成功,已恢复监控并自动执行已勾选功能,可在顶部停止")
self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常", running=True)
self.summaries[self.first].update(connected=True, connection_state="online", connection_message="游戏连接正常",
running=True, strategy_requested=True, strategy_state="running")
expect(status).to_contain_text("已恢复监控并自动执行已勾选功能")
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#data-summary")).to_contain_text("正在自动执行已配置且已勾选的功能")
@@ -436,31 +434,35 @@ class AutoReloginBrowserTests(unittest.TestCase):
self.open()
panel = self.go("login")
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("服务重启")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
before = len(self.writes)
self.page.reload(wait_until="networkidle")
panel = self.go("login")
expect(self.controls(panel)[0]).to_be_checked()
expect(self.controls(panel)[1]).to_have_value("30")
expect(self.delay_control(panel)).to_have_value("30")
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#strategy-toggle")).to_be_disabled()
expect(self.page.locator("#strategy-toggle")).to_have_text("停止")
expect(self.page.locator("#strategy-toggle")).to_be_enabled()
self.page.goto("about:blank")
self.page.close()
self.assertEqual(len(self.writes), before)
self.assertEqual(self.summaries[self.first]["auto_relogin_status"]["next_attempt_at"], target)
self.assertEqual(self.actions, [])
def test_manual_logout_cancels_countdown_without_disabling_account_setting(self):
def test_manual_logout_keeps_countdown_and_preserves_strategy_pause(self):
self.waiting()
self.summaries[self.first].update(strategy_requested=False, strategy_state="stopped")
self.open()
panel = self.go("login")
expect(panel.locator("[data-auto-relogin-countdown]")).to_contain_text("秒后自动重新登录")
panel.get_by_role("button", name="退出登录", exact=True).click()
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("已取消本次自动重登")
expect(panel.locator("[data-auto-relogin-countdown]")).to_be_hidden()
expect(self.controls(panel)[0]).to_be_checked()
expect(panel.locator("[data-auto-relogin-status]")).to_contain_text("仍按设定时长自动重登")
expect(panel.locator("[data-auto-relogin-countdown]")).to_be_visible()
expect(self.page.locator("#strategy-toggle")).to_have_text("开启")
expect(self.page.locator("#data-summary")).to_contain_text("用户暂停")
expect(self.delay_control(panel)).to_have_value("30")
self.assertEqual(self.actions, [(self.first, "logout", {})])
self.assertEqual(self.writes, [])
if __name__ == "__main__":