Browse Source

Merge upstream dev through cc65d55d with purchase and AreaBoss safeguards

Integrate 4e3528a6..cc65d55d (5 commits including one merge).
Adopt blue-ticket single/multiple dialog detection, jade price OCR and the
85-jade ceiling, affordable full-quantity purchases and partial-budget
one-at-a-time purchases. Include the jade PNG and image/OCR metadata.
Adopt AreaBoss's new battle settlement flow, repeat-challenge behavior,
battle long-wait refreshes, non-Windows desktop import guard and hook cleanup.

Regression replays exposed gaps in the incoming changes; complete them:
- Use actual dialog price for affordability, allowing a discounted 50-jade
  ticket with a 60-jade balance; keep fixed-price callers' existing gate.
- Check balance and remaining count for single-item dialogs too.
- Cancel unknown/non-one default quantities instead of falling back to the
  legacy increment-first buy_more(1), which can buy more than intended.
- Apply the configured AreaBoss strategy context as well as its options.
- Accept an already-returned filter screen after settlement instead of
  waiting indefinitely for a red close button that is no longer present.

Preserve local context-isolated strategy/options, bounded battle completion,
desktop initialization/recovery and ROI handling. Existing mail, raid,
exploration, cropped UI, activity and anti-ban idle cleanup fixes are unchanged.
No equivalent local replacement existed for the incoming new functionality;
normal merge retains every upstream commit without conflicts or skipped parts.

Validation: 435 pytest cases passed (tests/ and both FrogBoss test modules),
including 28 new purchase/AreaBoss cases. Nine failing incoming-path replays
were fixed; adapted the prepare mock to verify the new long-wait refresh.
10 Python syntax checks, 7 production imports, 2 JSON files, image/OCR rule
consistency, 42x52 PNG verification, 8 synthetic matching cases, 4 retained
AST checks and git diff --check passed. Two existing Pydantic warnings.
The upstream PNG emits a non-fatal invalid sBIT ancillary-metadata warning;
PIL/OpenCV decode and matching succeed, and the upstream pixels are retained.
No live emulator, game purchase or desktop game test was performed.
unknown 3 tuần trước cách đây
mục cha
commit
675f4911c3

+ 5 - 1
module/device/device.py

@@ -12,7 +12,11 @@ from module.base.timer import Timer
 from module.config.utils import get_server_next_update
 from module.device.app_control import AppControl
 from module.device.control import Control
