lycheedev 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,8 @@ Subcommand groups (design section 9):
7
7
  - ``profile`` bind one WoW client installation, addon dir and SV path
8
8
  - ``sv`` find account-level SavedVariables candidates; read a Ticket
9
9
  - ``capture`` poll the game window and decode the completion notice QR
10
- - ``send`` deliver one slash command through focus/clipboard/Enter
10
+ - ``send`` deliver one slash command through the selected input transport
11
+ - ``reload`` reload, recognize the nonce-bound ready QR locally, then clear it
11
12
  - ``run`` task flow: run command, notice, output reload, SavedVariables
12
13
  read and artifact save (the input-side reload that loads the
13
14
  new task block is a separate, operator-visible step)
@@ -42,6 +43,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
42
43
 
43
44
  from automation import registry, saved_variables as svlib # noqa: E402
44
45
  from automation import session as session_mod # noqa: E402
46
+ from automation import reload as reload_mod # noqa: E402
45
47
  from automation.registry import RegistryError # noqa: E402
46
48
  from automation.saved_variables import SavedVariablesError # noqa: E402
47
49
 
@@ -386,8 +388,8 @@ def _window_module():
386
388
  def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
387
389
  """Log the intent, then send exactly one command (design section 6.2)."""
388
390
 
389
- mode = getattr(args, "mode", "foreground")
390
- session.log_event("command_sent", hwnd=args.hwnd, text=text, mode=mode)
391
+ mode = getattr(args, "mode", "messages")
392
+ session.log_event("command_prepared", hwnd=args.hwnd, text=text, mode=mode)
391
393
  try:
392
394
  windows.send_command(args.hwnd, text, pid=getattr(args, "pid", None),
393
395
  exe_path=getattr(args, "exe_path", None),
@@ -396,6 +398,7 @@ def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
396
398
  session.log_event("command_failed", hwnd=args.hwnd, text=text,
397
399
  mode=mode, reason=str(error))
398
400
  raise CliError(f"command delivery failed: {error}", code=EXIT_INPUT)
401
+ session.log_event("command_submitted", hwnd=args.hwnd, text=text, mode=mode)
399
402
 
400
403
 
401
404
  def cmd_send(args) -> int:
@@ -410,11 +413,27 @@ def cmd_send(args) -> int:
410
413
  f"reload for {args.ticket} was already requested; check the saved "
411
414
  "variables file before repeating it")
412
415
  _deliver(session, windows, args, args.text)
413
- print("sent")
416
+ print("submitted; game execution is not yet confirmed")
414
417
  return 0
415
418
 
416
419
 
