copuppet 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,573 @@
1
+ """Copilot in Microsoft Edge, via Playwright on the installed Edge (channel "msedge": no browser download) with a
2
+ persistent profile (sign-in once, or through Windows single sign-on).
3
+
4
+ Contract v2 (docs/model.md): probe(), new_chat(temporary), send(chat, prompt), ask(), close(). Fail closed: a send
5
+ only happens when the page proves a temporary chat (when one was asked for), a signed-in session and the chat's
6
+ model label. Everything page-specific comes from the skin.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import os
12
+ import re
13
+ import sys
14
+ import time
15
+ from pathlib import Path
16
+
17
+ 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"
23
+
24
+
25
+ class ChallengeError(BackendError):
26
+ """A challenge or throttle marker: stop; no display fallback, no retry (I12)."""
27
+
28
+
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
+ class EdgeBackend:
75
+ name = "edge"
76
+
77
+ def __init__(self, config: dict):
78
+ self.config = config
79
+ self.sel = config["selectors"]
80
+ t = config.get("timeouts") or {}
81
+ self.reply_timeout = float(t.get("reply_seconds", 120))
82
+ self.start_timeout = float(t.get("start_seconds", 15))
83
+ self.settle = float(t.get("settle_seconds", 1.5))
84
+ self.rerender = float(t.get("rerender_seconds", 2.5))
85
+ self.signin = config.get("signin") or {}
86
+ self.dismiss = config.get("dismiss") or []
87
+ self.profile = Path(str(config.get("profile_dir") or "~/.copuppet/edge-profile")).expanduser()
88
+ self.type_delay = int(config.get("type_delay_ms", 5))
89
+ self.display = str(config.get("display", "auto")) # auto | headless | offscreen | visible
90
+ self.input_mode = str(config.get("input_mode", "auto")) # auto (paste, then type) | paste | type
91
+ self.mode_used = ""
92
+ self._pw = self._ctx = self.page = None
93
+ self._lock = None
94
+ self._chat_seq = 0
95
+ self.notes: list[str] = []
96
+ self.chat_notes: list[str] = [] # notes from new_chat, carried into the next send's Reply
97
+ self.verbose = bool(config.get("_verbose"))
98
+
99
+ def log(self, msg: str) -> None:
100
+ if self.verbose:
101
+ print(f"copuppet[edge] {time.strftime('%H:%M:%S')} {msg}", file=sys.stderr, flush=True)
102
+
103
+ # ---------- readiness ----------
104
+ def ready(self) -> list[str]:
105
+ problems = []
106
+ try:
107
+ import playwright # noqa: F401
108
+ except ImportError:
109
+ problems.append('Playwright is not installed; next: pip install --user "copuppet[edge]"')
110
+ if any(str(v).startswith(("TODO", "REPLACE")) for v in self.sel.values()):
111
+ problems.append("the skin's edge selectors are placeholders; next: run tools/discover_edge.py")
112
+ missing = [k for k in ("temporary_on", "signed_in") if not self.sel.get(k)]
113
+ if missing:
114
+ problems.append(f"the skin has no {missing} selector(s), so the page state cannot be proven (fail closed); "
115
+ "next: run tools/discover_edge.py --states")
116
+ return problems
117
+
118
+ # ---------- lock + browser lifecycle ----------
119
+ def _acquire_lock(self) -> None:
120
+ self.profile.mkdir(parents=True, exist_ok=True)
121
+ lock = self.profile / LOCK_NAME
122
+ 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
131
+
132
+ DISPLAY_ARGS = {
133
+ "headless": [],
134
+ "offscreen": ["--window-position=-32000,-32000", "--window-size=1280,900"],
135
+ "visible": [],
136
+ }
137
+
138
+ def _launch(self, mode: str) -> None:
139
+ from playwright.sync_api import sync_playwright
140
+ mark_clean_exit(self.profile)
141
+ if self._pw is None:
142
+ self._pw = sync_playwright().start()
143
+ self._ctx = self._pw.chromium.launch_persistent_context(
144
+ str(self.profile), channel="msedge", headless=(mode == "headless"),
145
+ viewport=None if mode != "headless" else {"width": 1280, "height": 900},
146
+ args=BROWSER_ARGS + self.DISPLAY_ARGS[mode])
147
+ self.page = self._ctx.pages[0] if self._ctx.pages else self._ctx.new_page()
148
+ self.mode_used = mode
149
+ self.log(f"Edge started ({mode}) with profile {self.profile}")
150
+
151
+ def _relaunch(self, mode: str) -> None:
152
+ if self._ctx is not None:
153
+ self._ctx.close()
154
+ self._ctx = self.page = None
155
+ self._launch(mode)
156
+
157
+ def _open(self) -> None:
158
+ if self.page is not None:
159
+ return
160
+ problems = self.ready()
161
+ if problems:
162
+ raise BackendError("; ".join(problems))
163
+ self._acquire_lock()
164
+ self._launch("headless" if self.display == "auto" else self.display)
165
+
166
+ def _fallback_modes(self) -> list[str]:
167
+ """Display modes still to try after the current one failed (auto only): headless -> offscreen -> visible.
168
+ Visible is last because it is the only mode in which a person can finish a login by hand."""
169
+ order = ["headless", "offscreen", "visible"]
170
+ if self.display != "auto" or self.mode_used not in order:
171
+ return []
172
+ return order[order.index(self.mode_used) + 1:]
173
+
174
+ def close(self) -> None:
175
+ try:
176
+ if self._ctx is not None:
177
+ self._ctx.close() # graceful: no 'Restore pages' next time
178
+ finally:
179
+ if self._pw is not None:
180
+ self._pw.stop()
181
+ if self._lock is not None:
182
+ try:
183
+ self._lock.unlink()
184
+ except OSError:
185
+ pass
186
+ self._pw = self._ctx = self.page = self._lock = None
187
+
188
+ # ---------- page state ----------
189
+ def _visible(self, key: str) -> bool:
190
+ s = self.sel.get(key)
191
+ return bool(s) and first_visible(self.page.locator(s)) is not None
192
+
193
+ def _text_of(self, key: str) -> str:
194
+ s = self.sel.get(key)
195
+ el = first_visible(self.page.locator(s)) if s else None
196
+ return normalise(el.inner_text()) if el is not None else ""
197
+
198
+ def _host(self) -> str:
199
+ return self.page.url.split("/")[2] if "://" in self.page.url else ""
200
+
201
+ def probe(self) -> Probe:
202
+ self._open()
203
+ markers = [k for k in ("limit_marker", "error_marker", "challenge_marker") if self._visible(k)]
204
+ if any(h in self._host() for h in LOGIN_HOSTS):
205
+ markers.append("login_page")
206
+ return Probe(temporary=self._visible("temporary_on"), signed_in=self._visible("signed_in"),
207
+ model_label=self._text_of("model"), markers=markers,
208
+ reply_count=self.page.locator(self.sel["reply"]).count(), url=self.page.url[:120])
209
+
210
+ def _dismiss_modals(self) -> None:
211
+ for rule in self.dismiss:
212
+ try:
213
+ if self.page.locator(rule["when"]).first.is_visible(timeout=300):
214
+ b = first_visible(self.page.locator(rule["click"]))
215
+ if b is not None:
216
+ b.click()
217
+ self.notes.append(f"dismissed a modal by rule ({rule['when']})")
218
+ time.sleep(0.5)
219
+ except Exception:
220
+ pass
221
+
222
+ def _unknown_modal(self) -> str:
223
+ try:
224
+ for d in self.page.locator(DIALOG_SELECTOR).all():
225
+ if d.is_visible():
226
+ return (d.get_attribute("aria-label") or d.get_attribute("data-testid") or "unnamed dialog")[:60]
227
+ except Exception:
228
+ pass
229
+ return ""
230
+
231
+ def _signin_button_visible(self) -> bool:
232
+ button = self.signin.get("button")
233
+ return bool(button and first_visible(self.page.locator(button)) is not None)
234
+
235
+ def _wait_usable(self, seconds: float) -> None:
236
+ """Until the prompt box is visible AND the session is proven signed in; clicks the site's Sign in button
237
+ once when the skin allows it. Raises with a next step otherwise."""
238
+ deadline, clicked, said = time.time() + seconds, False, set()
239
+
240
+ def once(key, msg):
241
+ if key not in said:
242
+ said.add(key)
243
+ self.log(msg)
244
+ while time.time() < deadline:
245
+ self._dismiss_modals()
246
+ if self._visible("challenge_marker"):
247
+ raise ChallengeError("a challenge or throttle marker is visible; stopping, never retrying through "
248
+ "it (I12)")
249
+ if self._visible("input") and self._visible("signed_in"):
250
+ once("ready", f"signed in, prompt box visible ({self.page.url[:60]})")
251
+ return
252
+ if any(h in self._host() for h in LOGIN_HOSTS):
253
+ once("login", f"on the login page ({self._host()}); waiting for single sign-on or the person")
254
+ elif self._signin_button_visible():
255
+ if self.signin.get("click_button") and not clicked:
256
+ first_visible(self.page.locator(self.signin["button"])).click()
257
+ clicked = True
258
+ self.notes.append("clicked the site's Sign in button (skin signin.click_button)")
259
+ self.log("clicked the site's Sign in button")
260
+ else:
261
+ once("signin", "sign-in needed; waiting for the person to sign in in the Edge window")
262
+ else:
263
+ once("wait", f"waiting for a signed-in prompt box ({self.page.url[:60]})")
264
+ time.sleep(1)
265
+ modal = self._unknown_modal()
266
+ if modal:
267
+ raise BackendError(f"a page modal blocks the chat ('{modal}'); next: add an edge.dismiss rule to the skin")
268
+ if self._signin_button_visible() or any(h in self._host() for h in LOGIN_HOSTS):
269
+ if self.mode_used != "visible":
270
+ raise BackendError(f"not signed in ({self.mode_used}: single sign-on did not complete); next: run "
271
+ "once with --display visible and sign in by hand")
272
+ raise BackendError("not signed in; next: sign in in the copuppet Edge window (or enable "
273
+ "edge.signin.click_button in the skin)")
274
+ raise BackendError("no signed-in prompt box appeared; next: re-run tools/discover_edge.py --states")
275
+
276
+ # ---------- chats ----------
277
+ def new_chat(self, *, temporary: bool = True) -> ChatHandle:
278
+ """Fresh page, signed in, and (by default) a PROVEN temporary chat: the toggle is clicked only when it is
279
+ off, then aria-pressed must read true (P5)."""
280
+ self._open()
281
+ while True:
282
+ try:
283
+ self.page.goto(self.config["url"], wait_until="domcontentloaded")
284
+ self._wait_usable(self.reply_timeout if self.mode_used == "visible" else 45)
285
+ break
286
+ except ChallengeError:
287
+ raise # I12: a challenge is not a display problem
288
+ except BackendError as e:
289
+ rest = self._fallback_modes()
290
+ if not rest:
291
+ raise
292
+ self.log(f"{self.mode_used} mode failed ({e}); falling back to {rest[0]}")
293
+ self.notes.append(f"display fallback {self.mode_used} -> {rest[0]}: {e}")
294
+ self._relaunch(rest[0])
295
+ if temporary:
296
+ if not self._visible("temporary_on"):
297
+ toggle = first_visible(self.page.locator(self.sel["temporary_chat"]))
298
+ if toggle is None:
299
+ raise BackendError("the temporary-chat control is not visible; refusing a normal chat (fail "
300
+ "closed); next: re-run tools/discover_edge.py --states")
301
+ toggle.click()
302
+ deadline = time.time() + 10
303
+ while time.time() < deadline and not self._visible("temporary_on"):
304
+ time.sleep(0.3)
305
+ if not self._visible("temporary_on"):
306
+ raise BackendError("temporary chat could not be proven after switching it on; refusing to send")
307
+ self._wait_usable(30)
308
+ if not self._wait_editor_stable(): # the toggle re-renders the editor once more
309
+ self.notes.append("the editor did not settle within 6 s after the chat switch")
310
+ self._chat_seq += 1
311
+ p = self.probe()
312
+ self.log(f"new {'temporary ' if temporary else ''}chat #{self._chat_seq} (model '{p.model_label}')")
313
+ self.chat_notes = list(self.notes)
314
+ return ChatHandle(chat_id=self._chat_seq, started_at=time.time(), temporary=temporary,
315
+ model_label=p.model_label)
316
+
317
+ def _assert_preconditions(self, chat: ChatHandle) -> Probe:
318
+ p = self.probe()
319
+ if "login_page" in p.markers or not p.signed_in:
320
+ raise BackendError("signed out mid-run; next: sign in in the copuppet Edge window, then rerun")
321
+ if chat.temporary and not p.temporary:
322
+ raise BackendError("the chat is no longer temporary; refusing to send (fail closed)")
323
+ if not p.model_label:
324
+ raise BackendError("the model label is unknown (empty); refusing to send (I9)")
325
+ if chat.chat_id != self._chat_seq:
326
+ raise BackendError(f"chat #{chat.chat_id} is no longer the open chat (#{self._chat_seq}); refusing to "
327
+ "send into another chat")
328
+ deadline = time.time() + 10
329
+ while self._visible("busy") and time.time() < deadline: # I11: never send while an answer is running
330
+ time.sleep(0.3)
331
+ if self._visible("busy"):
332
+ raise BackendError("an earlier answer is still running; refusing to send into it (I11)")
333
+ if p.model_label != chat.model_label:
334
+ raise BackendError(f"the model changed under the chat ('{chat.model_label}' -> '{p.model_label}'); "
335
+ "next: start a new chat and recalibrate (I9)")
336
+ if "challenge_marker" in p.markers:
337
+ raise BackendError("a challenge or throttle marker is visible; stopping, never retrying through it")
338
+ return p
339
+
340
+ def _wait_editor_stable(self, seconds: float = 6.0, hold: float = 1.0) -> bool:
341
+ """The editor is re-rendered some time after a chat switch; text entered before that is silently dropped.
342
+ Mark the current editor node and wait until the SAME node has survived `hold` seconds."""
343
+ deadline = time.time() + seconds
344
+ mark = f"cp{int(time.time() * 1000)}"
345
+ marked_at = None
346
+ while time.time() < deadline:
347
+ el = first_visible(self.page.locator(self.sel["input"]))
348
+ if el is None:
349
+ time.sleep(0.2)
350
+ continue
351
+ present = self.page.locator(f"[data-copuppet-mark='{mark}']").count() > 0
352
+ if not present:
353
+ try:
354
+ el.evaluate(f"e => e.setAttribute('data-copuppet-mark', '{mark}')")
355
+ except Exception:
356
+ pass
357
+ marked_at = time.time()
358
+ elif time.time() - marked_at >= hold:
359
+ return True
360
+ time.sleep(0.2)
361
+ return False
362
+
363
+ def _editor_text(self) -> str:
364
+ el = first_visible(self.page.locator(self.sel["input"]))
365
+ return normalise(el.inner_text()) if el is not None else ""
366
+
367
+ def _type_prompt(self, prompt: str) -> None:
368
+ """Newline-safe: a newline in keyboard.type presses Enter and would submit fragments, so lines are typed
369
+ with Shift+Enter between them."""
370
+ lines = prompt.replace("\r\n", "\n").split("\n")
371
+ for i, line in enumerate(lines):
372
+ if line:
373
+ self.page.keyboard.type(line, delay=self.type_delay)
374
+ if i < len(lines) - 1:
375
+ self.page.keyboard.press("Shift+Enter")
376
+
377
+ def _clear_editor(self, box) -> None:
378
+ box.click()
379
+ self.page.keyboard.press("Control+A")
380
+ self.page.keyboard.press("Delete")
381
+
382
+ def _enter_text(self, prompt: str) -> tuple[str, str]:
383
+ """Fast path first: insert the whole text at once (like a paste), read back, compare. Fallback: real
384
+ keystrokes. Lost input (the editor re-rendered under us: empty read-back) is retried with a short backoff
385
+ up to `rerender_seconds`, instead of a fixed wait before every send."""
386
+ want = normalise(prompt)
387
+ modes = {"auto": ["paste", "type"], "paste": ["paste"], "type": ["type"]}.get(self.input_mode, ["paste", "type"])
388
+ deadline = time.time() + self.rerender
389
+ accepted = ""
390
+ for mode in modes:
391
+ delay = 0.2
392
+ while True:
393
+ box = first_visible(self.page.locator(self.sel["input"]))
394
+ if box is None:
395
+ raise BackendError("the prompt box is gone; next: re-run tools/discover_edge.py")
396
+ self._clear_editor(box)
397
+ if mode == "paste":
398
+ self.page.keyboard.insert_text(prompt.replace("\r\n", "\n"))
399
+ else:
400
+ self._type_prompt(prompt)
401
+ accepted = self._editor_text()
402
+ if accepted == want:
403
+ return accepted, mode
404
+ if accepted or time.time() >= deadline:
405
+ break # wrong but not empty: this method changes the text; try the next one
406
+ time.sleep(delay) # empty: input lost during a re-render; back off and retry
407
+ delay = min(delay * 2, 1.0)
408
+ return accepted, ""
409
+
410
+ def _last_reply(self):
411
+ replies = self.page.locator(self.sel["reply"])
412
+ return replies.nth(replies.count() - 1) if replies.count() else None
413
+
414
+ def _code_blocks(self, reply) -> list[str]:
415
+ """Code blocks of one reply, read from its DOM: each `code` element's `code_text` part via inner_text (one
416
+ div per line, so text_content would drop the line breaks; the block's own text also holds the language
417
+ label and button labels)."""
418
+ if reply is None or not self.sel.get("code"):
419
+ return []
420
+ out = []
421
+ for block in reply.locator(self.sel["code"]).all():
422
+ part = block.locator(self.sel["code_text"]).first if self.sel.get("code_text") else block
423
+ out.append(ZERO_WIDTH.sub("", part.inner_text() if part.count() else "").strip("\n"))
424
+ return out
425
+
426
+ def _mark_seen(self, mark: str) -> list:
427
+ """Give every existing reply and user-message node its own id mark; returns [id, text] of the reply nodes
428
+ that held text (I11)."""
429
+ sels = [self.sel["reply"]] + ([self.sel["user_message"]] if self.sel.get("user_message") else [])
430
+ return self.page.evaluate(
431
+ """([sels, replySel, m]) => {
432
+ let i = 0;
433
+ sels.forEach(s => document.querySelectorAll(s).forEach(e => e.setAttribute('data-copuppet-seen', m + '-' + (i++))));
434
+ const norm = (s) => (s || '').replace(/[\\u200b\\u200c\\u200d\\u2060\\ufeff]/g, '').replace(/\\s+/g, ' ').trim();
435
+ return [...document.querySelectorAll(replySel)]
436
+ .map(e => [e.getAttribute('data-copuppet-seen'), norm(e.innerText)])
437
+ .filter(x => x[1].length > 0);
438
+ }""", [sels, self.sel["reply"], mark])
439
+
440
+ def _bind(self, kept: list) -> dict:
441
+ """I11 binding after the answer, from live behaviour: Copilot re-renders earlier reply nodes (an identical,
442
+ unmarked copy replaces one) and drops the oldest from the DOM as the chat grows (virtualisation). So:
443
+ - a missing marked node with an identical unmarked copy is a re-render (the copy is not new);
444
+ - a missing marked node without a copy is virtualised away (noted, not a failure: it cannot pose as new);
445
+ - a node that is NEW must come after this turn's own user message in document order;
446
+ Bound means exactly one new node, after this turn's user message (when user messages are known)."""
447
+ return self.page.evaluate(
448
+ """([replySel, userSel, kept]) => {
449
+ const norm = (s) => (s || '').replace(/[\\u200b\\u200c\\u200d\\u2060\\ufeff]/g, '').replace(/\\s+/g, ' ').trim();
450
+ document.querySelectorAll('[data-copuppet-fresh]').forEach(e => e.removeAttribute('data-copuppet-fresh'));
451
+ const unmarked = [...document.querySelectorAll(replySel)].filter(e => !e.hasAttribute('data-copuppet-seen'))
452
+ .map(e => ({el: e, text: norm(e.innerText), used: false}));
453
+ const missing = kept.filter(([id]) => !document.querySelector(`[data-copuppet-seen='${id}']`));
454
+ let copies = 0;
455
+ for (const [, text] of missing) {
456
+ const copy = unmarked.find(u => !u.used && u.text === text);
457
+ if (copy) { copy.used = true; copies++; }
458
+ }
459
+ let anchor = null;
460
+ if (userSel) {
461
+ const mine = [...document.querySelectorAll(userSel)].filter(e => !e.hasAttribute('data-copuppet-seen'));
462
+ anchor = mine.length ? mine[mine.length - 1] : null;
463
+ }
464
+ const after = (el) => !anchor || (anchor.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
465
+ const candidates = unmarked.filter(u => !u.used);
466
+ const fresh = candidates.filter(u => after(u.el));
467
+ fresh.forEach((u, i) => u.el.setAttribute('data-copuppet-fresh', String(i)));
468
+ return {missing: missing.length, copies, virtualised: missing.length - copies,
469
+ fresh: fresh.length, before_anchor: candidates.length - fresh.length,
470
+ anchored: !!anchor || !userSel};
471
+ }""", [self.sel["reply"], self.sel.get("user_message", ""), kept])
472
+
473
+ def send(self, chat: ChatHandle, prompt: str, *, timeout: float | None = None) -> Reply:
474
+ timeout = timeout or self.reply_timeout
475
+ self.notes = list(self.chat_notes)
476
+ self.chat_notes = []
477
+ self._assert_preconditions(chat)
478
+ t_type = time.time()
479
+ accepted, method = self._enter_text(prompt)
480
+ type_s = time.time() - t_type
481
+ if method:
482
+ self.notes.append(f"input via {method}")
483
+ want = normalise(prompt)
484
+ if accepted != want:
485
+ i = next((n for n, (x, y) in enumerate(zip(accepted, want)) if x != y), min(len(accepted), len(want)))
486
+ raise BackendError(f"the editor holds {len(accepted)} characters where {len(want)} were typed; first "
487
+ f"difference at {i}: typed {want[max(0, i - 15):i + 15]!r}, editor has "
488
+ f"{accepted[max(0, i - 15):i + 15]!r}; not submitting")
489
+ # reply binding (model v3, I10/I11): identity marks on every existing reply and user message
490
+ mark = f"cp{int(time.time() * 1000)}"
491
+ kept = self._mark_seen(mark)
492
+ fresh_sel = f"{self.sel['reply']}:not([data-copuppet-seen])"
493
+ 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
495
+ for attempt in (1, 2):
496
+ self.page.keyboard.press("Enter")
497
+ t_sent = time.time()
498
+ self.log(f"prompt submitted ({len(prompt)} chars, entered in {type_s:.1f}s, attempt {attempt})")
499
+ while time.time() - t_sent < self.start_timeout:
500
+ busy = self._visible("busy")
501
+ busy_seen = busy_seen or busy
502
+ if busy or self.page.locator(fresh_sel).count() > 0:
503
+ first_token = time.time()
504
+ break
505
+ time.sleep(0.2)
506
+ if first_token is not None:
507
+ break
508
+ # I10: resubmit only with proof that nothing was sent (no new user message, no new reply)
509
+ sent_evidence = (self.page.locator(user_sel).count() > 0) if user_sel else True
510
+ if attempt == 1 and not sent_evidence and self.page.locator(fresh_sel).count() == 0:
511
+ self.notes.append("nothing was sent (no new user message); re-entered and resubmitted once")
512
+ self._wait_editor_stable()
513
+ accepted, _ = self._enter_text(prompt)
514
+ if accepted != want:
515
+ break
516
+ continue
517
+ break
518
+ if first_token is None:
519
+ raise BackendError("no answer started after submitting; next: re-run tools/discover_edge.py --probe")
520
+ complete, last_text, stable_since = False, None, None
521
+ done_sel = f"{fresh_sel} {self.sel['done']}" if self.sel.get("done") else ""
522
+ while time.time() - t_sent < timeout:
523
+ self._dismiss_modals()
524
+ busy = self._visible("busy")
525
+ busy_seen = busy_seen or busy
526
+ fresh = self.page.locator(fresh_sel)
527
+ if not busy and fresh.count() > 0:
528
+ if done_sel and first_visible(self.page.locator(done_sel)) is not None:
529
+ complete = True # done marker scoped to the new reply
530
+ break
531
+ current = normalise(fresh.nth(fresh.count() - 1).inner_text())
532
+ if current and current == last_text and busy_seen:
533
+ if time.time() - stable_since >= self.settle:
534
+ complete = True
535
+ break
536
+ elif current != last_text:
537
+ last_text, stable_since = current, time.time()
538
+ else:
539
+ last_text, stable_since = None, None
540
+ time.sleep(0.3)
541
+ t_done = time.time()
542
+ after = self.probe()
543
+ b = self._bind(kept)
544
+ bound = b["fresh"] == 1 and b["before_anchor"] == 0 and b["anchored"] # I8 + I11
545
+ if b["copies"]:
546
+ self.notes.append(f"{b['copies']} earlier reply node(s) re-rendered as identical copies")
547
+ if b["virtualised"]:
548
+ self.notes.append(f"{b['virtualised']} old reply node(s) left the page (virtualised)")
549
+ if not b["anchored"]:
550
+ self.notes.append("this turn's user message was not found; the reply cannot be anchored (I11)")
551
+ if b["before_anchor"]:
552
+ self.notes.append(f"{b['before_anchor']} unexplained new node(s) before this turn's message (I11)")
553
+ if b["fresh"] != 1:
554
+ self.notes.append(f"{b['fresh']} new replies after this turn's message, expected exactly 1 (I8)")
555
+ if not busy_seen:
556
+ self.notes.append("the busy marker was never seen")
557
+ new_nodes = self.page.locator(f"{self.sel['reply']}[data-copuppet-fresh]")
558
+ last = new_nodes.nth(new_nodes.count() - 1) if new_nodes.count() else None
559
+ text = ZERO_WIDTH.sub("", last.inner_text()).strip() if last is not None else ""
560
+ code = self._code_blocks(last)
561
+ if not complete:
562
+ self.notes.append(f"stopped waiting after {timeout:g}s; the reply may be partial")
563
+ self.log(("reply complete" if complete else "reply incomplete") + ("" if bound else ", UNBOUND") +
564
+ f" (first token {first_token - t_sent:.1f}s, generation {t_done - first_token:.1f}s)")
565
+ return Reply(text=text, backend=self.name, complete=complete and bool(text), bound=bound,
566
+ seconds=round(t_done - t_type, 2), notes=list(self.notes), code_blocks=code,
567
+ prompt_chars_accepted=len(accepted), type_s=round(type_s, 2),
568
+ first_token_s=round(first_token - t_sent, 2), gen_s=round(t_done - first_token, 2),
569
+ markers=after.markers, model_label=after.model_label)
570
+
571
+ def ask(self, prompt: str, *, timeout: float | None = None) -> Reply:
572
+ chat = self.new_chat(temporary=True)
573
+ return self.send(chat, prompt, timeout=timeout)
@@ -0,0 +1,27 @@
1
+ """The Windows Copilot app, via Windows UI Automation (pywinauto, "uia" backend). Not implemented yet: the window
2
+ and element paths come from the skin, discovered with an inspector in a supervised session first."""
3
+ from __future__ import annotations
4
+
5
+ from ..backend import BackendError, Reply
6
+
7
+
8
+ class WinAppBackend:
9
+ name = "winapp"
10
+
11
+ def __init__(self, config: dict):
12
+ self.config = config
13
+
14
+ def ready(self) -> list[str]:
15
+ problems = []
16
+ try:
17
+ import pywinauto # noqa: F401
18
+ except ImportError:
19
+ problems.append('pywinauto is not installed; next: pip install "copuppet[winapp]"')
20
+ problems.append("the winapp backend is not implemented yet (scaffold)")
21
+ return problems
22
+
23
+ def ask(self, prompt: str, *, timeout: float = 120.0) -> Reply:
24
+ raise BackendError("the winapp backend is not implemented yet (scaffold)")
25
+
26
+ def close(self) -> None:
27
+ pass