-from module.device.desktop_device import DesktopDevice
+if IS_WINDOWS:
+    from module.device.desktop_device import DesktopDevice
+else:
+    class DesktopDevice:
+        pass
 from module.device.platform2 import Platform
 from module.device.screenshot import Screenshot
 from module.exception import (GameNotRunningError,

+ 18 - 7
tasks/AreaBoss/script_task.py

@@ -10,6 +10,8 @@ import re
 from module.atom.click import RuleClick
 from tasks.base_task import BaseTask
 from tasks.Component.GeneralBattle.general_battle import GeneralBattle
+from tasks.Component.GeneralBattle.battle import Battle
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy, battle_wait_options
 from tasks.GameUi.game_ui import GameUi
 from tasks.GameUi.page import page_area_boss, page_shikigami_records
 from tasks.Component.SwitchSoul.switch_soul import SwitchSoul
@@ -21,7 +23,7 @@ from module.atom.image import RuleImage
 from typing import List
 
 
-class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
+class ScriptTask(Battle, GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
 
     def _get_dynamic_boss_count(self) -> int:
         """
@@ -159,10 +161,10 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
             return False
 
         # 如果已经打过该BOSS,直接跳过不打了
-        if self.is_group_ranked():
-            logger.warning("There is no boss could be challenged")
-            self.ui_click_until_disappear(self.I_AB_CLOSE_RED, interval=3)
-            return True
+        # if self.is_group_ranked():
+        #     logger.warning("There is no boss could be challenged")
+        #     self.ui_click_until_disappear(self.I_AB_CLOSE_RED, interval=3)
+        #     return True
 
         # 根据 reward_floor 决定模式
         if reward_floor in (AreaBossFloor.ONE, AreaBossFloor.TEN):
@@ -182,6 +184,9 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
         if not self.start_fight():
             result = False
             logger.warning("Area Boss Fight Failed ")
+        self.screenshot()
+        if not self.appear(self.I_AB_CLOSE_RED) and self.appear(self.I_FILTER):
+            return result
         self.wait_until_appear(self.I_AB_CLOSE_RED)
         self.ui_click_until_disappear(self.I_AB_CLOSE_RED, interval=1)
         return result
@@ -193,8 +198,12 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
                 continue
             if not self.appear(self.I_AB_CLOSE_RED):  # 如果这个红色的关闭不见了才可以进行继续
                 break
-
-        return self.run_general_battle(self.config.area_boss.general_battle)
+        strategies, options = self.loadout_from_config(self.config.area_boss.general_battle)
+        options['completion'].check_imgs = [self.I_FIRE, self.I_FILTER]
+        self.loadout_show((strategies, options))  # 使用的是默认的策略: strategies
+        with battle_wait_strategy(**strategies), battle_wait_options(**options):
+            win = self.battle_wait()
+            return win
 
     def setup_ultra(self, floor: AreaBossFloor = AreaBossFloor.ONE) -> bool:
         # 确定进入鬼王界面
@@ -493,6 +502,8 @@ class ScriptTask(GeneralBattle, GameUi, SwitchSoul, AreaBossAssets):
             return 1
         else:
             return 0  # 如果交集的字符少于2个,可以根据需要返回其他值
+
+
 if __name__ == '__main__':
     from module.config.config import Config
     from module.device.device import Device

+ 4 - 0
tasks/Component/Buy/assets.py

@@ -30,10 +30,14 @@ class BuyAssets:
 	I_BUY_RMB = RuleImage(roi_front=(610,532,35,32), roi_back=(548,483,178,119), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_rmb.png")
 	# 购买成功 
 	I_BUY_SUCCESS = RuleImage(roi_front=(512,53,261,44), roi_back=(449,0,405,167), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_success.png")
+	# 确认按钮上的勾玉
+	I_BUY_JADE = RuleImage(roi_front=(604,537,42,52), roi_back=(540,480,200,120), threshold=0.8, method="Template matching", file="./tasks/Component/Buy/buy/buy_buy_jade.png")
 
 
 	# Ocr Rule Assets
 	# Ocr-description 
 	O_BUY_NUMBER = RuleOcr(roi=(578,416,52,71), area=(578,416,52,71), mode="Digit", method="Default", keyword="", name="buy_number")
+	# 确认按钮上的单价, roi 运行时按勾玉图标位置设置
+	O_BUY_PRICE = RuleOcr(roi=(646,537,60,52), area=(646,537,60,52), mode="Digit", method="Default", keyword="", name="buy_price")
 
 

+ 170 - 0
tasks/Component/Buy/buy.py

@@ -164,6 +164,176 @@ class Buy(BaseTask, BuyAssets):
                 continue
         return True
 
+    def buy_one_or_more(self, start_click: Union[RuleImage, RuleOcr, RuleClick],
+                        check_image: RuleImage, number: int = None,
+                        max_price: int = None, money: int = None, remain: int = None) -> bool:
+        """
+        购买弹窗可能是单个购买窗口, 也可能是带数量选择(加号)的多数量购买窗口
+        先点开弹窗, 出现加号走 buy_more, 出现单个购买窗口走 buy_one
+        :param start_click: 开始点击
+        :param check_image: 单个购买窗口确认时候的图片
+        :param number: 多数量窗口的购买数量, 不指定就是拉满. 指定 max_price 时不用, 数量按 money 和 remain 算
+        :param max_price: 单价上限, 不为 None 时先读确认按钮上的勾玉单价, 没有勾玉、读不到或超过上限就取消购买
+        :param money: 当前余额, 指定 max_price 时用来算买得起几个
+        :param remain: 剩余购买次数, 指定 max_price 时用来算购买数量
+        :return: 超时没等到任何购买弹窗或取消购买返回 False
+        """
+        timeout = Timer(10).start()
+        while 1:
+            self.screenshot()
+
+            if self.appear(self.I_BUY_PLUS):
+                if max_price is not None:
+                    return self._buy_with_price(start_click, check_image, True, max_price, money, remain)
+                if number == 1:
+                    # buy_more 指定数量时会先点一次加号再 OCR, 买 1 个会变成买 2 个
+                    return self._buy_more_default(start_click)
+                logger.info('Buy window with number selector, use buy_more')
+                return self.buy_more(start_click, number)
+            if self.appear(check_image):
+                if max_price is not None:
+                    return self._buy_with_price(start_click, check_image, False, max_price, money, remain)
+                logger.info('Single buy window, use buy_one')
+                return self.buy_one(start_click, check_image)
+            if timeout.reached():
+                logger.warning('Wait buy window timeout')
+                return False
+
+            if isinstance(start_click, RuleImage):
+                if self.appear_then_click(start_click, interval=1):
+                    continue
+            elif isinstance(start_click, RuleOcr):
+                if self.ocr_appear_click(start_click, interval=1):
+                    continue
+            elif isinstance(start_click, RuleClick):
+                if self.click(start_click, interval=1):
+                    continue
+
+    def _buy_with_price(self, start_click: Union[RuleImage, RuleOcr, RuleClick], check_image: RuleImage,
+                        more: bool, max_price: int, money: int, remain: int) -> bool:
+        """
+        购买弹窗已打开, 读确认按钮上的勾玉单价, 不超过上限才买
+        :param more: True 为多数量购买窗口, False 为单个购买窗口
+        :return: 买到返回 True, 取消购买或达到购买上限返回 False
+        """
+        price = self._buy_read_price()
+        if price is None or price > max_price:
+            logger.warning(f'Buy price {price} is unknown or over max price {max_price}, cancel buy')
+            self._buy_cancel(check_image)
+            return False
+        if (money is not None and money < price) or (remain is not None and remain < 1):
+            logger.warning('Balance or remaining purchases cannot cover one item, cancel buy')
+            self._buy_cancel(check_image)
+            return False
+        if not more:
+            logger.info(f'Single buy window, price {price}, buy number 1')
+            return self.buy_one(start_click, check_image)
+        if money is None or remain is None:
+            # 没传余额或剩余次数时只买 1 个
+            number = 1
+        else:
+            number = min(remain, money // price)
+        logger.info(f'Buy price {price}, money {money}, remain {remain}, buy number {number}')
+        if number < 1:
+            logger.warning('Money is not enough to buy one, cancel buy')
+            self._buy_cancel(check_image)
+            return False
+        if number == 1:
+            return self._buy_more_default(start_click)
+        if number == remain:
+            return self.buy_more(start_click, None)
+        # buy_more(start_click, number) 点加号后才读数量, 可能超过 number.
+        # 余额不够买满时每次只买 1 个, 调用方循环会重新读余额和剩余次数再买下一个
+        logger.info(f'Money is not enough to buy all {remain}, buy one by one')
+        return self._buy_more_default(start_click)
+
+    def _buy_read_price(self, min_price: int = 40) -> Union[int, None]:
+        """
+        读购买确认按钮上的勾玉单价: 先等勾玉图标出现, 再读图标右边的数字
+        :param min_price: 单价下限, 低于它当作 OCR 读错(例如 90 少读一位成 9). 默认 40: 蓝票已知最低价 50, 留一点余量
+        :return: 单价, 没有勾玉图标、读不到或低于下限返回 None
+        """
+        jade_timer = Timer(2).start()
+        while 1:
+            if self.appear(self.I_BUY_JADE):
+                break
+            if jade_timer.reached():
+                logger.warning('Jade icon is not found on buy button, maybe not paid by jade')
+                return None
+            self.screenshot()
+        x, y, w, h = self.I_BUY_JADE.roi_front
+        # 只取图标右边, 裁剪框碰到图标会把图标读成 1, 例如 90 读成 190
+        self.O_BUY_PRICE.roi = [x + w, y, 60, h]
+        price = self.O_BUY_PRICE.ocr(self.device.image)
+        try:
+            price = int(price)
+        except (TypeError, ValueError):
+            price = 0
+        if price == 0:
+            # Digit 读不到时返回 0
+            logger.warning('OCR buy price failed')
+            return None
+        if price < min_price:
+            logger.warning(f'Buy price {price} is lower than min price {min_price}, treat as OCR error')
+            return None
+        return price
+
+    def _buy_cancel(self, check_image: RuleImage) -> bool:
+        """
+        点取消关掉购买弹窗, 直到多数量窗口的加号和单个购买窗口的确认图都消失
+        :return: 关掉返回 True, 超时返回 False
+        """
+        timeout = Timer(10).start()
+        while 1:
+            self.screenshot()
+            if not self.appear(self.I_BUY_PLUS) and not self.appear(check_image):
+                return True
+            if timeout.reached():
+                logger.warning('Cancel buy window timeout')
+                return False
+            if self.click(self.C_BUY_CANCEL, interval=1):
+                continue
+
+    def _buy_more_default(self, start_click: Union[RuleImage, RuleOcr, RuleClick]) -> bool:
+        """
+        多数量购买窗口不调整数量, 默认数量为 1 时直接确认买 1 个
+        :param start_click: 保留与其他购买入口一致的调用参数
+        :return: 买到返回 True, 达到购买上限返回 False
+        """
+        ocr_timer = Timer(2).start()
+        while 1:
+            current = self.O_BUY_NUMBER.ocr(self.device.image)
+            if current == 1:
+                break
+            if ocr_timer.reached():
+                logger.warning(f'Default buy number is {current}, cancel unverified quantity')
+                self._buy_cancel(self.I_BUY_PLUS)
+                return False
+            self.screenshot()
+        logger.info('Buy window with number selector, buy one with default number')
+        while 1:
+            self.screenshot()
+
+            if self.ui_reward_appear_click():
+                while 1:
+                    self.screenshot()
+                    # 等待动画结束
+                    if not self.appear(self.I_UI_REWARD, threshold=0.6):
+                        logger.info('Get reward success')
+                        break
+                    # 一直点击
+                    if self.ui_reward_appear_click():
+                        continue
+                return True
+
+            if self.appear(self.I_UI_CONFIRM_SAMLL):
+                self.ui_click_until_disappear(self.I_UI_CONFIRM_SAMLL, interval=1)
+                logger.warning('Buy number limit')
+                return False
+
+            if self.click(self.C_BUY_MORE, interval=2):
+                continue
+
     def buy_check_money(self, target: RuleOcr, minimum: int):
         """
         检查钱是否足够

BIN
tasks/Component/Buy/buy/buy_buy_jade.png


+ 9 - 0
tasks/Component/Buy/buy/image.json

@@ -43,5 +43,14 @@
     "method": "Template matching",
     "threshold": 0.8,
     "description": "购买成功"
+  },
+  {
+    "itemName": "buy_jade",
+    "imageName": "buy_buy_jade.png",
+    "roiFront": "604,537,42,52",
+    "roiBack": "540,480,200,120",
+    "method": "Template matching",
+    "threshold": 0.8,
+    "description": "确认按钮上的勾玉"
   }
 ]

