Просмотр исходного кода

Merge upstream dev through b1c7186c and preserve cropped invite matching

Integrate all three upstream commits from 6d718fec through b1c7186c.
Adopt fresh-frame exploration scene checks before back navigation, broaden
the invite confirmation search region for WantedQuests, and restart already
logged-in desktop clients while reusing clients still at the login screen.
The desktop restart behavior is included despite its exploration commit title.

Resolve both invitation asset conflicts using the existing 68x32 cropped
template, not the upstream 132x60 dimensions. Apply the upstream search ROI
(473,505,409,121); translate the old crop offset (32,14) to the new button
position for roi_front=(549,567,68,32). Keep assets.py and image.json in sync.
The PNG is unchanged and both old/new dialog positions remain searchable.

Repair two omissions demonstrated by three failing replay cases: after the
second exit screenshot, yield to rewards/confirmation dialogs before clicking
back; if desktop shutdown fails, stop restart instead of reusing the residual
instance and marking the restart successful. Retain local chapter scrolling,
search guards, mail/login fixes, cropped UI assets, raid behavior, isolated
battle strategies and the previous desktop lifecycle fixes.

Validation: 378 tests pass (tests plus both FrogBoss unit suites), including
19 new cases for exit transitions/popups, restart modes/shutdown failure,
invite matching at both positions and outside the search ROI with padding 0/2,
and actual PNG/metadata consistency. Six Python files parse, three production
modules import, and two local AST checks are unchanged. git diff checks pass.
Image matching uses the real template in synthetic screens; no emulator or
desktop game client was launched and no live gameplay test is claimed.
unknown 4 недель назад
Родитель
Сommit
14099f4a74

+ 1 - 1
tasks/Component/GeneralInvite/assets.py

