@capagents/forgeqe 3.0.4 → 3.0.6

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 (99) hide show
  1. package/HOW_TO_USE.md +43 -18
  2. package/dist/docs-site/docs/index.html +32 -1
  3. package/dist/docs-site/docs/search.js +1 -1
  4. package/dist/forgeqe.js +1998 -1984
  5. package/dist/web/assets/Agent-yYv-sG28.js +8 -0
  6. package/dist/web/assets/AgentWork-CpY6-7HI.js +2 -0
  7. package/dist/web/assets/ApiTests-CiIvZiMo.js +10 -0
  8. package/dist/web/assets/Browse-Be7AuwHt.js +2 -0
  9. package/dist/web/assets/Chat-BCts4QGa.js +5 -0
  10. package/dist/web/assets/{CommandPalette-DMpA8mBk.js → CommandPalette-8TT9jdZs.js} +1 -1
  11. package/dist/web/assets/{Compare-DD1mmRB4.js → Compare-D736rcq4.js} +1 -1
  12. package/dist/web/assets/{Cost-B6BCZIxQ.js → Cost-FNg7VZwi.js} +1 -1
  13. package/dist/web/assets/{Data-CpKR98gM.js → Data-DcbrW5-J.js} +4 -4
  14. package/dist/web/assets/{Desktop-xUqFsJPz.js → Desktop-DP62qPnT.js} +1 -1
  15. package/dist/web/assets/DesktopReview-CvOsaLqf.js +1 -0
  16. package/dist/web/assets/{Evidence-CWcZvoOu.js → Evidence-CzgIQH9N.js} +1 -1
  17. package/dist/web/assets/{Explore-DuDQqmEn.js → Explore-eTri0oMt.js} +2 -2
  18. package/dist/web/assets/{Features-BJTX7utr.js → Features-DYIzplY5.js} +1 -1
  19. package/dist/web/assets/{Flags-BeG_gA9O.js → Flags-Dhw6rtB2.js} +2 -2
  20. package/dist/web/assets/{Flaky-DulQuBGi.js → Flaky-DyKQrSKH.js} +1 -1
  21. package/dist/web/assets/Impact-BPSNF_Wk.js +3 -0
  22. package/dist/web/assets/Jobs-CdZ_9uR8.js +5 -0
  23. package/dist/web/assets/KindPage-BX77XCmy.js +6 -0
  24. package/dist/web/assets/Migration-BsKltBC-.js +2 -0
  25. package/dist/web/assets/Product-BjK5mL11.js +7 -0
  26. package/dist/web/assets/{Production-DY9Gddm8.js → Production-Fh9Sscxj.js} +1 -1
  27. package/dist/web/assets/{Quality-B7M1Zna2.js → Quality-Ld82j0hy.js} +1 -1
  28. package/dist/web/assets/{Readiness-BtQ8RbJh.js → Readiness-BBQxbCqC.js} +1 -1
  29. package/dist/web/assets/Record-C5cEwqy-.js +1 -0
  30. package/dist/web/assets/Regression-gjrSoFfx.js +5 -0
  31. package/dist/web/assets/{RelationGraph-C7K_BfEF.js → RelationGraph-DVWg7aQv.js} +1 -1
  32. package/dist/web/assets/Reports-DP1a7XJS.js +2 -0
  33. package/dist/web/assets/Response-D2kQxq_Y.js +4 -0
  34. package/dist/web/assets/RunDiff-D6mEdE9S.js +1 -0
  35. package/dist/web/assets/{Runs-DvjM0xfG.js → Runs-Q10bNJEL.js} +2 -2
  36. package/dist/web/assets/Steps-De_8K9c1.js +2 -0
  37. package/dist/web/assets/{TestCases-Dc6bjNO5.js → TestCases-Dt8B7TOf.js} +1 -1
  38. package/dist/web/assets/{TestData-DWPcmhz4.js → TestData-CaGz4HQ1.js} +2 -2
  39. package/dist/web/assets/{TestDebt-BpYav19x.js → TestDebt-DCJ_GT7n.js} +1 -1
  40. package/dist/web/assets/TestManagement-uO9AjV8t.js +1 -0
  41. package/dist/web/assets/Tosca-CNvp2_fr.js +3 -0
  42. package/dist/web/assets/{WhatsNew-CRaJjaut.js → WhatsNew-BsvPslDU.js} +1 -1
  43. package/dist/web/assets/agentLink-DZqDlz5a.js +1 -0
  44. package/dist/web/assets/{dataParts-Bwh_DOs0.js → dataParts-DDONrWlN.js} +2 -2
  45. package/dist/web/assets/{families-C47Nrp6j.js → families-dexkG1XJ.js} +1 -1
  46. package/dist/web/assets/filters-C4y29lln.js +1 -0
  47. package/dist/web/assets/{fold-Bd5-4sjR.js → fold-B0BRJaD-.js} +1 -1
  48. package/dist/web/assets/frame-DsEMaf7r.js +18 -0
  49. package/dist/web/assets/index-DFHl9AbL.css +2 -0
  50. package/dist/web/assets/index-Do1FSXo9.js +68 -0
  51. package/dist/web/assets/{logos-CgYEz85j.js → logos-Bf_yvAjX.js} +1 -1
  52. package/dist/web/assets/{markdown-DSp3tP8i.js → markdown-DerN4WZw.js} +3 -3
  53. package/dist/web/assets/{paletteCommands-CGFwmBxN.js → paletteCommands-BHKI8Ajf.js} +1 -1
  54. package/dist/web/assets/{parts-DlmbVDzO.js → parts-CD8Iib6m.js} +1 -1
  55. package/dist/web/assets/poll-CHpac9Fb.js +1 -0
  56. package/dist/web/assets/{productParts-CL2tDIGF.js → productParts-ua-02OtT.js} +1 -1
  57. package/dist/web/assets/{qualityParts-Bs34Dzva.js → qualityParts-BGB8bK0j.js} +1 -1
  58. package/dist/web/assets/{recordTest-DHsT3pOe.js → recordTest-cdImm3Tn.js} +1 -1
  59. package/dist/web/assets/{rows-Baid_ASt.js → rows-HJE6LrRs.js} +1 -1
  60. package/dist/web/assets/{segmented-D0PvwMW_.js → segmented-C9eCOTSg.js} +1 -1
  61. package/dist/web/assets/usePageChat-fVgsHXcu.js +1 -0
  62. package/dist/web/index.html +5 -5
  63. package/docs/RELIABILITY.md +62 -0
  64. package/docs/TEST_MANAGEMENT_PLAN.md +95 -0
  65. package/docs/user-guide.html +32 -1
  66. package/forgeqe.example.yaml +5 -0
  67. package/package.json +1 -1
  68. package/prompts/README.md +1 -0
  69. package/prompts/suite-builder.md +44 -0
  70. package/py/forgeqe_engine/brand.py +49 -12
  71. package/py/forgeqe_engine/copilot_gateway.py +131 -3
  72. package/py/forgeqe_engine/diagnostics.py +5 -2
  73. package/py/forgeqe_engine/memory.py +12 -0
  74. package/py/forgeqe_engine/recordsession.py +68 -7
  75. package/py/forgeqe_engine/service.py +8 -1
  76. package/py/forgeqe_engine/video.py +14 -0
  77. package/dist/web/assets/Agent-CKlqZ4Eq.js +0 -8
  78. package/dist/web/assets/ApiTests-MARHrxdT.js +0 -10
  79. package/dist/web/assets/Browse-B2QYflth.js +0 -2
  80. package/dist/web/assets/Chat-DRkmiF4r.js +0 -5
  81. package/dist/web/assets/DesktopReview-CnLC9yMR.js +0 -1
  82. package/dist/web/assets/Impact-BvGp2rYG.js +0 -3
  83. package/dist/web/assets/Jobs-BXqBtH8C.js +0 -5
  84. package/dist/web/assets/KindPage-BGEobnS3.js +0 -6
  85. package/dist/web/assets/Migration-D1JVUQM0.js +0 -2
  86. package/dist/web/assets/Product-Y1dUpFfW.js +0 -7
  87. package/dist/web/assets/Record-W7ojjKNu.js +0 -2
  88. package/dist/web/assets/Regression-eV2N8m2P.js +0 -5
  89. package/dist/web/assets/Reports-D4v66mJR.js +0 -2
  90. package/dist/web/assets/Response-B_2R4FjH.js +0 -4
  91. package/dist/web/assets/RunDiff-Br5uN0Gu.js +0 -1
  92. package/dist/web/assets/Steps-DULf0k5w.js +0 -2
  93. package/dist/web/assets/Tosca-Bw-j_W-Q.js +0 -3
  94. package/dist/web/assets/agentLink-Dxy-IYQv.js +0 -1
  95. package/dist/web/assets/filters-Ca7by1u0.js +0 -1
  96. package/dist/web/assets/frame-BliO67Wd.js +0 -18
  97. package/dist/web/assets/index-B1U2Jkz_.js +0 -67
  98. package/dist/web/assets/index-Ce2EYROA.css +0 -2
  99. package/dist/web/assets/usePageChat-lmgkgnb4.js +0 -1