417
- def ack_command(ticket: str, outcome: str) -> str:
420
+ def reload_ready(session, windows, args, *, ticket=None, nonce=None, resume=False):
421
+ try:
422
+ return reload_mod.execute(windows, session, args, _deliver, nonce or new_request_id(),
423
+ ticket=ticket, resume=resume)
424
+ except reload_mod.ReloadError as error:
425
+ raise CliError(str(error), code=EXIT_NOTICE_TIMEOUT) from error
426
+
427
+
428
+ def cmd_reload(args) -> int:
429
+ session = session_mod.Session(data_dir=args.data_dir, installation=args.installation)
430
+ result = reload_ready(session, _window_module(), args, nonce=args.resume or args.nonce,
431
+ resume=bool(args.resume))
432
+ print(json.dumps(result, sort_keys=True))
433
+ return 0
434
+
435
+
436
+ def ack_command(ticket: str, outcome: str, nonce: str | None = None) -> str:
418
437
  """Build the in-game command that reports a ticket's read outcome.
419
438
 
420
439
  The plugin cannot see whether the host read a result, so the host says so
@@ -423,7 +442,11 @@ def ack_command(ticket: str, outcome: str) -> str:
423
442
 
424
443
  if outcome not in ("received", "failed"):
425
444
  raise CliError("ack status must be 'received' or 'failed'")
426
- return f"/dev auto ack {ticket} {outcome}"
445
+ if not svlib.TICKET_PATTERN.fullmatch(ticket) or len(ticket) > 64:
446
+ raise CliError("invalid acknowledgement ticket")
447
+ if nonce is not None and not registry.REQUEST_ID_PATTERN.fullmatch(nonce):
448
+ raise CliError("invalid acknowledgement nonce")
449
+ return f"/dev auto ack {ticket} {outcome}" + (f" {nonce}" if nonce else "")
427
450
 
428
451
 
429
452
  def cmd_ack(args) -> int:
@@ -432,13 +455,55 @@ def cmd_ack(args) -> int:
432
455
  windows = _window_module()
433
456
  session = session_mod.Session(data_dir=args.data_dir,
434
457
  installation=args.installation)
435
- text = ack_command(args.ticket, args.status)
458
+ nonce = new_request_id()
459
+ text = ack_command(args.ticket, args.status, nonce)
436
460
  _deliver(session, windows, args, text)
437
- session.log_event("ticket_ack_sent", ticket=args.ticket, status=args.status)
438
- print(f"ack sent: {args.ticket} {args.status}")
461
+ session.log_event("ticket_ack_submitted", ticket=args.ticket, status=args.status)
462
+ notice = poll_notice(windows, session, args, expected_task="ack", expected_run=nonce,
463
+ expected_ticket=args.ticket, expected_status=args.status)
464
+ if notice is None:
465
+ session.log_event("ticket_ack_unresolved", ticket=args.ticket, nonce=nonce)
466
+ raise CliError("ack was submitted but no matching game receipt arrived",
467
+ code=EXIT_NOTICE_TIMEOUT)
468
+ session.log_event("ticket_ack_confirmed", ticket=args.ticket, status=args.status, nonce=nonce)
469
+ _deliver(session, windows, args, f"/dev auto unidentify {nonce}")
470
+ if not wait_ack_cleared(windows, args, nonce):
471
+ session.log_event("ticket_ack_cleanup_unresolved", ticket=args.ticket, nonce=nonce)
472
+ raise CliError("ack confirmed, but its marker cleanup was not observed",
473
+ code=EXIT_NOTICE_TIMEOUT)
474
+ session.log_event("ticket_ack_cleared", ticket=args.ticket, nonce=nonce)
475
+ print(f"ack confirmed: {args.ticket} {args.status}")
439
476
  return 0
440
477
 
441
478
 
479
+ def wait_ack_cleared(windows, args, nonce: str) -> bool:
480
+ """Observe removal of this receipt; never dismiss a newer marker by nonce."""
481
+ interval = getattr(args, "interval", None) or DEFAULT_INTERVAL
482
+ deadline = time.monotonic() + min(args.timeout, 5.0)
483
+ absent = 0
484
+ with windows.open_notice_capture(args.hwnd, pid=getattr(args, "pid", None),
485
+ exe_path=getattr(args, "exe_path", None),
486
+ interval=interval) as capture:
487
+ while time.monotonic() < deadline:
488
+ if capture.window_closed:
489
+ return False
490
+ roi = capture.latest_roi()
491
+ if roi is not None:
492
+ visible = False
493
+ for payload in windows.decode_qr(roi):
494
+ try:
495
+ marker = json.loads(payload)
496
+ except (ValueError, TypeError):
497
+ continue
498
+ if isinstance(marker, dict) and marker.get("task") == "ack" and marker.get("run") == nonce:
499
+ visible = True
500
+ absent = 0 if visible else absent + 1
501
+ if absent >= 2:
502
+ return True
503
+ time.sleep(interval)
504
+ return False
505
+
506
+
442
507
  def validate_notice(json_text: str) -> dict:
443
508
  if not isinstance(json_text, str) or not json_text:
444
509
  raise SavedVariablesError("notice payload is empty")
@@ -488,7 +553,9 @@ def notice_identity_problems(notice: dict, *, expected_task: str | None,
488
553
 
489
554
  def poll_notice(windows, session: session_mod.Session, args, *,
490
555
  expected_task: str | None = None,
491
- expected_run: str | None = None) -> dict | None:
556
+ expected_run: str | None = None,
557
+ expected_ticket: str | None = None,
558
+ expected_status: str | None = None) -> dict | None:
492
559
  """Keep one WGC session open and poll until a matching notice or the deadline.
