copuppet 0.1.0__tar.gz → 0.1.1__tar.gz

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.
Files changed (81) hide show
  1. copuppet-0.1.1/.github/workflows/test.yml +24 -0
  2. {copuppet-0.1.0 → copuppet-0.1.1}/CHANGELOG.md +17 -0
  3. {copuppet-0.1.0 → copuppet-0.1.1}/PKG-INFO +27 -1
  4. {copuppet-0.1.0 → copuppet-0.1.1}/README.md +26 -0
  5. {copuppet-0.1.0 → copuppet-0.1.1}/config.example/skin.yaml +2 -0
  6. copuppet-0.1.1/docs/roadmap.md +32 -0
  7. {copuppet-0.1.0 → copuppet-0.1.1}/pyproject.toml +1 -1
  8. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/__init__.py +1 -1
  9. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/backends/edge.py +56 -74
  10. copuppet-0.1.1/src/copuppet/backends/edge_common.py +140 -0
  11. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/calibrate.py +1 -2
  12. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/cli.py +1 -0
  13. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/ledger.py +3 -0
  14. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/protocol.py +2 -1
  15. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/relay.py +8 -2
  16. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/skin.py +3 -0
  17. copuppet-0.1.1/tests/test_edge_codeblocks.py +34 -0
  18. copuppet-0.1.1/tests/test_notices.py +49 -0
  19. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_relay.py +24 -7
  20. {copuppet-0.1.0 → copuppet-0.1.1}/tools/discover_edge.py +37 -36
  21. {copuppet-0.1.0 → copuppet-0.1.1}/.gitattributes +0 -0
  22. {copuppet-0.1.0 → copuppet-0.1.1}/.github/workflows/release.yml +0 -0
  23. {copuppet-0.1.0 → copuppet-0.1.1}/.gitignore +0 -0
  24. {copuppet-0.1.0 → copuppet-0.1.1}/CLAUDE.md +0 -0
  25. {copuppet-0.1.0 → copuppet-0.1.1}/LICENSE +0 -0
  26. {copuppet-0.1.0 → copuppet-0.1.1}/RELEASING.md +0 -0
  27. {copuppet-0.1.0 → copuppet-0.1.1}/docs/model.md +0 -0
  28. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/actions.py +0 -0
  29. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/backend.py +0 -0
  30. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/backends/__init__.py +0 -0
  31. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/backends/winapp.py +0 -0
  32. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/driver.py +1 -1
  33. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/fake.py +0 -0
  34. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/mcp_server.py +0 -0
  35. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/policy.py +0 -0
  36. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/runner.py +0 -0
  37. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/session.py +1 -1
  38. {copuppet-0.1.0 → copuppet-0.1.1}/src/copuppet/tokens.py +0 -0
  39. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/README.md +0 -0
  40. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/recorded.json +0 -0
  41. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000001.a.json +0 -0
  42. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000001.q.json +0 -0
  43. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000002.a.json +0 -0
  44. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000002.q.json +0 -0
  45. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000003.a.json +0 -0
  46. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000003.q.json +0 -0
  47. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000004.a.json +0 -0
  48. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000004.q.json +0 -0
  49. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000005.a.json +0 -0
  50. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000005.q.json +0 -0
  51. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000006.a.json +0 -0
  52. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000006.q.json +0 -0
  53. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000007.a.json +0 -0
  54. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000007.q.json +0 -0
  55. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000008.a.json +0 -0
  56. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000008.q.json +0 -0
  57. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000009.a.json +0 -0
  58. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000009.q.json +0 -0
  59. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000010.a.json +0 -0
  60. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000010.q.json +0 -0
  61. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000011.a.json +0 -0
  62. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000011.q.json +0 -0
  63. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000013.a.json +0 -0
  64. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/copilot-000013.q.json +0 -0
  65. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/person-000012.a.json +0 -0
  66. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/done/person-000012.q.json +0 -0
  67. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/run/run.json +0 -0
  68. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/notes/fridge.md +0 -0
  69. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/pantry.md +0 -0
  70. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/recipes/omelette.md +0 -0
  71. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/recipes/pancakes.md +0 -0
  72. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/recipes/shortbread.md +0 -0
  73. {copuppet-0.1.0 → copuppet-0.1.1}/tests/fixtures/pantry/work/recipes/tomato-rice.md +0 -0
  74. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_calibrate.py +0 -0
  75. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_driver.py +0 -0
  76. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_ledger_and_fake.py +0 -0
  77. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_mcp_server.py +0 -0
  78. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_protocol_and_session.py +0 -0
  79. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_redteam_3.py +0 -0
  80. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_replay_fixture.py +0 -0
  81. {copuppet-0.1.0 → copuppet-0.1.1}/tests/test_skin.py +0 -0