+ 9 - 0
tasks/Component/Buy/buy/ocr.json

@@ -7,5 +7,14 @@
     "method": "Default",
     "keyword": "",
     "description": "Ocr-description"
+  },
+  {
+    "itemName": "buy_price",
+    "roiFront": "646,537,60,52",
+    "roiBack": "646,537,60,52",
+    "mode": "Digit",
+    "method": "Default",
+    "keyword": "",
+    "description": "确认按钮上的单价, roi 运行时按勾玉图标位置设置"
   }
 ]

+ 10 - 6
tasks/Component/GeneralBattle/battle_wait.py

@@ -1066,6 +1066,10 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         print('=' * 64)
         time.sleep(0.6)
 
+    def refresh_long_time(self) -> None:
+        self.device.stuck_record_add('BATTLE_STATUS_S')
+        self.device.click_record_clear()
+
     # ------------------------------------------------------------------------------------------------------------------
     # build in
     # ------------------------------------------------------------------------------------------------------------------
@@ -1073,8 +1077,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         self.C_REWARD_1.name = 'C_REWARD'
         self.C_REWARD_2.name = 'C_REWARD'
         self.C_REWARD_3.name = 'C_REWARD'
-        self.device.stuck_record_add('BATTLE_STATUS_S')
-        self.device.click_record_clear()
+        self.refresh_long_time()
         logger.info('Start battle process')
         return HookSignal.DONE
 
