Fix gift item instance IDs and per-monster cooldown scheduling

Use bag instance IDs required by the client protocol. Apply confirmed feel and giftDate values across stale queries, skip cooling targets, and schedule ready gifts independently of random polling. Replan cultivation locally and retain local strategy errors in diagnostics.
This commit is contained in:
AttilaNet
2026-11-08 13:08:12 +08:00
parent db17fc1288
commit 3b5da7ebcb
8 changed files with 331 additions and 21 deletions
+39
View File
@@ -16,6 +16,8 @@ from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Planner, Policy, Snapshot
from ranch_assistant.policy_io import import_config, portable_config
from ranch_assistant.tests.test_core import workspace_temp
from ranch_assistant.tests.test_accounts import fake_client, role_snapshot
from ranch_assistant.api import Session
def monster(catalog, mid, *, level=10, feel=0, scale=.3, species=1001010, process=3):
@@ -174,3 +176,40 @@ class CultivationGuiTests(unittest.TestCase):
self.assertTrue(window.gift_auto_representative.isChecked())
finally:
window.close()
def test_selecting_representatives_replans_locally_without_an_api_request(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
calls = []
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
session = Session("http://127.0.0.1/", "synthetic-token", account_id="fixture", server_id=1, role_id=101)
client = fake_client(session, window.catalog, calls)
window.result("connected", (client, Snapshot(role_snapshot(window.catalog, 101))))
window.gift_auto_representative.setChecked(True)
self.wait(lambda: not window.auto_save_timer.isActive() and not window.busy and bool(window.engine.cultivation.selected))
self.assertEqual(calls, [])
self.assertTrue(window.monitoring)
self.assertFalse(window.strategy_toggle.isChecked())
finally:
window.close()
def test_local_selection_failure_is_recorded_as_local_and_keeps_monitoring(self):
with workspace_temp() as folder:
window = Window(folder)
window.timer.stop()
try:
self.wait(lambda: not window.busy and window.engine.snapshot is not None)
window.monitoring = True
with patch.object(window.engine.cultivation, "select", side_effect=ValueError("fixture-selection-failure")):
window.gift_auto_representative.setChecked(True)
self.wait(lambda: any("fixture-selection-failure" in e.get("message", "") for e in window.trace.events))
self.wait(lambda: not window.busy)
event = next(e for e in window.trace.events if "fixture-selection-failure" in e.get("message", ""))
self.assertEqual(event["scope"], "local")
self.assertEqual(event["kind"], "error")
self.assertTrue(window.monitoring)
self.assertFalse(window.strategy_toggle.isChecked())
finally:
window.close()
+158
View File
@@ -0,0 +1,158 @@
import copy
import os
import time
import unittest
from unittest.mock import patch
os.environ.setdefault("QT_QPA_PLATFORM", "offscreen")
from PySide6 import QtWidgets as W
from PySide6.QtTest import QTest
from ranch_assistant.engine import Engine, demo_snapshot
from ranch_assistant.gifts import GiftPlanner
from ranch_assistant.gui import Window
from ranch_assistant.model import Catalog, Policy, Snapshot
from ranch_assistant.tests.test_core import workspace_temp
NOW = 1_800_000_000
GIFT = "monsterService/monsterSendGift"
def gift_snapshot(catalog):
raw = copy.deepcopy(demo_snapshot(catalog).raw)
first = copy.deepcopy(next(m for m in raw["monsters"] if m["process"] == 3))
first.update(id=1, feel=0, giftTime=0, entangleLevel=0)
second = first | {"id": 2}
raw.update(monsters=[first, second], stacks=[], teams=[],
items=[{"id": 10, "typeId": 30005, "num": 10}])
return Snapshot(raw)
def gift_policy():
return Policy(enabled=False, gift_enabled=True, gift_liked_only=False,
gift_targets={"1": 1, "2": 2}, gift_items={"30005": {"enabled": True, "reserve": 0}})
class GiftClient:
def __init__(self, catalog):
self.raw = gift_snapshot(catalog).raw
self.calls = []
self.response = {"feel": 10, "giftDate": NOW * 1000, "addFeel": 10}
def snapshot(self):
# A successful query can briefly lag behind the confirmed gift result.
return Snapshot(copy.deepcopy(self.raw))
def call(self, path, payload):
self.calls.append((path, payload))
if path != GIFT:
raise AssertionError(path)
return self.response
class GiftTimingTests(unittest.TestCase):
def setUp(self):
self.catalog = Catalog()
def test_gift_request_uses_bag_instance_id_instead_of_item_type(self):
snapshot = gift_snapshot(self.catalog)
action = GiftPlanner(self.catalog).plan(snapshot, gift_policy())[0]
self.assertEqual(action.payload["itemId"], 10)
self.assertNotEqual(action.payload["itemId"], 30005)
def test_success_response_updates_each_monster_despite_stale_queries(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
client = GiftClient(self.catalog)
engine = Engine(self.catalog, client)
engine.policy = gift_policy()
engine.auto = True
first, _, _ = engine.poll()
self.assertEqual(first.monsters[1]["feel"], 10)
self.assertEqual(first.monsters[1]["giftTime"], NOW)
engine.poll()
engine.poll()
self.assertEqual([payload["monsterId"] for _, payload in client.calls], [1, 2])
def test_next_due_uses_earliest_eligible_cooldown_and_ignores_full_targets(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
snapshot = gift_snapshot(self.catalog)
snapshot.monsters[1]["giftTime"] = (NOW - 7200 + 120) * 1000
snapshot.monsters[2]["giftTime"] = (NOW - 7200 + 15) * 1000
planner = GiftPlanner(self.catalog)
self.assertEqual(planner.plan(snapshot, gift_policy()), [])
self.assertEqual(planner.next_ready_at, NOW + 15)
snapshot.monsters[2]["feel"] = self.catalog.max_feel(snapshot.monsters[2])
planner.plan(snapshot, gift_policy())
self.assertEqual(planner.next_ready_at, NOW + 120)
snapshot.raw["items"][0]["num"] = 0
planner.plan(snapshot, gift_policy())
self.assertIsNone(planner.next_ready_at)
def test_unconfirmed_gift_result_stops_before_another_write(self):
with patch("ranch_assistant.model.time.time", return_value=NOW):
client = GiftClient(self.catalog)
client.response = {"feel": 10}
engine = Engine(self.catalog, client)
engine.policy = gift_policy()
engine.auto = True
with self.assertRaisesRegex(ValueError, "feel / giftDate"):
engine.poll()
self.assertFalse(engine.auto)
engine.poll()
self.assertEqual(len(client.calls), 1)
class GiftTimingGuiTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.app = W.QApplication.instance() or W.QApplication([])
def wait(self, window):
for _ in range(600):
self.app.processEvents()
QTest.qWait(2)
if not window.busy:
return
self.fail("Gift worker did not finish")
def test_gifts_continue_without_waiting_for_poll_and_stop_at_each_cooldown(self):
with workspace_temp() as folder, patch("ranch_assistant.model.time.time", return_value=NOW):
window = Window(folder)
window.timer.stop()
try:
self.wait(window)
window.engine = Engine(window.catalog)
window.engine.snapshot = gift_snapshot(window.catalog)
policy = gift_policy()
window.ranch_enabled.setChecked(False)
window.gift_enabled.setChecked(True)
window.gift_liked_only.setChecked(False)
window.gift_targets = policy.gift_targets
window.gift_items = policy.gift_items
window.monitoring = True
window.set_strategy_checked(True)
with patch.object(window, "poll_delay", return_value=300):
window.refresh(automated=True)
self.wait(window)
self.assertGreater(window.next_poll, time.monotonic() + 250)
window.schedule()
self.wait(window)
self.assertTrue(all(m["giftTime"] > 0 for m in window.engine.snapshot.raw["monsters"]))
self.assertGreater(window.next_gift, time.monotonic() + 7100)
window.schedule()
self.assertFalse(window.busy)
due = window.next_gift
window.next_poll = float("inf")
with patch("ranch_assistant.model.time.time", return_value=NOW + 7201), patch("ranch_assistant.gui.time.monotonic", return_value=due + 1):
window.schedule()
self.wait(window)
self.assertTrue(any(m["giftTime"] > NOW for m in window.engine.snapshot.raw["monsters"]))
window.stop_workflow()
self.assertEqual(window.next_gift, float("inf"))
self.assertTrue(window.monitoring)
finally:
window.close()
if __name__ == "__main__":
unittest.main()
+12 -2
View File
@@ -43,7 +43,7 @@ class GiftTests(unittest.TestCase):
def test_liked_item_respects_reserve_cap_and_cooldown(self):
action = self.planner.plan(self.snapshot, self.policy)[0]
self.assertEqual(action.payload, {"monsterId": 900, "itemId": int(self.liked)})
self.assertEqual(action.payload, {"monsterId": 900, "itemId": 2000})
self.snapshot.raw["items"][-2]["num"] = 2
self.assertEqual(self.planner.plan(self.snapshot, self.policy), [])
self.snapshot.raw["items"][-2]["num"] = 3
@@ -59,11 +59,21 @@ class GiftTests(unittest.TestCase):
self.policy.gift_items[self.liked]["enabled"] = False
self.assertEqual(self.planner.plan(self.snapshot, self.policy), [])
self.policy.gift_liked_only = False
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["itemId"], int(self.disliked))
self.assertEqual(self.planner.plan(self.snapshot, self.policy)[0].payload["itemId"], 2001)
def test_quest_reserves_take_precedence(self):
self.assertEqual(self.planner.plan(self.snapshot, self.policy, QuestPolicy(item_reserves={self.liked: 3})), [])
def test_cooling_manual_target_does_not_block_other_selected_targets(self):
other = copy.deepcopy(self.target)
other["id"] = 901
self.snapshot.raw["monsters"].append(other)
self.policy.gift_targets["901"] = 2
self.target["giftTime"] = self.snapshot.now * 1000
plans = self.planner.plan(self.snapshot, self.policy)
self.assertTrue(plans, "A cooling first target blocked another ready target")
self.assertEqual(plans[0].payload["monsterId"], 901)
def test_demo_consumes_one_item_and_clamps_feel(self):
engine = Engine(self.catalog)
engine.snapshot = self.snapshot