From 756abe99a87bf8669b2fb457e561c6b86f2ee590 Mon Sep 17 00:00:00 2001 From: Nik Afiq Date: Wed, 28 Oct 2026 20:52:35 +0900 Subject: [PATCH] feat(exit_game): kill BlueArchive.exe if still running after exit The graceful Escape/Enter exit can abort when the game is stuck (three aborts in q4h.log on 2026-10-28 alone), leaving the client open. run() now always finishes with a process check: after a ~10s grace period for Proton teardown, a still-running BlueArchive.exe is killed with SIGTERM, escalating to SIGKILL if needed. driver.kill_game() gains force=True. Co-Authored-By: Claude Opus 5.5 --- ba_auto/driver.py | 8 +++-- ba_auto/reference_notes/mapping.md | 2 +- ba_auto/tasks/exit_game.py | 53 +++++++++++++++++++++++++++--- 3 files changed, 55 insertions(+), 8 deletions(-) diff --git a/ba_auto/driver.py b/ba_auto/driver.py index df51aee..d11e542 100644 --- a/ba_auto/driver.py +++ b/ba_auto/driver.py @@ -161,11 +161,13 @@ def wait(seconds): time.sleep(seconds) -def kill_game(): +def kill_game(force=False): # check=False -- pkill exits 1 with no output when nothing matches, # which is a normal outcome here (e.g. the process already died on its - # own), not an error worth raising on. - run_command(["pkill", "-f", config.GAME_PROCESS_NAME], check=False) + # own), not an error worth raising on. force=True sends SIGKILL instead + # of pkill's default SIGTERM, for a hung process that ignores SIGTERM. + signal_args = ["-KILL"] if force else [] + run_command(["pkill", *signal_args, "-f", config.GAME_PROCESS_NAME], check=False) def launch_game(): diff --git a/ba_auto/reference_notes/mapping.md b/ba_auto/reference_notes/mapping.md index 7547a3d..1efe03c 100644 --- a/ba_auto/reference_notes/mapping.md +++ b/ba_auto/reference_notes/mapping.md @@ -15,7 +15,7 @@ Maps each local feature to the corresponding `~/repo/baas-reference/module/...` | Bounty | `module/rewarded_task.py` | `implement` (main flow, `get_task_count`/`purchase_bounty_ticket`/per-area `rewarded_task_status` loop, not ported -- see Status), `to_bounty`/`to_choose_bounty` (nav), `get_los`/`one_detect`/`bounty_common_operation` (per-row SSS-color scan + sweep) | `ba_auto/tasks/bounty.py` | `to_bounty`'s bottom-nav "bus" icon -> this client's Work-hub `指名手配` card (`config.BOUNTY_CARD`), landing directly on Location Select with no separate bus-icon sub-navigation step; `get_los`/`one_detect`'s per-row `color.check_sweep_availability` SSS-color scan across however many rows are visible -> a fixed bottom-most row click (`config.BOUNTY_LATEST_STAGE_ROW_Y`), since this client's 3 areas each have exactly 10 stages (confirmed live, scrolling past the 10th is a no-op) all already SSS-cleared, making "scroll to the bottom extreme, click the last row" equivalent to "the latest stage available" by construction; the reference's config-string per-area sweep-count list (`rewarded_task_times`, `get_task_count`) and its loop across all 3 areas -> a single date-ordinal-modulo rotation choosing ONE area per run, mirroring story_sweep.py/event_sweep.py's own rotation, per explicit user direction (2026-07-11); `purchase_bounty_ticket` (buying more tickets with real currency) -> not ported, matching plan.md's "OCR optional for coin balance/refresh logic, can skip for first version" | Done, live-tested for real -- see `plan.md` Phase 15. Live-calibrated against nik-gpu 2026-07-11 with **zero real tickets spent** during calibration (every ticket-usage confirm dialog reached was cancelled via Escape, verified by the ticket counter (6/6) unchanged before/after, across all 3 areas). All 3 areas (ハイウェイ/砂漠の線路/校舎, matching the reference's OVERPASS/DESSERT RAILWAY/CLASSROOM groupings) confirmed to share an identical layout: same area-row/stage-row/modal-button coordinates, same 10-stage-per-area structure. The 任務情報 modal's MAX stepper, minus-button raised-color check, and ticket-usage confirm dialog are pixel-identical to event_sweep.py's own stage modal / shared `SWEEP_CONFIRM_*` dialog -- confirmed live -- and reused directly. The modal-open probe could NOT be reused from `EVENT_STAGE_MODAL_PROBE`: that corner point reads dark on this screen regardless of modal state (different background art), so a fresh `BOUNTY_STAGE_MODAL_PROBE` was calibrated that does discriminate both states. **2 real sweeps confirmed live** (credits +180,000 then +36,000, clean automatic return home both times), which surfaced and fixed two real bugs: (1) `_set_sweep_count`'s count==1 path wrongly assumed the modal defaults to count=1 on open -- it actually remembers the last-used count -- causing an unintended 5-ticket spend instead of the intended 1; fixed via a new `_click_min_and_verify` that always forces a known baseline first. (2) `BOUNTY_SWEEP_RESULT_BUTTON_REGION`'s first-guess copy of event_sweep's own region overlapped `BOUNTY_SWEEP_START_BUTTON`'s real cyan pixels, causing `_find_result_button` to re-click it once tickets hit 0 -- which surfaced a real Pyroxene ticket-purchase prompt (no gem actually spent, confirmed by an unchanged balance, but a real near-miss). Fixed three ways: the region was corrected to the real pixel-scanned OK-button bbox; a new `min_pixels` parameter on `detector.find_color_centroid` (plus `config.BOUNTY_RESULT_BUTTON_MIN_PIXELS`) filters out a second, smaller contamination source (stray cyan-range pixels in the modal's own reward-icon artwork); and `_watch_sweep_result` now has an explicit `_is_ticket_purchase_prompt` guard as a named `ends` condition. **Not yet re-confirmed live**: a fresh sweep with the fixes deployed (account at 0/6 tickets as of session end) and any bulk/MAX-count sweep's result-screen flow (only count=1 was ever tested; a bulk sweep may show a SKIP-then-OK sequence like story_sweep/event_sweep instead of the single-OK dialog confirmed here). **Real hazard found and fixed via a real unattended `daily` cron run (2026-07-17)**: reported live by the user -- a real "Battle Complete" screen (a live ~3-minute combat timer) was found on the account instead of an instant sweep, with `_watch_sweep_result` having reported "swept" cleanly and no warnings anywhere in the log; every task that ran for the rest of that `daily` invocation failed to open its own screen. Manually reproducing the flow live (reaching the real confirm dialog and cancelling before confirming, the same safe-calibration pattern the original live-testing used) found the actual hazard: the 任務情報 modal has TWO separate action buttons stacked vertically -- the intended cyan 掃討開始 (start sweep, instant) and a separate gold 任務開始 (start mission, a REAL manual battle) directly below it, both showing an identical ticket-cost preview. Every check along the commit path (`_count_raised_above_one`/`_is_sweep_usage_confirm`/`_watch_sweep_result`'s own "swept" conditions) is a generic color/position probe with no verification of what's actually showing. Fixed with `_confirm_dialog_is_sweep`, an OCR text check (`config.BOUNTY_SWEEP_CONFIRM_TEXT_RECT`, captured live from the real dialog: "指名手配チケットをN使用して、掃討をN回行いますか?") gating the one irreversible click in this flow -- cancels rather than confirms if the dialog doesn't read as a sweep. The exact mechanism that let a real run reach 任務開始 instead of 掃討開始 was not fully reproduced live (would mean deliberately repeating a real battle); the fix closes the hazard regardless of the exact upstream cause. Not yet re-verified live against a fresh real sweep. **Expanded from 3 areas to 5 (2026-09-24)**, per explicit user request once the game added two new areas, 道路 (Road) and 屋敷 (Mansion). Config-only change (`config.BOUNTY_AREA_NAMES`/`BOUNTY_AREA_ROW_Y` extended to 5 entries) -- `bounty.py`'s own logic was already generic over the area count, no code changes needed. Verified live via a read-only recon (zero tickets touched): both new areas fit on the same non-scrolling Location Select screen continuing the existing 175px row spacing (825/1000), and share the identical 10-stage/already-SSS-cleared structure as the original 3. Rotation is now modulo 5. **Live-tested for real the same day**: `./ba_dailies.sh bounty` ran end-to-end against 道路 (that day's rotation pick) and completed cleanly, `result: swept`. One cosmetic-only gap found: the bottom-row stage-number OCR diagnostic log (not on the decision path -- selection is always the bottom-most row regardless) read `None` instead of a real digit string on this new area; left as-is per explicit user direction since it doesn't affect the sweep. | | Login | `core/Baas_thread.py`, `module/restart.py` | `to_main_page` (generic post-launch arrival routine, reused by every other reference feature's own navigation -- no separate "login" module exists in the reference), `restart.py`'s `implement`/`start` (check app running, launch if not) | `ba_auto/tasks/login.py` | Reference detects every one-off popup (~20 named `img_reactions`/`rgb_possibles`) via `picture.co_detect` image-template matching; this port scopes down to what was actually confirmed live (title screen via a fixed-chrome logo-color probe, a real network-error notice, the daily attendance card, S.C.H.A.L.E NEWS) plus a bounded generic Enter-press fallback for anything else recognized, mirroring co_detect's own "blind action once nothing matches" fallback shape but using this project's own established Enter-dismiss idiom rather than a blind coordinate click. `module/restart.py`'s kill-then-relaunch pattern ported directly via new `driver.kill_game`/`launch_game`/`is_game_running`/`window_exists` primitives (`pkill -f`/the account's own `/usr/local/bin/launch-blue-archive.sh`/`pgrep -f`/`xdotool search`) | Done. Live-calibrated 2026-07-16 on nik-gpu against the account's real overnight login-screen state (native 1920x1200 captures throughout, not the non-native `screenshots/daily_login/*.png` reference photos originally supplied -- same not-1:1 gap already documented for `screenshots/gem_shop/`/`screenshots/cafe/student/`). Confirmed live: the title screen's own logo reads a fixed brand-chrome color independent of rotating seasonal background art (confirmed across two different pieces), bright when clean and uniformly dimmed when a real notice is open on top of it (a genuine "ネットワークへの接続に失敗しました" network error surfaced unprompted during calibration); the daily attendance card only appears once per day (confirmed absent on an immediate same-day re-run after being claimed) and, like the network notice, responds to a plain Enter with no dedicated detection needed; the S.C.H.A.L.E NEWS popup needed a dedicated header-color probe since `navigation.is_on_subscreen`/`is_modal_open` both proved unreliable on it (same class of mismatch as `gem_shop.py`'s own dialog -- confirmed live by direct pixel comparison). **A real stuck-loading incident hit live during calibration itself**: the loading transition (a full-bleed variant with no chrome, distinct from a brief chrome-visible variant also seen) stalled past 6 minutes with zero progress, confirmed not a network/process-health issue; the user's own live guidance ("kill the game and rerun it") identified the relaunch script, and a second attempt after manually killing+relaunching completed the entire remaining flow (title tap -> attendance card -> home) in well under 15 seconds, confirming the stall was a genuine stuck state now handled automatically by `_recover`. Also observed live (twice, non-deterministically) but deliberately NOT worked around: a known pre-existing client rendering bug (per the user) where the news popup's own promo image can get stuck as a blank white rectangle after closing -- confirmed harmless to this module specifically (sits clear of every probe point used here, and the shared home-check probes still read correctly through it), and the user's own fix for it (reload the app) is already this module's existing stuck-recovery path. Added as the very first step in `DEFAULT_ORDER`, ahead of mailbox, since no other task can reach home from the title/loading/attendance-card states on its own. **Not yet live-confirmed**: the infrequent 業務復帰ログインボーナス welcome-back login bonus card from the user's own reference screenshots (account wasn't in that state during calibration) -- expected to fall through to the same generic-Enter path already confirmed for the attendance card and network notice, but not yet exercised for real; and the kill+relaunch recovery path has only been exercised once, manually, not yet through a fresh invocation of the actual `login.py` module hitting a real stuck state on its own. **Connectivity-probe fix, `_connectivity_confirmed` (2026-07-17)**: reported live by the user via real pulled cron logs -- a 4:30 AM `daily` fire logged a clean `[login] reached home`, but every task that ran afterward (cafe, event_sweep, circle, lesson, arena, both shops, gem_shop, mailbox, stamina) failed to open its own screen, persisting across multiple consecutive `q4h` fires spanning hours. Per the user's own direct knowledge: the server's daily reset or a concurrent login from another device can silently kill the session while the client keeps showing a cached-looking, visually normal home screen -- the error only surfaces as the game's own "connection lost" popup once an actual navigation/API call is attempted, which `_true_home`'s purely-visual checks never triggered. Fixed per the user's own suggested design ("enter the stamina claim/reward area then go back home"): `_connectivity_confirmed` now opens the Mission panel and closes it again before `_wait_for_home` will return success. Reproducing this live (the user logged into the account on their phone to trigger a real session kill) surfaced two FURTHER false positives in the same family, both from an unusually long, multi-frame animated loading sequence that never resolved on its own: first with `navigation.is_on_subscreen` (single-pixel) as the panel-opened check, then again after upgrading to `navigation.is_header_bar_visible` (8-point) -- each independently got fooled by a different coincidental splash frame within the same run. Fixed by requiring `_true_home` to re-verify a second time, after a short wait, before finally trusting a passed connectivity check. **Confirmed live**: the stuck session was cleared with a manual kill+relaunch, then a genuinely fresh cold-start `login` run (game process not running at all) correctly launched the game, passed through the title screen, and reached independently-verified true home (full HUD -- Lv/AP/credits/gems/bottom nav all visible, confirmed via direct screenshot and a separate `_true_home`/`is_header_bar_visible` check, not just the module's own printed message). Not yet re-confirmed against a fresh instance of the original silent-session-death failure mode specifically (the live reproduction available this session was the full-kick-to-login-screen variant, not the "still looks like home but isn't" variant from the cron logs), though the same `_connectivity_confirmed` mechanism covers both by design. **Faster stuck-loading detection, `_loading_buffer_visible` (2026-07-19)**: a manual `ba_cron_run.sh daily` run left the game stuck at login; `_recover`'s existing kill+relaunch DID fire correctly once the generic 240s timeout elapsed (confirmed live -- the user reported "the game did relaunched"), but waiting the full generic timeout for this specific, recognizable state is slower than necessary. Live-captured the real stuck screen and pixel-probed it (`screenshots/daily_login/stuck_loading_buffer.png`, calibrated via `scratchpad/probe_login_buffer.py`): the full-bleed loading variant's center spinner badge reads a flat, exact neutral gray `(118,118,118)` at a fixed screen-center position, independent of whichever splash-art frame is rotating behind it -- unlike the earlier `_true_home`/`_connectivity_confirmed` false positives, this doesn't share the "different frame fools a single-snapshot check" failure class, since the badge is a fixed UI overlay, not art. `_wait_for_home` now tracks continuous badge visibility and bails out to `_recover` after `config.LOGIN_LOADING_BUFFER_STUCK_SECONDS` (60s) instead of the full 240s once this exact state is confidently recognized. Verified offline against the real capture (all 6 probe points matched). Not yet live-confirmed against a fresh stuck instance recovering via this specific faster path (the triggering instance had already recovered via the pre-existing generic timeout by the time the fix was written). **Real Steam-signed-out incident + crash-cascade fix (2026-09-20)**: the user reported 3 consecutive real cron failures (`q4h` 01:00, `daily` 03:30 and 04:30, all same day). Every one logged `[login] game window not found -- launching` then `[login] warning: game window never appeared after launch -- giving up`, followed immediately by the NEXT task in the sequence crashing with an uncaught `RuntimeError` from `driver.focus_game()`. Root-caused with a live screenshot (superpowers:systematic-debugging) to Steam itself sitting on its own account sign-in dialog (username/password + QR code) the entire time -- not a Blue Archive client issue at all, and not something any amount of retrying/relaunching the GAME can fix, since it needs a real person to sign in. Two fixes: (1) `login._steam_needs_sign_in` (new `detector.read_text_white_on_dark`, since the dialog's own "SIGN IN WITH ACCOUNT NAME" label is light-blue-on-dark-navy, the opposite polarity of this project's usual OCR assumption -- confirmed live the label's grayscale luminance tops out at 126, needing a threshold well under the existing `read_int_white_on_dark`'s default 150) recognizes this exact state and turns the generic "never appeared" warning into a specific, actionable one; (2) `ba_daily.py`'s `_run_sequence` now checks `driver.window_exists()` after every task (except the last, and except `exit_game`, which is expected to close it) and aborts the whole run immediately with one clear message if the window is gone, instead of letting every remaining task independently rediscover this via its own doomed pre-task retry cycle before crashing -- still propagates as a real `FAILED` exit code (this project deliberately never swallows a genuine crash), just immediately and legibly instead of two tasks deep in a stack trace. **Confirmed live**: reproduced the exact original failure via a real `./ba_cron_run.sh q4h` run while Steam was still genuinely signed out, confirmed the new diagnostic message fired correctly and the sequence aborted right after `login` instead of wasting ~15s on `cafe`'s own doomed retry-then-crash. After the user signed back into Steam manually (confirmed via a live screenshot showing the real Blue Archive title screen), a real `./ba_cron_run.sh daily` recovery run was executed to catch up the account's daily claims -- see this row's own task entries for that run's outcome. | | Commissions | `module/clear_special_task_power.py` | Need to inspect | `ba_auto/tasks/commission.py` | sweep/color adaptation | Not started | -| Exit game | None -- searched `~/repo/baas-reference/` thoroughly, no counterpart exists. The closest match, `core/Baas_thread.py`'s `shutdown()`/`start_shutdown()` (line ~984), is an optional full Windows OS shutdown (`subprocess.run(["shutdown", "-s", "-t", "60"])`) gated by a user toggle, not a game-client exit -- out of scope (this project's game and X display run on `nik-gpu`, shutting the host down would kill the SSH session too, nothing like what was requested). The only other app-closing call, `connection.py`'s `close_current_app` (line 381, plain ADB `app_stop`), exists purely for `Baas_thread.py`'s own error-recovery restarts (`deal_with_package_incorrect`/`deal_with_func_call_timeout`) inside a persistent background scheduler that's designed to keep running indefinitely -- it never deliberately exits once daily tasks finish. This feature is new, desktop-specific convenience logic motivated by this project's different architecture (cron launches a fresh one-shot process per preset, so closing the game after a run has real value the reference's always-on scheduler never needed), not a port of anything. | `ba_auto/tasks/exit_game.py` | No new driver/detector primitives needed -- reuses `navigation.return_to_home` (must-be-true-home gate), `navigation.is_modal_open` (verifies the Escape-triggered "exit the game?" dialog actually opened, the same generic dim-probe reused across bounty/gem_shop/circle's own confirm dialogs), `driver.keypress("Escape"/"Return")`, and `driver.window_exists()` (verifies the game process/window is actually gone afterward, not just that Enter was sent) | Done. `navigation.return_to_home`'s own docstring already documents the mechanism this relies on: an Escape press on the confirmed true home screen (nowhere else) raises this exact dialog -- every other task treats that as a hazard to avoid triggering by accident; this is the one task that wants it, gated the same way (only fires from a verified true-home state). No force-kill fallback if the graceful Escape/Enter path doesn't verify -- matches this project's established "abort cleanly on unknown state rather than guess" convention (gem_shop/bounty), rather than reaching for `driver.kill_game()`. Opt-in only, appended to the end of the `daily`/`q4h` presets (not `DEFAULT_ORDER`), since it deliberately ends the session. **Confirmed live (2026-07-18)** via a standalone `./ba_dailies.sh exit_game` run, user-reported "works well" -- `is_modal_open`'s generic dim-probe correctly read the exit-confirmation dialog after Escape, and the game closed cleanly after Enter. Not yet exercised as the tail end of a full `daily`/`q4h` preset run (only standalone so far), though nothing in its own logic depends on which task ran before it. | +| Exit game | None -- searched `~/repo/baas-reference/` thoroughly, no counterpart exists. The closest match, `core/Baas_thread.py`'s `shutdown()`/`start_shutdown()` (line ~984), is an optional full Windows OS shutdown (`subprocess.run(["shutdown", "-s", "-t", "60"])`) gated by a user toggle, not a game-client exit -- out of scope (this project's game and X display run on `nik-gpu`, shutting the host down would kill the SSH session too, nothing like what was requested). The only other app-closing call, `connection.py`'s `close_current_app` (line 381, plain ADB `app_stop`), exists purely for `Baas_thread.py`'s own error-recovery restarts (`deal_with_package_incorrect`/`deal_with_func_call_timeout`) inside a persistent background scheduler that's designed to keep running indefinitely -- it never deliberately exits once daily tasks finish. This feature is new, desktop-specific convenience logic motivated by this project's different architecture (cron launches a fresh one-shot process per preset, so closing the game after a run has real value the reference's always-on scheduler never needed), not a port of anything. | `ba_auto/tasks/exit_game.py` | No new driver/detector primitives needed -- reuses `navigation.return_to_home` (must-be-true-home gate), `navigation.is_modal_open` (verifies the Escape-triggered "exit the game?" dialog actually opened, the same generic dim-probe reused across bounty/gem_shop/circle's own confirm dialogs), `driver.keypress("Escape"/"Return")`, and `driver.window_exists()` (verifies the game process/window is actually gone afterward, not just that Enter was sent). The final process check reuses `driver.is_game_running()`/`driver.kill_game()` (login.py's own kill-and-relaunch primitives), with `kill_game` gaining a `force=True` SIGKILL option | Done. `navigation.return_to_home`'s own docstring already documents the mechanism this relies on: an Escape press on the confirmed true home screen (nowhere else) raises this exact dialog -- every other task treats that as a hazard to avoid triggering by accident; this is the one task that wants it, gated the same way (only fires from a verified true-home state). The graceful Escape/Enter path itself still aborts cleanly on any unverified state rather than pressing keys blindly (gem_shop/bounty's convention). **Process-kill fallback added 2026-10-28** per explicit user request ("sometimes the game stuck" -- q4h.log showed three exit_game aborts that day, each leaving the game open): however the graceful path ends (closed, aborted, or raised), `run()` finishes by checking `config.GAME_PROCESS_NAME` is gone after a ~10s grace period, and if not, kills it (SIGTERM, then SIGKILL if that doesn't take). Opt-in only, appended to the end of the `daily`/`q4h` presets (not `DEFAULT_ORDER`), since it deliberately ends the session. **Confirmed live (2026-07-18)** via a standalone `./ba_dailies.sh exit_game` run, user-reported "works well" -- `is_modal_open`'s generic dim-probe correctly read the exit-confirmation dialog after Escape, and the game closed cleanly after Enter. Not yet exercised as the tail end of a full `daily`/`q4h` preset run (only standalone so far), though nothing in its own logic depends on which task ran before it. | | Arena | `module/arena.py` | `implement` (main flow), `to_tactical_challenge` (nav from main page), `get_tickets` (ticket-count OCR), `choose_enemy` (self/opponent level OCR + bounded refresh-reroll loop), `check_skip_button` (skip-toggle color probe), `fight` (click fight, wait for win/lose), `collect_tactical_challenge_reward` (two reward-slot color probes) | `ba_auto/tasks/arena.py` | Ticket count/self level/opponent level/rank are plain digit OCR (`detector.read_int`/`read_text`, plus a new `read_int_white_on_dark` for the profile card's bright-on-dark level text). Skip-toggle state and the two reward-slot claimed-vs-claimable colors are plain pixel-color probes (`driver.color_at`/`_color_in_range`). The post-fight WIN/LOSE result modal and an unrelated list-refresh-expired notice are NOT detected by precisely locating a button (a color-region search proved unreliable — see Status); they're dismissed via a bounded blind-Enter-press loop matching `lesson.py`'s own `_run_one_schedule` pattern, gated by a hard safety check against the one modal where Enter is dangerous (opponent-info's own attack-formation button, checked via its fixed-position gold button). `choose_enemy`'s refresh-reroll loop is direct Python control flow, bounded by `maxArenaRefreshTimes`. Config knobs carried over from reference defaults: `ArenaComponentNumber`=1, `ArenaLevelDiff`=0, `maxArenaRefreshTimes`=10, `ArenaStopFightWhenRank1`=False | Done. Live-tested for real across all 5 of the account's daily tickets (2 WIN, 1 LOSE, 2 spent debugging the result-modal detection — see `plan.md` Phase 13 for the full writeup). Real navigation differences confirmed live: Tactical Challenge is a Work-hub card, not a bottom-nav icon; the reference's separate opponent-info and formation-edit screens are merged into one modal here with a live ticket-preview; `navigation.is_modal_open`'s shared probe reads *inverted* on this screen (own `_is_modal_open` via `config.ARENA_MODAL_PROBE`). Three real bugs fixed: a level-OCR crop too small for tesseract despite looking legible (fixed by widening the crop, not the pipeline); level text being bright-on-dark unlike every other OCR read in this project (fixed via `read_int_white_on_dark`); and the result-modal detection cycling through two failed color-based designs (fixed by switching to bounded blind-Enter dismissal with a hard safety gate — a real near-miss of the same "mistimed keypress" hazard class `CLAUDE.md` already documents from story_sweep). Deliberately opt-in only, never in `DEFAULT_ORDER` — unlike every other opt-in task so far (which spend a known-safe resource on a config-driven target list), this one fights a real ranked PvP battle that can win or lose and moves the account's actual arena rank. Per explicit user decision: fights exactly one battle per invocation, matching the reference's own per-call pacing (its `next_time = 55` background-thread rescheduling has no equivalent in this project's one-shot CLI). Not yet exercised live: the "no ticket" mid-flow race, an actual reroll click (every opponent offered was already an acceptable level), and `ArenaStopFightWhenRank1`'s rank-1 stop condition — all implemented per the reference's logic, just not yet hit by real game state. `detector.find_template`/`template_visible` (generalized named-template matcher, built during scaffolding) ended up unused — state detection stayed OCR/color-probe-driven throughout, like every other task in this project. Follow-up (2026-07-11): live bug report — this task never returned home at the end, so a second consecutive invocation starting from wherever the first left the game (the Tactical Challenge screen itself) sent `_open_tactical_challenge`'s home-relative clicks to the wrong place and failed all 3 retries. Fixed by calling the shared `navigation.return_to_home(driver)` at the very start of `run()`, reusing the generic Escape-based recovery primitive built for `event_sweep.py`'s own wrong-page recovery. Confirmed live (2026-07-11): reproduced the stuck-on-arena-screen scenario manually, then a real `arena` invocation recovered and completed a full fight normally (rank 14位's opponent-list entry moved 10位→9位, ticket 2→1, credits +1,080), with no repeat of the original failure. Follow-up #2 (2026-07-12), per explicit user request: reversed the original "exactly one battle per invocation" decision — `_fight_one` now holds the single-battle logic and `run()` loops it (`while tickets > 0 and fights < config.ARENA_MAX_FIGHTS_PER_RUN`), re-reading the OCR'd ticket count after each fight and waiting `config.ARENA_POST_BATTLE_COOLDOWN` (30s, per the user's own info about the real in-game lockout between fights) before continuing. `ArenaStopFightWhenRank1` is now re-checked before every fight in the loop, not just once. See `plan.md`'s Phase 13 follow-up #2 — not yet live-tested (spends multiple real tickets, needs the user's go-ahead first). **This DID subsequently run live via cron and surfaced a real hazard (2026-07-17)**: the log showed "battle skip already on" for all 5 fights and a clean "fought 5 battle(s) this run", but the account was left showing a real "Battle Complete" screen with a ~3-minute combat timer -- battles had run in full, not skipped -- and every task for the rest of that `daily` invocation failed to open its own screen. Two compounding bugs: (1) `_ensure_skip_on`'s "on" detection was never actually verified to reject a real "off" state (`ARENA_SKIP_ON_RGB` was only ever confirmed against a session where skip happened to already be on); (2) `_wait_for_result` had no early-exit signal and always ran its full fixed 15s budget before unconditionally declaring success -- far too short for a real battle -- and `_fight_one` discarded `_wait_for_result`'s return value entirely, so even a correctly detected failure never stopped the fight loop. Fixed by widening `RESULT_MODAL_MAX_POLLS` substantially (tolerating a real battle's full duration regardless of whether the skip-mode detection gets fully root-caused) plus a new `_back_on_challenge_list` early exit (so the normal fast case doesn't slow down), and by making `_fight_one` actually stop on a `_wait_for_result` failure. The skip-toggle's own "off" detection was not independently re-verified (would need a real ticket at a moment the account had none left) -- deliberately structured so the fix is safe even if that root cause isn't fully resolved. | | Common Shop | `module/shop/common_shop.py`, `module/shop/shop_utils.py` | `implement`, `to_common_shop`, `get_item_position`/`ensure_choose`/`buy` (shared, see Tactical Shop row) | `ba_auto/tasks/shop_common.py`, `ba_auto/tasks/shop_utils.py` | Originally ported as fixed grid-position targets (`config.COMMON_SHOP_TARGETS`) + price-digit OCR verify, matching the reference's own external-price-list-index design as closely as this repo's missing external table allows. **Revised 2026-08-01**: fixed position turned out not to hold live -- this shop sinks sold-out items to the bottom of its grid and shifts everything after them up, so `(row, col)` drifted the moment anything sold out (see plan.md Phase 25 follow-up #2). `select_targets_by_name` now identifies items by OCR'd name instead, scanning/scrolling the full (scrollable, ~24-slot) grid and matching on name + exact price + a purchasable-button color check -- arguably *closer* to the reference's item-identity-based design intent than the original position table was, just using a local OCR read in place of the reference's external price-list index. Tactical Shop stays on the original position-based path (never showed this symptom). Purchase-confirm dialog + reward-acquired banner still handled via a single overlay-darkness probe (`config.SHOP_OVERLAY_PROBE`). **Rewritten again 2026-09-17** after a real live under-purchase (reported by the user with their own cron log pasted in: a real `daily` run bought only 4 of 8 configured targets, logging the other 4 as "not found available" even though, hours later with nothing else touched, those exact 4 sat unbought at their exact expected prices right at the top of the unscrolled grid) -- see the Status column for the full root-cause writeup; fixed three distinct bugs, not one | Done, re-verified live post-2026-08-01-rewrite (superseded by the 2026-09-17 fixes below): real run correctly bought the one target that was actually available (`中級レポート`, 125,000 credits, matching a real credit-balance delta) and correctly logged the other 7 as unavailable this cycle rather than misdiagnosing them as a catalog change. **2026-09-17 live debugging** (superpowers:systematic-debugging, root-caused from the user's own pasted `~/repo/scratchpad/ba_logs/daily.log` excerpt cross-checked against live screenshots -- see `ba_auto/tasks/shop_utils.py`'s own docstrings for the full writeup) found and fixed THREE separate real bugs, confirmed one at a time via five consecutive real `./ba_dailies.sh shop_common` runs against the account's actual daily catalog: (1) `select_targets_by_name`'s old row/col loop kept iterating with stale screenshot-implied positions after a successful buy, even though buying an item collapses its grid slot and shifts every later item forward -- fixed by re-scanning the current viewport from scratch (`_scan_current_view`) after every single buy instead of continuing the old pass; (2) even with that fix, two more confirmed-available targets were still missed, because the checkbox's own "checked" confirmation settles well before the rest of the grid's reflow/collapse animation visually finishes -- fixed with `config.SHOP_REFLOW_SETTLE_WAIT` (1.5s, not yet tuned down from a measured minimum), an explicit wait before the post-buy rescan; (3) the deepest bug: Common Shop's own tier-naming convention nests a shorter tier name inside a longer one (`上級強化珠`/Advanced is a literal substring of `最上級強化珠`/Highest, same for the レポート pair), and the original substring-only name match had no preference for an exact match, so scanning a "最上級..." card while its "上級..." sibling was still also a remaining target could resolve to the WRONG (shorter) target, compare against the wrong price, and permanently skip a genuinely-available card every run -- confirmed live: `最上級強化珠` sat available at its exact listed price across three consecutive real runs, never once bought, until fixed via `_match_name`'s exact-match-first resolution (substring fallback now prefers the longest/most-specific candidate). All 8 of today's configured targets were confirmed successfully bought across the debugging session's real runs (credit balance deltas matched each purchase's exact expected price sum throughout), and a final clean run correctly reported all 8 as sold out for the day with no further false skips. Earlier finding, still true: no visible purchase-count indicator (unlike the 青輝石 tab's "あと1回購入可能" labels). Also encountered but unrelated to this task: a stray already-open MomoTalk panel intercepted a `SHOP_ICON` click mid-session (closed manually); `navigation.is_on_subscreen`/`is_modal_open` don't recognize MomoTalk as a blocking state, same class of blind spot already documented for the old gem_shop dialog and cafe's rank-up cutscene -- not fixed here, out of scope for this incident, flagged for future attention if it recurs. **A FOURTH real bug found 2026-09-19**, two days after the above: the user reported the account still only showing 4 bought items on a given check. Re-investigating with the user's own cron logs (`~/ba_logs/daily.log`/`q4h.log`) found that, taken across both real `daily` cron fires each day, all 8 targets genuinely were being bought (the two fires split the 8 into complementary halves, each catching whatever the other one's timing missed) -- so the "only 4" symptom was a same-day timing snapshot, not a standing bug, EXCEPT for one real, separately-confirmed defect: `shop_utils.confirm_purchase` checked the purchase-confirmation overlay exactly once after clicking Buy and returned success as soon as that single read was "idle" -- with nothing distinguishing "confirmed and closed" from "the Buy click missed and the confirm dialog never opened at all". Caught live: a real cron run's log claimed "bought 4 item(s) for 303000 credits", but those exact 4 items were still sitting unbought at their base price hours later; re-running the task then genuinely bought them (confirmed via an exact matching credit-balance delta). Fixed by requiring the currency balance to have actually dropped by the exact expected spend once the overlay reports idle (re-read with the same `SHOP_PRICE_OCR_RETRIES` stray-misread-digit tolerance already used elsewhere in this module), returning `False` -- not a false "purchased" -- if it never does. Logically verified and syntax-checked, but **not yet live-confirmed against a real purchase specifically**: by the time the fix was written, all 8 of today's targets were already bought (from the same day's own earlier debugging), so no fresh purchasable item was available to exercise the new balance-check end-to-end; needs re-confirming the next time a genuinely fresh target is available (tomorrow's catalog reset, or Tactical Shop once its own separate price-misread bug -- see that row -- is fixed). **A FIFTH real bug found 2026-09-21**: the user reported only 4 of 8 targets bought again. Investigation (read-only OCR probes against the live screen, then a real `./ba_dailies.sh shop_common` run, then a before/after screenshot of a single scroll) found the remaining 4-5 "not found available" targets were genuinely available, correctly priced, purchasable, and even matched cleanly by a read-only replay of the exact same matching code -- yet the real production scan still missed them. Root cause: `config.SHOP_SCROLL_STEP_CLICKS`'s "advances by exactly one row" assumption (true when originally calibrated) no longer holds now that the catalog mixes in raw-material items whose two-line-wrapped names make some rows taller than others -- a single scroll call can overshoot a clean row boundary and land mid-row. Confirmed live: a before/after screenshot pair showed the grid jumping ~1.5-2 rows in one scroll, cutting card titles off above the viewport; every fixed-offset OCR/color read after that came back empty/garbled, and `_is_purchasable` read `False` across all 8 cells (vs. 7-8/8 `True` on a genuinely aligned frame) -- so the scan silently treated a torn frame's unreadable cells as "target not found" rather than "my crop coordinates are pointing at nothing". Fixed with `shop_utils._grid_looks_aligned`/`_ensure_grid_aligned`: after every scroll, verify at least one cell still reads purchasable before trusting the frame, nudging back up in small steps (`config.SHOP_SCROLL_REALIGN_NUDGE_CLICKS`/`_MAX_NUDGES`) if not, rather than scanning (and misreporting from) a misaligned frame. Only bites items that get reflowed out of the first two visible rows mid-run by earlier purchases in the same pass -- explains why the specific "missing 4" vary day to day rather than being a fixed set. Deployed and live-tested: see `plan.md` for the outcome. **That fix turned out NOT to be the actual cause of the recurring pattern** -- the next morning (2026-09-22) the exact same symptom recurred (real `daily` cron logs: the 03:38 run found ALL 8 targets "not found available" within 3 seconds -- far too fast for a genuine multi-row OCR scan -- and the 04:53 run then bought only the same familiar "top 4", leaving the same familiar "bottom 4" unbought). Re-investigated live: a read-only probe and a fresh interactive replay of the real matching code both found the "stuck" 4 sitting unscrolled at the top of the grid, correctly priced and purchasable -- confirming the scroll-alignment fix from the day before was never even being exercised for this failure. **A SIXTH real bug, found the same session**: while manually replaying the exact production logic step by step to gather evidence, a genuine in-game "ネットワークアクセスに問題が生じました" (network access problem) modal appeared over the shop grid mid-flow -- a real, first-party dialog, not anything this project's code triggers. It dims the whole grid, so every fixed-offset OCR/color read behind it comes back empty/garbled; and because a static dialog doesn't change frame to frame, `select_targets_by_name`'s own "screenshot unchanged" stop condition fires almost immediately, misreporting every remaining target as unavailable in a couple of seconds flat -- an exact match for the 03:38 run's suspiciously fast full-failure. Fixed by checking `navigation.is_modal_open` (the same screen-dimming probe used throughout this project) at the top of every scan pass, before trusting anything read from that frame; skipped targets from an aborted scan now get a distinct `blocked_by_modal` reason instead of the misleading "sold out this cycle, or catalog changed" message. Deliberately does not try to dismiss the dialog itself (this specific one's own "OK" button logs all the way out to the title screen, confirmed live when recovering from it via the `login` task) -- an unrecognized modal gets a loud, honest stop instead of a guessed keypress. **Confirmed live**: with the game recovered to a clean state, a real `./ba_dailies.sh shop_common` run then correctly found and bought all 4 remaining "stuck" targets for 303,000 credits (credit balance delta matched exactly), completing the full day's 8/8 targets (908,500 earlier + 303,000 = 1,211,500, the exact full catalog total) with zero items ever falsely reported unavailable. Whether the 2026-09-21 scroll-alignment fix was itself a real, separate bug (yes, confirmed independently that day) or was ever actually the cause of a cron-observed failure (unconfirmed either way) remains open -- both fixes are kept, since each addresses a distinct, independently-confirmed way a frame can be misread as "nothing here" when something really is. **A major debugging session, 2026-09-24**, per explicit user direction to "select, screenshot, never buy" until confident, then implement -- found and fixed FOUR more distinct real bugs using that exact safe methodology (repeatable selection-only runs via a scratchpad probe calling `select_targets_by_name` directly and always Cancel-ing, never Buy-ing, so free to iterate without touching real currency): (1) `中級レポート`'s price OCR deterministically misread "125,000" as "1250060" -- a digit-only tesseract whitelist forces the thousands-separator comma to be misclassified as a phantom digit instead of punctuation it's simply not allowed to output; fixed by adding ',' to `detector.read_int`'s whitelist (the existing digit-only filter afterward means this is a strict improvement with zero behavior change for comma-free reads, and also covers `CREDIT_BALANCE_OCR_RECT`'s routinely-multi-comma reads). (2) `_match_name` could not resolve internal single-character insertions/deletions ('初級レポート' read as '初級レポボート', '中級強化珠' read as '中級化珠') since plain substring containment requires unbroken contiguity; fixed with a two-stage fallback in `_match_name` -- strip whitespace, then fall back to `difflib.SequenceMatcher` similarity (`SIMILARITY_THRESHOLD = 0.75`, calibrated against real corrupted samples scoring 0.857-0.923 vs. unrelated catalog items topping out at 0.462). (3) A promotional ribbon/badge decoration on '初級強化珠' and '最上級強化珠' specifically (not the two middle tiers) overlapped the left ~40px of the name-OCR crop, corrupting the read badly enough that no matching stage could resolve it; fixed by measuring the decoration's real pixel extent (never past x=42 across both ribbon colors sampled) and shifting `SHOP_NAME_OCR_OFFSET`'s left edge by +45px. A second, subtler variant then surfaced on '最上級強化珠' alone: two small stray dark blobs in the crop's first ~5 vertical pixels (present even when the raw crop looked completely clean to the eye) confused psm 7's single-line assumption; fixed by shifting the top edge down 10px. (4) The deepest one: OCR corruption on a given cell was confirmed live to be STABLE for as long as the shop tab stays open (reading the identical wrong text 5/5 times with no navigation in between) but to reset to a genuinely different render on every fresh tab reopen (4/5 reopens gave different text, one exactly correct) -- so in-place rescanning (the 2026-09-22 fix's own retry loop) can structurally never help a stuck cell, only leaving and re-entering the tab can. Fixed by escalating to a bounded full reopen cycle (`config.SHOP_REOPEN_MAX_ATTEMPTS`) once in-place retries (`SHOP_NO_MATCH_RETRIES`, lowered from 10 to 2 once proven useless) are exhausted. **This reopen fix itself then caused a real under-purchase**, caught before it could recur: reopening turned out to also silently uncheck every checkbox ticked so far (checked state lives in the tab's own UI, not the account, until Buy is clicked), but `select_targets_by_name` kept trusting its own in-memory `selected` bookkeeping -- a real run logged all 8 targets matched (summing to the full 1,211,500) yet the actual balance only dropped by 125,000, the one target found right after the run's one reopen; every earlier "selected" target had gone back to unchecked in the live game without the code noticing. A same-day interim fix (move `selected` back into `remaining` on every reopen) closed the under-purchase but was pathological -- it forced the WHOLE batch to be re-earned on every single reopen, not just the stuck target, and a real run cycled through 20+ reopens chasing a shrinking-then-growing batch, eventually colliding with a real scheduled `q4h` cron fire on the same game window (confirmed via `~/ba_logs/q4h.log`'s own crash traceback landing the same second) and crashing on cascading screenshot corruption. **Final, correct fix**: `select_targets_by_name` now buys incrementally, committing (via a real, balance-verified `confirm_purchase` call) whatever's checked in the *current* batch immediately before any reopen, so a reopen can only ever cost re-scanning time, never already-real spending -- it now owns its own purchase confirmation end-to-end (`HANDLES_OWN_PURCHASE` flag; `run_shop_tab` defers to it instead of buying again on its behalf; Tactical Shop's `select_targets` path is completely unchanged). **Confirmed live end-to-end**: a real run bought 3 items (178,000 credits) in one batch after one reopen, correctly recognized the other 5 as already-bought-today (from the interim fix's own real purchases plus the concurrent cron's), and the day's cumulative real spend (125,000 + 908,500 + 178,000 = 1,211,500) exactly matches the full 8-item catalog total with zero double-buys or silent under-purchases. | | Tactical Shop | `module/shop/tactical_challenge_shop.py`, `module/shop/shop_utils.py` | `implement`, `goto_shop_by_name`, shared `get_item_position`/`ensure_choose`/`buy` | `ba_auto/tasks/shop_tactical.py`, `ba_auto/tasks/shop_utils.py` | `goto_shop_by_name`'s OCR swipe-search over the shop-tab list → fixed click (`config.SHOP_TAB_TACTICAL`): this account's tab list is only 7 entries and fits on screen with no scroll needed, confirmed live, so there's nothing to search for — not an OCR-avoidance shortcut. Same grid-position + price-OCR-verify + overlay-probe design as Common Shop, sharing `shop_utils.run_shop_tab` | Done. Live-tested with real purchases (both configured AP-recovery drinks bought; AP and tactical-coin balance changes matched exactly). **Regression noticed 2026-09-19, not yet investigated or fixed**: both configured targets (`初級栄養ドリンク(AP30)`/`中級栄養ドリンク(AP60)`) now consistently OCR-read price 50 for BOTH items (real prices 15/30), across multiple separate real runs -- always skipped as `price_mismatch`, `confirm_purchase` never reached. Same "50" for two different real prices points at either a real catalog/UI change (e.g. a display format change, or these items hitting some daily cap and showing a placeholder) rather than ordinary OCR noise, but unconfirmed -- flagged for a future live investigation, out of scope for the 2026-09-19 cafe/shop_common fixes. | diff --git a/ba_auto/tasks/exit_game.py b/ba_auto/tasks/exit_game.py index e0442d9..a70fdc0 100644 --- a/ba_auto/tasks/exit_game.py +++ b/ba_auto/tasks/exit_game.py @@ -17,9 +17,18 @@ own reward dismissal). Success is verified against driver.window_exists() actually going False, not just against the keypress having been sent, matching every other verified-keypress helper in this project. -No force-kill fallback if the graceful path doesn't verify -- matches this -project's "abort cleanly on unknown state rather than guess" convention -(gem_shop/bounty) rather than reaching for driver.kill_game(). +The graceful path itself still never guesses: it aborts cleanly on any +unverified state (gem_shop/bounty's convention) rather than pressing keys +blindly. But whichever way it ends -- closed, aborted, or raised -- run() +finishes with a process check: if config.GAME_PROCESS_NAME is still +running after a short grace period (Proton teardown after a clean close +isn't instant), it's killed via driver.kill_game(), SIGTERM first, then +SIGKILL if that doesn't take. Added 2026-10-28 per explicit user request +("sometimes the game stuck"): q4h.log showed three exit_game aborts that +same day alone (01:23, 10:09, 17:13), each leaving the game open on +whatever screen it had wedged on. Safe to kill unconditionally here, unlike +mid-task, because exit_game is always the last task in a preset and its +whole purpose is for the game to end up closed. Confirmed live (2026-07-18) via a standalone `exit_game` run: the is_modal_open dim-probe correctly detected the exit-confirmation dialog @@ -32,6 +41,11 @@ from ba_auto import navigation CONFIRM_RETRIES = 3 CLOSE_WAIT_ITERATIONS = 15 CLOSE_WAIT_INTERVAL = 1 +# Grace period for the process to exit on its own after a clean close, +# then how long to wait after each kill signal before escalating/giving up. +PROCESS_EXIT_WAIT_ITERATIONS = 10 +KILL_WAIT_ITERATIONS = 5 +PROCESS_WAIT_INTERVAL = 1 def _alert_if_ap_left_unspent(driver, config): @@ -76,7 +90,31 @@ def _confirm_exit(driver, config): return not driver.window_exists() -def run(driver, config): +def _wait_for_process_exit(driver, iterations): + for _ in range(iterations): + if not driver.is_game_running(): + return True + driver.wait(PROCESS_WAIT_INTERVAL) + return not driver.is_game_running() + + +def _kill_if_still_running(driver, config): + if _wait_for_process_exit(driver, PROCESS_EXIT_WAIT_ITERATIONS): + return + print(f"[exit_game] {config.GAME_PROCESS_NAME} still running after the exit attempt -- killing it") + driver.kill_game() + if _wait_for_process_exit(driver, KILL_WAIT_ITERATIONS): + print(f"[exit_game] {config.GAME_PROCESS_NAME} killed.") + return + print(f"[exit_game] {config.GAME_PROCESS_NAME} ignored SIGTERM -- sending SIGKILL") + driver.kill_game(force=True) + if _wait_for_process_exit(driver, KILL_WAIT_ITERATIONS): + print(f"[exit_game] {config.GAME_PROCESS_NAME} killed.") + return + print(f"[exit_game] warning: {config.GAME_PROCESS_NAME} still running even after SIGKILL") + + +def _graceful_exit(driver, config): driver.focus_game() if not navigation.return_to_home(driver): print("[exit_game] could not confirm the true home screen -- aborting without pressing Escape") @@ -93,3 +131,10 @@ def run(driver, config): return print("[exit_game] game closed.") + + +def run(driver, config): + try: + _graceful_exit(driver, config) + finally: + _kill_if_still_running(driver, config)