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
+243 -35
View File
@@ -50,13 +50,13 @@ from ranch_assistant.battles import CancelledBeforeDispatch
from ranch_assistant.debug import TraceLog, sensitive
from ranch_assistant.engine import Engine
from ranch_assistant.login import PasswordLogin
from ranch_assistant.model import Catalog
from ranch_assistant.model import Catalog, seconds
from .activity import ActivityLog, ActivityLogError
from .log_categories import endpoint_category, legacy_category, normalize_category, note_hints, operation_category, route_message
from .policies import apply_config, default_config, validate_config
from .scheduler import AccountSchedule, FAST_KINDS, Scheduler
from .store import WebStore, session_identity
from .store import WebStore, _unlinked, atomic_json, session_identity
PAGES = frozenset("login incubator bag ranch daily hatching mainline battles gifts commissions exploration maps statistics plans yields".split())
@@ -172,6 +172,14 @@ class AccountWorker:
self._view_epoch = 0
self._generation = 0
self._running = False
self._intent_error = ""
self._legacy_pending = {}
self._run_intents = self._load_run_intents()
self._execution_retry_deadline = None
self._execution_retry_at = None
self._execution_retry_attempt = 0
self._execution_error = ""
self._execution_block = ""
self._closing = False
self._active = None
self._execution = None
@@ -222,8 +230,163 @@ class AccountWorker:
login = self.manager.store.load_config(self._login_settings_root)
if login:
value["auto_relogin"] = validate_config(login["config"])["auto_relogin"]
# A saved role is durable keep-login authorization. Old releases used
# enabled=False as their default; it was never an explicit account clear.
if re.fullmatch(r"[a-f0-9]{64}", folder.name):
value["auto_relogin"]["enabled"] = True
return value, revision
def _load_run_intents(self):
try:
path = _unlinked(self.profile_root / "run_intent.json")
if not path.exists():
return {}
value = json.loads(path.read_text(encoding="utf-8"))
if (not isinstance(value, dict) or value.get("schema") != 1
or not isinstance(value.get("roles"), dict)
or any(not isinstance(scope, str) or not re.fullmatch(r"[a-f0-9]{64}|demo|disconnected", scope)
or type(requested) is not bool for scope, requested in value["roles"].items())):
raise ValueError("invalid run intent")
pending = value.get("legacy_pending", {})
if (not isinstance(pending, dict) or any(not re.fullmatch(r"[a-f0-9]{64}", scope)
or not isinstance(record, dict) or record.get("kind") not in {"gift", "hatch", "feed"}
or not isinstance(record.get("evidence"), dict) for scope, record in pending.items())):
raise ValueError("invalid pending evidence")
self._legacy_pending = pending
return value["roles"]
except (OSError, ValueError, TypeError):
self._intent_error = "运行意愿记录无法读取;已保留原文件,请检查 Web 数据目录后重试"
return {}
@property
def strategy_requested(self):
# Missing records migrate to enabled. Transient running=False from an
# old process is not evidence that the user pressed Stop.
if self.demo:
return self._run_intents.get("demo", False)
return self._run_intents.get(self._workspace(), self._run_intents.get("disconnected", True))
def _set_strategy_requested(self, requested):
"""Only the explicit manager Stop and Start paths may call this."""
with self.lock:
if requested:
# The Start may have waited behind persistence while a later
# synchronous Stop revoked its generation.
self.check_intent()
if self._intent_error:
raise OSError(self._intent_error)
self._run_intents[self._workspace()] = bool(requested)
self._save_run_intents()
def _save_run_intents(self):
try:
atomic_json(self.profile_root / "run_intent.json", {"schema": 1, "roles": self._run_intents,
"legacy_pending": self._legacy_pending})
except (OSError, ValueError):
self._intent_error = "运行意愿或待核对记录无法持久保存;请检查 Web 数据目录"
raise OSError(self._intent_error) from None
def _legacy_write(self, path, payload):
"""Fence only three legacy writes lacking Engine's durable journals."""
if path not in {"monsterService/monsterSendGift", "stackService/stackAddMonster", "monsterService/monsterIntensify"}:
return None
if not self.active_identity or self.engine.snapshot is None:
return None
if self.active_identity in self._legacy_pending:
raise ValueError("上次赠礼、装填或喂养请求待核对,禁止自动重发")
payload = payload or {}
if path == "monsterService/monsterSendGift":
mid = int(payload["monsterId"])
evidence = {"monster": mid, "gift_time": seconds(self.engine.snapshot.monsters[mid].get("giftTime"))}
kind = "gift"
elif path == "stackService/stackAddMonster":
stacks = {int(row["id"]): int(row.get("monsterId") or 0) for row in self.engine.snapshot.raw.get("stacks", [])}
evidence = {str(egg["stackId"]): stacks[int(egg["stackId"])] for egg in payload["eggs"]}
kind = "hatch"
elif path == "monsterService/monsterIntensify" and payload.get("foods"):
evidence = {"foods": list(payload["foods"])}
kind = "feed"
else:
return None
with self.lock:
self._legacy_pending[self.active_identity] = {"kind": kind, "evidence": evidence}
self._save_run_intents() # A failure here prevents sending the write.
return self.active_identity
def _reconcile_legacy_write(self, snapshot, identity):
# Raw server snapshots precede Engine's local optimistic gift/growth
# overlays. An unchanged read, heartbeat or elapsed time is not proof.
with self.lock:
record = self._legacy_pending.get(identity)
if not record:
return
evidence, kind = record["evidence"], record["kind"]
if kind == "gift":
mon = snapshot.monsters.get(int(evidence["monster"]))
confirmed = mon is None or seconds(mon.get("giftTime")) > seconds(evidence["gift_time"])
elif kind == "feed":
confirmed = all(int(mid) not in snapshot.monsters for mid in evidence["foods"])
else:
stacks = {str(row["id"]): int(row.get("monsterId") or 0) for row in snapshot.raw.get("stacks", [])}
confirmed = bool(evidence) and all(stacks.get(slot, 0) > 0 and stacks[slot] != previous
for slot, previous in evidence.items())
if confirmed:
self._legacy_pending.pop(identity)
self._save_run_intents()
def _pending_execution_reason(self):
if self.active_identity in self._legacy_pending:
return "赠礼、装填或喂养请求结果待核对,禁止自动重发;后台继续读取游戏状态,确认后自动恢复已勾选策略"
if self.engine.snapshot is not None and (self.engine._progression_pending()
or self.engine.explore_planner.pending(self.engine.snapshot) or self.engine._breakthrough_pending):
return "存在未确认的任务、战斗、探险或突破请求,禁止自动重发;后台继续核对,核对完成后恢复已勾选策略"
return ""
def _refresh_execution(self):
"""Rearm desired execution, never grant writes to a read-only callback."""
with self.lock:
self._execution_block = self._intent_error or self._pending_execution_reason()
ready = self.demo or self.connection_state == "online" and self.engine.client is not None
if ready and self.engine.snapshot is not None and not self.schedule.monitoring:
self.schedule.monitor(True)
if self._execution_retry_deadline is not None and self.schedule.clock() >= self._execution_retry_deadline:
self._execution_retry_deadline = self._execution_retry_at = None
self._running = bool(self.strategy_requested and ready and self.engine.snapshot is not None
and not self._execution_block and self._execution_retry_deadline is None
and not self._closing and not self.manager._closing and not getattr(self, "_session_write_error", ""))
if not self._running:
self.engine.auto = False
self.schedule.stop()
return self._running
def _strategy_status(self):
requested = self.strategy_requested
if not requested:
state, message = "stopped", "已按用户选择停止策略;离线后仍按配置间隔重登,点击开始可恢复策略"
elif self._execution_block:
state, message = "blocked", self._execution_block
elif self._execution_retry_deadline is not None:
state, message = "recovering", self._execution_error + ";等待退避后自动恢复已勾选策略"
elif self.connection_state == "retrying":
state, message = "recovering", self.connection_message
elif not self._running:
state, message = "offline", self.connection_message
else:
state, message = "running", "已勾选的策略将自动执行"
return {"strategy_requested": requested, "manual_stop": not requested,
"strategy_state": state, "strategy_message": self.safe_text(message),
"strategy_retry_at": self._execution_retry_at or (self.next_retry_at if requested else None)}
def _execution_failed(self, error):
self.stop()
if self._pending_execution_reason():
return
self._execution_retry_attempt += 1
delay = min(5 * 2 ** min(self._execution_retry_attempt - 1, 4), 60)
self._execution_retry_deadline = self.schedule.clock() + delay
self._execution_retry_at = (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat(timespec="milliseconds")
self._execution_error = self.safe_text(str(error)) or type(error).__name__
def _engine(self, client=None, *, state_root=None, config=None):
state_root = self.state_root if state_root is None else state_root
config = self.config if config is None else config
@@ -425,7 +588,7 @@ class AccountWorker:
"demo": self.demo, "running": self._running, "busy": False, "player": player,
"revision": self.revision, "error": self.error, "connection_state": self.connection_state,
"connection_message": self.connection_message, "last_game_success_at": self.last_game_success_at,
"next_retry_at": self.next_retry_at, "auto_relogin_status": self._auto_relogin_status()})
"next_retry_at": self.next_retry_at, "auto_relogin_status": self._auto_relogin_status(), **self._strategy_status()})
def _auto_relogin_status(self):
with self.lock:
@@ -504,6 +667,7 @@ class AccountWorker:
# A decoded business rejection proves neither disconnection nor
# expiry. Keep monitoring, but never retry its rejected write.
self.error = self._last_game_error_message = self.safe_text(str(error))
self._execution_failed(error)
self.log(self.error, level="error")
return
self.engine.heartbeat_enabled = False
@@ -514,11 +678,11 @@ class AccountWorker:
self.next_retry_at = None
if expired:
self.connection_state = "expired"
message = "游戏会话已失效(408);策略已停止,游戏请求已暂停,请手动恢复会话或重新登录"
message = "游戏会话已失效(408);游戏请求已暂停,将按配置间隔重新登录,策略运行意愿已保留"
elif temporary and client is not None:
self.connection_state = "retrying"
reason = "游戏网络请求超时" if isinstance(error, requests.Timeout) or isinstance(cause, requests.Timeout) else "游戏网络暂时不可用"
message = f"{reason};策略已停止,{delay} 秒后只读重试,未确认记录保留"
message = f"{reason};{delay} 秒后只读重试,连接恢复后自动继续已勾选策略,未确认记录保留"
self.next_retry_at = (datetime.now(timezone.utc) + timedelta(seconds=delay)).isoformat(timespec="milliseconds")
elif temporary:
self.connection_state = "offline"
@@ -546,6 +710,7 @@ class AccountWorker:
self._auto_relogin_blocked = False
self.schedule.game_resumed()
self.engine.heartbeat_enabled = True
self._refresh_execution()
if previous != "online" and not activated:
self.log("游戏连接已确认;" + ("已勾选的策略继续运行" if self.running else "策略保持停止"), category="login")
@@ -554,6 +719,7 @@ class AccountWorker:
result = deepcopy(self._summary)
result.update(running=self._running, busy=bool(self._active or self._pending))
result["auto_relogin_status"] = self._auto_relogin_status()
result.update(self._strategy_status())
return result
@property
@@ -675,13 +841,15 @@ class AccountWorker:
if self.connection_state not in {"expired", "retrying"} and not (
self.engine.client is not None and job.operation in {"login", "enter_server", "restore_session"}):
self.error = message
if job.consuming:
self.stop()
if (job.consuming and job.operation != "start"
and failure_sequence == self._game_failure_sequence):
self._execution_failed(error)
self.log(message, category=job.category, level="error")
finally:
job.payload = {}
try:
self._persist_session()
self._refresh_execution()
summary = self._make_summary()
except Exception as error:
self.stop()
@@ -722,12 +890,12 @@ class AccountWorker:
self.config, self.revision = self._load_config(self.state_root)
self.active_identity = saved
self.engine = self._engine()
self.connection_message = "服务已启动或重启;已保留保存的会话,请手动恢复会话或重新登录,策略保持停止"
self.connection_message = "服务已启动或重启;已保留会话与策略运行意愿,将等待配置分钟后重新登录原区服、原角色"
# Opt-in only: retain the known startup offline origin even
# while disabled, so enabling later can reuse that timestamp.
self._mark_disconnected(session, saved)
if self.config["auto_relogin"]["enabled"]:
self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色,策略保持停止"
self.connection_message = "服务已启动或重启;将等待配置分钟后使用保存的密码重新登录原区服、原角色"
self.log(self.connection_message, category="login")
if self.demo:
self.result(*self.engine.poll())
@@ -791,6 +959,8 @@ class AccountWorker:
# login authorization. Never erase or enable this preference.
source["auto_relogin"] = deepcopy(self.config["auto_relogin"])
value = validate_config(source)
if self.active_identity and not self.demo:
value["auto_relogin"]["enabled"] = True
new_revision = self.revision + 1
self.manager.store.save_config(self.state_root, value, new_revision)
if self.state_root != self._login_settings_root:
@@ -802,8 +972,9 @@ class AccountWorker:
with self.lock:
self.config, self.revision = value, new_revision
# A policy job never clears cancellation or resurrects a stopped start.
self.engine.auto = bool(self._running and not self._closing and self._execution
and self._execution.generation == self._generation)
if not (self._running and not self._closing and self._execution
and self._execution.generation == self._generation):
self.engine.auto = False
self.schedule.poll_finished(value)
self.schedule.arm(self.engine, value, self._running, self.engine.plans() if self.engine.snapshot else ())
self._invalidate_views()
@@ -863,6 +1034,7 @@ class AccountWorker:
return active
def _tick(self, job):
self._refresh_execution()
kind = self.schedule.due(self.engine, self.config, self._running)
job.due_kind, job.category = kind, operation_category(kind)
if kind is None:
@@ -897,6 +1069,7 @@ class AccountWorker:
self.engine.snapshot = self.engine.client.snapshot()
finally:
self._retry_probe = False
self._refresh_execution()
self.schedule.poll_finished(self.config)
self._invalidate_views()
return {"kind": kind}
@@ -928,7 +1101,13 @@ class AccountWorker:
# while preserving the user's running switch. Only a pause
# by the current Engine generation turns that switch off.
if auto and job.generation == self._generation and not self.engine.auto:
self.stop()
if self._pending_execution_reason():
self.stop()
else:
self._execution_failed(ValueError(value[2] or "策略暂不可用"))
elif auto and job.generation == self._generation:
self._execution_retry_attempt = 0
self._execution_error = ""
self.schedule.arm(self.engine, self.config, self._running, value[1], completed=kind)
elif isinstance(value, str):
self._log_message(value)
@@ -1069,11 +1248,32 @@ class AccountWorker:
# A repaired directory may be retried. Client.persist_session
# sets this before Trace.begin blocks an unsafe dispatch.
self._session_write_error = ""
legacy = self._legacy_write(path, args[1] if len(args) > 1 else kwargs.get("payload")) if active else None
try:
response = original(*args, **kwargs)
except Exception as error:
if legacy is not None and (isinstance(error, CancelledBeforeDispatch)
or isinstance(error, ApiError) and error.code is not None):
# A decoded rejection did not apply the write; it needs
# bounded backoff and fresh planning, not uncertainty.
with self.lock:
self._legacy_pending.pop(legacy, None)
self._save_run_intents()
self._game_failed(error, client)
raise
if legacy is not None and path == "monsterService/monsterSendGift":
try:
feel, gifted_at = float(response["feel"]), seconds(response["giftDate"])
before = self._legacy_pending[legacy]["evidence"]["gift_time"]
confirmed = math.isfinite(feel) and feel >= 0 and math.isfinite(gifted_at) and gifted_at > before
except (KeyError, TypeError, ValueError):
confirmed = False
if confirmed:
# The same authoritative response used by GiftPlanner's
# cooldown is sufficient even if role reads lag behind.
with self.lock:
self._legacy_pending.pop(legacy, None)
self._save_run_intents()
path = args[0] if args else kwargs.get("path")
if active and path == "heartBeatService/keepAlive":
self._game_succeeded()
@@ -1091,6 +1291,7 @@ class AccountWorker:
except Exception as error:
self._game_failed(error, client)
raise
self._reconcile_legacy_write(snapshot, session_identity(client.session))
if client is self.engine.client:
self._game_succeeded()
return snapshot
@@ -1178,15 +1379,10 @@ class AccountWorker:
self.schedule.poll_finished(self.config)
self._game_succeeded(activated=True)
self._invalidate_views(clear=True)
# Activation and its new start authorization share the final
# generation check/lock. Never queue a start that could outlive
# a stop, logout or policy replacement during persistence.
try:
self._start({}, require_selection=False)
except ValueError as error:
message = login_message + ";策略保持停止:" + self.safe_text(str(error))
else:
message = login_message + ";策略已自动开启,仅执行已勾选的规则"
# A verified connection never changes durable user intent or
# grants writes to this authentication/read-only operation.
self._refresh_execution()
message = login_message + ";" + self._strategy_status()["strategy_message"]
result = {"connected": True, "running": self._running,
"has_saved_password": self._has_saved_password, "message": message}
self.log(message, category="login")
@@ -1312,20 +1508,19 @@ class AccountWorker:
client.close()
def _logout(self, payload):
identity = self.active_identity
session = (self.engine.client.session if self.engine.client is not None else
self.securestore.load(identity) if identity else None)
self._release_clients()
self.manager._release_identity(self)
self.active_identity = None
self.securestore.set_active(None)
self.state_root = self.state = self.manager.store.role_root(self.id, demo=self.demo)
config, revision = self._load_config(self.state_root)
self.config, self.revision = config, max(self.revision, revision) + 1
self.engine = self._engine()
with self.lock:
self._servers = []
self.schedule.monitor(False)
self.schedule.game_failed()
if session is not None:
self._mark_disconnected(session, identity)
self.connection_state = "offline"
self.connection_message = "已手动退出游戏;请登录或手动恢复保存的会话,策略保持停止"
self.connection_message = "已退出当前游戏连接;会话、密码与策略运行意愿已保留,将按配置间隔重新登录"
self.next_retry_at = None
self.error = ""
self._refresh_login_metadata()
@@ -1335,12 +1530,20 @@ class AccountWorker:
def _forget_login(self, payload):
self._logout(payload)
self.securestore.forget()
self.manager._release_identity(self)
self.active_identity = None
self.state_root = self.state = self.manager.store.role_root(self.id, demo=self.demo)
config, revision = self._load_config(self.state_root)
self.config, self.revision = config, max(self.revision, revision) + 1
self.engine = self._engine()
self.connection_message = "已清空保存的登录,不再自动重登;请重新登录并选择区服"
self._refresh_login_metadata()
self._invalidate_views()
return {"connected": False, "running": False, "has_saved_password": False}
def _start(self, payload, *, require_selection=True):
self.check_intent()
self._set_strategy_requested(True)
if not self.demo:
self._require_game()
if self.engine.snapshot is None or not (self.demo or self.engine.client):
@@ -1354,16 +1557,19 @@ class AccountWorker:
raise ValueError("请先勾选至少一项功能,并启用对应策略")
if require_selection and ranch and not other and not any(rule["enabled"] for rule in policy["egg_rules"].values()):
raise ValueError("请先在背包魔物蛋勾选要孵化的蛋,并设置优先级和孵出后的去向")
if (self.engine._progression_pending() or self.engine.explore_planner.pending(self.engine.snapshot)
or self.engine._breakthrough_pending):
raise ValueError("存在未确认的任务、战斗、探险或突破请求,禁止自动重发;请先核对")
reason = self._pending_execution_reason()
if reason:
raise ValueError(reason)
with self.lock:
self.check_intent()
self._running = self.engine.auto = True
self._execution_retry_deadline = self._execution_retry_at = None
self._execution_retry_attempt = 0
self._execution_error = ""
self._refresh_execution()
self.engine.heartbeat_enabled = True
self.schedule.monitor(True)
self._invalidate_views()
return {"running": True}
return {"running": self._running, **self._strategy_status()}
def _stop(self, payload):
# submit('stop') already made cancellation effective synchronously.
@@ -1513,12 +1719,14 @@ class WebManager:
with worker.condition:
if operation == "stop":
worker.stop()
worker._set_strategy_requested(False)
# Stop is complete before returning; it never waits behind a model.
job = _Job(uuid.uuid4().hex, operation, {}, worker._generation, status="succeeded", result={"running": False})
job = _Job(uuid.uuid4().hex, operation, {}, worker._generation, status="succeeded",
result={"running": False, **worker._strategy_status()})
worker._jobs[job.id] = job
return job.public()
if operation in STOP_ACTIONS or operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}:
if operation in {"login", "enter_server", "restore_session", "logout", "forget_login"}:
if operation == "forget_login":
worker.suspend_auto_relogin()
worker.stop()
consuming = operation not in READ_ACTIONS and operation not in LOCAL_ACTIONS and operation not in {"logout", "forget_login"}