@@ -0,0 +1,24 @@
1
+ # copuppet - offline test suite (fake, relay and replay backends; no Edge, no Copilot) on pull requests and main.
2
+ name: test
3
+ on:
4
+ pull_request:
5
+ push:
6
+ branches: [main]
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ pytest:
13
+ strategy:
14
+ fail-fast: false
15
+ matrix:
16
+ os: [ubuntu-latest, windows-latest]
17
+ python: ['3.10', '3.13']
18
+ runs-on: ${{ matrix.os }}
19
+ steps:
20
+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
21
+ - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
22
+ with: { python-version: '${{ matrix.python }}' }
23
+ - run: python -m pip install -e ".[dev,mcp]"
24
+ - run: python -m pytest -q
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.1 (2026-11-29)
4
+
5
+ Fixes from the first live runs.
6
+
7
+ - Code blocks are read until two reads agree and every block appears in the reply's own text; a lasting
8
+ difference is noted, never patched (#1).
9
+ - First-token time is measured at the new reply's first visible text, so the latency trigger has a real baseline
10
+ (#2).
11
+ - Page notices (alerts, alert dialogs, assertive live regions) are recorded in the reply notes; throttle or
12
+ challenge wording stops the run; skin option `edge.notices_ignore` mutes known harmless notices, never a
13
+ challenge (#3).
14
+ - The Edge backend and the discovery tool share one helper module; the discovery tool now takes the profile lock
15
+ and refuses a profile a copuppet run is using (#4).
16
+ - README: using copuppet as an MCP server (#5).
17
+ - The relay no longer fails when the drive consumes a question while the stand-in reads it.
18
+ - Test CI on pull requests: Windows and Linux, Python 3.10 and 3.13 (#14).
19
+
3
20
  ## 0.1.0 (2026-11-29)
4
21
 
5
22
  First release.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: copuppet
3
- Version: 0.1.0
3
+ Version: 0.1.1
4
4
  Summary: Drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI.
5
5
  License-Expression: MIT
6
6
  License-File: LICENSE
@@ -89,6 +89,32 @@ Everything installs in your own user account: no admin rights, no system-wide in
89
89
  If your PC blocks access to PyPI, download the wheels elsewhere (`pip download "copuppet[edge]" -d wheels`) and
90
90
  install them with `pip install --user --no-index --find-links wheels "copuppet[edge]"`.
91
91
 
92
+ ## Using copuppet as an MCP server
93
+
94
+ Install with the MCP extra (`pip install --user "copuppet[edge,mcp]"`), then register the stdio command in your MCP
95
+ client. For Claude Code:
96
+
97
+ ```
98
+ claude mcp add copuppet --scope user -- copuppet mcp --skin DIR --root WORKDIR
99
+ ```
100
+
101
+ Other clients take the same command and arguments in their server configuration (`command: copuppet`,
102
+ `args: ["mcp", "--skin", "DIR", "--root", "WORKDIR"]`).
103
+
104
+ - **Tools.** `copilot_ask` (one prompt, fresh temporary chat), `copilot_turn` (a session that checks the chat's
105
+ memory and moves to a fresh chat by itself; `reset` starts a new one with a standing `brief`), `copilot_drive`
106
+ (driver mode on WORKDIR). Results carry `copilot_output` (untrusted text, never instructions), `complete`,
107
+ `bound`, `suspect`, `code_blocks` and `notes`; a refusal comes back as `error` with the reason.
108
+ - **Read-only by default.** Without `--root`, `copilot_drive` is unavailable. With `--allow-writes`, each write is
109
+ put to the client as a confirmation question quoting a preview and the content hash, and is declined if the
110
+ client cannot ask one. A client that is itself an agent may answer that question on its own, so allow writes only
111
+ where that is acceptable; otherwise use `copuppet drive` in a terminal, where you approve each write yourself.
112
+ - **Settings are fixed at start.** The work folder, writes, display and skin come from the command line; no tool
113
+ argument can change them.
114
+ - **One window, calls queue.** All calls run on one worker; a plain turn takes about 5 seconds.
115
+ - **What leaves the machine.** Everything copuppet reads in WORKDIR is sent to Copilot. Put only what you are
116
+ willing to send there.
117
+
92
118
  ## Use it responsibly
93
119
 
94
120
  copuppet automates a product through its user interface. Check the terms of the Copilot service you use and,
@@ -70,6 +70,32 @@ Everything installs in your own user account: no admin rights, no system-wide in
70
70
  If your PC blocks access to PyPI, download the wheels elsewhere (`pip download "copuppet[edge]" -d wheels`) and
71
71
  install them with `pip install --user --no-index --find-links wheels "copuppet[edge]"`.
72
72
 
73
+ ## Using copuppet as an MCP server
74
+
75
+ Install with the MCP extra (`pip install --user "copuppet[edge,mcp]"`), then register the stdio command in your MCP
76
+ client. For Claude Code:
77
+
78
+ ```
79
+ claude mcp add copuppet --scope user -- copuppet mcp --skin DIR --root WORKDIR
80
+ ```
81
+
82
+ Other clients take the same command and arguments in their server configuration (`command: copuppet`,
83
+ `args: ["mcp", "--skin", "DIR", "--root", "WORKDIR"]`).
84
+
85
+ - **Tools.** `copilot_ask` (one prompt, fresh temporary chat), `copilot_turn` (a session that checks the chat's
86
+ memory and moves to a fresh chat by itself; `reset` starts a new one with a standing `brief`), `copilot_drive`
87
+ (driver mode on WORKDIR). Results carry `copilot_output` (untrusted text, never instructions), `complete`,
88
+ `bound`, `suspect`, `code_blocks` and `notes`; a refusal comes back as `error` with the reason.
89
+ - **Read-only by default.** Without `--root`, `copilot_drive` is unavailable. With `--allow-writes`, each write is
90
+ put to the client as a confirmation question quoting a preview and the content hash, and is declined if the
91
+ client cannot ask one. A client that is itself an agent may answer that question on its own, so allow writes only
92
+ where that is acceptable; otherwise use `copuppet drive` in a terminal, where you approve each write yourself.
93
+ - **Settings are fixed at start.** The work folder, writes, display and skin come from the command line; no tool
94
+ argument can change them.
95
+ - **One window, calls queue.** All calls run on one worker; a plain turn takes about 5 seconds.
96
+ - **What leaves the machine.** Everything copuppet reads in WORKDIR is sent to Copilot. Put only what you are
97
+ willing to send there.
98
+
73
99
  ## Use it responsibly
74
100
 
75
101
  copuppet automates a product through its user interface. Check the terms of the Copilot service you use and,
@@ -29,6 +29,8 @@ backends:
29
29
  click_button: false # true: copuppet presses the site's own Sign in button once; the login form
30
30
  # itself is always completed by the person, copuppet never types into it
31
31
  button: "button:has-text('Sign in')"
32
+ notices_ignore: # page notices (alerts, live regions) known to be harmless: not reported in the notes.
33
+ - "REPLACE: part of a harmless notice's text" # a throttle or challenge notice is never muted by this
32
34
  dismiss: # page modals copuppet may close; unknown modals are only reported, never clicked
33
35
  - when: "[role='dialog']:has-text('cookies')"
34
36
  click: "button:has-text('Reject')" # prefer the button that declines optional cookies
@@ -0,0 +1,32 @@
1
+ # Roadmap
2
+
3
+ Tracked as GitHub milestones and issues; this page says why each release contains what it does.
4
+
5
+ ## 0.1.0 (released 2026-11-29)
6
+ Edge backend (headless with single sign-on), `ask`, sessions with memory checks and rotation, `calibrate`,
7
+ `drive` (driver mode under a policy), `mcp`, the hash-chained ledger, relay and replay backends. Verified live: a
8
+ read-only drive, a drive with one confirmed write, an MCP call, three calibration runs.
9
+
10
+ ## 0.1.1: what the live runs found
11
+ Small fixes that make the existing features trustworthy. Each comes from a live run.
12
+ - #1 A code block read back with extra text after the JSON (the first live write drive needed a retry).
13
+ - #2 First-token time measures the busy marker, so the latency trigger is blind.
14
+ - #3 Selectors for challenge and limit notices, so those stops do not rely on reply text alone.
15
+ - #4 One set of helpers for the discovery tool and the backend.
16
+ - #5 Using copuppet as an MCP server, documented.
17
+
18
+ ## 0.1.2: real runs become tests
19
+ Builds on 0.1.1: once read-back and timing are right, real runs are worth recording.
20
+ - #6 Record real runs in the relay format, so they replay as regression tests.
21
+ - #7 Resume a stopped drive from its ledger, never repeating a recorded step.
22
+ - #8 Find the real recall ceiling (today only a lower bound of 378,000 characters).
23
+ - #9 Calibrate the off-screen and visible display modes.
24
+ - #10 Progress and cancel for `copilot_drive` over MCP.
25
+
26
+ ## Later
27
+ - #11 winapp backend: parked until a PC blocks Edge automation.
28
+ - #12 Edge on macOS and Linux.
29
+
30
+ ## Release rule
31
+ A release is a tag plus a GitHub Release; the release workflow publishes to PyPI through Trusted Publishing
32
+ (RELEASING.md). Every release passes the full test suite, including the replay fixtures.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "copuppet"
7
- version = "0.1.0"
7
+ version = "0.1.1"
8
8
  description = "Drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI."
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -1,2 +1,2 @@
1
1
  """copuppet: drive Microsoft Copilot from a deterministic Python harness, as a normal user through its own UI."""
2
- __version__ = "0.1.0"
2
+ __version__ = "0.1.1"
@@ -7,70 +7,31 @@ model label. Everything page-specific comes from the skin.
7
7
  """
8
8
  from __future__ import annotations
9
9
 
10
- import json
11
- import os
12
- import re
13
10
  import sys
14
11
  import time
15
12
  from pathlib import Path
16
13
 
17
14
  from ..backend import BackendError, ChatHandle, Probe, Reply
18
-
19
- BROWSER_ARGS = ["--hide-crash-restore-bubble", "--no-first-run", "--no-default-browser-check"]
20
- DIALOG_SELECTOR = "[role='dialog'], [role='alertdialog'], [aria-modal='true']"
21
- LOGIN_HOSTS = ("login.live.com", "login.microsoftonline.com", "login.microsoft.com")
22
- LOCK_NAME = "copuppet.lock"
15
+ from .edge_common import (
16
+ BROWSER_ARGS,
17
+ DIALOG_SELECTOR,
18
+ LOGIN_HOSTS,
19
+ ZERO_WIDTH,
20
+ ProfileBusy,
21
+ acquire_lock,
22
+ classify_notices,
23
+ first_visible,
24
+ mark_clean_exit,
25
+ normalise,
26
+ release_lock,
27
+ visible_notices,
28
+ )
23
29
 
24
30
 
25
31
  class ChallengeError(BackendError):
26
32
  """A challenge or throttle marker: stop; no display fallback, no retry (I12)."""
27
33
 
28
34
 
29
- def mark_clean_exit(profile: Path) -> None:
30
- """Prevent Edge's 'Restore pages' bubble (browser UI, unclickable from Playwright) after an unclean exit."""
31
- pref = profile / "Default" / "Preferences"
32
- try:
33
- data = json.loads(pref.read_text(encoding="utf-8"))
34
- except (OSError, ValueError):
35
- return
36
- prof = data.setdefault("profile", {})
37
- if prof.get("exit_type") != "Normal" or prof.get("exited_cleanly") is not True:
38
- prof["exit_type"], prof["exited_cleanly"] = "Normal", True
39
- pref.write_text(json.dumps(data), encoding="utf-8")
40
-
41
-
42
- def first_visible(locator, limit: int = 10):
43
- for i in range(min(locator.count(), limit)):
44
- if locator.nth(i).is_visible():
45
- return locator.nth(i)
46
- return None
47
-
48
-
49
- ZERO_WIDTH = re.compile("[\u200b\u200c\u200d\u2060\ufeff]")
50
-
51
-
52
- def normalise(text: str) -> str:
53
- """Whitespace collapsed and zero-width characters removed: the chat editor inserts U+200B U+200C at line ends."""
54
- return re.sub(r"\s+", " ", ZERO_WIDTH.sub("", text or "")).strip()
55
-
56
-
57
- def _pid_alive(pid: int) -> bool:
58
- if pid <= 0:
59
- return False
60
- try:
61
- if os.name == "nt":
62
- import ctypes
63
- h = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
64
- if not h:
65
- return False
66
- ctypes.windll.kernel32.CloseHandle(h)
67
- return True
68
- os.kill(pid, 0)
69
- return True
70
- except OSError:
71
- return False
72
-
73
-
74
35
  class EdgeBackend:
75
36
  name = "edge"
76
37
 
@@ -84,6 +45,7 @@ class EdgeBackend:
84
45
  self.rerender = float(t.get("rerender_seconds", 2.5))
85
46
  self.signin = config.get("signin") or {}
86
47
  self.dismiss = config.get("dismiss") or []
48
+ self.notices_ignore = [s.lower() for s in config.get("notices_ignore") or []] # #3: known harmless notices
87
49
  self.profile = Path(str(config.get("profile_dir") or "~/.copuppet/edge-profile")).expanduser()
88
50
  self.type_delay = int(config.get("type_delay_ms", 5))
89
51
  self.display = str(config.get("display", "auto")) # auto | headless | offscreen | visible
@@ -93,7 +55,8 @@ class EdgeBackend:
93
55
  self._lock = None
94
56
  self._chat_seq = 0
95
57
  self.notes: list[str] = []
96
- self.chat_notes: list[str] = [] # notes from new_chat, carried into the next send's Reply
58
+ self.chat_notes: list[str] = []
59
+ self._notices_seen: set = set() # page notices already reported (#3) # notes from new_chat, carried into the next send's Reply
97
60
  self.verbose = bool(config.get("_verbose"))
98
61
 
99
62
  def log(self, msg: str) -> None:
@@ -117,17 +80,10 @@ class EdgeBackend:
117
80
 
118
81
  # ---------- lock + browser lifecycle ----------
119
82
  def _acquire_lock(self) -> None:
120
- self.profile.mkdir(parents=True, exist_ok=True)
121
- lock = self.profile / LOCK_NAME
122
83
  try:
123
- holder = int(lock.read_text(encoding="utf-8").strip() or 0)
124
- except (OSError, ValueError):
125
- holder = 0
126
- if holder and holder != os.getpid() and _pid_alive(holder):
127
- raise BackendError(f"another copuppet run (pid {holder}) is using {self.profile}; next: wait for it or "
128
- "stop it")
129
- lock.write_text(str(os.getpid()), encoding="utf-8")
130
- self._lock = lock
84
+ self._lock = acquire_lock(self.profile)
85
+ except ProfileBusy as err:
86
+ raise BackendError(str(err)) from None
131
87
 
132
88
  DISPLAY_ARGS = {
133
89
  "headless": [],
@@ -178,11 +134,7 @@ class EdgeBackend:
178
134
  finally:
179
135
  if self._pw is not None:
180
136
  self._pw.stop()
181
- if self._lock is not None:
182
- try:
183
- self._lock.unlink()
184
- except OSError:
185
- pass
137
+ release_lock(self._lock)
186
138
  self._pw = self._ctx = self.page = self._lock = None
187
139
 
188
140
  # ---------- page state ----------
@@ -203,6 +155,13 @@ class EdgeBackend:
203
155
  markers = [k for k in ("limit_marker", "error_marker", "challenge_marker") if self._visible(k)]
204
156
  if any(h in self._host() for h in LOGIN_HOSTS):
205
157
  markers.append("login_page")
158
+ try:
159
+ found, notes = classify_notices(visible_notices(self.page), self._notices_seen, # #3
160
+ ignore=self.notices_ignore)
161
+ except Exception: # a notice scan must never break a probe
162
+ found, notes = [], []
163
+ markers += [m for m in found if m not in markers]
164
+ self.notes += notes
206
165
  return Probe(temporary=self._visible("temporary_on"), signed_in=self._visible("signed_in"),
207
166
  model_label=self._text_of("model"), markers=markers,
208
167
  reply_count=self.page.locator(self.sel["reply"]).count(), url=self.page.url[:120])
@@ -423,6 +382,23 @@ class EdgeBackend:
423
382
  out.append(ZERO_WIDTH.sub("", part.inner_text() if part.count() else "").strip("\n"))
424
383
  return out
425
384
 
385
+ def _stable_code_blocks(self, reply, reply_text: str) -> list[str]:
386
+ """Read the code blocks until two reads agree and every block appears in the reply's own text (issue #1:
387
+ live, a block was once read with an extra line the reply text did not contain, during the editor's last
388
+ re-render). After the retries the last read is returned with a note, never silently patched."""
389
+ flat = " ".join(normalise(reply_text).split())
390
+ prev = None
391
+ for _ in range(6):
392
+ cur = self._code_blocks(reply)
393
+ contained = all(" ".join(normalise(b).split()) in flat for b in cur)
394
+ if cur == prev and contained:
395
+ return cur
396
+ prev = cur
397
+ time.sleep(0.25)
398
+ if not all(" ".join(normalise(b).split()) in flat for b in prev or []):
399
+ self.notes.append("a code block read back differs from the reply text (issue #1)")
400
+ return prev or []
401
+
426
402
  def _mark_seen(self, mark: str) -> list:
427
403
  """Give every existing reply and user-message node its own id mark; returns [id, text] of the reply nodes
428
404
  that held text (I11)."""
@@ -491,7 +467,9 @@ class EdgeBackend:
491
467
  kept = self._mark_seen(mark)
492
468
  fresh_sel = f"{self.sel['reply']}:not([data-copuppet-seen])"
493
469
  user_sel = f"{self.sel['user_message']}:not([data-copuppet-seen])" if self.sel.get("user_message") else ""
494
- first_token, t_sent, busy_seen = None, time.time(), False
470
+ # `started` = the service took the prompt (busy marker or a new reply node); `first_token` = the new reply
471
+ # first shows text (#2: the busy marker appears at once, so it says nothing about latency)
472
+ started, first_token, t_sent, busy_seen = None, None, time.time(), False
495
473
  for attempt in (1, 2):
496
474
  self.page.keyboard.press("Enter")
497
475
  t_sent = time.time()
@@ -500,10 +478,10 @@ class EdgeBackend:
500
478
  busy = self._visible("busy")
501
479
  busy_seen = busy_seen or busy
502
480
  if busy or self.page.locator(fresh_sel).count() > 0:
503
- first_token = time.time()
481
+ started = time.time()
504
482
  break
505
483
  time.sleep(0.2)
506
- if first_token is not None:
484
+ if started is not None:
507
485
  break
508
486
  # I10: resubmit only with proof that nothing was sent (no new user message, no new reply)
509
487
  sent_evidence = (self.page.locator(user_sel).count() > 0) if user_sel else True
@@ -515,7 +493,7 @@ class EdgeBackend:
515
493
  break
516
494
  continue
517
495
  break
518
- if first_token is None:
496
+ if started is None:
519
497
  raise BackendError("no answer started after submitting; next: re-run tools/discover_edge.py --probe")
520
498
  complete, last_text, stable_since = False, None, None
521
499
  done_sel = f"{fresh_sel} {self.sel['done']}" if self.sel.get("done") else ""
@@ -524,6 +502,8 @@ class EdgeBackend:
524
502
  busy = self._visible("busy")
525
503
  busy_seen = busy_seen or busy
526
504
  fresh = self.page.locator(fresh_sel)
505
+ if first_token is None and fresh.count() > 0 and normalise(fresh.nth(fresh.count() - 1).inner_text()):
506
+ first_token = time.time()
527
507
  if not busy and fresh.count() > 0:
528
508
  if done_sel and first_visible(self.page.locator(done_sel)) is not None:
529
509
  complete = True # done marker scoped to the new reply
@@ -539,6 +519,8 @@ class EdgeBackend:
539
519
  last_text, stable_since = None, None
540
520
  time.sleep(0.3)
541
521
  t_done = time.time()
522
+ if first_token is None:
523
+ first_token = t_done # no text was ever seen: generation time 0, the reply is empty
542
524
  after = self.probe()
543
525
  b = self._bind(kept)
544
526
  bound = b["fresh"] == 1 and b["before_anchor"] == 0 and b["anchored"] # I8 + I11
@@ -557,7 +539,7 @@ class EdgeBackend:
557
539
  new_nodes = self.page.locator(f"{self.sel['reply']}[data-copuppet-fresh]")
558
540
  last = new_nodes.nth(new_nodes.count() - 1) if new_nodes.count() else None
559
541
  text = ZERO_WIDTH.sub("", last.inner_text()).strip() if last is not None else ""
560
- code = self._code_blocks(last)
542
+ code = self._stable_code_blocks(last, text) if last is not None else []
561
543
  if not complete:
562
544
  self.notes.append(f"stopped waiting after {timeout:g}s; the reply may be partial")
563
545
  self.log(("reply complete" if complete else "reply incomplete") + ("" if bound else ", UNBOUND") +
@@ -0,0 +1,140 @@
1
+ """What the Edge backend and tools/discover_edge.py share, so a fix lands once (#4): browser arguments, login hosts,
2
+ the clean-exit mark, text normalisation, visible-dialog reading and the profile lock. No Playwright import here."""
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import re
8
+ from pathlib import Path
9
+
10
+ BROWSER_ARGS = ["--hide-crash-restore-bubble", "--no-first-run", "--no-default-browser-check"]
11
+ DIALOG_SELECTOR = "[role='dialog'], [role='alertdialog'], [aria-modal='true']"
12
+ LOGIN_HOSTS = ("login.live.com", "login.microsoftonline.com", "login.microsoft.com", "account.microsoft.com")
13
+ LOCK_NAME = "copuppet.lock"
14
+ ZERO_WIDTH = re.compile("[\u200b\u200c\u200d\u2060\ufeff]")
15
+
16
+
17
+ class ProfileBusy(RuntimeError):
18
+ """Another copuppet process holds the Edge profile."""
19
+
20
+
21
+ def mark_clean_exit(profile: Path) -> None:
22
+ """Prevent Edge's 'Restore pages' bubble (browser UI, unclickable from Playwright) after an unclean exit."""
23
+ pref = profile / "Default" / "Preferences"
24
+ try:
25
+ data = json.loads(pref.read_text(encoding="utf-8"))
26
+ except (OSError, ValueError):
27
+ return
28
+ prof = data.setdefault("profile", {})
29
+ if prof.get("exit_type") != "Normal" or prof.get("exited_cleanly") is not True:
30
+ prof["exit_type"], prof["exited_cleanly"] = "Normal", True
31
+ pref.write_text(json.dumps(data), encoding="utf-8")
32
+
33
+
34
+ def first_visible(locator, limit: int = 10):
35
+ for i in range(min(locator.count(), limit)):
36
+ if locator.nth(i).is_visible():
37
+ return locator.nth(i)
38
+ return None
39
+
40
+
41
+ def normalise(text: str) -> str:
42
+ """Whitespace collapsed and zero-width characters removed: the chat editor inserts U+200B U+200C at line ends."""
43
+ return re.sub(r"\s+", " ", ZERO_WIDTH.sub("", text or "")).strip()
44
+
45
+
46
+ def pid_alive(pid: int) -> bool:
47
+ if pid <= 0:
48
+ return False
49
+ try:
50
+ if os.name == "nt":
51
+ import ctypes
52
+ h = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION
53
+ if not h:
54
+ return False
55
+ ctypes.windll.kernel32.CloseHandle(h)
56
+ return True
57
+ os.kill(pid, 0)
58
+ return True
59
+ except OSError:
60
+ return False
61
+
62
+
63
+ def acquire_lock(profile: Path) -> Path:
64
+ """Take the profile lock (one copuppet process per Edge profile); returns the lock file to release."""
65
+ profile.mkdir(parents=True, exist_ok=True)
66
+ lock = profile / LOCK_NAME
67
+ try:
68
+ holder = int(lock.read_text(encoding="utf-8").strip() or 0)
69
+ except (OSError, ValueError):
70
+ holder = 0
71
+ if holder and holder != os.getpid() and pid_alive(holder):
72
+ raise ProfileBusy(f"another copuppet run (pid {holder}) is using {profile}; next: wait for it or stop it")
73
+ lock.write_text(str(os.getpid()), encoding="utf-8")
74
+ return lock
75
+
76
+
77
+ def release_lock(lock: Path | None) -> None:
78
+ if lock is None:
79
+ return
80
+ try:
81
+ if lock.read_text(encoding="utf-8").strip() == str(os.getpid()):
82
+ lock.unlink()
83
+ except OSError:
84
+ pass
85
+
86
+
87
+ VISIBLE_DIALOGS_JS = r"""
88
+ (sel) => [...document.querySelectorAll(sel)].filter(el => {
89
+ const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== 'hidden';
90
+ }).map(el => ({
91
+ role: el.getAttribute('role') || '', aria_label: (el.getAttribute('aria-label') || '').slice(0, 80),
92
+ testid: el.getAttribute('data-testid') || '', id: el.id || '',
93
+ buttons: [...el.querySelectorAll("button, [role='button'], a")].map(b =>
94
+ ((b.getAttribute('aria-label') || b.innerText || '').trim().replace(/\s+/g, ' ')).slice(0, 40)).filter(Boolean).slice(0, 8),
95
+ }))
96
+ """
97
+
98
+
99
+ def visible_dialogs(page) -> list:
100
+ """Visible page modals, each with its role, label and the labels of its buttons (structure only)."""
101
+ return page.evaluate(VISIBLE_DIALOGS_JS, DIALOG_SELECTOR)
102
+
103
+
104
+ # ---------- notices (#3) ----------
105
+ THROTTLE = re.compile(r"(?i)(too many (requests|messages)|try again later|reached (the|your) (daily |message )?limit|"
106
+ r"slow down|unusual activity|verify (that )?you are (a )?human|are you a robot|captcha)")
107
+ NOTICE_SELECTOR = "[role='alert'], [role='alertdialog'], [aria-live='assertive']"
108
+ NOTICES_JS = r"""
109
+ (sel) => [...document.querySelectorAll(sel)].filter(el => {
110
+ const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== 'hidden';
111
+ }).map(el => ({
112
+ role: el.getAttribute('role') || ('live:' + (el.getAttribute('aria-live') || '')),
113
+ testid: el.getAttribute('data-testid') || '', aria_label: (el.getAttribute('aria-label') || '').slice(0, 80),
114
+ text: (el.innerText || '').trim().replace(/\s+/g, ' ').slice(0, 160),
115
+ })).filter(n => n.text || n.aria_label)
116
+ """
117
+
118
+
119
+ def visible_notices(page) -> list:
120
+ """Visible alerts, alert dialogs and assertive live regions (where challenge and limit notices would appear)."""
121
+ return page.evaluate(NOTICES_JS, NOTICE_SELECTOR)
122
+
123
+
124
+ def classify_notices(notices: list, seen: set, ignore=()) -> tuple[list, list]:
125
+ """(markers, notes) for a list of notices. Throttle or challenge wording becomes `challenge_marker` (fail closed:
126
+ the run stops); every notice not seen before becomes a note with its structure, so the skin can get a real
127
+ selector once one has been observed. `seen` is updated."""
128
+ markers, notes = [], []
129
+ for n in notices:
130
+ text = n.get("text") or n.get("aria_label") or ""
131
+ if THROTTLE.search(text) and "challenge_marker" not in markers: # checked before `ignore`: never muted
132
+ markers.append("challenge_marker")
133
+ if any(s in text.lower() for s in ignore): # skin edge.notices_ignore
134
+ continue
135
+ key = (n.get("role"), n.get("testid"), text)
136
+ if key not in seen:
137
+ seen.add(key)
138
+ notes.append(f"page notice ({n.get('role')}{', testid ' + n['testid'] if n.get('testid') else ''}): "
139
+ f"{text[:120]}")
140
+ return markers, notes
@@ -25,11 +25,10 @@ from pathlib import Path
25
25
  import yaml
26
26
 
27
27
  from .backend import BackendError
28
+ from .backends.edge_common import THROTTLE # one throttle pattern for calibration and the backend
28
29
 
29
30
  STORE = Path.home() / ".copuppet" / "limits.yaml"
30
31
  METHOD = 2 # 2: prompt cap by doubling and bisection, recall filler at 80% of the cap
31
- THROTTLE = re.compile(r"(?i)(too many (requests|messages)|try again later|reached (the|your) (daily |message )?limit|"
32
- r"slow down|unusual activity|verify (that )?you are (a )?human)")
33
32
  WORDS = ["ledger", "amount", "invoice", "north", "river", "column", "status", "pending", "review", "folder", "branch", "archive", "meter", "client", "record", "field", "window", "value", "report", "export", "label", "budget", "sample", "margin", "vendor", "ticket", "batch"]
34
33
 
35
34
 
@@ -135,6 +135,7 @@ def ask(skin, a) -> int:
135
135
  def relay_cmd(a) -> int:
136
136
  import json
137
137
  import time
138
+
138
139
  from .relay import Relay, render
139
140
  try:
140
141
  rl = Relay.attach(a.dir)
@@ -99,8 +99,11 @@ class Ledger:
99
99
  "code_blocks": len(reply.code_blocks), "type_s": reply.type_s,
100
100
  "first_token_s": reply.first_token_s, "gen_s": reply.gen_s, "markers": reply.markers,
101
101
  "model_label": reply.model_label, **extra}
102
+ if reply.notes:
103
+ data["notes"] = list(reply.notes)
102
104
  if self.keep_text:
103
105
  data["text"] = reply.text
106
+ data["code_text"] = list(reply.code_blocks) # issue #1: keep the raw read-back for diagnosis
104
107
  return self.append("reply", **data)
105
108
 
106
109
  def executed(self, step_id: str) -> bool:
@@ -10,9 +10,10 @@ The catalog is plain data: {name: {"args": {arg: type_name}, "required": [...],
10
10
  from __future__ import annotations
11
11
 
12
12
  import json
13
- from . import tokens
14
13
  from dataclasses import dataclass, field
15
14
 
15
+ from . import tokens
16
+
16
17
  TYPES = {"str": str, "int": int, "float": (int, float), "bool": bool, "list": list, "dict": dict}
17
18
  EFFECTS = ("read", "write-local", "external")
18
19
 
@@ -145,7 +145,10 @@ class Relay:
145
145
  for ch in ([channel] if channel else CHANNELS):
146
146
  for q in sorted((self.run / ch).glob("*.q.json")):
147
147
  if not q.with_name(q.name.replace(".q.json", ".a.json")).exists():
148
- item = _read(q)
148
+ try:
149
+ item = _read(q)
150
+ except (FileNotFoundError, ValueError): # consumed (moved to done/) or mid-write: skip
151
+ continue
149
152
  item.pop("token", None) # the stand-in never needs to see it
150
153
  out.append(item)
151
154
  return sorted(out, key=lambda i: i["id"])
@@ -160,7 +163,10 @@ class Relay:
160
163
  a = q.with_name(f"{qid}.a.json")
161
164
  if a.exists():
162
165
  raise BackendError(f"relay item {qid} is already answered")
163
- data = {"id": qid, "token": _read(q)["token"], "text": text}
166
+ try:
167
+ data = {"id": qid, "token": _read(q)["token"], "text": text}
168
+ except FileNotFoundError: # consumed in the meantime
169
+ raise BackendError(f"no open relay item {qid}") from None
164
170
  for k, v in (meta or {}).items():
165
171
  if k not in META or not isinstance(v, META[k]):
166
172
  raise BackendError(f"unknown or mistyped answer field {k!r}; known: {', '.join(META)}")
@@ -78,6 +78,9 @@ def load(path: str | Path | None = None) -> Skin:
78
78
  raise SkinError(f"{f}: edge.signin.click_button must be true or false")
79
79
  if signin.get("click_button") and not signin.get("button"):
80
80
  raise SkinError(f"{f}: edge.signin.click_button is on, so edge.signin.button must name the element")
81
+ ignore = section.get("notices_ignore") or []
82
+ if not isinstance(ignore, list) or not all(isinstance(x, str) and x.strip() for x in ignore):
83
+ raise SkinError(f"{f}: edge.notices_ignore must be a list of non-empty texts")
81
84
  for i, rule in enumerate(section.get("dismiss") or []):
82
85
  if not isinstance(rule, dict) or not rule.get("when") or not rule.get("click"):
83
86
  raise SkinError(f"{f}: edge.dismiss[{i}] needs both 'when' (the modal) and 'click' (the button)")
@@ -0,0 +1,34 @@
1
+ """Issue #1: the code-block read-back must agree across reads and with the reply's own text."""
2
+ from copuppet.backends import edge as edge_mod
3
+ from copuppet.backends.edge import EdgeBackend
4
+
5
+ GOOD = '{"nonce":"2725f329","step_id":"s2","action":"read_file","args":{"path":"README.md"}}'
6
+ REPLY_TEXT = "JSON\n" + GOOD
7
+
8
+
9
+ def backend_with_reads(reads, monkeypatch):
10
+ b = EdgeBackend.__new__(EdgeBackend) # no browser: only the read-back logic is under test
11
+ b.notes = []
12
+ seq = list(reads)
13
+ b._code_blocks = lambda reply: seq.pop(0) if len(seq) > 1 else seq[0]
14
+ monkeypatch.setattr(edge_mod.time, "sleep", lambda s: None)
15
+ return b
16
+
17
+
18
+ def test_a_transient_extra_line_is_read_again(monkeypatch):
19
+ b = backend_with_reads([[GOOD + "\n" + GOOD[:20]], [GOOD], [GOOD]], monkeypatch)
20
+ assert b._stable_code_blocks(object(), REPLY_TEXT) == [GOOD] and b.notes == []
21
+
22
+
23
+ def test_a_lasting_difference_is_noted_not_patched(monkeypatch):
24
+ bad = GOOD + "\nextra"
25
+ b = backend_with_reads([[bad]], monkeypatch)
26
+ assert b._stable_code_blocks(object(), REPLY_TEXT) == [bad]
27
+ assert any("issue #1" in n for n in b.notes)
28
+
29
+
30
+ def test_multiline_blocks_match_with_collapsed_whitespace(monkeypatch):
31
+ block = '{\n "a": 1,\n "b": [1, 2]\n}'
32
+ b = backend_with_reads([[block]], monkeypatch)
33
+ assert b._stable_code_blocks(object(), "JSON\n{\n \"a\": 1,\n \"b\": [1, 2]\n}\nCopy") == [block]
34
+ assert b.notes == []
@@ -0,0 +1,49 @@
1
+ """#3: page notices become notes once each; throttle or challenge wording becomes a challenge marker."""
2
+ from copuppet.backends.edge_common import THROTTLE, classify_notices
3
+
4
+
5
+ def test_a_throttle_notice_is_a_challenge_marker_and_a_note():
6
+ seen = set()
7
+ markers, notes = classify_notices([{"role": "alert", "testid": "banner", "text": "Too many requests. Try again later."}], seen)
8
+ assert markers == ["challenge_marker"]
9
+ assert notes and "testid banner" in notes[0] and "Too many requests" in notes[0]
10
+
11
+
12
+ def test_each_notice_is_reported_once():
13
+ seen = set()
14
+ n = [{"role": "alert", "testid": "", "text": "Something went wrong"}]
15
+ assert classify_notices(n, seen)[1] and classify_notices(n, seen) == ([], [])
16
+
17
+
18
+ def test_ordinary_notices_are_noted_but_do_not_stop():
19
+ markers, notes = classify_notices([{"role": "live:assertive", "text": "Response copied"}], set())
20
+ assert markers == [] and len(notes) == 1
21
+
22
+
23
+ def test_throttle_wording_variants():
24
+ for text in ("You've reached your daily limit", "Please verify you are a human", "Are you a robot?",
25
+ "unusual activity detected", "complete the CAPTCHA"):
26
+ assert THROTTLE.search(text), text
27
+ assert not THROTTLE.search("Here is the summary you asked for.")
28
+
29
+
30
+ def test_ignored_notices_are_muted_but_never_a_challenge():
31
+ ign = ("use the up or down arrow keys", "too many")
32
+ markers, notes = classify_notices([{"role": "live:assertive", "text": "Use the Up or Down arrow keys to open"}],
33
+ set(), ignore=ign)
34
+ assert (markers, notes) == ([], [])
35
+ markers, _ = classify_notices([{"role": "alert", "text": "Too many requests"}], set(), ignore=ign)
36
+ assert markers == ["challenge_marker"] # an ignore entry can never mute a challenge
37
+
38
+
39
+ def test_skin_validates_notices_ignore(tmp_path):
40
+ import pytest
41
+ from copuppet.skin import SkinError, load
42
+ base = (tmp_path / "skin.yaml")
43
+ text = ("format: 1\nname: t\nbackends:\n edge:\n url: https://example.invalid/\n selectors:\n"
44
+ " input: a\n send: b\n reply: c\n busy: d\n notices_ignore: {ignore}\n")
45
+ base.write_text(text.format(ignore='["hint"]'), encoding="utf-8")
46
+ assert load(str(tmp_path)).backends["edge"]["notices_ignore"] == ["hint"]
47
+ base.write_text(text.format(ignore='"hint"'), encoding="utf-8")
48
+ with pytest.raises(SkinError, match="notices_ignore"):
49
+ load(str(tmp_path))
@@ -7,6 +7,7 @@ import threading
7
7
  import time
8
8
 
9
9
  import pytest
10
+ from test_driver import planner
10
11
 
11
12
  from copuppet import tokens
12
13
  from copuppet.backend import BackendError
@@ -16,8 +17,6 @@ from copuppet.policy import Policy
16
17
  from copuppet.relay import Relay, RelayBackend, ReplayBackend, code_blocks, person, render
17
18
  from copuppet.session import Limits, Session, SessionStop
18
19
 
19
- from test_driver import planner
20
-
21
20
  ENV = {**os.environ, "PYTHONPATH": "src"}
22
21
 
23
22
 
@@ -33,11 +32,14 @@ def stand_in(relay, copilot, people=None, stop=None, meta=None):
33
32
  side = Relay.attach(relay.run.parent)
34
33
  while not stop.is_set():
35
34
  for item in side.pending():
36
- if item["channel"] == "copilot":
37
- turn += 1
38
- side.answer(item["id"], copilot(item["text"], turn), (meta or {}).get(turn))
39
- else:
40
- side.answer(item["id"], people(item))
35
+ try:
36
+ if item["channel"] == "copilot":
37
+ side.answer(item["id"], copilot(item["text"], turn + 1), (meta or {}).get(turn + 1))
38
+ turn += 1
39
+ else:
40
+ side.answer(item["id"], people(item))
41
+ except BackendError: # consumed or answered meanwhile: the next poll decides
42
+ pass
41
43
  time.sleep(0.05)
42
44
  t = threading.Thread(target=loop, daemon=True)
43
45
  t.start()
@@ -184,3 +186,18 @@ def test_replay_detects_divergence(tmp_path):
184
186
  assert res.status == "stopped" and "diverged" in res.reason
185
187
  tokens.seed(None)
186
188
  _ = render, SessionStop
189
+
190
+
191
+ def test_pending_skips_a_question_consumed_mid_read(tmp_path, monkeypatch):
192
+ import copuppet.relay as relay_mod
193
+ relay = Relay.start(tmp_path, seed=1)
194
+ relay.post("copilot", "a", chat_id=1, chat_turn=1)
195
+ qid2 = relay.post("copilot", "b", chat_id=1, chat_turn=2)
196
+ real = relay_mod._read
197
+
198
+ def racing(path):
199
+ if path.name.startswith("000001.q"):
200
+ raise FileNotFoundError(path) # moved to done/ between glob and read
201
+ return real(path)
202
+ monkeypatch.setattr(relay_mod, "_read", racing)
203
+ assert [i["id"] for i in Relay.attach(tmp_path).pending()] == [qid2]
@@ -17,6 +17,28 @@ import sys
17
17
  import time
18
18
  from pathlib import Path
19
19
 
20
+ try:
21
+ from copuppet.backends.edge_common import (
22
+ BROWSER_ARGS,
23
+ LOGIN_HOSTS,
24
+ ProfileBusy,
25
+ acquire_lock,
26
+ mark_clean_exit,
27
+ release_lock,
28
+ visible_dialogs,
29
+ )
30
+ except ImportError: # run from a checkout without installing
31
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
32
+ from copuppet.backends.edge_common import (
33
+ BROWSER_ARGS,
34
+ LOGIN_HOSTS,
35
+ ProfileBusy,
36
+ acquire_lock,
37
+ mark_clean_exit,
38
+ release_lock,
39
+ visible_dialogs,
40
+ )
41
+
20
42
  PROMPT_CANDIDATES = "textarea, [contenteditable='true'], [role='textbox'], input[type='text']"
21
43
  INTERESTING = ("textarea, [contenteditable='true'], [role='textbox'], input, button, [role='button'], "
22
44
  "[aria-live], [role='log'], [role='article'], [role='status'], [data-testid], [aria-busy]")
@@ -75,7 +97,6 @@ REPLY_JS = r"""
75
97
 
76
98
 
77
99
  SIGNIN_TEXT = ("sign in", "log in", "aanmelden", "se connecter", "anmelden")
78
- LOGIN_HOSTS = ("login.live.com", "login.microsoftonline.com", "login.microsoft.com", "account.microsoft.com")
79
100
 
80
101
 
81
102
  def signin_needed(page) -> str:
@@ -93,38 +114,6 @@ def signin_needed(page) -> str:
93
114
  return ""
94
115
 
95
116
 
96
- BROWSER_ARGS = ["--hide-crash-restore-bubble", "--no-first-run", "--no-default-browser-check"]
97
- DIALOG_SELECTOR = "[role='dialog'], [role='alertdialog'], [aria-modal='true']"
98
-
99
-
100
- def mark_clean_exit(profile: Path) -> None:
101
- """Edge shows a 'Restore pages' bubble (browser UI, not page DOM, so unclickable from Playwright) after a run
102
- that did not close cleanly. Mark the profile as cleanly closed before launch; harmless when already clean."""
103
- pref = profile / "Default" / "Preferences"
104
- try:
105
- data = json.loads(pref.read_text(encoding="utf-8"))
106
- except (OSError, ValueError):
107
- return
108
- prof = data.setdefault("profile", {})
109
- if prof.get("exit_type") != "Normal" or prof.get("exited_cleanly") is not True:
110
- prof["exit_type"], prof["exited_cleanly"] = "Normal", True
111
- pref.write_text(json.dumps(data), encoding="utf-8")
112
-
113
-
114
- def visible_dialogs(page) -> list:
115
- """Visible page modals, each with its role, label and the labels of its buttons (structure only)."""
116
- return page.evaluate(r"""
117
- (sel) => [...document.querySelectorAll(sel)].filter(el => {
118
- const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0 && getComputedStyle(el).visibility !== 'hidden';
119
- }).map(el => ({
120
- role: el.getAttribute('role') || '', aria_label: (el.getAttribute('aria-label') || '').slice(0, 80),
121
- testid: el.getAttribute('data-testid') || '', id: el.id || '',
122
- buttons: [...el.querySelectorAll("button, [role='button'], a")].map(b =>
123
- ((b.getAttribute('aria-label') || b.innerText || '').trim().replace(/\s+/g, ' ')).slice(0, 40)).filter(Boolean).slice(0, 8),
124
- }))
125
- """, DIALOG_SELECTOR)
126
-
127
-
128
117
  def handle_dialogs(page, rules: list, reported: set) -> None:
129
118
  """Report each new modal once; dismiss only through explicit rules (skin edge.dismiss): when `when` matches a
130
119
  visible element, click the first visible match of `click`. Unknown dialogs are never clicked."""
@@ -344,10 +333,22 @@ def main(argv=None) -> int:
344
333
  return 2
345
334
  out = Path(a.out).expanduser()
346
335
  out.mkdir(parents=True, exist_ok=True)
347
- Path(a.profile).expanduser().mkdir(parents=True, exist_ok=True)
336
+ profile = Path(a.profile).expanduser()
337
+ try:
338
+ lock = acquire_lock(profile) # never open the profile a copuppet run is using (#4)
339
+ except ProfileBusy as e:
340
+ print(f"discover_edge: {e}", file=sys.stderr)
341
+ return 2
342
+ try:
343
+ return _discover(a, out, profile, sync_playwright)
344
+ finally:
345
+ release_lock(lock)
346
+
347
+
348
+ def _discover(a, out, profile, sync_playwright) -> int:
348
349
  with sync_playwright() as p:
349
- mark_clean_exit(Path(a.profile).expanduser())
350
- ctx = p.chromium.launch_persistent_context(str(Path(a.profile).expanduser()), channel="msedge",
350
+ mark_clean_exit(profile)
351
+ ctx = p.chromium.launch_persistent_context(str(profile), channel="msedge",
351
352
  headless=False, viewport=None, args=BROWSER_ARGS)
352
353
  page = ctx.pages[0] if ctx.pages else ctx.new_page()
353
354
  page.goto(a.url, wait_until="domcontentloaded")
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
@@ -13,8 +13,8 @@ import time
13
13
  from dataclasses import dataclass, field
14
14
 
15
15
  from . import actions as A
16
- from .protocol import ProtocolError, contract_text, new_nonce, parse_action
17
16
  from .backend import BackendError
17
+ from .protocol import ProtocolError, contract_text, new_nonce, parse_action
18
18
 
19
19
 
20
20
  def _paths(args_json: str) -> str:
File without changes
@@ -19,10 +19,10 @@ from __future__ import annotations
19
19
 
20
20
  import dataclasses
21
21
  import re
22
- from . import tokens
23
22
  import statistics
24
23
  from dataclasses import dataclass, field
25
24
 
25
+ from . import tokens
26
26
  from .backend import BackendError
27
27
 
28
28
 
File without changes
File without changes