lycheedev 1.1.0 → 1.1.1

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.
@@ -386,8 +386,8 @@ def _window_module():
386
386
  def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
387
387
  """Log the intent, then send exactly one command (design section 6.2)."""
388
388
 
389
- mode = getattr(args, "mode", "foreground")
390
- session.log_event("command_sent", hwnd=args.hwnd, text=text, mode=mode)
389
+ mode = getattr(args, "mode", "messages")
390
+ session.log_event("command_prepared", hwnd=args.hwnd, text=text, mode=mode)
391
391
  try:
392
392
  windows.send_command(args.hwnd, text, pid=getattr(args, "pid", None),
393
393
  exe_path=getattr(args, "exe_path", None),
@@ -396,6 +396,7 @@ def _deliver(session: session_mod.Session, windows, args, text: str) -> None:
396
396
  session.log_event("command_failed", hwnd=args.hwnd, text=text,
397
397
  mode=mode, reason=str(error))
398
398
  raise CliError(f"command delivery failed: {error}", code=EXIT_INPUT)
399
+ session.log_event("command_submitted", hwnd=args.hwnd, text=text, mode=mode)
399
400
 
400
401
 
401
402
  def cmd_send(args) -> int:
@@ -410,11 +411,11 @@ def cmd_send(args) -> int:
410
411
  f"reload for {args.ticket} was already requested; check the saved "
411
412
  "variables file before repeating it")
412
413
  _deliver(session, windows, args, args.text)
413
- print("sent")
414
+ print("submitted; game execution is not yet confirmed")
414
415
  return 0
415
416
 
416
417
 
417
- def ack_command(ticket: str, outcome: str) -> str:
418
+ def ack_command(ticket: str, outcome: str, nonce: str | None = None) -> str:
418
419
  """Build the in-game command that reports a ticket's read outcome.
419
420
 
420
421
  The plugin cannot see whether the host read a result, so the host says so
@@ -423,7 +424,11 @@ def ack_command(ticket: str, outcome: str) -> str:
423
424
 
424
425
  if outcome not in ("received", "failed"):
425
426
  raise CliError("ack status must be 'received' or 'failed'")
426
- return f"/dev auto ack {ticket} {outcome}"
427
+ if not svlib.TICKET_PATTERN.fullmatch(ticket) or len(ticket) > 64:
428
+ raise CliError("invalid acknowledgement ticket")
429
+ if nonce is not None and not registry.REQUEST_ID_PATTERN.fullmatch(nonce):
430
+ raise CliError("invalid acknowledgement nonce")
431
+ return f"/dev auto ack {ticket} {outcome}" + (f" {nonce}" if nonce else "")
427
432
 
428
433
 
429
434
  def cmd_ack(args) -> int:
@@ -432,13 +437,55 @@ def cmd_ack(args) -> int:
432
437
  windows = _window_module()
433
438
  session = session_mod.Session(data_dir=args.data_dir,
434
439
  installation=args.installation)
435
- text = ack_command(args.ticket, args.status)
440
+ nonce = new_request_id()
441
+ text = ack_command(args.ticket, args.status, nonce)
436
442
  _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}")
443
+ session.log_event("ticket_ack_submitted", ticket=args.ticket, status=args.status)
444
+ notice = poll_notice(windows, session, args, expected_task="ack", expected_run=nonce,
445
+ expected_ticket=args.ticket, expected_status=args.status)
446
+ if notice is None:
447
+ session.log_event("ticket_ack_unresolved", ticket=args.ticket, nonce=nonce)
448
+ raise CliError("ack was submitted but no matching game receipt arrived",
449
+ code=EXIT_NOTICE_TIMEOUT)
450
+ session.log_event("ticket_ack_confirmed", ticket=args.ticket, status=args.status, nonce=nonce)
451
+ _deliver(session, windows, args, f"/dev auto unidentify {nonce}")
452
+ if not wait_ack_cleared(windows, args, nonce):
453
+ session.log_event("ticket_ack_cleanup_unresolved", ticket=args.ticket, nonce=nonce)
454
+ raise CliError("ack confirmed, but its marker cleanup was not observed",
455
+ code=EXIT_NOTICE_TIMEOUT)
456
+ session.log_event("ticket_ack_cleared", ticket=args.ticket, nonce=nonce)
457
+ print(f"ack confirmed: {args.ticket} {args.status}")
439
458
  return 0
440
459
 
441
460
 
461
+ def wait_ack_cleared(windows, args, nonce: str) -> bool:
462
+ """Observe removal of this receipt; never dismiss a newer marker by nonce."""
463
+ interval = getattr(args, "interval", None) or DEFAULT_INTERVAL
464
+ deadline = time.monotonic() + min(args.timeout, 5.0)
465
+ absent = 0
466
+ with windows.open_notice_capture(args.hwnd, pid=getattr(args, "pid", None),
467
+ exe_path=getattr(args, "exe_path", None),
468
+ interval=interval) as capture:
469
+ while time.monotonic() < deadline:
470
+ if capture.window_closed:
471
+ return False
472
+ roi = capture.latest_roi()
473
+ if roi is not None:
474
+ visible = False
475
+ for payload in windows.decode_qr(roi):
476
+ try:
477
+ marker = json.loads(payload)
478
+ except (ValueError, TypeError):
479
+ continue
480
+ if isinstance(marker, dict) and marker.get("task") == "ack" and marker.get("run") == nonce:
481
+ visible = True
482
+ absent = 0 if visible else absent + 1
483
+ if absent >= 2:
484
+ return True
485
+ time.sleep(interval)
486
+ return False
487
+
488
+
442
489
  def validate_notice(json_text: str) -> dict:
443
490
  if not isinstance(json_text, str) or not json_text:
444
491
  raise SavedVariablesError("notice payload is empty")
@@ -488,7 +535,9 @@ def notice_identity_problems(notice: dict, *, expected_task: str | None,
488
535
 
489
536
  def poll_notice(windows, session: session_mod.Session, args, *,
490
537
  expected_task: str | None = None,
491
- expected_run: str | None = None) -> dict | None:
538
+ expected_run: str | None = None,
539
+ expected_ticket: str | None = None,
540
+ expected_status: str | None = None) -> dict | None:
492
541
  """Keep one WGC session open and poll until a matching notice or the deadline.