@@ -6,18 +6,22 @@ ForgeQE's look in the browser it drives, when the browser is visible:
6
6
  person's mouse and keyboard while the agent thinks, lifted while it acts so its own clicks and typing get through
7
7
 
8
8
  The overlay is left out of the page the model reads (the library's exclude attribute), hidden from screen readers and the
9
- accessibility checks (aria-hidden, shadow DOM, outside <body>), and taken out of a screenshot only while its pixels are
10
- captured. The step bar stays on screen while the agent clicks, types and scrolls. Nothing in it loads a URL, so a page's
11
- Content-Security-Policy has nothing to block or log.
9
+ accessibility checks (aria-hidden, shadow DOM, outside <body>). The step bar stays on screen the whole run, through the
10
+ agent's clicks, typing, scrolling and its own screenshots, so it never blinks: the model's screenshot shows it (the agent
11
+ is told it is ForgeQE's, `AGENT_NOTE`), and only the glow, which pulses anyway, is taken out of those. A capture that is
12
+ compared with a baseline or kept as the page's own look (`clean_capture`) takes the whole overlay out while its pixels
13
+ are taken. Nothing in it loads a URL, so a page's Content-Security-Policy has nothing to block or log.
12
14
  """
13
15
  from __future__ import annotations
14
16
 
15
17
  import asyncio
18
+ import contextlib
19
+ import contextvars
16
20
  import json
17
21
  import logging
18
22
  import os
19
23
  import re
20
- from typing import Any, Dict, Optional, Tuple
24
+ from typing import Any, Dict, Iterator, Optional, Tuple
21
25
  from urllib.parse import urlparse
22
26
 
23
27
  from .brand_assets import ICON_PNG, MARK_RGBA, MARK_SIZE
@@ -30,6 +34,26 @@ CDP_TIMEOUT = 3.0
30
34
 
31
35
  _OVERLAYS: Dict[int, "Overlay"] = {}
32
36
 
37
+ # Set while ForgeQE takes a screenshot that must show the page alone (a visual baseline's, a localization check's).
38
+ _CLEAN = contextvars.ContextVar("forgeqe_clean_capture", default=False)
39
+
40
+ # Told to the browser agent when the overlay is on: the bar is in its screenshots, and is not the page's.
41
+ AGENT_NOTE = (
42
+ "ForgeQE shows a dark bar along the bottom of the browser with the current step. It is ForgeQE's, not the page's: it is "
43
+ "not in the page's elements, it never blocks your clicks, and it is never a finding. Ignore it in screenshots; to see "
44
+ "what it covers, scroll."
45
+ )
46
+
47
+
48
+ @contextlib.contextmanager
49
+ def clean_capture() -> Iterator[None]:
50
+ """Screenshots taken inside take the whole overlay out while their pixels are captured (it blinks once for them)."""
51
+ token = _CLEAN.set(True)
52
+ try:
53
+ yield
54
+ finally:
55
+ _CLEAN.reset(token)
56
+
33
57
  # Runs in every top-level page (and on the pages open when the overlay starts). Starts unlocked: a page that loads in
34
58
  # the middle of the agent's actions must not block the rest of them. Overlay.update() locks it once the step is over.
35
59
  OVERLAY_JS = r"""(() => {
@@ -42,9 +66,10 @@ OVERLAY_JS = r"""(() => {
42
66
  replaying: ['From memory', 'rgba(167,139,250,.22)', '#c4b5fd'],
43
67
  waiting: ['Your turn', 'rgba(251,191,36,.18)', '#fcd34d'],
44
68
  };
45
- // hide counts screenshots in progress. The bar stays up through clicks, typing and scrolling; only a shot takes it down.
46
- const state = { text: CFG.text, mode: CFG.mode, lock: false, hide: 0 };
47
- let host = null, textEl, chipEl, lockEl, blocker, restores = 0, restoreAt = 0;
69
+ // hide counts clean captures in progress (everything down); dim counts the agent's own screenshots (only the glow down).
70
+ // The bar stays up through clicks, typing, scrolling and the agent's screenshots, so it never blinks.
71
+ const state = { text: CFG.text, mode: CFG.mode, lock: false, hide: 0, dim: 0 };
72
+ let host = null, glow, textEl, chipEl, lockEl, blocker, restores = 0, restoreAt = 0;
48
73
 
49
74
  const el = (tag, css, text) => { const e = document.createElement(tag); e.style.cssText = css; if (text) e.textContent = text; return e; };
50
75
  const locked = () => state.lock && !state.hide;
@@ -69,7 +94,7 @@ OVERLAY_JS = r"""(() => {
69
94
  const css = document.createElement('style');
70
95
  css.textContent = '*{pointer-events:none!important;}';
71
96
  root.append(css);
72
- const glow = el('div', 'position:fixed;inset:0;pointer-events:none;border-radius:6px;' +
97
+ glow = el('div', 'position:fixed;inset:0;pointer-events:none;border-radius:6px;' +
73
98
  'box-shadow:inset 0 0 0 2px rgba(50,210,234,.85),inset 0 0 34px 5px rgba(23,87,194,.4);');
74
99
  try { glow.animate([{ opacity: .45 }, { opacity: 1 }], { duration: 1600, direction: 'alternate', iterations: Infinity, easing: 'ease-in-out' }); } catch (_) {}
75
100
  blocker = el('div', 'position:fixed;inset:0;background:transparent;');
@@ -101,6 +126,7 @@ OVERLAY_JS = r"""(() => {
101
126
  host.style.setProperty('pointer-events', 'none', 'important');
102
127
  host.style.setProperty('visibility', hidden ? 'hidden' : 'visible', 'important');
103
128
  host.style.setProperty('display', hidden ? 'none' : 'block', 'important');
129
+ glow.style.visibility = state.dim > 0 ? 'hidden' : 'visible';
104
130
  try {
105
131
  if (hidden) { if (host.hidePopover && host.matches(':popover-open')) host.hidePopover(); }
106
132
  else if (host.showPopover && !host.matches(':popover-open')) host.showPopover();
@@ -152,9 +178,11 @@ OVERLAY_JS = r"""(() => {
152
178
 
153
179
  window.__forgeqeOverlay = {
154
180
  mount,
155
- set(s) { Object.assign(state, s); if (state.hide < 0) state.hide = 0; mount(); },
181
+ set(s) { Object.assign(state, s); if (state.hide < 0) state.hide = 0; if (state.dim < 0) state.dim = 0; mount(); },
156
182
  hide() { state.hide++; mount(); },
157
183
  show() { state.hide = Math.max(0, state.hide - 1); mount(); },
184
+ dim() { state.dim++; mount(); },
185
+ undim() { state.dim = Math.max(0, state.dim - 1); mount(); },
158
186
  };
159
187
  if (document.documentElement) mount();
160
188
  document.addEventListener('DOMContentLoaded', mount, { once: true });
@@ -189,6 +217,7 @@ START_JS = r"""(() => {
189
217
  })()"""
190
218
 
191
219
  _SET_JS = "(() => { const o = window.__forgeqeOverlay; if (o) o.set(%s); })()"
220
+ _DIM_JS = "(() => { const o = window.__forgeqeOverlay; if (o && o.dim) o.%s(); })()"
192
221
  _HIDDEN_JS = (
193
222
  "(() => { const o = window.__forgeqeOverlay; if (o) o.%s(); "
194
223
  "const s = document.getElementById('" + START_ID + "'); if (s && !o) s.style.visibility = '%s'; })()"
@@ -230,6 +259,12 @@ class Overlay:
230
259
  async def show(self) -> None:
231
260
  await self._each_page(_HIDDEN_JS % ("show", "visible"), install=False)
232
261
 
262
+ async def dim(self) -> None:
263
+ await self._each_page(_DIM_JS % "dim", install=False)
264
+
265
+ async def undim(self) -> None:
266
+ await self._each_page(_DIM_JS % "undim", install=False)
267
+
233
268
  async def start_page(self, target_id: str) -> None:
234
269
  start = (
235
270
  START_JS.replace("__ID__", json.dumps(START_ID))
@@ -312,15 +347,17 @@ def install() -> None:
312
347
  return
313
348
 
314
349
  async def captureScreenshot(page: Any, params: Any = None, session_id: Optional[str] = None) -> Any:
315
- # Hide for the capture itself, not for the slow work around it, so the step bar stays up while the agent acts.
350
+ # The agent's screenshots keep the step bar on screen (taking it down for each one made it blink several times a
351
+ # step); only the glow, which pulses anyway, goes. A clean capture takes everything down for its pixels alone.
316
352
  overlays = [o for o in list(_OVERLAYS.values()) if o is not None]
353
+ clean = _CLEAN.get()
317
354
  for overlay in overlays:
318
- await overlay.hide()
355
+ await (overlay.hide() if clean else overlay.dim())
319
356
  try:
320
357
  return await original_capture(page, params=params, session_id=session_id)
321
358
  finally:
322
359
  for overlay in overlays:
323
- await overlay.show()
360
+ await (overlay.show() if clean else overlay.undim())
324
361
 
325
362
  captureScreenshot.__forgeqe__ = True # type: ignore[attr-defined]
326
363
  PageClient.captureScreenshot = captureScreenshot # type: ignore[method-assign]
@@ -494,6 +494,17 @@ class Copilot:
494
494
  gateway_log(rid, f"start model={req['model']} tools={len(req['tools'])} schema={req['schema'] is not None} stream={bool(on_text)}")
495
495
  try:
496
496
  out = await self._complete(rid, req, on_text, gone)
497
+ # Copilot sometimes ends a turn with no words and no call of the caller's tools. Answered as it is, the
498
+ # agent runtime takes that for a finished answer and the person's request ends in silence, its plan
499
+ # half done. It is asked once more; a second empty turn is an error the caller sees.
500
+ if empty_reply(req, out):
501
+ gateway_log(rid, "Copilot ended its turn with no reply and no call of the caller's tools: asked once more")
502
+ out = await self._complete(rid, req, on_text, gone)
503
+ if empty_reply(req, out):
504
+ # The turn's shape, never its text, goes to the caller: ForgeQE's own session log then says what
505
+ # Copilot sent, without the gateway's log.
506
+ raise GatewayError(502, f"{EMPTY_REPLY} ({out.get(SHAPE_KEY) or 'no detail'})")
507
+ out.pop(SHAPE_KEY, None)
497
508
  except CallerGone:
498
509
  gateway_log(rid, f"caller gone after {time.monotonic() - started:.1f}s: its Copilot session was stopped")
499
510
  raise
@@ -527,7 +538,7 @@ class Copilot:
527
538
  statuses: List[Optional[int]] = []
528
539
  calls: List[Dict[str, Any]] = []
529
540
  # The last root reply without tool requests, and the timer that ends the wait when a turn ends without idle.
530
- turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event()}
541
+ turn: Dict[str, Any] = {"final": None, "timer": None, "settled": asyncio.Event(), "messages": []}
531
542
 
532
543
  def on_loop(fn: Callable[[], None]) -> None:
533
544
  """The SDK may call on_event from a thread of its own; timers and events belong to the server's loop."""
@@ -555,6 +566,7 @@ class Copilot:
555
566
  usage["output"] += data.output_tokens or 0
556
567
  usage["cached"] += data.cache_read_tokens or 0
557
568
  usage["premium"] += float(getattr(data, "cost", None) or 0)
569
+ usage["reasoning"] = usage.get("reasoning", 0) + (getattr(data, "reasoning_tokens", None) or 0)
558
570
  if not getattr(data, "parent_tool_call_id", None):
559
571
  finish["reason"] = "content_filter" if getattr(data, "content_filter_triggered", False) else getattr(data, "finish_reason", None)
560
572
  elif isinstance(data, SessionErrorData):
@@ -566,6 +578,9 @@ class Copilot:
566
578
  stream["to"](data.delta_content)
567
579
  elif isinstance(data, AssistantMessageData) and not data.parent_tool_call_id:
568
580
  turn["final"] = None if data.tool_requests else event
581
+ # Every root message of the turn: a reply split into chunks or phases, and tool requests Copilot never
582
+ # handed to the relay, are read from them (reply_of, requested_calls).
583
+ turn["messages"].append(data)
569
584
  elif isinstance(data, AssistantTurnStartData) and not data.parent_tool_call_id:
570
585
  on_loop(unsettle)
571
586
  elif isinstance(data, AssistantTurnEndData) and not data.parent_tool_call_id:
@@ -584,6 +599,7 @@ class Copilot:
584
599
  calls.clear()
585
600
  on_loop(unsettle)
586
601
  turn["final"] = None
602
+ turn["messages"] = []
587
603
  turn["settled"] = asyncio.Event()
588
604
  names = {t["name"] for t in req["tools"]}
589
605
  tools = relay_tools(req["tools"], calls, replaces=self.replaces & names)
@@ -655,14 +671,32 @@ class Copilot:
655
671
  raise self.refusal(errors[-1], statuses[-1] if statuses else None)
656
672
  gateway_log(rid, cache_note(req, usage))
657
673
  data = getattr(reply, "data", None)
674
+ messages = list(turn["messages"]) or ([data] if isinstance(data, AssistantMessageData) else [])
658
675
  content = (data.content or "") if isinstance(data, AssistantMessageData) else ""
659
676
  if calls:
660
677
  return completion(req["model"], content, usage, calls)
661
- if not isinstance(data, AssistantMessageData):
678
+ caller = {t["name"] for t in req["tools"]}
679
+ # A call of the caller's tools Copilot asked for but never handed to the relay (a call it failed itself leaves
680
+ # its loop running): the call goes back to the caller all the same, instead of an empty answer.
681
+ recovered = requested_calls(messages, caller)
682
+ if recovered:
683
+ gateway_log(rid, f"Copilot asked for {','.join(c['name'] for c in recovered)} without handing the call over: passed on as tool calls")
684
+ return completion(req["model"], "", usage, recovered)
685
+ if not isinstance(data, AssistantMessageData) and not messages:
662
686
  raise GatewayError(502, "GitHub Copilot sent no reply.")
687
+ if not content.strip():
688
+ # A reply sent in chunks or phases, whose last message holds none of it.
689
+ content = reply_of(messages)
690
+ if content.strip():
691
+ gateway_log(rid, "the reply's last message was empty: its text was taken from the turn's earlier messages")
663
692
  if req["schema"] is not None or req["json_only"]:
664
693
  content = strip_fences(content)
665
- return completion(req["model"], content, usage, finish=finish["reason"])
694
+ out = completion(req["model"], content, usage, finish=finish["reason"])
695
+ if not content.strip():
696
+ shape = turn_shape(messages, usage, finish["reason"], caller)
697
+ gateway_log(rid, f"empty turn: {shape}")
698
+ out[SHAPE_KEY] = shape
699
+ return out
666
700
 
667
701
 
668
702
  async def _wait(self, rid: str, session: Any, req: Dict[str, Any], turn: Dict[str, Any], gone: Optional["asyncio.Future[Any]"]) -> Tuple[Any, bool]:
@@ -708,6 +742,100 @@ _LIMITED = re.compile(r"rate.?limit|too many requests|quota|premium request|allo
708
742
  LIMITED_HINT = "the seat's rate limit or premium request allowance; wait, or pick a model with a lower multiplier: forgeqe models --copilot"
709
743
 
710
744
 
745
+ EMPTY_REPLY = "GitHub Copilot ended its turn twice with no reply and no tool call."
746
+ # Where an empty answer carries its turn's shape inside the gateway; removed before anything is sent.
747
+ SHAPE_KEY = "_forgeqe_turn_shape"
748
+ _PLAIN = re.compile(r"^[A-Za-z0-9_.-]{1,40}$")
749
+
750
+
751
+ def reply_of(messages: List[Any]) -> str:
752
+ """
753
+ The reply's text from a turn's root messages: after the last one that asked for a tool, the last message with words,
754
+ its chunks joined in order (one per chunk_index, the latest kept). Copilot can send a reply in chunks, or a final
755
+ message with no words after one that had them; the last message alone then loses the reply.
756
+ """
757
+ after: List[Any] = []
758
+ for m in messages:
759
+ if getattr(m, "tool_requests", None):
760
+ after = []
761
+ else:
762
+ after.append(m)
763
+ groups: Dict[str, List[Any]] = {}
764
+ order: List[str] = []
765
+ for i, m in enumerate(after):
766
+ key = str(getattr(m, "message_id", "") or f"#{i}")
767
+ if key not in groups:
768
+ groups[key] = []
769
+ order.append(key)
770
+ groups[key].append(m)
771
+ for key in reversed(order):
772
+ parts = groups[key]
773
+ if any(isinstance(getattr(p, "chunk_index", None), int) for p in parts):
774
+ by_index: Dict[int, str] = {}
775
+ for p in parts:
776
+ idx = getattr(p, "chunk_index", None)
777
+ by_index[idx if isinstance(idx, int) else -1] = str(getattr(p, "content", "") or "")
778
+ text = "".join(by_index[k] for k in sorted(by_index))
779
+ else:
780
+ text = str(getattr(parts[-1], "content", "") or "")
781
+ if text.strip():
782
+ return text
783
+ return ""
784
+
785
+
786
+ def requested_calls(messages: List[Any], caller: set) -> List[Dict[str, Any]]:
787
+ """
788
+ The calls of the caller's tools the turn's last root message asked for, as the relay records them; none when it
789
+ asked for another tool too (Copilot's own, or one nobody has), since the caller could not answer that one.
790
+ """
791
+ if not messages:
792
+ return []
793
+ asked = list(getattr(messages[-1], "tool_requests", None) or [])
794
+ if not asked or any(str(getattr(t, "name", "") or "") not in caller for t in asked):
795
+ return []
796
+ out = []
797
+ for t in asked[:16]:
798
+ args = getattr(t, "arguments", None)
799
+ out.append({
800
+ "id": str(getattr(t, "tool_call_id", "") or f"call_{uuid.uuid4().hex[:24]}")[:64],
801
+ "name": str(t.name),
802
+ "arguments": args if isinstance(args, str) else json.dumps(args if args is not None else {}),
803
+ })
804
+ return out
805
+
806
+
807
+ def turn_shape(messages: List[Any], usage: Dict[str, Any], finish: Optional[str], caller: set) -> str:
808
+ """
809
+ What an empty turn was made of, for the log and the caller's error: counts, phases, the finish reason and the tools
810
+ asked for. Never the turn's text; a name the model wrote only when it is one of the caller's or Copilot's own tools.
811
+ """
812
+ phases = sorted({str(getattr(m, "phase", "") or "") for m in messages} - {""})
813
+ asked = [str(getattr(t, "name", "") or "") for m in messages for t in (getattr(m, "tool_requests", None) or [])]
814
+ known = sorted({n for n in asked if n in caller or n in BUILTIN_TOOLS})
815
+ other = len([n for n in asked if n not in caller and n not in BUILTIN_TOOLS])
816
+ reasoning_only = any(str(getattr(m, "reasoning_text", "") or "").strip() for m in messages) and not any(str(getattr(m, "content", "") or "").strip() for m in messages)
817
+ bits = [
818
+ f"messages {len(messages)}",
819
+ f"phases {'/'.join(p for p in phases if _PLAIN.match(p)) or 'none'}",
820
+ f"finish {finish if finish and _PLAIN.match(str(finish)) else 'none'}",
821
+ f"output tokens {int(usage.get('output') or 0)}",
822
+ f"reasoning tokens {int(usage.get('reasoning') or 0)}",
823
+ f"tools asked {', '.join(known) or 'none'}{f' and {other} other' if other else ''}",
824
+ ]
825
+ if reasoning_only:
826
+ bits.append("reasoning without a reply")
827
+ return "; ".join(bits)
828
+
829
+
830
+ def empty_reply(req: Dict[str, Any], out: Dict[str, Any]) -> bool:
831
+ """A plain-text answer with no words and no tool calls that Copilot did not cut short: nothing the caller can use."""
832
+ if req.get("schema") is not None or req.get("json_only"):
833
+ return False
834
+ choice = (out.get("choices") or [{}])[0]
835
+ message = choice.get("message") or {}
836
+ return not message.get("tool_calls") and not str(message.get("content") or "").strip() and choice.get("finish_reason") == "stop"
837
+
838
+
711
839
  def limited(message: str, status: Optional[int] = None) -> bool:
712
840
  """Whether Copilot's error is a rate limit or a used-up premium request allowance."""
713
841
  return status == 429 or bool(_LIMITED.search(message or ""))
@@ -15,6 +15,7 @@ from pathlib import Path
15
15
  from typing import Any, Dict, List, Optional, Set, Tuple
16
16
  from urllib.parse import urlsplit
17
17
 
18
+ from .brand import clean_capture
18
19
  from .network import NetworkCapture, hook
19
20
 
20
21
  logger = logging.getLogger(__name__)
@@ -463,7 +464,8 @@ class Diagnostics:
463
464
  continue
464
465
  await asyncio.sleep(0.1)
465
466
  entry[mode] = await self._eval(session, L10N_MEASURE % "false") or {}
466
- shot = await session.cdp_client.send.Page.captureScreenshot(params={"format": "jpeg", "quality": 60, "fromSurface": True}, session_id=session.session_id)
467
+ with clean_capture():
468
+ shot = await session.cdp_client.send.Page.captureScreenshot(params={"format": "jpeg", "quality": 60, "fromSurface": True}, session_id=session.session_id)
467
469
  if (shot or {}).get("data"):
468
470
  entry.setdefault("_shots", {})[mode] = base64.b64decode(shot["data"])
469
471
  except Exception:
@@ -514,7 +516,8 @@ class Diagnostics:
514
516
  width, height = int(size.get("width") or 0), min(int(size.get("height") or 0), MAX_FULL_HEIGHT)
515
517
  if width and height:
516
518
  params.update({"captureBeyondViewport": True, "clip": {"x": 0, "y": 0, "width": width, "height": height, "scale": 1}})
517
- shot = await send.Page.captureScreenshot(params=params, session_id=session.session_id)
519
+ with clean_capture():
520
+ shot = await send.Page.captureScreenshot(params=params, session_id=session.session_id)
518
521
  data = (shot or {}).get("data")
519
522
  if data:
520
523
  title = str(await self._eval(session, "document.title") or "")
@@ -1223,6 +1223,18 @@ def _present_first(target: Dict[str, Any]) -> List[Dict[str, Any]]:
1223
1223
  return [l for l in locs if (l["type"], l["value"]) in current] + [l for l in locs if (l["type"], l["value"]) not in current]
1224
1224
 
1225
1225
 
1226
+ UNSAVED_SECRET = (
1227
+ "typed into a password field a value that is not a saved secret, so replays stop there and the model signs in "
1228
+ "again on every run. Make the password a secret: in env.yaml, a variable whose value is only $NAME of an "
1229
+ "environment variable (the browser model then types <secret>…</secret>), or a login in forgeqe.yaml"
1230
+ )
1231
+
1232
+
1233
+ def unsaved_secret_steps(steps: List[Dict[str, Any]]) -> List[int]:
1234
+ """The 1-based numbers of the flow's steps that typed into a password field without a saved secret (never replayable)."""
1235
+ return [n for n, s in enumerate(steps or [], 1) if isinstance(s, dict) and s.get("secret")]
1236
+
1237
+
1226
1238
  def flow_step(action: str, params: Dict[str, Any], target: Optional[Dict[str, Any]], line: str) -> Dict[str, Any]:
1227
1239
  """One replayable action. Element actions keep the element's ranked locators and fingerprint, never its index."""
1228
1240
  step: Dict[str, Any] = {"action": action, "params": {k: v for k, v in (params or {}).items() if k != "index"}, "line": line}
@@ -58,6 +58,28 @@ MAX_SHOTS = 400
58
58
  MAX_STEP_TIMES = 1000
59
59
  SHOT_QUALITY = 55
60
60
  # The tester's tab as a video (browser.video): the page's own screencast, on the recorder's connection (video.py).
61
+ # How often, and how long apart, a tab's history is asked for when it cannot answer yet (a back-forward cache restore).
62
+ HISTORY_TRIES = 6
63
+ HISTORY_RETRY_S = 0.1
64
+ # The tab's history addresses kept to tell back from forward when its history cannot be read.
65
+ MAX_HISTORY = 200
66
+
67
+
68
+ def history_step(prev: Any, urls: Any, url: str) -> str:
69
+ """
70
+ Back or forward from the address alone, when the tab's history cannot be read: the entry just before the one the tab
71
+ was on is back, the one just after forward; anything else is a new page. Read as untrusted (only the shapes kept).
72
+ """
73
+ if not (isinstance(prev, tuple) and len(prev) == 3 and isinstance(prev[0], int) and isinstance(urls, list) and url):
74
+ return "new"
75
+ cur = prev[0]
76
+ if 1 <= cur <= len(urls) and urls[cur - 1] == url:
77
+ return "back"
78
+ if 0 <= cur + 1 < len(urls) and urls[cur + 1] == url:
79
+ return "forward"
80
+ return "new"
81
+
82
+
61
83
  VIDEO_SCREENCAST = {"format": "jpeg", "quality": 60, "maxWidth": 1920, "maxHeight": 1200, "everyNthFrame": 1}
62
84
 
63
85
  # What the page shows after a step, for the review to suggest checks from and to pick an element on the screenshot:
@@ -387,6 +409,8 @@ class RecordSession:
387
409
  with contextlib.suppress(Exception):
388
410
  await self.network.settle(3.0)
389
411
  sid, self._video_sid = self._video_sid, None
412
+ # The browser is about to close: the last picture is taken now, while its tab is there (_finish_video comes after).
413
+ await self._last_picture(self.video, sid)
390
414
  if self.video is not None and sid and sid in self.pages:
391
415
  with contextlib.suppress(Exception):
392
416
  await self.send("Page.stopScreencast", {}, sid)
@@ -772,7 +796,7 @@ class RecordSession:
772
796
  await self.send("Page.startScreencast", dict(VIDEO_SCREENCAST), sid)
773
797
  except Exception as ex:
774
798
  logger.debug("record: no screencast of the page: %s", ex)
775
- how = await self._how(sid, page)
799
+ how = await self._how(sid, page, url)
776
800
  renderer = page.pop("renderer", False)
777
801
  started = page.pop("started", None)
778
802
  if page.pop("initial", False) or (page.get("opener") and not page.get("seen")):
@@ -789,16 +813,34 @@ class RecordSession:
789
813
  if msg:
790
814
  self._changed(msg)
791
815
 
792
- async def _how(self, sid: str, page: Dict[str, Any]) -> str:
793
- """How the tab got to its page, from its history: "back", "forward", "reload", or "new"."""
794
- try:
795
- h = await self.send("Page.getNavigationHistory", None, sid)
796
- except Exception:
797
- return "new"
816
+ async def _how(self, sid: str, page: Dict[str, Any], url: str = "") -> str:
817
+ """
818
+ How the tab got to its page, from its history: "back", "forward", "reload", or "new". A page restored from the
819
+ back-forward cache answers "Not attached to an active page" for a moment: the history is asked again, and if it
820
+ still cannot be read, the address tells back from forward (the entry before or after the one it was on).
821
+ """
822
+ h: Optional[Dict[str, Any]] = None
823
+ for attempt in range(HISTORY_TRIES):
824
+ try:
825
+ h = await self.send("Page.getNavigationHistory", None, sid)
826
+ break
827
+ except Exception as ex:
828
+ if attempt + 1 < HISTORY_TRIES:
829
+ await asyncio.sleep(HISTORY_RETRY_S)
830
+ else:
831
+ logger.debug("record: no history of the tab: %s", ex)
832
+ if h is None:
833
+ how = history_step(page.get("history"), page.get("history_urls"), url)
834
+ # Where the tab now is in its history, so the next navigation is judged from here.
835
+ if how in ("back", "forward"):
836
+ cur, length, _ = page["history"]
837
+ page["history"] = (cur - 1 if how == "back" else cur + 1, length, None)
838
+ return how
798
839
  entries = h.get("entries") or []
799
840
  cur = int(h.get("currentIndex") or 0)
800
841
  entry = entries[cur]["id"] if 0 <= cur < len(entries) else None
801
842
  prev, page["history"] = page.get("history"), (cur, len(entries), entry)
843
+ page["history_urls"] = [str(e.get("url") or "") for e in entries][:MAX_HISTORY]
802
844
  if not prev:
803
845
  return "new"
804
846
  p_cur, p_len, p_entry = prev
@@ -1741,11 +1783,30 @@ class RecordSession:
1741
1783
  except Exception as ex:
1742
1784
  logger.debug("record: no screencast of the page: %s", ex)
1743
1785
 
1786
+ async def _last_picture(self, video: Any, sid: Optional[str]) -> None:
1787
+ """
1788
+ Chrome sends a screencast picture only when the page repaints: a short recording of a still page can end with
1789
+ none. Its screen as it is now is taken once, while the tab is still there, so the recording keeps its video
1790
+ (never while paused, never when a picture came).
1791
+ """
1792
+ if video is None or not sid or sid not in self.pages or self.paused or getattr(video, "pictured", True):
1793
+ return
1794
+ try:
1795
+ shot = await self.send("Page.captureScreenshot", {"format": "jpeg", "quality": VIDEO_SCREENCAST["quality"]}, sid)
1796
+ data = shot.get("data") if isinstance(shot, dict) else None
1797
+ if isinstance(data, str):
1798
+ import base64
1799
+
1800
+ video.frame(base64.b64decode(data, validate=True))
1801
+ except Exception as ex:
1802
+ logger.debug("record: no last picture for the video: %s", ex)
1803
+
1744
1804
  async def _finish_video(self) -> Optional[str]:
1745
1805
  video, self.video = self.video, None
1746
1806
  if video is None:
1747
1807
  return None
1748
1808
  sid, self._video_sid = self._video_sid, None
1809
+ await self._last_picture(video, sid)
1749
1810
  if sid and sid in self.pages:
1750
1811
  try:
1751
1812
  await self.send("Page.stopScreencast", {}, sid)
@@ -23,7 +23,7 @@ from typing import Any, Callable, Dict, List, Optional, Set, Tuple
23
23
  from . import brand, userlike
24
24
  from .diagnostics import Diagnostics, box_for
25
25
  from .logins import _host_matches, can_sign_in, code_logins, guard_secrets, load_sessions, parse_logins, passkey_logins, prompt_block, push_logins, register_code_action, register_mfa_actions, save_sessions, use_env_secrets, use_logins
26
- from .memory import READ_ONLY_ACTIONS, MemoryStore, compact_step, flow_step, page_id
26
+ from .memory import READ_ONLY_ACTIONS, UNSAVED_SECRET, MemoryStore, compact_step, flow_step, page_id, unsaved_secret_steps
27
27
  from .prompts import CONVENTIONS, text as prompt_text, use_prompts
28
28
  from .report import CASE_REPORT_INSTRUCTION, CaseReport, build_timeline, case_report_from_history
29
29
  from .replay import ReplayOutcome, handoff_task, replay_flow
@@ -1436,6 +1436,8 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1436
1436
  extra_parts.append(saved_logins)
1437
1437
  if req.case_steps > 0:
1438
1438
  extra_parts.append(prompt_text("browser-case-report", CASE_REPORT_INSTRUCTION).replace("{n}", str(req.case_steps)))
1439
+ if overlay is not None:
1440
+ extra_parts.append(brand.AGENT_NOTE)
1439
1441
  if (req.extend_system_message or "").strip():
1440
1442
  extra_parts.append((req.extend_system_message or "").strip())
1441
1443
  if req.skills:
@@ -1920,6 +1922,11 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1920
1922
  _save(out, "history", history=history, shot=shot)
1921
1923
  return out
1922
1924
  finally:
1925
+ if mem is not None:
1926
+ unsaved = unsaved_secret_steps(mem.steps)
1927
+ if unsaved:
1928
+ # Said in every run it happens: a sign-in the replay cannot do costs model steps on each run after.
1929
+ emit({"type": "log", "level": "warn", "text": f"Step {', '.join(map(str, unsaved[:5]))} {UNSAVED_SECRET}"})
1923
1930
  if mem is not None and not mem.finished:
1924
1931
  with contextlib.suppress(Exception):
1925
1932
  mem.store.flush()
@@ -280,11 +280,25 @@ class FrameVideo:
280
280
  return
281
281
  self._stop.wait(step)
282
282
 
283
+ @property
284
+ def pictured(self) -> bool:
285
+ """Whether a picture has come: a recording of a page that never repainted has none until one is taken."""
286
+ with self._lock:
287
+ return self._latest is not None
288
+
283
289
  def close(self, timeout: float = FINISH_SECONDS) -> Optional[Path]:
284
290
  """Finish the file: its path, or None (nothing removed is left behind) when no video was made."""
285
291
  self._stop.set()
286
292
  if self._thread is not None:
287
293
  self._thread.join(timeout=10)
294
+ # A picture that came after the writer's last turn (the only one, on a short recording of a still page): written
295
+ # once, so the video shows it rather than nothing at all.
296
+ if self.written == 0 and not self._held and not self.error:
297
+ with self._lock:
298
+ self._fresh = self._latest is not None
299
+ pixels = self._pixels_now()
300
+ if pixels is not None and self.exe and (self._proc is not None or self._open()):
301
+ self._write(pixels)
288
302
  proc = self._proc
289
303
  if proc is None:
290
304
  return None