from __future__ import annotations import os from pathlib import Path import subprocess import sys import time from dx_productivity.trial_task_center.store import TaskStore _SOURCE = Path(__file__).resolve().parents[2] / 'src' _APP = 'dx_productivity.trial_task_center.application' def _wait_for(predicate, description): deadline = time.monotonic() + 90 while time.monotonic() < deadline: if predicate(): return time.sleep(.05) raise AssertionError(description) def test_concurrent_gui_launches_activate_one_owner_and_recover_after_kill(tmp_path): root = tmp_path / 'Shared Root' independent = tmp_path / 'Independent Root' root.mkdir() store = TaskStore(root / 'task-center.db') try: task = store.create_task('Existing task') finally: store.close() processes = [] env = os.environ | {'PYTHONPATH': str(_SOURCE), 'QT_QPA_PLATFORM': 'offscreen'} def launch(path, *arguments): process = subprocess.Popen( [sys.executable, '-m', _APP, '--data-root', str(path), *arguments], env=env, ) processes.append(process) return process def log(path): logfile = path / 'logs/application.log' return logfile.read_text(encoding='utf-8') if logfile.exists() else '' try: alias = root.with_name(root.name.upper()) if os.name == 'nt' else root contenders = [launch(root), launch(alias), launch(root), launch(alias)] _wait_for(lambda: sum(p.poll() is not None for p in contenders) >= 3, 'Three concurrent launches should exit after handing off to one GUI') owners = [p for p in contenders if p.poll() is None] assert len(owners) == 1 assert [p.returncode for p in contenders if p not in owners] == [0, 0, 0] _wait_for(lambda: log(root).count('instance_conflict') == 3, 'The GUI should handle and log all three activation requests') assert log(root).count('application_start ') == 1 other = launch(independent) _wait_for(lambda: 'application_start ' in log(independent), 'Different root should start independently') assert other.poll() is None and owners[0].poll() is None helper = launch(root, '--native-helper') assert helper.wait(timeout=60) == 2 # The helper validates its own required snapshot. assert log(root).count('instance_conflict') == 3 owners[0].kill() owners[0].wait(timeout=10) assert launch(root, '--smoke-test').wait(timeout=60) == 0 assert log(root).count('application_start ') == 2 assert log(root).count('application_clean_shutdown') == 1 assert other.poll() is None store = TaskStore(root / 'task-center.db') try: assert [record.task_id for record in store.list_tasks()] == [task.task_id] finally: store.close() finally: for process in processes: if process.poll() is None: process.kill() process.wait(timeout=10)