493
542
 
494
543
  The session outlives a single frame because a task can run far longer than
@@ -516,6 +565,10 @@ def poll_notice(windows, session: session_mod.Session, args, *,
516
565
  problems = notice_identity_problems(
517
566
  notice, expected_task=expected_task,
518
567
  expected_run=expected_run)
568
+ if expected_ticket is not None and notice["ticket"] != expected_ticket:
569
+ problems.append("receipt ticket mismatch")
570
+ if expected_status is not None and notice.get("status") != expected_status:
571
+ problems.append("receipt status mismatch")
519
572
  if problems:
520
573
  session.log_event("notice_identity_mismatch",
521
574
  ticket=notice["ticket"],
@@ -668,6 +721,11 @@ def cmd_run(args) -> int:
668
721
  expected_request_id = args.request_id or definition["requestId"]
669
722
  revision = args.revision or definition["revision"]
670
723
 
724
+ if not registry.TASK_ID_PATTERN.fullmatch(args.task):
725
+ raise CliError("invalid task id")
726
+ if not expected_request_id or not registry.REQUEST_ID_PATTERN.fullmatch(expected_request_id):
727
+ raise CliError("run requires an installed task block or an explicit --request-id")
728
+
671
729
  session.log_event("run_started", task=args.task,
672
730
  requestId=expected_request_id, revision=revision)
673
731
  _deliver(session, windows, args, f"/dev auto run {args.task}")
@@ -689,8 +747,11 @@ def cmd_bugs(args) -> int:
689
747
  raise CliError("--count must be an integer between 1 and 100")
690
748
  session = session_mod.Session(data_dir=args.data_dir,
691
749
  installation=args.installation)
692
- session.log_event("bugs_started", count=args.count)
693
- _deliver(session, windows, args, f"/dev auto bug {args.count}")
750
+ args.request_id = args.request_id or new_request_id()
751
+ if not registry.REQUEST_ID_PATTERN.fullmatch(args.request_id):
752
+ raise CliError("invalid bug request id")
753
+ session.log_event("bugs_started", count=args.count, requestId=args.request_id)
754
+ _deliver(session, windows, args, f"/dev auto bug {args.count} {args.request_id}")
694
755
  notice = poll_notice(windows, session, args, expected_task=BUG_TASK_ID,
695
756
  expected_run=args.request_id)
696
757
  if notice is None:
@@ -819,11 +880,9 @@ def build_parser() -> argparse.ArgumentParser:
819
880
  window.add_argument("--pid", type=int, help="expected process id")
820
881
  window.add_argument("--exe-path", help="expected executable path")
821
882
  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)")
883
+ "--mode", choices=("foreground", "messages"), default="messages",
884
+ help="foreground uses clipboard readback; messages posts input to the "
885
+ "target HWND without changing foreground (execution needs a receipt)")
827
886
 
828
887
  polling = argparse.ArgumentParser(add_help=False)
829
888
  polling.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT,
@@ -841,7 +900,7 @@ def build_parser() -> argparse.ArgumentParser:
841
900
  send.add_argument("--ticket", help="ticket used to dedup a '/reload' command")
842
901
  send.set_defaults(func=cmd_send)
843
902
 
844
- ack = sub.add_parser("ack", parents=[window],
903
+ ack = sub.add_parser("ack", parents=[window, polling],
845
904
  help="report a ticket's read outcome to the running game")
846
905
  ack.add_argument("--ticket", required=True, help="exact ticket that was read")
847
906
  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()