@@ -1216,6 +1219,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         if pri_options.lock_team or self.is_in_real_battle(False):
             logger.info('Prepare stage finish')
             state.done = True
+            self.refresh_long_time()
             return runtime.hook_enabled_update(
                 enable=('green', 'red', 'echo'),
                 disable=('prepare', 'preset'),
@@ -1258,7 +1262,6 @@ class BattleWait(BaseTask, GeneralBattleAssets):
             return HookSignal.CONTINUE
         if not pri_options.preset_enable or state.done:
             return HookSignal.CONTINUE
-
         logger.info("Preset is enable")
         # 点击预设按钮
         while 1:
@@ -1446,6 +1449,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
             # 点击绿标
             self.device.click(x, y)
         state.done = True
+        self.refresh_long_time()
         return runtime.hook_enabled_update(
             enable=(),
             disable=('green',),
@@ -1489,8 +1493,8 @@ class BattleWait(BaseTask, GeneralBattleAssets):
     # custom
     # ------------------------------------------------------------------------------------------------------------------
     def _bw_success_soul(self, pub: PublicContext, pri: PrivateContext) -> HookSignal:
-        state = pri.per_battle
-        options = pri.options
+        state: PerBattleSuccess = pri.per_battle
+        options: OptionSuccessDefault = pri.options
         if not isinstance(state, PerBattleSuccess) or not isinstance(options, OptionSuccessDefault):
             raise TypeError("battle wait option 'success' must be an OptionSuccessDefault")
         if state.click_stage_1 is None:
@@ -1533,7 +1537,7 @@ class BattleWait(BaseTask, GeneralBattleAssets):
         return HookSignal.CONTINUE
 
     @cached_property
-    def exclude_click_activity(self, areas: list[str] = None) -> RuleClickExclude:
+    def exclude_click_activity(self) -> RuleClickExclude:
         inputs = []
         for area in ['C_END_MESSAGE_RIGHT_TOP', 'C_END_ACTIVITY_REWARD']:
             click = getattr(self, area, None)

+ 2 - 1
tasks/MysteryShop/script_task.py

@@ -88,7 +88,8 @@ class ScriptTask(FriendshipPoints, MysteryShopAssets, GeneralInvite):
         """
         if shop_config.mystery_amulet:
             while self.buy_mall_one(buy_button=self.I_MS_BLUE, buy_check=self.I_MS_CHECK_BLUE,
-                                    money_ocr=self.O_MALL_RESOURCE_5, buy_money=85):
+                                    money_ocr=self.O_MALL_RESOURCE_5, buy_money=85, more_window=True,
+                                    max_price=85):
                 pass
         if shop_config.black_daruma_scrap:
             while self.buy_mall_one(buy_button=self.I_MS_BLACK, buy_check=self.I_MS_CHECK_BLACK,

+ 14 - 2
tasks/RichMan/mall/friendship_points.py

@@ -32,13 +32,16 @@ class FriendshipPoints(Special):
             self.buy_mall_more(buy_button=self.I_FS_BROKEN, remain_number=False, money_ocr=self.I_MALL_RESOURCE_FRIENDS.build_mall_resource_ocr(self.device.image),
                                buy_number=con.broken_amulet, buy_max=99, buy_money=100)
 
-    def buy_mall_one(self, buy_button: RuleImage, buy_check: RuleImage, money_ocr: RuleOcr, buy_money: int):
+    def buy_mall_one(self, buy_button: RuleImage, buy_check: RuleImage, money_ocr: RuleOcr, buy_money: int,
+                     more_window: bool = False, max_price: int = None):
         """
         针对只能买一个的
         :param buy_button:
         :param buy_check:
         :param money_ocr:
         :param buy_money: 买这一个花多少
+        :param more_window: 购买弹窗可能是多数量窗口(剩余次数大于1时), 为 True 时按弹窗类型选 buy_more 或 buy_one
+        :param max_price: 单价上限, 不为 None 时从购买弹窗读单价, 超过上限或读不到就不买, 数量按剩余次数和余额算
         :return:
         """
         logger.hr(buy_button.name, 3)
@@ -57,11 +60,20 @@ class FriendshipPoints(Special):
         if not isinstance(current_money, int):
             logger.warning('Money ocr failed')
             return False
-        money_enough = current_money >= buy_money
+        # 读单价的路径稍后按实际价格判断余额,不能以价格上限过滤折扣商品。
+        money_enough = current_money > 0 if max_price is not None else current_money >= buy_money
         if not money_enough:
             logger.warning(f'No enough money {current_money}')
             return False
         # 点击购买
+        if max_price is not None:
+            # 单价从购买弹窗上读,由 buy_one_or_more 按实际价格检查余额和数量。
+            logger.info(f'Money {current_money}, remain {_remain}, max price {max_price}')
+            return self.buy_one_or_more(buy_button, buy_check, max_price=max_price,
+                                        money=current_money, remain=_remain)
+        if more_window:
+            # 不读单价时只买 1 个, 由调用方循环重新检查剩余次数和余额再买
+            return self.buy_one_or_more(buy_button, buy_check, 1)
         return self.buy_one(buy_button, buy_check)
 
     def buy_mall_more(self, buy_button: RuleImage, remain_number: bool, money_ocr: RuleOcr,

+ 54 - 0
tests/tasks/AreaBoss/test_area_battle.py

@@ -0,0 +1,54 @@
+from types import SimpleNamespace
+
+import pytest
+
+from tasks.AreaBoss.script_task import ScriptTask
+from tasks.AreaBoss.config_boss import AreaBossFloor
+from tasks.Component.GeneralBattle.config_general_battle import GeneralBattleConfig
+from tasks.Component.GeneralBattle.battle_wait import battle_wait_strategy, battle_wait_options
+
+
+@pytest.mark.parametrize('win', [True, False])
+def test_start_fight_applies_configured_strategies_and_return_markers(win):
+    task = object.__new__(ScriptTask)
+    task.config = SimpleNamespace(area_boss=SimpleNamespace(
+        general_battle=GeneralBattleConfig(random_click_swipt_enable=True)))
+    task.screenshot = lambda: None
+    task.appear_then_click = lambda *args, **kwargs: False
+    task.appear = lambda *args, **kwargs: False
+    task.loadout_show = lambda *args: None
+    strategies, options = task.loadout_from_config(task.config.area_boss.general_battle)
+    seen = []
+    def battle():
+        plan = battle_wait_strategy._context.get()
+        assert plan is not None
+        assert all(getattr(plan, key) == value for key, value in strategies.items())
+        active = battle_wait_options._context.get()
+        assert active['completion'].check_imgs == [task.I_FIRE, task.I_FILTER]
+        seen.append(True)
+        return win
+    task.battle_wait = battle
+    assert task.start_fight() is win
+    assert seen == [True]
+    assert battle_wait_strategy._context.get() is None
+    assert battle_wait_options._context.get() is None
+
+
+@pytest.mark.parametrize('returned_to_filter', [True, False])
+@pytest.mark.parametrize('win', [True, False])
+def test_boss_fight_accepts_either_supported_return_screen(returned_to_filter, win):
+    task = object.__new__(ScriptTask)
+    task.config = SimpleNamespace(area_boss=SimpleNamespace(boss=SimpleNamespace(reward_floor=AreaBossFloor.DEFAULT)))
+    task.appear = lambda asset: asset is task.I_FILTER and returned_to_filter
+    task.open_boss_detail = lambda *args: True
+    task.is_group_ranked = lambda: False
+    task.start_fight = lambda: win
+    task.screenshot = lambda: None
+    calls = []
+    def wait(asset):
+        assert not returned_to_filter, 'Already back at filter: red close will never appear'
+        calls.append('wait')
+    task.wait_until_appear = wait
+    task.ui_click_until_disappear = lambda *args, **kwargs: calls.append('close')
+    assert task.boss_fight(None, fileter_open=False) is win
+    assert calls == ([] if returned_to_filter else ['wait', 'close'])

+ 80 - 0
tests/tasks/Component/Buy/test_priced_buy.py

@@ -0,0 +1,80 @@
+from types import SimpleNamespace
+
+import pytest
+
+from tasks.Component.Buy import buy as buy_module
+from tasks.Component.Buy.buy import Buy
+from tasks.RichMan.mall.friendship_points import FriendshipPoints
+
+
+def priced_task(price):
+    task = object.__new__(Buy)
+    task.calls = []
+    task._buy_read_price = lambda: price
+    task._buy_cancel = lambda check: task.calls.append('cancel')
+    task.buy_one = lambda *args: task.calls.append('one') or True
+    task.buy_more = lambda start, number: task.calls.append(('more', number)) or True
+    task._buy_more_default = lambda start: task.calls.append('default') or True
+    return task
+
+
+@pytest.mark.parametrize('price,money,remain,more,expected', [
+    (None, 500, 5, True, 'cancel'), (90, 500, 5, True, 'cancel'),
+    (85, 85, 5, True, 'default'), (50, 100, 5, True, 'default'),
+    (50, 250, 5, True, ('more', None)), (50, 49, 5, True, 'cancel'),
+    (50, 49, 1, False, 'cancel'), (50, 50, 0, False, 'cancel'),
+    (50, 50, 1, False, 'one'),
+])
+def test_price_and_affordability_guard_both_dialogs(price, money, remain, more, expected):
+    task = priced_task(price)
+    assert task._buy_with_price(None, None, more, 85, money, remain) is (expected != 'cancel')
+    assert task.calls == [expected]
+
+
+@pytest.mark.parametrize('balance,priced,expected', [(60, True, True), (60, False, False), (0, True, False)])
+def test_discounted_ticket_uses_actual_price_not_max_price_as_balance_gate(balance, priced, expected):
+    task = object.__new__(FriendshipPoints)
+    task.device = SimpleNamespace(image=None)
+    task.screenshot = lambda: None
+    task.appear = lambda asset: True
+    task._special_check_remain = lambda asset: 5
+    task.buy_one_or_more = lambda *args, **kwargs: kwargs['money'] == balance
+    task.buy_one = lambda *args: pytest.fail('Unexpected single purchase')
+    assert task.buy_mall_one(SimpleNamespace(name='ticket'), None,
+                             SimpleNamespace(ocr=lambda image: balance), 85,
+                             max_price=85 if priced else None) is expected
+
+
+@pytest.mark.parametrize('current', [0, 2])
+def test_unverified_default_quantity_cancels_instead_of_incrementing(monkeypatch, current):
+    monkeypatch.setattr(buy_module, 'Timer', lambda *args: SimpleNamespace(
+        start=lambda: SimpleNamespace(reached=lambda: True)))
+    task = object.__new__(Buy)
+    task.device = SimpleNamespace(image=None)
+    task.O_BUY_NUMBER = SimpleNamespace(ocr=lambda image: current)
+    calls = []
+    task._buy_cancel = lambda check: calls.append('cancel') or True
+    task.buy_more = lambda *args: pytest.fail('Increment fallback can exceed budget')
+    assert task._buy_more_default(None) is False
+    assert calls == ['cancel']
+
+
+@pytest.mark.parametrize('price,expected', [(0, None), (9, None), ('bad', None), (50, 50), (85, 85), (90, 90)])
+def test_price_ocr_rejects_partial_digits_and_excludes_jade_icon(price, expected):
+    task = object.__new__(Buy)
+    task.device = SimpleNamespace(image=None)
+    task.appear = lambda asset: True
+    task.I_BUY_JADE = SimpleNamespace(roi_front=(600, 530, 42, 52))
+    task.O_BUY_PRICE = SimpleNamespace(roi=None, ocr=lambda image: price)
+    assert task._buy_read_price() == expected
+    assert task.O_BUY_PRICE.roi == [642, 530, 60, 52]
+
+
+@pytest.mark.parametrize('multiple', [True, False])
+def test_dialog_detection_routes_to_price_check(multiple):
+    task = object.__new__(Buy)
+    task.screenshot = lambda: None
+    check = object()
+    task.appear = lambda asset: (asset is task.I_BUY_PLUS and multiple) or asset is check
+    task._buy_with_price = lambda start, image, more, price, money, remain: more == multiple
+    assert task.buy_one_or_more(None, check, max_price=85, money=100, remain=5)

+ 7 - 0
tests/tasks/Component/GeneralBattle/test_battle_wait.py

@@ -436,6 +436,11 @@ def test_prepare_dismisses_soul_mismatch_dialog_before_progressing(locked):
         def __init__(self):
             self.visible = [self.I_DISABLE_7DAYS_DIFF_SOUL, self.I_CONFIRM_CLOSE_DIFF_SOUL]
             self.clicked = []
+            self.device_events = []
+            self.device = SimpleNamespace(
+                stuck_record_add=lambda name: self.device_events.append(name),
+                click_record_clear=lambda: self.device_events.append('clear'),
+            )
 
         def appear_then_click(self, target, **kwargs):
             if self.visible and target is self.visible[0]:
@@ -453,5 +458,7 @@ def test_prepare_dismisses_soul_mismatch_dialog_before_progressing(locked):
         assert battle._bw_prepare_default() == HookSignal.CONTINUE
         assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is False
     assert battle.clicked == [battle.I_DISABLE_7DAYS_DIFF_SOUL, battle.I_CONFIRM_CLOSE_DIFF_SOUL]
+    assert battle.device_events == []
     battle._bw_prepare_default()
     assert runtime.pri_ctx['_bw_prepare_default'].per_battle.done is True
+    assert battle.device_events == ['BATTLE_STATUS_S', 'clear']