Fix fast automation routing and blocked quest navigation loops

Isolate hatch, gift, exploration and breakthrough timers; cancel queued automation after settings change. Check battle readiness before local quest navigation and reject exploring teams or disabled sweeps before entry.
This commit is contained in:
AttilaNet
2026-11-09 12:14:47 +08:00
parent 9f819d828a
commit eaaad3488b
9 changed files with 931 additions and 37 deletions
+4 -5
View File
@@ -29,6 +29,7 @@ from .drop_statistics import event_reward
from .maps import stages
from .quests import indexed, stage_has_level
from .sweeping import SweepPolicy
from .team_availability import team_availability_reason
def value(obj, name, default=None):
@@ -338,11 +339,9 @@ class BattleOrchestrator:
limit = max(0, int(policy.stop_after_loss))
if limit and self.journal.role(snapshot)["losses"] >= limit:
return "已达战败停止次数,请核对阵容后重置战败计数"
teams = snapshot.raw.get("teams", [])
team = next((t for t in teams if t.get("teamName") == policy.team and t.get("teamType") == "battleTeam"), {})
ids = [int(mid) for mid in team.get("monsters", []) if mid and int(mid) > 0]
if not ids or any(mid not in snapshot.monsters for mid in ids):
return "所选战队无有效魔物或实例缺失"
reason = team_availability_reason(snapshot, policy.team)
if reason:
return reason
stage_id = str(value(intent, "stage_id", "") or "")
difficulty = str(value(intent, "difficulty", "1") or "1")
if not stage_id:
+59 -3
View File
@@ -341,6 +341,9 @@ class Engine:
self.game_data = load_progression_data()
if self.progression_planner is None:
self.progression_planner = ProgressionPlanner(self.catalog, self.game_data, account_key=self._progression_namespace)
# This is a read-only preflight; the same check must precede navigation
# and dialogue, not just the battle action they lead to.
self.progression_planner.battle_capability = self._battle_capability
if not self._progression_state_loaded and self.snapshot is not None:
stored = deepcopy(self.battle_journal.role(self.snapshot).get("planner_state"))
if stored:
@@ -712,6 +715,8 @@ class Engine:
self._recover_confirmed_progression()
self._battle_snapshot_source = self.snapshot
self._battle_snapshot_digest = digest(self.snapshot.raw)
self.progression_planner.battle_capability_key = digest({
"snapshot": self._battle_snapshot_digest, "runtime": id(self.battles.runtime)})
key = digest({"snapshot": self._battle_snapshot_digest, "policy": vars(self.progression_policy),
"quests": vars(self.quest_policy), "ranch": vars(self.policy), "local_state": self.progression_planner.state_signature(self.snapshot),
"pending": self._progression_pending(), "runtime": id(self.battles.runtime), "day": int(self.snapshot.now // 86400)})
@@ -1022,9 +1027,7 @@ class Engine:
except (ValueError, TypeError, KeyError, AttributeError) as error:
self.auto = False
return self.snapshot, [], "状态已读取;策略暂不可用:" + str(error)
commission_actions = [action for action in plans if action.kind.startswith("quest_") or
action.kind == "progression" and self._is_commission(action.payload["intent"])]
actions = (commission_actions or self.pending_hatches) if hatch_only else plans
actions = self.pending_hatches if hatch_only else plans
action = actions[0] if actions else None
if action and defer_hatch and action.kind == "hatch":
action = None
@@ -1100,6 +1103,59 @@ class Engine:
message += ";" + ";".join(dict.fromkeys(self.planner.notes))
return self.snapshot, plans, message
@single_flight
@account_serial
def poll_automation(self, kind):
"""Execute one fast-scheduler kind without dispatching other strategies."""
if kind not in {"explore", "breakthrough", "gift", "hatch"}:
raise ValueError("快速自动操作类型无效")
self.last_executed = False
if self.demo:
if self.snapshot is None:
self.snapshot = demo_snapshot(self.catalog)
else:
self.read_snapshot(sync_master=False)
if self._progression_pending():
pending = self.battle_journal.pending(self.snapshot) or {}
return self.snapshot, [], pending.get("message") or "有待核对的任务 / 战斗,快速操作未执行"
explore_pending = self.explore_planner.pending(self.snapshot)
if explore_pending or self._breakthrough_pending:
message = (explore_pending or self._breakthrough_pending).get("message", "自动操作待核对")
return self.snapshot, [], message
plans = self.plans()
allowed = {"explore": {"explore_start", "explore_finish"},
"breakthrough": {"potential", "breakthrough"}, "gift": {"gift"}, "hatch": {"hatch"}}[kind]
candidates = self.pending_hatches if kind == "hatch" else plans
action = next((action for action in candidates if action.kind in allowed and action.path), None)
if not self.auto or self._progression_cancel.is_set():
return self.snapshot, plans, "策略已停止,快速操作未执行"
if action is None:
return self.snapshot, plans, {"explore": "探险", "breakthrough": "突破",
"gift": "赠礼", "hatch": "孵化"}[kind] + "当前无可执行动作"
self.last_executed = True
if kind == "explore":
return self._execute_explore(action)
if kind == "breakthrough":
return self._execute_breakthrough(action)
if self.demo:
self.apply_demo(action)
else:
response = self.client.call(action.path, action.payload)
if kind == "gift":
try:
self.gift_planner.remember_success(self.snapshot, action, response)
except ValueError:
self.auto = False
raise
self.read_snapshot(sync_master=False)
if kind == "hatch":
stack_id = action.payload["eggs"][0]["stackId"]
slot = next((slot for slot in self.snapshot.raw["stacks"] if int(slot["id"]) == stack_id), None)
if slot is None or int(slot.get("monsterId") or 0) <= 0:
self.auto = False
raise ValueError("装填已返回,但坑位状态尚未同步;已停止,请刷新核对后再继续")
return self.snapshot, self.plans(), ("[演示] " if self.demo else "") + action.description
def _execute_legacy_task(self, action):
"""Keep the commission scheduler, with the same durable replay barrier."""
payload = action.payload
+47 -8
View File
@@ -159,6 +159,7 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
self.pending_exploration_view = False
self.monster_data_pending = False
self.pending_schedule = False
self.automation_generation = 0
self.next_explore = float("inf")
self.next_breakthrough = float("inf")
self.monster_view_visible = False
@@ -669,6 +670,7 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
self.update_workflow_status()
def stop_workflow(self):
self.automation_generation += 1
self.set_strategy_checked(False)
self.engine.auto = False
self.cancel_progression()
@@ -1337,6 +1339,9 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
self.progression_views = None
if self.presentation_active and self.tabs.currentWidget() in (self.progression_page, self.battle_records_page):
self.pending_progression_view = True
self.arm_hatching()
self.arm_gifting()
self.arm_extended_automation()
if self.pending_schedule and not self.closed and not self.close_after_job:
self.pending_schedule = False
self.schedule()
@@ -1567,7 +1572,14 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
if hatch_only:
self.hatch_timer.stop()
self.next_hatch = float("inf")
self.run_job("hatch" if hatch_only else "poll", lambda: self.engine.poll(hatch_only=hatch_only, defer_hatch=not hatch_only))
engine, generation = self.engine, self.automation_generation
def dispatch():
if automated and (generation != self.automation_generation or engine is not self.engine):
return engine.snapshot, [], "自动化设置已变化,未开始的自动轮询已取消"
return engine.poll(hatch_only=hatch_only, defer_hatch=not hatch_only)
self.run_job("hatch" if hatch_only else "poll", dispatch)
except ValueError as error:
self.stop_workflow()
self.engine.policy = Policy(enabled=False)
@@ -1577,18 +1589,41 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
self.submit("poll", self.engine.poll)
def run_extended_automation(self):
if self.busy or not self.engine.auto or not self.engine.snapshot:
if self.busy or not self.monitoring or not self.strategy_toggle.isChecked() or not self.engine.snapshot:
return
self.submit("automation", self.engine.poll)
now = time.monotonic()
if now >= self.next_explore and self.explore_enabled.isChecked():
self.run_fast_automation("explore")
elif now >= self.next_breakthrough and self.breakthrough_targets:
self.run_fast_automation("breakthrough")
def run_fast_automation(self, kind):
if self.busy or self.closed or self.logout_phase is not None:
return
self.automation_generation += 1
setattr(self, "next_" + kind, float("inf"))
generation = self.automation_generation
engine = self.engine
def dispatch():
if generation != self.automation_generation or engine is not self.engine:
return engine.snapshot, [], "自动化设置已变化,未开始的快速任务已取消"
return engine.poll_automation(kind)
self.submit("automation", dispatch)
def arm_extended_automation(self):
active = self.monitoring and self.strategy_toggle.isChecked() and not self.closed and self.engine.snapshot is not None
plans = self.latest_render[1] if self.latest_render else []
explore = active and self.explore_enabled.isChecked() and any(
action.kind in ("explore_start", "explore_finish") and action.path for action in plans)
breakthrough = active and any(action.kind in ("potential", "breakthrough") for action in plans)
self.next_explore = time.monotonic() + 1 if explore else float("inf")
self.next_breakthrough = time.monotonic() + 1 if breakthrough else float("inf")
breakthrough = active and bool(self.breakthrough_targets) and any(
action.kind in ("potential", "breakthrough") for action in plans)
now = time.monotonic()
for kind, enabled in (("explore", explore), ("breakthrough", breakthrough)):
attribute = "next_" + kind
deadline = getattr(self, attribute)
setattr(self, attribute, (now + 1 if deadline == float("inf") else deadline) if enabled else float("inf"))
def poll_delay(self):
return random.uniform(0, self.interval.currentData())
@@ -1654,11 +1689,11 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
self.submit("growth_sync", self.engine.sync_growth)
elif (self.monitoring and self.strategy_toggle.isChecked() and self.fill.isChecked()
and self.ranch_enabled.isChecked() and now >= self.next_hatch):
self.refresh(automated=True, hatch_only=True)
self.run_fast_automation("hatch")
elif self.monitoring and now >= self.next_poll:
self.refresh(automated=True)
elif self.monitoring and self.strategy_toggle.isChecked() and now >= self.next_gift:
self.refresh(automated=True)
self.run_fast_automation("gift")
elif self.monitoring and self.strategy_toggle.isChecked() and now >= min(self.next_explore, self.next_breakthrough):
self.run_extended_automation()
@@ -2067,7 +2102,11 @@ class Window(ExplorationPages, ProgressionPages, ActivityPages, W.QMainWindow):
def settings_changed(self, *args):
if not self.closed and not self.loading_config and hasattr(self, "auto_save_timer"):
self.automation_generation += 1
self.auto_save_timer.start(300)
self.arm_hatching()
self.arm_gifting()
self.arm_extended_automation()
def persist_settings(self):
if self.closed or self.loading_config:
+44 -10
View File
@@ -615,34 +615,68 @@ class ProgressionPlanner:
return block(reason)
if script and not policy.auto_dialogue:
return block("自动对话未启用")
if has_battle:
local_action = self._battle_preflight_needed(step, record, number)
reason = self._battle_step_gate(snapshot, policy, ranch, scope, account, task, info, step, number, kind,
capability=local_action)
if reason:
return block(reason)
if step.get("position") and account["position"] != step["position"]:
return make("progression_navigate", "前往任务位置:" + self.location_text(step["position"]))
if story and number not in record["before"]:
return make("progression_dialogue", "完成任务对话:" + story, story=story, phase="before")
if has_battle:
return make("progression_battle", "执行任务战斗:" + info.get("name", ""),
path="battleService/battleStart", payload={"battleType": "task", "taskTypeId": str(task["typeId"])})
return make("progression_step", "提交任务步骤:" + requirement,
path="taskService/taskCompleteStep", payload={"taskId": _integer(task["id"]), "taskTypeId": str(task["typeId"]), "removeIds": ids})
@staticmethod
def _battle_preflight_needed(step, record, number):
"""Only local actions need the early runtime/team readiness check."""
return bool(step.get("position") or step.get("story") and number not in record["before"])
def _battle_step_gate(self, snapshot, policy, ranch, scope, account, task, info, step, number, kind, *, capability):
"""Reject an unusable battle before navigation or its before-story."""
if _integer(snapshot.raw["master"].get("ti")) < policy.reserve_ti:
return block("当前体力低于保留体力")
return "当前体力低于保留体力"
if account["losses"] >= policy.stop_after_loss:
return block("达到任务战败停止次数")
return "达到任务战败停止次数"
if kind == "battle" and not step.get("battle"):
return block("任务战斗配置缺失")
return "任务战斗配置缺失"
if kind == "passStage":
value = step.get("statusValue") or {}
stage_id, level = str(value.get("stage", "")), _integer(value.get("level"), -1)
reason = self._stage_gate(snapshot, account, stage_id, level)
if reason:
return block(reason)
return reason
stage = self.data.stage(stage_id)
entry = (stage.get("level") or {}).get(str(level), {})
if not entry.get("battle_available", bool(entry.get("battle"))):
return block("关卡战斗配置缺失")
return "关卡战斗配置缺失"
reason = self._battle_resources(snapshot, policy, ranch, stage, level)
if reason:
return block(reason)
return make("progression_battle", "执行任务战斗:" + info.get("name", ""),
path="battleService/battleStart", payload={"battleType": "task", "taskTypeId": str(task["typeId"])})
return make("progression_step", "提交任务步骤:" + requirement,
path="taskService/taskCompleteStep", payload={"taskId": _integer(task["id"]), "taskTypeId": str(task["typeId"]), "removeIds": ids})
return reason
check = getattr(self, "battle_capability", None) if capability else None
if callable(check):
intent = self._intent(scope, task, number, step, "progression_battle",
"执行任务战斗:" + info.get("name", ""), policy,
path="battleService/battleStart",
payload={"battleType": "task", "taskTypeId": str(task["typeId"])})
key = (getattr(self, "battle_capability_key", None), scope, intent.task_id, intent.task_type_id, number, intent.position, intent.stage_id,
intent.difficulty, intent.team, intent.battle_mode,
tuple(sorted((str(row.get("id")), row.get("curStep")) for row in snapshot.raw.get("currentTasks", []))),
account["losses"])
cached = getattr(self, "_battle_capability_cache", {}).get(key)
supported, reason = cached if cached is not None else check(intent)
if not hasattr(self, "_battle_capability_cache"):
self._battle_capability_cache = {}
self._battle_capability_cache[key] = (supported, reason)
while len(self._battle_capability_cache) > 64:
self._battle_capability_cache.pop(next(iter(self._battle_capability_cache)))
if not supported:
return reason or "战斗运行时或阵容尚不可用"
return ""
def _battle_resources(self, snapshot, policy, ranch, stage, level):
base = stage.get("cost") or {}
+8 -2
View File
@@ -8,6 +8,7 @@ import uuid
from .daily import day
from .maps import stages
from .drop_statistics import SweepStatistics, event_reward, normalize_reward
from .team_availability import team_availability_reason
def settled_reward_event(response):
@@ -125,6 +126,8 @@ class SweepRunner:
return [mid for mid in ids if mid in monsters]
def reason(self, snapshot, stage, policy, *, team_ids=None, challenge=False):
if not policy.enabled:
return "扫荡 / 自动挑战已关闭,禁止新的入场"
if self.state.get("pending"):
return "有未完成的扫荡,请先在游戏内检查"
if challenge:
@@ -135,8 +138,9 @@ class SweepRunner:
return "特殊关卡当前不支持自动挑战"
elif not stage.sweep:
return stage.reason
if not (self.team_ids(snapshot, policy) if team_ids is None else team_ids):
return "所选战队无有效魔物"
reason = team_availability_reason(snapshot, policy.team)
if reason:
return reason
positions = self.catalog.data.get("stage_task_positions", {})
for task in snapshot.raw.get("currentTasks", []):
steps = positions.get(str(task.get("typeId")), [])
@@ -159,6 +163,8 @@ class SweepRunner:
return ""
def next(self, snapshot, policy):
if not policy.enabled:
return None
for stage in sorted(stages(self.catalog, snapshot), key=lambda s: (s.city, s.number, s.stage_id, s.level)):
rule = policy.rules.get(stage.stage_id) or {}
if not rule.get("enabled") or str(rule.get("level", "3")) != stage.level:
+46
View File
@@ -0,0 +1,46 @@
"""Read-only availability checks shared by combat planners and runners."""
def _identifier(value):
if isinstance(value, bool):
return None
try:
result = int(value)
except (TypeError, ValueError, OverflowError):
return None
return result if result > 0 else None
def _exploring_ids(snapshot):
result = set()
for team in snapshot.raw.get("exploreTeams") or []:
if not isinstance(team, dict) or _identifier(team.get("status")) != 1:
continue
members = team.get("monsters")
if isinstance(members, str):
members = members.split(",")
if not isinstance(members, (list, tuple)):
continue
result.update(mid for value in members if (mid := _identifier(value)) is not None)
return result
def team_availability_reason(snapshot, team_name):
"""Return why the complete selected battle team cannot enter combat.
An active exploration team or an individual exploration marker reserves
the whole selected lineup. Never drop busy members to make a partial team.
"""
team = next((row for row in snapshot.raw.get("teams") or []
if isinstance(row, dict) and row.get("teamName") == team_name
and row.get("teamType") == "battleTeam"), {})
if not team:
return "未找到所选战队"
ids = [mid for value in team.get("monsters") or [] if (mid := _identifier(value)) is not None]
if not ids or any(mid not in snapshot.monsters for mid in ids):
return "所选战队无有效魔物或实例缺失"
active = _exploring_ids(snapshot)
busy = {mid for mid in ids if mid in active or (_identifier(snapshot.monsters[mid].get("inExploreTeam")) or 0) > 0}
if busy:
return f"所选战队有 {len(busy)}/{len(ids)} 只魔物正在探险,须整队空闲后才能战斗"
return ""
@@ -0,0 +1,315 @@
"""Fast GUI timers must not dispatch unrelated account automation."""
import os
import threading
import time
import unittest
from types import SimpleNamespace
from unittest.mock import Mock
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant import gui
from ranch_assistant.model import Action
from ranch_assistant.tests.test_core import workspace_temp
class FakeAutomationEngine:
"""A plan-first-mainline fake which records the Engine dispatch seam."""
def __init__(self, snapshot, actions):
self.snapshot = snapshot
self.actions = actions
self.calls = []
self.pending_hatches = []
self.gift_planner = SimpleNamespace(next_ready_at=None)
self.demo = False
self.auto = True
self.heartbeat_enabled = False
self.last_heartbeat = time.monotonic()
def __getattr__(self, name):
# Window still uses the real offline Engine for rendering and policy state.
return getattr(self.offline, name)
def poll(self, **kwargs):
self.calls.append(("poll", kwargs))
return self.snapshot, self.actions, "unfiltered poll"
def poll_automation(self, kind):
self.calls.append(("poll_automation", kind))
return self.snapshot, self.actions, f"isolated {kind}"
def pending_recovery_due(self):
return False
def master_sync_due(self):
return False
def growth_sync_due(self):
return False
class AutomationSchedulingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.window = gui.Window(self.folder)
self.window.timer.stop()
self.window.auto_save_timer.stop()
self.wait()
def tearDown(self):
self.window.stop_workflow()
self.window.pool.clear()
self.window.pool.waitForDone(3000)
self.window.close()
self.app.processEvents()
def wait(self, predicate=lambda: True, timeout=5):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
self.app.processEvents()
QTest.qWait(2)
if not self.window.busy and predicate():
return
self.fail("Real Window/fake Engine Qt scheduling did not settle")
def action(self, kind):
return Action(kind=kind, description=kind, path="synthetic/" + kind, payload={})
def install_engine(self, *kinds):
actions = [self.action("progression"), self.action("map_challenge"), self.action("sweep")]
actions.extend(self.action(kind) for kind in kinds)
offline = self.window.engine
engine = FakeAutomationEngine(offline.snapshot, actions)
engine.offline = offline
engine.demo = True
self.window.engine = engine
self.window.latest_render = (engine.snapshot, actions)
self.window.monitoring = True
self.window.set_strategy_checked(True)
self.window.next_poll = float("inf")
return engine
def install_engine_policy(self):
self.window.engine.policy = self.window.read_policy()
self.window.apply_explore_policy(self.window.read_explore_policy())
def drain(self):
"""Let already queued real Jobs start after a stop request."""
self.window.pool.waitForDone(3000)
self.wait()
def test_real_window_expired_extended_timer_never_uses_full_poll(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.window.arm_extended_automation()
self.window.next_explore = time.monotonic() - 1
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "explore")])
def test_each_due_extended_kind_is_dispatched_separately(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
self.window.arm_extended_automation()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
self.window.run_extended_automation()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "explore")])
self.wait()
self.window.next_breakthrough = time.monotonic() - 1
self.window.run_extended_automation()
self.wait(lambda: len(engine.calls) >= 2)
self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"])
def test_fast_hatch_and_gift_dispatch_only_their_own_kind(self):
for kind in ("hatch", "gift"):
with self.subTest(kind=kind):
engine = self.install_engine()
if kind == "hatch":
engine.pending_hatches = [self.action("hatch")]
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
else:
self.window.gift_enabled.setChecked(True)
setattr(self.window, "next_" + kind, time.monotonic() - 1)
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", kind)])
self.wait()
def test_disabling_explore_cancels_unsent_queue_before_worker_entry(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.window.next_explore = time.monotonic() - 1
release = threading.Event()
blocker = threading.Event()
def held_job():
blocker.set()
if not release.wait(4):
raise TimeoutError("test blocker was not released")
return "held"
queued = []
original_start = self.window.pool.start
def hold_next(runnable):
queued.append(runnable)
try:
self.install_engine_policy()
self.window.submit("fixture_blocker", held_job)
self.assertTrue(blocker.wait(1))
self.window.pool.start = hold_next
self.window.schedule()
self.assertTrue(self.window.busy)
self.window.explore_enabled.setChecked(False)
self.window.persist_settings()
self.assertEqual(self.window.next_explore, float("inf"))
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
release.set()
self.drain()
self.assertNotIn(("poll_automation", "explore"), engine.calls)
self.assertFalse(self.window.busy)
def test_stop_cancels_every_fast_deadline_and_queued_worker(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
self.window.gift_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
engine.pending_hatches = [self.action("hatch")]
self.install_engine_policy()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
self.window.next_hatch = self.window.next_gift = time.monotonic() - 1
queued = []
original_start = self.window.pool.start
self.window.pool.start = queued.append
try:
self.window.schedule()
self.window.stop_workflow()
self.assertTrue(all(getattr(self.window, "next_" + kind) == float("inf")
for kind in ("explore", "breakthrough", "hatch", "gift")))
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
self.drain()
self.assertEqual(engine.calls, [])
self.assertFalse(self.window.busy)
def test_completed_kind_does_not_postpone_other_due_extended_kind(self):
engine = self.install_engine("explore_start", "breakthrough")
self.window.explore_enabled.setChecked(True)
self.window.breakthrough_targets = {"900": 1}
self.window.arm_extended_automation()
self.window.next_explore = self.window.next_breakthrough = time.monotonic() - 1
due_breakthrough = self.window.next_breakthrough
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(self.window.next_breakthrough, due_breakthrough)
self.window.schedule()
self.wait(lambda: len(engine.calls) == 2)
self.assertEqual([call[1] for call in engine.calls], ["explore", "breakthrough"])
def test_gift_completion_preserves_due_hatch_and_gift_is_not_starved(self):
engine = self.install_engine()
self.window.fill.setChecked(True)
self.window.ranch_enabled.setChecked(True)
self.window.gift_enabled.setChecked(True)
engine.pending_hatches = [self.action("hatch")]
self.window.arm_hatching()
self.window.arm_gifting()
self.window.next_hatch = self.window.next_gift = time.monotonic() - 1
due_hatch = self.window.next_hatch
self.window.schedule()
self.wait(lambda: bool(engine.calls))
self.assertEqual(engine.calls, [("poll_automation", "hatch")])
engine.gift_planner.next_ready_at = engine.snapshot.now
self.window.arm_gifting()
self.window.next_gift = time.monotonic() - 1
self.window.schedule()
self.wait(lambda: len(engine.calls) == 2)
self.assertEqual(engine.calls[-1], ("poll_automation", "gift"))
self.assertGreaterEqual(self.window.next_hatch, due_hatch)
def test_closing_map_cancels_queued_automatic_poll_before_engine_entry(self):
engine = self.install_engine()
self.window.map_enabled.setChecked(True)
self.install_engine_policy()
self.window.next_poll = time.monotonic() - 1
queued = []
original_start = self.window.pool.start
self.window.pool.start = queued.append
try:
self.window.schedule()
self.assertTrue(self.window.busy)
self.window.map_enabled.setChecked(False)
finally:
self.window.pool.start = original_start
for runnable in queued:
original_start(runnable)
self.drain()
self.assertEqual(engine.calls, [])
self.assertFalse(self.window.map_enabled.isChecked())
def test_disabling_while_busy_applies_before_next_fast_dispatch(self):
engine = self.install_engine("explore_start")
self.window.explore_enabled.setChecked(True)
self.install_engine_policy()
release = threading.Event()
entered = threading.Event()
def held_automation(kind):
engine.calls.append(("poll_automation", kind))
entered.set()
if not release.wait(4):
raise TimeoutError("test automation was not released")
return engine.snapshot, [], "held automation"
engine.poll_automation = held_automation
self.window.next_explore = time.monotonic() - 1
self.window.schedule()
self.assertTrue(entered.wait(1))
self.window.explore_enabled.setChecked(False)
self.window.persist_settings()
self.assertIsNotNone(self.window.pending_policy)
self.assertEqual(self.window.next_explore, float("inf"))
release.set()
self.drain()
self.window.schedule()
self.drain()
self.assertEqual(engine.calls, [("poll_automation", "explore")])
self.assertIsNone(self.window.pending_policy)
self.assertFalse(self.window.explore_enabled.isChecked())
self.assertEqual(self.window.next_explore, float("inf"))
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,275 @@
"""Offline regressions for exploring teams and isolated fast schedulers."""
from copy import deepcopy
from types import SimpleNamespace
import unittest
from unittest.mock import Mock
from ranch_assistant.battles import BattleOrchestrator
from ranch_assistant.engine import Engine
from ranch_assistant.exploration import ExplorePolicy
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.maps import stages
from ranch_assistant.model import Action, Catalog, Policy, Snapshot
from ranch_assistant.sweeping import SweepPolicy, SweepRunner
from ranch_assistant.team_availability import team_availability_reason
from ranch_assistant.tests.test_activities import scenario
from ranch_assistant.tests.test_battle_orchestration import ExperimentalRuntime
from ranch_assistant.tests.test_gift_timing import GIFT, GiftClient, gift_policy
from ranch_assistant.tests.test_hatch_timing import HatchClient, policy_for as hatch_policy
from ranch_assistant.tests.test_ranch_automation_integration import FakeClient as AutomationClient
from ranch_assistant.tests.test_ranch_automation_integration import raw as automation_raw
from ranch_assistant.tests.test_core import workspace_temp
COMBAT_WRITES = {"stageService/stageStart", "battleService/battleStart",
"battleService/battleEnd", "taskService/taskCompleteStep"}
class BusyTeamTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
self.catalog, snapshot = scenario()
self.raw = deepcopy(snapshot.raw)
self.raw["currentTasks"] = []
self.raw["teams"][0]["monsters"] = [900, 901, 902]
for mid in (901, 902):
member = deepcopy(self.raw["monsters"][0])
member["id"] = mid
self.raw["monsters"].append(member)
self.snapshot = Snapshot(deepcopy(self.raw))
self.client = Mock()
self.client.snapshot.side_effect = lambda: Snapshot(deepcopy(self.raw))
self.client.call.side_effect = lambda path, payload: (
{"resCode": 0, "triggerEvent": False} if path.endswith("stageStart")
else {"resCode": 0, "reward": {}})
self.runtime = ExperimentalRuntime()
def occupy(self, count, *, active=False):
self.raw = deepcopy(self.snapshot.raw)
selected = {int(mid) for mid in self.raw["teams"][0]["monsters"][:count]}
for member in (mon for mon in self.raw["monsters"] if int(mon["id"]) in selected):
if active:
member.pop("inExploreTeam", None)
else:
member["inExploreTeam"] = 1
if active:
self.raw["exploreTeams"] = [{"id": 77, "status": 1, "area": "1",
"monsters": ",".join(str(mid) for mid in (900, 901, 902)[:count]), "endTime": 9999999999999}]
self.snapshot = Snapshot(deepcopy(self.raw))
def map_engine(self, *, cleared):
self.raw["history"]["passStage"]["0102"] = ["1", "2", "3"] if cleared else []
info = deepcopy(self.catalog.data["stage_info"])
for row in info.values():
for level in row["level"].values():
level["battle"] = {"fixture": True}
data = ProgressionData({"task_info": {}, "stage_info": info,
"game_setting": self.catalog.data["game_setting"]})
engine = Engine(self.catalog, self.client, self.folder / "purchase.json",
game_data=data, experimental_runtime=self.runtime)
engine.policy = Policy(enabled=False, keep_money=0)
engine.sweep_policy = SweepPolicy(True,
{"0102": {"enabled": True, "level": "1", "limit": 3}})
engine.master_sync.settle = Mock()
engine.auto = True
return engine
def assert_no_combat_writes(self):
paths = [call.args[0] for call in self.client.call.call_args_list]
self.assertFalse(COMBAT_WRITES.intersection(paths), paths)
self.runtime.run.assert_not_called()
def test_shared_reason_is_pure_and_rejects_the_whole_selected_team(self):
for active in (False, True):
for count, expected in ((0, ""), (1, "1/3"), (3, "3/3")):
with self.subTest(active=active, count=count):
self.setUp()
self.occupy(count, active=active)
before = deepcopy(self.raw)
reason = team_availability_reason(self.snapshot, "teamA")
if expected:
self.assertIn("探险", reason)
self.assertIn(expected, reason)
self.assertIn("整队", reason)
else:
self.assertEqual(reason, "")
self.assertEqual(self.raw, before)
self.assertEqual(team_availability_reason(self.snapshot, "missing"), "未找到所选战队")
def test_all_sweep_kinds_reject_any_exploring_member_before_writes(self):
for cleared in (True, False):
for active in (False, True):
for count in (1, 3):
with self.subTest(cleared=cleared, active=active, count=count):
self.setUp()
self.occupy(count, active=active)
engine = self.map_engine(cleared=cleared)
engine.poll()
stage = next(stage for stage in stages(self.catalog, engine.snapshot)
if stage.stage_id == "0102" and stage.level == "1")
reason = engine.map_stage_reason(engine.snapshot, stage, engine.sweep_policy)
self.assertIn("探险", reason)
self.assertIn("整队", reason)
self.assert_no_combat_writes()
def test_direct_sweep_rechecks_occupancy_instead_of_filtering_members(self):
self.occupy(1, active=True)
runner = SweepRunner(self.catalog)
policy = SweepPolicy(True, {"0101": {"enabled": True, "level": "3", "limit": 3}})
stage = next(stage for stage in stages(self.catalog, self.snapshot)
if stage.stage_id == "0101" and stage.level == "3")
with self.assertRaisesRegex(ValueError, "探险.*整队"):
runner.run(self.client, self.snapshot, stage, policy)
self.assert_no_combat_writes()
self.assertEqual(runner.used(self.snapshot, stage), 0)
def test_task_and_ordinary_battles_reject_either_occupancy_marker(self):
for active in (False, True):
for task in (False, True):
with self.subTest(active=active, task=task):
self.setUp()
self.occupy(2, active=active)
runner = BattleOrchestrator(self.catalog, runtime=self.runtime)
intent = {"kind": "progression_battle", "task_id": 5 if task else 0,
"task_type_id": "100" if task else "", "step_number": 1,
"stage_id": "0101", "difficulty": "1",
"battle_kind": "battle" if task else "ordinary_stage"}
if task:
self.snapshot.raw["currentTasks"] = [{"id": 5, "typeId": "100", "curStep": 1}]
message = runner.run(self.client, self.snapshot, intent, SimpleNamespace(
enabled=True, team="teamA", stop_after_loss=0, reserve_ti=0,
allow_items=True, item_reserves={}, max_money=100000, battle_mode="experimental"))
self.assertIn("探险", message)
self.assertIn("整队", message)
self.assert_no_combat_writes()
def test_disabling_sweep_invalidates_old_rules_without_touching_pending_barrier(self):
stage = next(stage for stage in stages(self.catalog, self.snapshot)
if stage.stage_id == "0101" and stage.level == "3")
runner = SweepRunner(self.catalog)
runner.state["pending"] = {"stage": "0101", "level": "3", "phase": "扫荡结算待确认"}
pending = deepcopy(runner.state["pending"])
policy = SweepPolicy(False, {"0101": {"enabled": True, "level": "3", "limit": 3}})
self.assertIn("关闭", runner.reason(self.snapshot, stage, policy))
self.assertIsNone(runner.next(self.snapshot, policy))
with self.assertRaisesRegex(ValueError, "关闭"):
runner.run(self.client, self.snapshot, stage, policy)
self.assertEqual(runner.state["pending"], pending)
self.client.call.assert_not_called()
class FastSchedulingTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
def automation_engine(self):
catalog = Catalog()
client = AutomationClient(automation_raw(catalog))
engine = Engine(catalog, client, self.folder / "purchase.json")
engine.master_sync.settle = Mock()
engine.settle_pending_growth = Mock(return_value=False)
engine.auto = True
return engine, client
def test_hatch_only_cannot_execute_a_commission(self):
client = HatchClient(Catalog())
engine = Engine(client=client, catalog=Catalog())
engine.policy = hatch_policy(client)
engine.auto = True
hatch_actions = engine.hatch_planner.hatch_actions
engine.hatch_planner.hatch_actions = Mock(return_value=[])
engine.tasks.plan = Mock(return_value=[Action("quest_test", "不应执行委托",
"taskService/acceptTask", {"taskId": 1})])
engine.poll(hatch_only=True)
self.assertEqual(client.calls, [])
engine.hatch_planner.hatch_actions = hatch_actions
engine.tasks.plan = Mock(return_value=[])
engine.poll(hatch_only=True)
self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"])
def test_hatch_fast_kind_retains_existing_hatch_behavior(self):
catalog = Catalog()
client = HatchClient(catalog)
engine = Engine(catalog, client)
engine.policy = hatch_policy(client)
engine.auto = True
engine.poll_automation("hatch")
self.assertEqual([path for path, _ in client.calls], ["stackService/stackAddMonster"])
def test_fast_kinds_execute_only_their_own_action(self):
for kind in ("explore", "breakthrough"):
with self.subTest(kind=kind):
self.setUp()
engine, client = self.automation_engine()
if kind == "explore":
engine.explore_policy = ExplorePolicy(True,
{"77": {"enabled": True, "area": "1", "monsters": []}})
area = engine.explore_planner.areas["1"]
client.value["history"]["passStage"] = {area["passStage"]: {"1": True}}
client.value["monsters"][0]["level"] = 60
else:
engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False,
breakthrough_targets={"900": 1})
engine.poll_automation(kind)
expected = "exploreService/start" if kind == "explore" else "monsterService/monsterPotentialUpgrade"
self.assertEqual([path for path, _ in client.calls], [expected])
def test_fast_kind_ignores_another_due_kind_and_all_other_strategies(self):
engine, client = self.automation_engine()
engine.explore_policy = ExplorePolicy(True,
{"77": {"enabled": True, "area": "1", "monsters": []}})
area = engine.explore_planner.areas["1"]
client.value["history"]["passStage"] = {area["passStage"]: {"1": True}}
client.value["monsters"][0]["level"] = 60
engine.policy = Policy(fill=False, collect=False, dispatch=False, feed=False,
breakthrough_targets={"900": 1})
other = Action("progression", "不应执行", "taskService/navigate", {"intent": {}})
engine._execute_legacy_task = Mock()
original_plans = engine.plans
engine.plans = Mock(side_effect=lambda: [other] + original_plans())
_, _, message = engine.poll_automation("breakthrough")
self.assertEqual([path for path, _ in client.calls], ["monsterService/monsterPotentialUpgrade"])
engine._execute_legacy_task.assert_not_called()
client.calls.clear()
client.value["monsters"][0]["pAtk"] += 1
_, _, message = engine.poll_automation("gift")
self.assertEqual(client.calls, [])
self.assertIn("赠礼", message)
def test_gift_fast_path_does_not_run_progression_or_maps(self):
catalog = Catalog()
client = GiftClient(catalog)
engine = Engine(catalog, client)
engine.policy = gift_policy()
engine.auto = True
forbidden = Action("progression", "不应执行", "taskService/navigate", {"intent": {}})
original_plans = engine.plans
engine.plans = Mock(side_effect=lambda: [forbidden] + original_plans())
engine._execute_legacy_task = Mock()
snapshot, _, _ = engine.poll_automation("gift")
self.assertEqual([path for path, _ in client.calls], [GIFT])
self.assertEqual(snapshot.monsters[1]["feel"], 10)
engine._execute_legacy_task.assert_not_called()
def test_fast_path_respects_stop_and_cross_kind_pending_barriers(self):
for kind in ("explore", "breakthrough", "gift"):
with self.subTest(kind=kind, stopped=True):
engine, client = self.automation_engine()
engine.auto = False
engine.poll_automation(kind)
self.assertEqual(client.calls, [])
with self.subTest(kind=kind, pending=True):
engine, client = self.automation_engine()
engine._breakthrough_pending = {"kind": "invalid", "role_id": "1",
"uncertain": True, "message": "待核对"}
_, plans, _ = engine.poll_automation(kind)
self.assertEqual((client.calls, plans), ([], []))
def test_unknown_fast_kind_is_rejected(self):
engine, _ = self.automation_engine()
with self.assertRaises(ValueError):
engine.poll_automation("progression")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,124 @@
"""Offline regression for restored battle gates preceding local navigation."""
from copy import deepcopy
import unittest
from unittest.mock import Mock, patch
from ranch_assistant.engine import Engine
from ranch_assistant.game_data import ProgressionData
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.progression import ProgressionPolicy
from ranch_assistant.tests.test_core import workspace_temp
def fixture():
data = ProgressionData({
"task_info": {
"1002003": {"type": 1, "name": "mainline", "steps": [{"statusType": "passStage",
"position": "city2_wild_stage0203_level1", "story": "main_before",
"afterStory": "main_after", "statusValue": {"stage": "0203", "level": 1}}]},
"2001006": {"type": 2, "name": "side battle", "steps": [
{"statusType": "none", "story": "side_before"},
{"statusType": "battle", "position": "city1_wild_stage0109",
"story": "side_before", "afterStory": "side_after", "battle": {"teams": []}}]},
"2001999": {"type": 2, "name": "side dialogue", "steps": [
{"statusType": "none", "position": "city1_market", "story": "side_before"}]},
},
"scripts": {name: {"supported": True} for name in
("main_before", "main_after", "side_before", "side_after")},
"game_setting": {"cityInfo": {"1": {"name": "one"}, "2": {"name": "two"}}},
"stage_info": {key: {"city": city, "cost": {}, "level": {"1": {"cost": 0, "battle_available": True}}}
for key, city in (("0203", 2), ("0109", 1))},
})
raw = {"master": {"id": 71, "level": 30, "ti": 100, "money": 1000},
"currentTasks": [{"id": 51, "typeId": "1002003", "curStep": 1, "stepValue": 0},
{"id": 52, "typeId": "2001006", "curStep": 2, "stepValue": 0}],
"history": {"unlockCity": {"1": True, "2": True},
"unlockStage": {"0203": [1], "0109": [1]}},
"monsters": [], "items": [], "teams": [], "stacks": [], "rooms": []}
return data, raw
class ProgressionReplayLoopTests(unittest.TestCase):
def setUp(self):
self.folder = self.enterContext(workspace_temp())
@staticmethod
def add_team(raw):
raw["monsters"] = [{"id": 900, "typeId": 1001010, "mode": 2, "process": 3, "level": 1}]
raw["teams"] = [{"teamName": "teamA", "teamType": "battleTeam", "monsters": [900]}]
def engine(self, raw, data, *, losses=1, runtime=False, position=""):
self.catalog = Catalog()
client = Mock()
client.snapshot.side_effect = lambda: Snapshot(deepcopy(raw))
client.call.side_effect = AssertionError("offline replay must not call the game")
engine = Engine(self.catalog, client, self.folder / "account" / "purchase.json", game_data=data,
battle_runtime=Mock() if runtime else None)
if runtime:
engine.battles.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
"faithful": True, "approximate": False}
engine.progression_policy = ProgressionPolicy(enabled=True, sidequests=True)
engine.policy = Policy(enabled=False, gift_enabled=False, fill=False)
engine.snapshot = Snapshot(deepcopy(raw))
engine._ensure_progression()
scope, account = engine.progression_planner._account(engine.snapshot)
account.update(position=position, losses=losses)
engine._persist_progression()
restored = Engine(self.catalog, client, self.folder / "account" / "purchase.json", game_data=data,
battle_runtime=Mock() if runtime else None)
if runtime:
restored.battles.runtime.inspect.return_value = {"supported": True, "settlement_eligible": True,
"faithful": True, "approximate": False}
restored.progression_policy = ProgressionPolicy(enabled=True, sidequests=True)
restored.policy = Policy(enabled=False, gift_enabled=False, fill=False)
restored.auto = True
restored.refresh_progression()
return restored
def test_restored_loss_blocks_both_battles_before_navigation(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=1, runtime=True, position="city1_wild_stage0109")
before = engine.progression_planner.export_state()
navigations = []
for _ in range(8):
engine.poll()
navigations.extend(r for r in engine.battle_journal.records(engine.snapshot)
if r["kind"] == "progression_navigate")
self.assertEqual(navigations, [])
self.assertEqual(engine.progression_planner.export_state(), before)
def test_runtime_gate_is_position_independent(self):
data, raw = fixture()
reasons = set()
for position in ("", "city2_wild_stage0203_level1", "city1_wild_stage0109"):
with self.subTest(position=position):
self.add_team(raw)
engine = self.engine(raw, data, losses=0, runtime=False, position=position)
self.assertFalse(any(i.kind == "progression_navigate" and not i.blocked
for i in engine._progression_intents))
reasons.add(next(r["block_reason"] for r in engine.progression_rows()
if r["task_type_id"] == "1002003"))
self.assertEqual(len(reasons), 1)
self.assertIn("运行时", reasons.pop())
def test_missing_team_blocks_before_navigation(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=0, runtime=True, position="city2_wild_stage0203_level1")
reason = next(r["block_reason"] for r in engine.progression_rows() if r["task_type_id"] == "1002003")
self.assertIn("队", reason)
self.assertEqual(engine.battle_journal.records(engine.snapshot), [])
def test_stopped_restored_loss_writes_no_journal(self):
data, raw = fixture()
engine = self.engine(raw, data, losses=1, runtime=True, position="city1_wild_stage0109")
engine.cancel_progression()
with patch.object(engine.battle_journal, "save", wraps=engine.battle_journal.save) as save:
for _ in range(8):
engine.poll()
save.assert_not_called()
def test_blocked_mainline_does_not_starve_executable_side_dialogue(self):
data, raw = fixture()
raw["currentTasks"].append({"id": 53, "typeId": "2001999", "curStep": 1, "stepValue": 0})
engine = self.engine(raw, data, losses=1, position="city1_market")
self.assertEqual(engine._progression_intents[0].task_type_id, "2001999")
self.assertEqual(engine._progression_intents[0].kind, "progression_dialogue")