diff --git a/ranch_assistant/README.md b/ranch_assistant/README.md index a8666eb..0e87a7d 100644 --- a/ranch_assistant/README.md +++ b/ranch_assistant/README.md @@ -115,13 +115,17 @@ ## 多账号与恢复会话 -1. 每个账号使用独立页签。用顶部“新增账号页签”添加账号,用页签或“打开已保存账号”切换。 +1. 每个账号使用独立页签。菜单“账号 → 新增账号页签”添加账号,用页签或“打开已保存账号”切换。 2. 每个账号首次在本版本正常登录一次;此前版本只保存在内存的 Token 不能从脱敏日志补回。 -3. 重启后在“登录”页点击“恢复选中会话”,或在顶部点击“恢复各页签的保存会话”。 +3. 重启后在“登录”页点击“恢复选中会话”,或使用菜单“账号 → 恢复各页签的保存会话”。 恢复会先读取角色并核对角色编号,成功后才显示为真实数据;不会自动开启消耗类策略。 -4. 各页签可分别开启监控和自动执行。顶部“全部开始监控”只开启已连接账号的监控, +4. 各页签可分别开启监控和自动执行。菜单“监控 → 全部开始监控”只开启已连接账号的监控, 自动执行仍由各账号的勾选决定;“全部停止”停止所有页签的监控和自动执行。 -5. 关闭一个页签会停止该账号,其他账号继续运行;保存的账号和会话仍可再次打开。 +5. 关闭页签会停止该账号,并立即保存关闭状态;重启后不再自动打开。账号记录仍可用“账号 → 打开已保存账号”重新打开。 + 退出整个程序时,会保留当时仍打开的页签;关闭所有页签后,下次启动保持空白。 +6. 彻底删除本地账号记录:右键账号页签选“移除此账号…”,或用“账号 → 移除当前账号…”。 + 已关闭的账号可用“账号 → 移除已保存账号…”选择。确认后删除所选账号的本地密码、会话、策略、地图缓存和运行记录,不会注销游戏账号。 + 若有请求正在执行,先停止调度,待当前请求结束再移除;其他账号继续运行且记录保留。移除后重启也不会恢复该账号。 账号工作区各自保存凭据、会话和日志;区服/角色各自保存策略、喂养目标和扫荡次数。 切换区服时不沿用其他角色的策略。相同账号区服不会在两个页签重复运行。 @@ -224,7 +228,7 @@ - 自定义表:`typeId, sell_money, sell_exp, time_total`(秒),可只提供部分 覆盖列;中文列名“编号、派遣金币、强化经验、孵化秒数”也支持。 - 测试:`python -m unittest discover -s ranch_assistant/tests -v`。 -- 166 项本地测试通过,覆盖登录、会话隔离、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡和每日奖励。 +- 175 项本地测试通过,覆盖登录、会话隔离、账号关闭与移除、菜单账号路由、数字框滚轮、地图缓存、请求计数、等级与体力结算、成长同步、孵蛋与补货、批量喂养、派遣、赠礼、统一策略配置、委托、扫荡和每日奖励。 新增牧场树形/平铺切换、分组数量与空位、刷新保留折叠和控件、4S保留条件、随机刷新间隔及到期独立同步的回归测试。 双账号与大量库存的界面响应继续通过测试;测试使用本地模拟数据和模拟服务,不操作真实账号库存。 - 网络写请求发生异常后不会直接重试,以免重复消耗魔物或物品。 diff --git a/ranch_assistant/account_storage.py b/ranch_assistant/account_storage.py new file mode 100644 index 0000000..4749d8b --- /dev/null +++ b/ranch_assistant/account_storage.py @@ -0,0 +1,41 @@ +"""Delete one local account workspace without touching sibling accounts.""" +from pathlib import Path +import re +import shutil + + +DEFAULT_ACCOUNT_ENTRIES = ("credentials.json", "credentials.tmp", "sessions", "roles", + "settings.json", "settings.tmp", "purchase_budget.json", "purchase_budget.tmp", + "daily_claims.json", "daily_claims.tmp", "sweep_runs.json", "sweep_runs.tmp", + "maps.json", "maps.tmp", "network_debug.jsonl", "network_debug.previous.jsonl") + + +def profile_directory(root, identifier): + root = Path(root).resolve() + if not isinstance(identifier, str) or not re.fullmatch(r"default|[a-f0-9]{32}", identifier): + raise ValueError("无效的账号工作区编号") + folder = root if identifier == "default" else root / "profiles" / identifier + if folder.resolve() != folder: + raise ValueError("账号工作区包含链接路径,已停止删除") + return folder + + +def remove_account_files(root, identifier): + """Caller holds workspace.lock; the legacy default shares the registry root.""" + folder = profile_directory(root, identifier) + if not folder.exists(): + return + if identifier == "default": + targets = [folder / name for name in DEFAULT_ACCOUNT_ENTRIES if (folder / name).exists() or (folder / name).is_symlink()] + else: + targets = [path for path in folder.iterdir() if path.name != "workspace.lock"] + # Validate the whole deletion set before removing anything. In particular, + # never recursively delete the default root, which contains other accounts. + for path in targets: + if path.resolve().parent != folder or path.is_symlink() or getattr(path, "is_junction", lambda: False)(): + raise ValueError("账号记录包含链接路径,已停止删除") + for path in targets: + if path.is_dir(): + shutil.rmtree(path) + else: + path.unlink() diff --git a/ranch_assistant/accounts_gui.py b/ranch_assistant/accounts_gui.py index e05d16a..e590afa 100644 --- a/ranch_assistant/accounts_gui.py +++ b/ranch_assistant/accounts_gui.py @@ -9,6 +9,7 @@ from PySide6 import QtCore as C, QtWidgets as W from . import gui from .api import Session from .sessions import identity +from .account_storage import profile_directory, remove_account_files class AccountsWindow(W.QMainWindow): @@ -19,6 +20,7 @@ class AccountsWindow(W.QMainWindow): self.root.mkdir(parents=True, exist_ok=True) self.index_path = self.root / "accounts.json" self.windows, self.locks, self.profiles = {}, {}, [] + self.pending_closes, self.pending_removals = set(), set() self.setWindowTitle("牧羊人之心牧场辅助 — 多账号") font = self.font() font.setPointSizeF(8.5) @@ -35,6 +37,8 @@ class AccountsWindow(W.QMainWindow): self.tabs.currentChanged.connect(self.activate_profile) self.tabs.setTabsClosable(True) self.tabs.tabCloseRequested.connect(self.close_profile) + self.tabs.tabBar().setContextMenuPolicy(C.Qt.ContextMenuPolicy.CustomContextMenu) + self.tabs.tabBar().customContextMenuRequested.connect(self.account_tab_menu) layout.addWidget(self.tabs, 1) try: self.profiles = json.loads(self.index_path.read_text(encoding="utf-8"))["profiles"] @@ -42,9 +46,9 @@ class AccountsWindow(W.QMainWindow): self.profiles = [{"id": "default", "label": "账号 1"}] self.profiles = [p for p in self.profiles if isinstance(p, dict) and re.fullmatch(r"default|[a-f0-9]{32}", str(p.get("id", "")))] for profile in list(self.profiles): - self.open_profile(profile) - if not self.profiles: - self.add_profile() + if profile.get("open", True): + self.open_profile(profile) + self.update_account_actions() gui.compact_layouts(central) def setup_menus(self): @@ -52,6 +56,10 @@ class AccountsWindow(W.QMainWindow): for text, handler in (("新增账号页签", self.add_profile), ("打开已保存账号…", self.choose_profile), ("恢复各页签的保存会话", self.resume_all)): accounts.addAction(text, handler) + self.close_account_action = accounts.addAction("关闭当前账号页签", lambda: self.close_profile(self.tabs.currentIndex())) + self.remove_account_action = accounts.addAction("移除当前账号…", self.remove_current_profile) + self.remove_saved_action = accounts.addAction("移除已保存账号…", self.choose_remove_profile) + accounts.aboutToShow.connect(self.update_account_actions) accounts.addSeparator() accounts.addAction("退出", self.close) monitoring = self.menuBar().addMenu("监控(&M)") @@ -73,6 +81,9 @@ class AccountsWindow(W.QMainWindow): window = self.tabs.currentWidget() for action in self.policy_actions: action.setEnabled(window is not None and not window.closed) + for action in (self.close_account_action, self.remove_account_action): + action.setEnabled(window is not None and not window.closed) + self.remove_saved_action.setEnabled(bool(self.profiles)) def run_account_action(self, method): window = self.tabs.currentWidget() @@ -93,10 +104,18 @@ class AccountsWindow(W.QMainWindow): def open_profile(self, profile): identifier = profile["id"] + if not any(p["id"] == identifier for p in self.profiles): + return + if identifier in self.pending_removals: + self.statusBar().showMessage("此账号正在移除,请等待当前请求完成", 5000) + return if identifier in self.windows: + if self.windows[identifier].closed: + self.statusBar().showMessage("此账号正在关闭,请稍后重新打开", 5000) + return self.tabs.setCurrentWidget(self.windows[identifier]) return - folder = self.root if identifier == "default" else self.root / "profiles" / identifier + folder = profile_directory(self.root, identifier) folder.mkdir(parents=True, exist_ok=True) lock = C.QLockFile(str(folder / "workspace.lock")) if not lock.tryLock(0): @@ -109,9 +128,11 @@ class AccountsWindow(W.QMainWindow): self.windows[identifier], self.locks[identifier] = window, lock self.tabs.addTab(window, profile.get("label", "账号")) self.tabs.setCurrentWidget(window) + profile["open"] = True + self.save_index() def add_profile(self): - profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}"} + profile = {"id": uuid.uuid4().hex, "label": f"账号 {len(self.profiles) + 1}", "open": True} self.profiles.append(profile) self.open_profile(profile) self.save_index() @@ -125,10 +146,11 @@ class AccountsWindow(W.QMainWindow): def choose_profile(self): if not self.profiles: return - labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in self.profiles] + profiles = list(self.profiles) + labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles] label, accepted = W.QInputDialog.getItem(self, "打开账号页签", "保存的账号工作区", labels, 0, False) if accepted: - self.open_profile(self.profiles[labels.index(label)]) + self.open_profile(profiles[labels.index(label)]) def rename_profile(self, identifier, label): for profile in self.profiles: @@ -180,20 +202,113 @@ class AccountsWindow(W.QMainWindow): window = self.tabs.widget(index) if window is None: return + identifier = next(k for k, value in self.windows.items() if value is window) + self.close_profile_id(identifier) + + def close_profile_id(self, identifier): + window = self.windows.get(identifier) + if window is None: + return + profile = next(p for p in self.profiles if p["id"] == identifier) + if profile.get("open", True): + profile["open"] = False + self.save_index() window.start_monitor.setChecked(False) + window.execute.setChecked(False) window.timer.stop() + window.hatch_timer.stop() + window.engine.auto = False window.closed = True window.pending_refresh = None + window.setEnabled(False) + self.update_account_actions() if window.busy: - C.QTimer.singleShot(250, lambda: self.close_profile(self.tabs.indexOf(window))) + if identifier not in self.pending_closes: + self.pending_closes.add(identifier) + C.QTimer.singleShot(100, lambda: self.finish_close_profile(identifier)) return - identifier = next(k for k, value in self.windows.items() if value is window) window.close() - self.tabs.removeTab(index) + self.tabs.removeTab(self.tabs.indexOf(window)) del self.windows[identifier] self.locks.pop(identifier).unlock() - # Workspaces and saved sessions remain on disk for the next launch. window.deleteLater() + if identifier in self.pending_removals: + self.finish_remove_profile(identifier) + + def finish_close_profile(self, identifier): + self.pending_closes.discard(identifier) + self.close_profile_id(identifier) + + def account_tab_menu(self, position): + index = self.tabs.tabBar().tabAt(position) + window = self.tabs.widget(index) + if window is None: + return + identifier = next(k for k, value in self.windows.items() if value is window) + menu = W.QMenu(self) + self.tab_context_menu = menu + menu.addAction("关闭账号页签", lambda: self.close_profile_id(identifier)) + menu.addAction("移除此账号…", lambda: self.confirm_remove_profile(identifier)) + menu.popup(self.tabs.tabBar().mapToGlobal(position)) + + def remove_current_profile(self): + window = self.tabs.currentWidget() + if window is not None: + self.confirm_remove_profile(next(k for k, value in self.windows.items() if value is window)) + + def choose_remove_profile(self): + if not self.profiles: + return + profiles = list(self.profiles) + labels = [p.get("label", "账号") + " [" + p["id"][:6] + "]" for p in profiles] + label, accepted = W.QInputDialog.getItem(self, "移除已保存账号", "选择要移除的账号(含已关闭页签)", labels, 0, False) + if accepted and label: + self.confirm_remove_profile(profiles[labels.index(label)]["id"]) + + def confirm_remove_profile(self, identifier): + profile = next((p for p in self.profiles if p["id"] == identifier), None) + if profile is None or identifier in self.pending_removals: + return + label = profile.get("label", "账号") + text = f"移除“{label}”?\n\n将删除该账号的本地密码、会话、策略、地图缓存和运行记录,无法恢复。\n此操作不会注销游戏账号。" + if W.QMessageBox.question(self, "移除账号", text, W.QMessageBox.StandardButton.Yes | W.QMessageBox.StandardButton.No, + W.QMessageBox.StandardButton.No) != W.QMessageBox.StandardButton.Yes: + return + self.pending_removals.add(identifier) + if identifier in self.windows: + self.statusBar().showMessage("正在停止该账号,当前请求完成后移除", 5000) + self.close_profile_id(identifier) + else: + self.finish_remove_profile(identifier) + + def finish_remove_profile(self, identifier): + lock = None + try: + folder = profile_directory(self.root, identifier) + if folder.exists(): + lock = C.QLockFile(str(folder / "workspace.lock")) + if not lock.tryLock(0): + raise ValueError("该账号正在其他窗口使用,请关闭后重试") + remove_account_files(self.root, identifier) + lock.unlock() + lock = None + if identifier != "default": + folder.rmdir() + old_profiles = self.profiles + self.profiles = [p for p in self.profiles if p["id"] != identifier] + try: + self.save_index() + except OSError: + self.profiles = old_profiles + raise + self.statusBar().showMessage("已移除账号及其本地记录", 5000) + except (OSError, ValueError) as error: + self.statusBar().showMessage("账号未完全移除:" + str(error), 10000) + finally: + if lock is not None: + lock.unlock() + self.pending_removals.discard(identifier) + self.update_account_actions() def closeEvent(self, event): self.stop_all() @@ -207,6 +322,9 @@ class AccountsWindow(W.QMainWindow): C.QTimer.singleShot(250, self.close) event.ignore() return + for identifier in list(self.pending_removals): + if identifier in self.windows: + self.close_profile_id(identifier) for window in self.windows.values(): window.close() for lock in self.locks.values(): diff --git a/ranch_assistant/tests/test_account_removal.py b/ranch_assistant/tests/test_account_removal.py new file mode 100644 index 0000000..0b93830 --- /dev/null +++ b/ranch_assistant/tests/test_account_removal.py @@ -0,0 +1,208 @@ +import json +import os +from pathlib import Path +import threading +import unittest +from unittest.mock import patch + +os.environ.setdefault("QT_QPA_PLATFORM", "offscreen") +from PySide6 import QtCore as C, QtWidgets as W +from PySide6.QtTest import QTest + +from ranch_assistant.account_storage import profile_directory, remove_account_files +from ranch_assistant.accounts_gui import AccountsWindow +from ranch_assistant.tests.test_core import workspace_temp + + +class RemovalTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.app = W.QApplication.instance() or W.QApplication([]) + + def wait(self, predicate): + for _ in range(1000): + self.app.processEvents() + QTest.qWait(2) + if predicate(): + return + self.fail("Account shutdown did not finish") + + def idle(self, hub): + for window in hub.windows.values(): + window.timer.stop() + self.wait(lambda: all(not w.busy and w.engine.snapshot is not None for w in hub.windows.values())) + + def remove(self, hub, identifier): + with patch.object(W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.Yes): + hub.confirm_remove_profile(identifier) + + def test_close_all_remains_closed_and_manual_reopen_is_persisted(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + self.idle(hub) + hub.close_profile(0) + hub.close() + hub = AccountsWindow(folder) + try: + self.assertEqual(hub.tabs.count(), 0) + self.assertEqual(len(hub.profiles), 1) + hub.open_profile(hub.profiles[0]) + self.idle(hub) + hub.close() + hub = AccountsWindow(folder) + self.idle(hub) + self.assertEqual(hub.tabs.count(), 1) + finally: + hub.close() + + def test_remove_closed_account_deletes_only_its_workspace_and_stays_removed(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + hub.add_profile() + self.idle(hub) + identifier = hub.profiles[-1]["id"] + target = profile_directory(folder, identifier) + hub.close_profile(hub.tabs.count() - 1) + (target / "sessions").mkdir() + (target / "sessions" / "test.json").write_text("synthetic session", encoding="utf-8") + protected = folder / "credentials.json" + protected.write_text("{}", encoding="utf-8") + try: + self.remove(hub, identifier) + self.assertFalse(target.exists()) + self.assertTrue(protected.exists()) + self.assertIn("default", hub.windows) + self.assertFalse(any(p["id"] == identifier for p in hub.profiles)) + hub.close() + hub = AccountsWindow(folder) + self.idle(hub) + self.assertFalse(any(p["id"] == identifier for p in hub.profiles)) + self.assertNotIn(identifier, hub.windows) + finally: + hub.close() + + def test_remove_default_preserves_other_accounts_registry_and_shared_files(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + hub.add_profile() + self.idle(hub) + other = hub.profiles[-1]["id"] + sentinel = profile_directory(folder, other) / "keep.txt" + sentinel.write_text("another account", encoding="utf-8") + (folder / "sessions").mkdir() + (folder / "sessions" / "old.json").write_text("synthetic", encoding="utf-8") + (folder / "roles" / "role").mkdir(parents=True) + (folder / "roles" / "role" / "maps.json").write_text("{}", encoding="utf-8") + shared = folder / "shared-note.txt" + shared.write_text("keep", encoding="utf-8") + try: + self.remove(hub, "default") + for name in ("credentials.json", "sessions", "roles", "settings.json"): + self.assertFalse((folder / name).exists()) + self.assertTrue(sentinel.exists()) + self.assertTrue(shared.exists()) + self.assertTrue(hub.index_path.exists()) + self.assertEqual([p["id"] for p in hub.profiles], [other]) + hub.close() + hub = AccountsWindow(folder) + self.idle(hub) + self.assertNotIn("default", hub.windows) + self.assertIn(other, hub.windows) + finally: + hub.close() + + def test_cancel_removal_keeps_live_account_untouched(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + self.idle(hub) + try: + with patch.object(W.QMessageBox, "question", return_value=W.QMessageBox.StandardButton.No): + hub.confirm_remove_profile("default") + self.assertIn("default", hub.windows) + self.assertFalse(hub.windows["default"].closed) + self.assertTrue(hub.profiles[0]["open"]) + finally: + hub.close() + + def test_busy_account_is_removed_only_after_worker_finishes_without_recreating_records(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + self.idle(hub) + window = hub.windows["default"] + release, started = threading.Event(), threading.Event() + def work(): + started.set() + release.wait(3) + return "synthetic completed job" + try: + window.submit("test", work) + self.wait(started.is_set) + self.remove(hub, "default") + self.assertIn("default", hub.windows) + self.assertIn("default", hub.pending_removals) + self.assertFalse(window.execute.isChecked()) + self.assertFalse(window.monitoring) + release.set() + self.wait(lambda: not hub.windows and not hub.pending_removals) + QTest.qWait(400) + self.assertFalse((folder / "settings.json").exists()) + self.assertFalse((folder / "credentials.json").exists()) + self.assertEqual(json.loads(hub.index_path.read_text(encoding="utf-8"))["profiles"], []) + hub.close() + hub = AccountsWindow(folder) + self.assertEqual(hub.tabs.count(), 0) + self.assertEqual(hub.profiles, []) + finally: + release.set() + self.idle(hub) + hub.close() + + def test_external_lock_blocks_removal_and_keeps_account_in_registry(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + hub.add_profile() + self.idle(hub) + identifier = hub.profiles[-1]["id"] + hub.close_profile(hub.tabs.count() - 1) + target = profile_directory(folder, identifier) + lock = C.QLockFile(str(target / "workspace.lock")) + self.assertTrue(lock.tryLock(0)) + try: + self.remove(hub, identifier) + self.assertTrue(target.exists()) + self.assertTrue(any(p["id"] == identifier for p in hub.profiles)) + self.assertIn("其他窗口", hub.statusBar().currentMessage()) + finally: + lock.unlock() + hub.close() + + def test_failed_file_removal_keeps_registry_for_retry(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + self.idle(hub) + try: + with patch("ranch_assistant.accounts_gui.remove_account_files", side_effect=OSError("synthetic failure")): + self.remove(hub, "default") + self.assertTrue(any(p["id"] == "default" for p in hub.profiles)) + self.assertIn("未完全移除", hub.statusBar().currentMessage()) + finally: + hub.close() + + def test_profile_deletion_rejects_invalid_identifier_and_directory_links(self): + with workspace_temp() as folder, workspace_temp() as outside: + for identifier in ("..", "profiles", "../outside", "", None): + with self.assertRaises(ValueError): + profile_directory(folder, identifier) + (folder / "profiles").mkdir() + target = folder / "profiles" / ("a" * 32) + try: + target.symlink_to(outside, target_is_directory=True) + except OSError: + return # Some Windows installations do not permit symlinks. + try: + (outside / "keep.txt").write_text("keep", encoding="utf-8") + with self.assertRaises(ValueError): + remove_account_files(folder, "a" * 32) + self.assertTrue((outside / "keep.txt").exists()) + finally: + target.unlink() diff --git a/ranch_assistant/tests/test_accounts.py b/ranch_assistant/tests/test_accounts.py index cd85b58..d368190 100644 --- a/ranch_assistant/tests/test_accounts.py +++ b/ranch_assistant/tests/test_accounts.py @@ -208,6 +208,31 @@ class AccountGuiTests(unittest.TestCase): finally: hub.close() + def test_closed_tab_stays_closed_after_restart_and_can_be_opened_manually(self): + with workspace_temp() as folder: + hub = AccountsWindow(folder) + hub.add_profile() + for window in hub.windows.values(): + window.timer.stop() + self.wait(list(hub.windows.values())) + closed = hub.profiles[-1] + hub.close_profile(hub.tabs.count() - 1) + hub.close() + restarted = AccountsWindow(folder) + for window in restarted.windows.values(): + window.timer.stop() + try: + self.wait(list(restarted.windows.values())) + self.assertNotIn(closed["id"], restarted.windows) + self.assertTrue(any(p["id"] == closed["id"] for p in restarted.profiles)) + restarted.open_profile(next(p for p in restarted.profiles if p["id"] == closed["id"])) + for window in restarted.windows.values(): + window.timer.stop() + self.wait(list(restarted.windows.values())) + self.assertIn(closed["id"], restarted.windows) + finally: + restarted.close() + def test_failed_resume_saves_counters_before_response_and_keeps_execution_off(self): with workspace_temp() as folder: window = gui.Window(folder)