493
560
 
494
561
  The session outlives a single frame because a task can run far longer than
@@ -516,6 +583,10 @@ def poll_notice(windows, session: session_mod.Session, args, *,
516
583
  problems = notice_identity_problems(
517
584
  notice, expected_task=expected_task,
518
585
  expected_run=expected_run)
586
+ if expected_ticket is not None and notice["ticket"] != expected_ticket:
587
+ problems.append("receipt ticket mismatch")
588
+ if expected_status is not None and notice.get("status") != expected_status:
589
+ problems.append("receipt status mismatch")
519
590
  if problems:
520
591
  session.log_event("notice_identity_mismatch",
521
592
  ticket=notice["ticket"],
@@ -625,7 +696,7 @@ def _notice_to_sv(session: session_mod.Session, windows, notice: dict, args,
625
696
  f"reload for {ticket} was already requested; check the saved "
626
697
  "variables file before repeating the reload")
627
698
  baseline = session.file_snapshot(args.sv)
628
- _deliver(session, windows, args, "/reload")
699
+ reload_ready(session, windows, args, ticket=ticket)
629
700
  if not session.wait_for_saved_variables(args.sv, timeout=args.timeout,
630
701
  baseline=baseline):
631
702
  session.log_event("sv_write_timeout", ticket=ticket)
@@ -668,6 +739,11 @@ def cmd_run(args) -> int:
668
739
  expected_request_id = args.request_id or definition["requestId"]
669
740
  revision = args.revision or definition["revision"]
670
741
 
742
+ if not registry.TASK_ID_PATTERN.fullmatch(args.task):
743
+ raise CliError("invalid task id")
744
+ if not expected_request_id or not registry.REQUEST_ID_PATTERN.fullmatch(expected_request_id):
745
+ raise CliError("run requires an installed task block or an explicit --request-id")
746
+
671
747
  session.log_event("run_started", task=args.task,
672
748
  requestId=expected_request_id, revision=revision)
673
749
  _deliver(session, windows, args, f"/dev auto run {args.task}")
@@ -689,8 +765,11 @@ def cmd_bugs(args) -> int:
689
765
  raise CliError("--count must be an integer between 1 and 100")
690
766
  session = session_mod.Session(data_dir=args.data_dir,
691
767
  installation=args.installation)
692
- session.log_event("bugs_started", count=args.count)
693
- _deliver(session, windows, args, f"/dev auto bug {args.count}")
768
+ args.request_id = args.request_id or new_request_id()
769
+ if not registry.REQUEST_ID_PATTERN.fullmatch(args.request_id):
770
+ raise CliError("invalid bug request id")
771
+ session.log_event("bugs_started", count=args.count, requestId=args.request_id)
772
+ _deliver(session, windows, args, f"/dev auto bug {args.count} {args.request_id}")
694
773
  notice = poll_notice(windows, session, args, expected_task=BUG_TASK_ID,
695
774
  expected_run=args.request_id)
696
775
  if notice is None:
@@ -744,7 +823,15 @@ def cmd_recover(args) -> int:
744
823
  for ticket in pending:
745
824
  print(f"UNRESOLVED: reload requested for {ticket} but not received yet; "
746
825
  "inspect the saved variables file manually before any retry")
747
- if not pending:
826
+ requests = {(e.get("installation"), e.get("nonce")) for e in
827
+ session.read_events("reload_handshake_requested", installation=scope)}
828
+ cleared = {(e.get("installation"), e.get("nonce")) for e in
829
+ session.read_events("reload_ready_cleared", installation=scope)}
830
+ unresolved = requests - cleared
831
+ for installation, nonce in sorted(unresolved):
832
+ print(f"UNRESOLVED: installation {installation!r}, reload handshake {nonce}; "
833
+ f"use reload --resume {nonce} with its original window binding; do not reload again")
834
+ if not pending and not unresolved:
748
835
  print(f"no unresolved reload requests in installation "
749
836
  f"{session.installation!r}")
750
837
  return 0
@@ -819,11 +906,9 @@ def build_parser() -> argparse.ArgumentParser:
819
906
  window.add_argument("--pid", type=int, help="expected process id")
820
907
  window.add_argument("--exe-path", help="expected executable path")
821
908
  window.add_argument(
822
- "--mode", choices=("foreground", "messages"), default="foreground",
823
- help="input strategy: 'foreground' focuses the window and uses "
824
- "SendInput; 'messages' posts keys straight to the window and needs "
825
- "no foreground but requires the chat box to be open already "
826
- "(default: foreground)")
909
+ "--mode", choices=("foreground", "messages"), default="messages",
910
+ help="foreground uses clipboard readback; messages posts input to the "
911
+ "target HWND without changing foreground (execution needs a receipt)")
827
912
 
828
913
  polling = argparse.ArgumentParser(add_help=False)
829
914
  polling.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
@@ -841,7 +926,14 @@ def build_parser() -> argparse.ArgumentParser:
841
926
  send.add_argument("--ticket", help="ticket used to dedup a '/reload' command")
842
927
  send.set_defaults(func=cmd_send)
843
928
 
844
- ack = sub.add_parser("ack", parents=[window],
929
+ reload_parser = sub.add_parser("reload", parents=[window, polling],
930
+ help="reload and locally confirm the nonce-bound ready marker")
931
+ identity = reload_parser.add_mutually_exclusive_group()
932
+ identity.add_argument("--nonce", help="unique reload identity (default: generated)")
933
+ identity.add_argument("--resume", help="wait/clean up this existing nonce without another reload")
934
+ reload_parser.set_defaults(func=cmd_reload)
935
+
936
+ ack = sub.add_parser("ack", parents=[window, polling],
845
937
  help="report a ticket's read outcome to the running game")
846
938
  ack.add_argument("--ticket", required=True, help="exact ticket that was read")
847
939
  ack.add_argument("--status", required=True, choices=("received", "failed"),
@@ -478,11 +478,7 @@ else:
478
478
  cli._window_module = real_window_module
479
479
  print("CLI window/input exit codes (4 for window/dependency, 1 otherwise) OK")
480
480
 
481
- # --- command delivery order: open chat, paste, submit ------------------------
482
- #
483
- # Regression: the sequence used to paste BEFORE opening the chat box, so the
484
- # client opened an empty chat and no command ran. Reference behaviour is
485
- # Return -> Ctrl+V -> Return.
481
+ # --- input transaction regressions (no live game access) ----------------------
486
482
 
487
483
  try:
488
484
  from automation import windows as winmod
@@ -492,69 +488,10 @@ except Exception: # pragma: no cover - non-Windows hosts
492
488
  if winmod is None: # pragma: no cover - non-Windows hosts
493
489
  print("command delivery order (skipped: no windows module)")
494
490
  else:
495
- class _RecordingClipboard:
496
- def __init__(self):
497
- self.value = None
498
- self.writes = []
499
-
500
- def read_text(self):
501
- return self.value
502
-
503
- def copy_text(self, text):
504
- self.value = text
505
- self.writes.append(text)
506
-
507
- def clear(self):
508
- self.value = None
509
-
510
- pressed = []
511
- real_send_key = winmod._send_key
512
- real_set_fg = winmod.user32.SetForegroundWindow
513
- real_is_foreground = winmod.is_foreground
514
- real_confirm = winmod.confirm_window
515
- real_sleep = winmod.time.sleep
516
- try:
517
- def fake_send_key(vk, *, ctrl=False):
518
- pressed.append(("ctrl+v" if ctrl else "key") + ":%#x" % vk)
519
-
520
- winmod._send_key = fake_send_key
521
- winmod.user32.SetForegroundWindow = lambda _hwnd: 1
522
- winmod.is_foreground = lambda _hwnd: True
523
- winmod.confirm_window = lambda *a, **k: None
524
- winmod.time.sleep = lambda _seconds: None
525
-
526
- delivery_clipboard = _RecordingClipboard()
527
- winmod.send_command(1, "/reload", clipboard=delivery_clipboard)
528
- expected = ["key:0xd", "ctrl+v:0x56", "key:0xd"]
529
- assert pressed == expected, f"delivery order was {pressed}, expected {expected}"
530
- assert delivery_clipboard.writes[0] == "/reload", delivery_clipboard.writes
531
- finally:
532
- winmod._send_key = real_send_key
533
- winmod.user32.SetForegroundWindow = real_set_fg
534
- winmod.is_foreground = real_is_foreground
535
- winmod.confirm_window = real_confirm
536
- winmod.time.sleep = real_sleep
537
- print("command delivery order (Return, Ctrl+V, Return) OK")
538
-
539
- posted = []
540
- real_post = winmod.user32.PostMessageW
541
- real_sleep_messages = winmod.time.sleep
542
- try:
543
- winmod.user32.PostMessageW = (
544
- lambda hwnd, msg, wparam, lparam: posted.append((msg, wparam)) or 1)
545
- winmod.time.sleep = lambda _seconds: None
546
- winmod.send_command_messages(1, "/reload")
547
- finally:
548
- winmod.user32.PostMessageW = real_post
549
- winmod.time.sleep = real_sleep_messages
550
-
551
- chars = "".join(chr(w) for m, w in posted if m == winmod.WM_CHAR)
552
- assert chars == "/reload", chars
553
- down = [w for m, w in posted if m == winmod.WM_KEYDOWN]
554
- assert down == [winmod.VK_RETURN], down
555
- assert all(m in (winmod.WM_CHAR, winmod.WM_KEYDOWN, winmod.WM_KEYUP)
556
- for m, _w in posted), posted
557
- print("command delivery via posted messages (no foreground) OK")
491
+ import unittest
492
+ from test_input_safety import InputSafetyTests
493
+ result = unittest.TextTestRunner().run(unittest.defaultTestLoader.loadTestsFromTestCase(InputSafetyTests))
494
+ assert result.wasSuccessful(), "input transaction regressions failed"
558
495
 
559
496
  # The notice is drawn at the top-left corner of the game window, so the scan
560
497
  # area must cover that corner. A ROI that drifts back to another corner makes
@@ -724,6 +661,20 @@ timeout_events = [r["event"] for r in timeout_session.read_events()]
724
661
  assert "notice_seen" not in timeout_events
725
662
  print("poll_notice: stale notice rejected, fresh accepted, timeout bounded OK")
726
663
 
664
+ # Acknowledgement receipts must match Ticket, nonce, task and outcome together.
665
+ ack_good = notice_json(task="ack", run="ack-nonce", status="received")
666
+ ack_stale = notice_json(task="ack", run="old-nonce", status="received")
667
+ ack_wrong_ticket = notice_json(task="ack", run="ack-nonce", ticket="LYCHEE-other", status="received")
668
+ ack_wrong_status = notice_json(task="ack", run="ack-nonce", status="failed")
669
+ ack_resolved = cli.poll_notice(
670
+ _FakeWindows([[ack_stale, ack_wrong_ticket, ack_wrong_status], [ack_good]]),
671
+ fake_session, poll_args, expected_task="ack", expected_run="ack-nonce",
672
+ expected_ticket=ticket, expected_status="received")
673
+ assert ack_resolved and ack_resolved["status"] == "received"
674
+ for bad_ticket in ("LYCHEE-1\n/reload", "LYCHEE-1 received", "bad"):
675
+ expect_failure("ack ticket validation", lambda t=bad_ticket: cli.ack_command(t, "received"), cli.CliError)
676
+ print("ack receipt exact identity and command validation OK")
677
+
727
678
  # --- registry: schema/kind rejection, hash, region preservation ---------------
728
679
 
729
680
  def registry_text(*blocks):
@@ -979,14 +930,14 @@ try:
979
930
  scoped = [r["event"] for r in
980
931
  ses.Session(data_dir=send_data, installation="send-scope").read_events()]
981
932
  assert scoped.count("reload_requested") == 1, scoped
982
- assert scoped.count("command_sent") == 1, scoped
933
+ assert scoped.count("command_submitted") == 1, scoped
983
934
  every = ses.Session(data_dir=send_data).read_events(
984
935
  installation=ses.ALL_INSTALLATIONS)
985
- assert [r["event"] for r in every].count("command_sent") == 2
936
+ assert [r["event"] for r in every].count("command_submitted") == 2
986
937
  assert _FakeSendWindows.sent == [(1, "/reload"), (1, "/dev auto status x")]
987
- assert _FakeSendWindows.modes == ["foreground", "foreground"], _FakeSendWindows.modes
938
+ assert _FakeSendWindows.modes == ["messages", "messages"], _FakeSendWindows.modes
988
939
  assert cli.main(["--data-dir", send_data, "send", "--hwnd", "0x1",
989
- "--mode", "messages", "--text", "hi"]) == 0
940
+ "--mode", "messages", "--text", "/dev"]) == 0
990
941
  assert _FakeSendWindows.modes[-1] == "messages", _FakeSendWindows.modes
991
942
 
992
943
  cli._window_module = lambda: _FailingSendWindows
@@ -999,6 +950,46 @@ finally:
999
950
  cli._window_module = original_window_module
1000
951
  print("send host log + reload dedup + input failure exit OK")
1001
952
 
953
+ # Drive the actual CLI acknowledgement flow: submission alone is unresolved.
954
+ from unittest.mock import patch
955
+ ack_data = os.path.join(tmp, "ack-flow")
956
+ ack_args = ["--data-dir", ack_data, "ack", "--hwnd", "1", "--ticket", "LYCHEE-1",
957
+ "--status", "received", "--timeout", "0.1"]
958
+ with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
959
+ patch.object(cli, "poll_notice", return_value=None):
960
+ assert cli.main(ack_args) == 5
961
+ ack_events = [r["event"] for r in ses.Session(data_dir=ack_data).read_events()]
962
+ assert "ticket_ack_unresolved" in ack_events and "ticket_ack_confirmed" not in ack_events
963
+ with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
964
+ patch.object(cli, "poll_notice", return_value={"status": "received"}) as poll, \
965
+ patch.object(cli, "wait_ack_cleared", return_value=True):
966
+ assert cli.main(ack_args) == 0
967
+ sent_nonce = _FakeSendWindows.sent[-2][1].split()[-1]
968
+ assert _FakeSendWindows.sent[-1][1] == f"/dev auto unidentify {sent_nonce}"
969
+ assert poll.call_args.kwargs["expected_run"] == sent_nonce
970
+ assert poll.call_args.kwargs["expected_ticket"] == "LYCHEE-1"
971
+ assert poll.call_args.kwargs["expected_status"] == "received"
972
+ with patch.object(cli, "_window_module", return_value=_FakeSendWindows), \
973
+ patch.object(cli, "poll_notice", return_value={}) as poll, \
974
+ patch.object(cli, "_notice_to_sv", return_value=0):
975
+ assert cli.main(["--data-dir", ack_data, "bugs", "--hwnd", "1", "--count", "2",
976
+ "--sv", "unused", "--request-id", "bug-proof-1"]) == 0
977
+ assert _FakeSendWindows.sent[-1][1] == "/dev auto bug 2 bug-proof-1"
978
+ assert poll.call_args.kwargs["expected_run"] == "bug-proof-1"
979
+ # Cleanup requires observed frames, and a still-visible receipt must time out.
980
+ cleanup_args = argparse.Namespace(hwnd=1, pid=None, exe_path=None, timeout=0.03, interval=0.001)
981
+ assert cli.wait_ack_cleared(_FakeWindows([[], []]), cleanup_args, "cleanup-nonce")
982
+ visible_receipt = notice_json(task="ack", run="cleanup-nonce", status="received")
983
+ assert not cli.wait_ack_cleared(_FakeWindows([[visible_receipt], [visible_receipt]]),
984
+ cleanup_args, "cleanup-nonce")
985
+ class _NoFrameCapture(_FakeCapture):
986
+ def latest_roi(self): return None
987
+ no_frames = _FakeWindows([])
988
+ no_frames.open_notice_capture = lambda *a, **k: _NoFrameCapture()
989
+ assert not cli.wait_ack_cleared(no_frames, cleanup_args, "cleanup-nonce")
990
+ print("ack CLI unresolved/confirmed lifecycle and bug request delivery OK")
991
+
992
+
1002
993
  # --- packaging metadata -------------------------------------------------------
1003
994
 
1004
995
  requirements = os.path.join(HERE, "requirements.txt")
@@ -0,0 +1,132 @@
1
+ """Offline input regression: all window, keyboard and clipboard calls are mocked."""
2
+ import unittest
3
+ from unittest.mock import patch
4
+ from automation import windows
5
+
6
+ class Clipboard:
7
+ def __init__(self): self.text = "previous clipboard"
8
+ def read_text(self): return self.text
9
+ def copy_text(self, value): self.text = value
10
+ def clear(self): self.text = None
11
+
12
+ class InputSafetyTests(unittest.TestCase):
13
+ def test_windows_path_aliases_match(self):
14
+ identity = windows.WindowIdentity(1, 2, r"D:\Game\Wow.exe", "test")
15
+ self.assertTrue(identity.matches(pid=2, exe_path="d:/game/WOW.EXE"))
16
+ self.assertFalse(identity.matches(pid=3))
17
+
18
+ def exercise(self, draft=None, *, paste=True, copy=True, lose_focus=False, mode="foreground", escape=True):
19
+ clipboard = Clipboard()
20
+ state = {"open": draft is not None, "text": draft or "", "selected": False,
21
+ "foreground": True, "public": [], "commands": []}
22
+ def key(vk, ctrl=False):
23
+ if vk == 0x1b:
24
+ if escape: state.update(open=False, text="", selected=False)
25
+ elif vk == 0xBF:
26
+ state["open"] = True
27
+ state["text"] += "/"
28
+ elif vk == windows.VK_RETURN:
29
+ if state["open"]:
30
+ text = state["text"]
31
+ if text: state["commands" if text.startswith("/") else "public"].append(text)
32
+ state.update(open=False, text="", selected=False)
33
+ else: state["open"] = True
34
+ elif ctrl and vk == 0x41: state["selected"] = True
35
+ elif ctrl and vk == windows.VK_V and state["open"]:
36
+ if paste:
37
+ state["text"] = ("" if state["selected"] else state["text"]) + clipboard.text
38
+ state["selected"] = False
39
+ if lose_focus: state["foreground"] = False
40
+ elif ctrl and vk == 0x43 and state["open"] and state["selected"] and copy:
41
+ clipboard.text = state["text"]
42
+ error = None
43
+ with patch.object(windows, "confirm_window", return_value=windows.WindowIdentity(1, 2, "D:/Game/Wow.exe", "test")), \
44
+ patch.object(windows, "focus_window"), \
45
+ patch.object(windows, "is_foreground", side_effect=lambda hwnd: state["foreground"]), \
46
+ patch.object(windows, "_send_key", side_effect=key), patch.object(windows.time, "sleep"):
47
+ try:
48
+ windows.send_command(1, "/reload", clipboard=clipboard, mode=mode)
49
+ except windows.InputError as exc: error = exc
50
+ self.assertEqual(state["public"], [], "automation submitted a public chat draft")
51
+ if paste:
52
+ self.assertEqual(clipboard.text, "previous clipboard")
53
+ return state, error
54
+
55
+ def test_existing_draft_is_cancelled(self):
56
+ state, error = self.exercise("unfinished public chat ")
57
+ self.assertIsNone(error)
58
+ self.assertEqual(state["commands"], ["/reload"])
59
+
60
+ def test_ignored_escape_cannot_submit_draft(self):
61
+ state, error = self.exercise("public draft", escape=False)
62
+ self.assertIsNone(error)
63
+ self.assertEqual(state["commands"], ["/reload"])
64
+
65
+ def test_messages_stays_background_and_cancels_draft(self):
66
+ state = {"open": True, "text": "public draft", "public": [], "commands": []}
67
+ def post(hwnd, message, value, lparam):
68
+ self.assertEqual(hwnd, 1)
69
+ if message == windows.WM_KEYDOWN:
70
+ if value == windows.VK_ESCAPE:
71
+ state.update(open=False, text="")
72
+ elif value == windows.VK_RETURN:
73
+ if state["open"]:
74
+ text = state["text"]
75
+ if text: state["commands" if text.startswith("/") else "public"].append(text)
76
+ state.update(open=False, text="")
77
+ else: state["open"] = True
78
+ elif message == windows.WM_CHAR:
79
+ self.assertEqual(lparam, 1)
80
+ if state["open"]: state["text"] += chr(value)
81
+ return 1
82
+ with patch.object(windows, "confirm_window", return_value=windows.WindowIdentity(1, 2, "D:/Wow.exe", "test")), \
83
+ patch.object(windows.user32, "PostMessageW", side_effect=post), \
84
+ patch.object(windows, "focus_window", side_effect=AssertionError("must stay background")), \
85
+ patch.object(windows, "_send_key", side_effect=AssertionError("must not SendInput")), \
86
+ patch.object(windows, "Clipboard", side_effect=AssertionError("must not use clipboard")), \
87
+ patch.object(windows.time, "sleep"):
88
+ windows.send_command(1, "/reload", mode="messages")
89
+ self.assertEqual(state["public"], [])
90
+ self.assertEqual(state["commands"], ["/reload"])
91
+
92
+ def test_background_rejection_does_not_queue_submit(self):
93
+ posted = []
94
+ def post(hwnd, message, value, lparam):
95
+ posted.append((message, value))
96
+ return message != windows.WM_CHAR
97
+ with patch.object(windows, "confirm_window", return_value=windows.WindowIdentity(1, 2, "D:/Wow.exe", "test")), \
98
+ patch.object(windows.user32, "PostMessageW", side_effect=post), \
99
+ patch.object(windows.time, "sleep"):
100
+ with self.assertRaises(windows.InputError):
101
+ windows.send_command(1, "/reload", mode="messages")
102
+ returns = [entry for entry in posted if entry == (windows.WM_KEYDOWN, windows.VK_RETURN)]
103
+ self.assertEqual(len(returns), 1, "failed typing must not queue final submit")
104
+ self.assertEqual(posted[-1], (windows.WM_KEYUP, windows.VK_ESCAPE))
105
+
106
+ def test_invalid_commands_never_focus_or_type(self):
107
+ with patch.object(windows, "focus_window") as focus, patch.object(windows, "_send_key") as key:
108
+ for command in ("hello", "/reload\n/dev", "/" + "a" * 255):
109
+ with self.assertRaises(windows.InputError):
110
+ windows.send_command(1, command)
111
+ focus.assert_not_called()
112
+ key.assert_not_called()
113
+
114
+ def test_closed_and_empty_chat(self):
115
+ for draft in (None, ""):
116
+ state, error = self.exercise(draft)
117
+ self.assertIsNone(error)
118
+ self.assertEqual(state["commands"], ["/reload"])
119
+
120
+ def test_failed_paste_or_copy_never_submits(self):
121
+ for options in ({"paste": False}, {"copy": False}):
122
+ state, error = self.exercise(**options)
123
+ self.assertIsNotNone(error)
124
+ self.assertEqual(state["commands"], [])
125
+ self.assertFalse(state["open"])
126
+
127
+ def test_focus_loss_never_submits(self):
128
+ state, error = self.exercise(lose_focus=True)
129
+ self.assertIsNotNone(error)
130
+ self.assertEqual(state["commands"], [])
131
+
132
+ if __name__ == "__main__": unittest.main()