@@ -46,7 +46,7 @@ class GeneralInviteAssets:
 	# 左上角退出 
 	I_BACK_YELLOW = RuleImage(roi_front=(19,13,58,55), roi_back=(19,13,58,55), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_back_yellow.png")
 	# 点击邀请 
-	I_INVITE_ENSURE = RuleImage(roi_front=(742,558,68,32), roi_back=(710,544,132,60), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_invite_ensure.png")
+	I_INVITE_ENSURE = RuleImage(roi_front=(549,567,68,32), roi_back=(473,505,409,121), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_invite_ensure.png")
 	# 判断是否点中好友了 
 	I_SELECTED = RuleImage(roi_front=(895,373,33,32), roi_back=(895,373,33,32), threshold=0.8, method="Template matching", file="./tasks/Component/GeneralInvite/gi/gi_selected.png")
 	# 用来判断当前的列表是哪儿的 

+ 2 - 2
tasks/Component/GeneralInvite/gi/image.json

@@ -155,8 +155,8 @@
   {
     "itemName": "invite_ensure",
     "imageName": "gi_invite_ensure.png",
-    "roiFront": "742,558,68,32",
-    "roiBack": "710,544,132,60",
+    "roiFront": "549,567,68,32",
+    "roiBack": "473,505,409,121",
     "method": "Template matching",
     "threshold": 0.8,
     "description": "点击邀请"

+ 15 - 2
tasks/Exploration/base.py

@@ -425,8 +425,21 @@ class BaseExploration(GameUi, GeneralBattle, GeneralRoom, GeneralInvite, Replace
 
             if self.appear_then_click(self.I_E_EXIT_CONFIRM, interval=0.8):
                 continue
-            if self.appear_then_click(self.I_BACK_YOLLOW, interval=3.5):
-                continue
+            if self.appear(self.I_BACK_YOLLOW):
+                self.screenshot()
+                # 复核截图期间可能出现奖励或退出确认,先交回主循环处理弹窗。
+                if self.appear(self.I_BATTLE_REWARD) or self.appear(self.I_E_EXIT_CONFIRM):
+                    continue
+                # https://github.com/runhey/OnmyojiAutoScript/issues/1935
+                if not self.appear(self.I_BACK_YOLLOW) or self.appear(self.I_E_EXPLORATION_CLICK):
+                    continue
+                is_main = (
+                        self.appear(self.I_E_SETTINGS_BUTTON)
+                        or self.appear(self.I_E_AUTO_ROTATE_ON)
+                        or self.appear(self.I_E_AUTO_ROTATE_OFF)
+                )
+                if is_main and self.click(self.I_BACK_YOLLOW, interval=3.5):
+                    continue
             
             if self.appear(self.I_EXPLORATION_TITLE) or self.appear(self.I_CHECK_EXPLORATION):
                 continue

+ 5 - 1
tasks/Restart/script_task.py

@@ -48,7 +48,11 @@ class ScriptTask(LoginHandler):
     def app_restart(self):
         logger.hr('App restart')
         if self.device.is_desktop:
-            # 客户端可能刚被自动拉起(停在登录页),先停再起会白关一次
+            # 客户端可能刚被自动拉起并停在登录页,此时直接复用;已登录时才真正重启
+            if self.device.app_is_running():
+                if not self.device.desktop_stop_client():
+                    logger.critical('桌面客户端无法关闭,停止重启以免复用残留实例')
+                    raise RequestHumanTakeover
             self._desktop_start_and_login()
         else:
             self.device.app_stop()

+ 39 - 0
tests/tasks/Component/GeneralInvite/test_invite_asset.py

@@ -0,0 +1,39 @@
+from copy import deepcopy
+import json
+from pathlib import Path
+
+import numpy as np
+import pytest
+from PIL import Image
+
+from module.atom import image as image_module
+from tasks.Component.GeneralInvite.assets import GeneralInviteAssets
+
+
+@pytest.mark.parametrize('pad', [0, 2])
+@pytest.mark.parametrize('position,expected', [((742, 558), True), ((549, 567), True), ((100, 100), False)])
+def test_cropped_invitation_template_covers_both_dialog_positions(monkeypatch, pad, position, expected):
+    monkeypatch.setattr(image_module, 'ROI_MATCH_PAD', pad)
+    rule = deepcopy(GeneralInviteAssets.I_INVITE_ENSURE)
+    template = rule.image
+    height, width = template.shape[:2]
+    screen = np.zeros((720, 1280, 3), dtype=np.uint8)
+    x, y = position
+    screen[y:y + height, x:x + width] = template
+    assert rule.match(screen) is expected
+    if expected:
+        assert tuple(rule.roi_front[:2]) == position
+
+
+def test_invitation_metadata_keeps_crop_and_search_region_consistent():
+    rule = GeneralInviteAssets.I_INVITE_ENSURE
+    rows = json.loads(Path('tasks/Component/GeneralInvite/gi/image.json').read_text(encoding='utf-8'))
+    row, = [entry for entry in rows if entry['itemName'] == 'invite_ensure']
+    with Image.open(rule.file) as template:
+        assert template.size == (68, 32) == tuple(rule.roi_front[2:])
+        template.verify()
+    assert tuple(map(int, row['roiFront'].split(','))) == tuple(rule.roi_front)
+    assert tuple(map(int, row['roiBack'].split(','))) == tuple(rule.roi_back)
+    assert row['threshold'] == rule.threshold
+    assert row['method'] == rule.method
+    assert row['imageName'] == Path(rule.file).name

+ 58 - 0
tests/tasks/Exploration/test_exit.py

@@ -0,0 +1,58 @@
+from types import SimpleNamespace
+
+import pytest
+
+from module.base import timer
+from tasks.Exploration.base import BaseExploration
+
+
+class ExitReplay(BaseExploration):
+    def __init__(self, monkeypatch, frames):
+        self.frames = iter(frames)
+        self.frame = set()
+        self.clicks = []
+        self.now = 100.0
+        self.device = SimpleNamespace(click_record_remove=lambda name: None)
+        monkeypatch.setattr(timer, 'time', SimpleNamespace(time=lambda: self.now))
+
+    def screenshot(self):
+        self.now += 0.5
+        self.frame = next(self.frames)
+
+    def appear(self, asset, **kwargs):
+        return any(asset is getattr(self, name) for name in self.frame)
+
+    def click(self, asset, **kwargs):
+        self.clicks.append(asset)
+        return True
+
+    def appear_then_click(self, asset, **kwargs):
+        return self.appear(asset) and self.click(asset, **kwargs)
+
+
+@pytest.mark.parametrize('second_frame', [
+    set(), {'I_BACK_YOLLOW'}, {'I_BACK_YOLLOW', 'I_E_EXPLORATION_CLICK'},
+])
+def test_exit_does_not_click_back_on_transition_or_unconfirmed_scene(monkeypatch, second_frame):
+    task = ExitReplay(monkeypatch, [{'I_BACK_YOLLOW'}, second_frame, {'I_CHECK_EXPLORATION'}])
+    task.quit_explore()
+    assert task.clicks == []
+
+
+@pytest.mark.parametrize('marker', ['I_E_SETTINGS_BUTTON', 'I_E_AUTO_ROTATE_ON', 'I_E_AUTO_ROTATE_OFF'])
+def test_exit_clicks_back_only_on_verified_exploration_scene(monkeypatch, marker):
+    task = ExitReplay(monkeypatch, [
+        {'I_BACK_YOLLOW'}, {'I_BACK_YOLLOW', marker}, {'I_E_EXIT_CONFIRM'}, {'I_CHECK_EXPLORATION'},
+    ])
+    task.quit_explore()
+    assert task.clicks == [task.I_BACK_YOLLOW, task.I_E_EXIT_CONFIRM]
+
+
+@pytest.mark.parametrize('popup', ['I_E_EXIT_CONFIRM', 'I_BATTLE_REWARD'])
+def test_exit_prioritizes_popup_appearing_on_second_screenshot(monkeypatch, popup):
+    task = ExitReplay(monkeypatch, [
+        {'I_BACK_YOLLOW'}, {'I_BACK_YOLLOW', 'I_E_SETTINGS_BUTTON', popup},
+        {popup}, {'I_CHECK_EXPLORATION'},
+    ])
+    task.quit_explore()
+    assert task.clicks == [getattr(task, popup)]

+ 39 - 0
tests/tasks/Restart/test_restart.py

@@ -0,0 +1,39 @@
+from types import SimpleNamespace
+from unittest.mock import Mock
+
+import pytest
+
+from module.exception import RequestHumanTakeover
+from tasks.Restart.script_task import ScriptTask
+
+
+@pytest.mark.parametrize('desktop,running', [(False, True), (True, True), (True, False)])
+def test_restart_reuses_only_a_desktop_client_that_is_not_logged_in(desktop, running):
+    calls = []
+    task = object.__new__(ScriptTask)
+    task.config = SimpleNamespace(restart=SimpleNamespace(harvest_config=SimpleNamespace(enable_ap=False)))
+    task.device = SimpleNamespace(
+        is_desktop=desktop, app_is_running=lambda: running,
+        app_stop=lambda: calls.append('stop'),
+        desktop_stop_client=lambda: calls.append('stop') or True,
+        app_start=lambda: calls.append('start'),
+    )
+    task._desktop_start_and_login = lambda: calls.append('desktop-login')
+    task.app_handle_login = lambda: calls.append('login')
+    task.set_next_run = lambda **kwargs: calls.append('scheduled')
+    task.app_restart()
+    assert calls == (['stop', 'start', 'login', 'scheduled'] if not desktop else
+                     (['stop'] if running else []) + ['desktop-login', 'scheduled'])
+
+
+def test_failed_desktop_stop_cannot_report_a_successful_restart():
+    task = object.__new__(ScriptTask)
+    task.config = SimpleNamespace(restart=SimpleNamespace(harvest_config=SimpleNamespace(enable_ap=False)))
+    task.device = SimpleNamespace(is_desktop=True, app_is_running=lambda: True,
+                                  app_stop=lambda: None, desktop_stop_client=lambda: False)
+    task._desktop_start_and_login = Mock()
+    task.set_next_run = Mock()
+    with pytest.raises(RequestHumanTakeover):
+        task.app_restart()
+    task._desktop_start_and_login.assert_not_called()
+    task.set_next_run.assert_not_called()