@capagents/forgeqe 3.1.7 → 3.1.8

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 (61) hide show
  1. package/dist/forgeqe.js +1700 -1699
  2. package/dist/web/assets/{3d-force-graph-BmczCBlL.js → 3d-force-graph-OeCdKJJ-.js} +1 -1
  3. package/dist/web/assets/{Agent-y4MCu8wo.js → Agent-DrdDwck4.js} +1 -1
  4. package/dist/web/assets/{AgentWork-BWblSkId.js → AgentWork-wNaA-i2T.js} +1 -1
  5. package/dist/web/assets/ApiTests-B3X6NIn8.js +10 -0
  6. package/dist/web/assets/{Browse-C3r1fDvS.js → Browse-Cd1DEgYR.js} +1 -1
  7. package/dist/web/assets/{Chat-C5WRZ7EO.js → Chat-4GknHS5Z.js} +1 -1
  8. package/dist/web/assets/{CommandPalette-ab9Dujgu.js → CommandPalette-zRrrp6F_.js} +1 -1
  9. package/dist/web/assets/{Compare-ObjtkAZ2.js → Compare-DJVhkzqO.js} +1 -1
  10. package/dist/web/assets/{Cost-XLrxpQZz.js → Cost-CbKnuQuB.js} +1 -1
  11. package/dist/web/assets/{Data-DmfILc8f.js → Data-Bt5yqqvq.js} +1 -1
  12. package/dist/web/assets/{Desktop-C9cgaHSS.js → Desktop-CPDo3Ir-.js} +1 -1
  13. package/dist/web/assets/{DesktopReview-QuculN-N.js → DesktopReview-CCaqTSu5.js} +1 -1
  14. package/dist/web/assets/{Evidence-IFtgLPK-.js → Evidence-BAuIgj1h.js} +1 -1
  15. package/dist/web/assets/{Explore-DhskIcmJ.js → Explore-BqzEPdP7.js} +1 -1
  16. package/dist/web/assets/{Features-OMov_t5a.js → Features-DFuPCW9x.js} +1 -1
  17. package/dist/web/assets/{Flags-v34h7tMQ.js → Flags-UBakvqIq.js} +1 -1
  18. package/dist/web/assets/{Flaky-llIyrSlY.js → Flaky-DUzdfQW4.js} +1 -1
  19. package/dist/web/assets/{Impact-BDY3keAo.js → Impact-jLZqUzz9.js} +1 -1
  20. package/dist/web/assets/{Jobs-C6W440Zy.js → Jobs-De3NyY5s.js} +1 -1
  21. package/dist/web/assets/{KindPage-DalVU3V4.js → KindPage-DWznWcLB.js} +1 -1
  22. package/dist/web/assets/{Migration-DycKheEL.js → Migration-BdOq6RO6.js} +1 -1
  23. package/dist/web/assets/{PageAgent-qe1dHEIV.js → PageAgent-dVvZtNoB.js} +1 -1
  24. package/dist/web/assets/{Product-xPHPwyRb.js → Product-ByZ8Qr3i.js} +3 -3
  25. package/dist/web/assets/{Production-C0xJTE_A.js → Production-D8L2TchK.js} +1 -1
  26. package/dist/web/assets/{Quality-HN4Y1xcO.js → Quality-CSZEuhZo.js} +1 -1
  27. package/dist/web/assets/{Readiness-CtTpkOIF.js → Readiness-bBu_84mx.js} +1 -1
  28. package/dist/web/assets/{Record-DEEvHQMt.js → Record-DWJEDj2C.js} +1 -1
  29. package/dist/web/assets/{Regression-BlTPM7di.js → Regression-D2VkPIhZ.js} +1 -1
  30. package/dist/web/assets/{Reports-C-pKyOOd.js → Reports-dF-O5HTI.js} +1 -1
  31. package/dist/web/assets/{Response-xh7r4ldF.js → Response-D4JW3pwi.js} +1 -1
  32. package/dist/web/assets/{Responsive-7uoXE0-6.js → Responsive-CLX9S27s.js} +1 -1
  33. package/dist/web/assets/{RunDiff-wZSP-_yc.js → RunDiff-BuL_-GwF.js} +1 -1
  34. package/dist/web/assets/{Runs-CatjSiWh.js → Runs-DyyaAiyA.js} +1 -1
  35. package/dist/web/assets/{Settings-26cvU21X.js → Settings-DnG6_QQj.js} +3 -3
  36. package/dist/web/assets/{Steps-DlqnuxiM.js → Steps-C-0zwG7T.js} +1 -1
  37. package/dist/web/assets/{TestCases-DWhXIHc9.js → TestCases-DXk9qsEL.js} +1 -1
  38. package/dist/web/assets/{TestData-Z9fozptW.js → TestData-D4al7-3Z.js} +1 -1
  39. package/dist/web/assets/{TestDebt-_R-P8oXN.js → TestDebt-BzOVDuS8.js} +1 -1
  40. package/dist/web/assets/{TestManagement-BS8Al6g-.js → TestManagement-T-NIlhc9.js} +1 -1
  41. package/dist/web/assets/{Tosca-zhsG-p3K.js → Tosca-D7tqMGK0.js} +1 -1
  42. package/dist/web/assets/{WhatsNew-gJQO1DB7.js → WhatsNew-DBViE2Qt.js} +1 -1
  43. package/dist/web/assets/{dataParts-Ds4Gjeep.js → dataParts-D56_9p6T.js} +1 -1
  44. package/dist/web/assets/{fold-DQqF7F_f.js → fold-UP5ihvz-.js} +1 -1
  45. package/dist/web/assets/{head-BQ9P1hk0.js → head-BpR3dGRT.js} +1 -1
  46. package/dist/web/assets/{highlight-CQWNqo7N.js → highlight--Ayfy7Gy.js} +1 -1
  47. package/dist/web/assets/{index-DeYZJBWf.js → index-CljX5dI4.js} +5 -5
  48. package/dist/web/assets/{logos-Cbs1qp4G.js → logos-B4e5nBuL.js} +1 -1
  49. package/dist/web/assets/{paletteCommands-BSqUaeAr.js → paletteCommands-ar4wAGok.js} +1 -1
  50. package/dist/web/assets/{qualityParts-j9yO6-qk.js → qualityParts-D_U5zhKC.js} +1 -1
  51. package/dist/web/index.html +1 -1
  52. package/package.json +1 -1
  53. package/py/forgeqe_engine/brand.py +45 -27
  54. package/py/forgeqe_engine/browser.py +34 -1
  55. package/py/forgeqe_engine/browserlaunch.py +16 -3
  56. package/py/forgeqe_engine/orb_assets.py +30 -0
  57. package/py/forgeqe_engine/profilename.py +168 -0
  58. package/py/forgeqe_engine/pwlaunch.mjs +3 -2
  59. package/py/forgeqe_engine/service.py +7 -1
  60. package/py/forgeqe_engine/settings.py +17 -0
  61. package/dist/web/assets/ApiTests-DMwtosgK.js +0 -10
@@ -9,6 +9,7 @@ import json
9
9
  import logging
10
10
  import math
11
11
  import os
12
+ import shutil
12
13
  import sys
13
14
  import time
14
15
  from pathlib import Path
@@ -677,7 +678,19 @@ async def _start_one(launch: Dict[str, Any], make: Any, timeout: float) -> Any:
677
678
  browser = make(_connect_kwargs(launch, url, local=True))
678
679
  keep_launcher(browser, proc, profile)
679
680
  else:
680
- browser = make(library_kwargs(launch))
681
+ kwargs = library_kwargs(launch)
682
+ made = None
683
+ if not kwargs.get("user_data_dir"):
684
+ # A fresh profile as before, but one the browser shows by the run's name (profilename.py).
685
+ from .profilename import named_profile
686
+
687
+ made = named_profile(launch.get("_profile_name"))
688
+ kwargs["user_data_dir"] = made
689
+ if launch.get("headless") is not True:
690
+ kwargs["args"] = [*(kwargs.get("args") or []), *tab_group_args(made, launch.get("_profile_name"), merged=True)]
691
+ browser = make(kwargs)
692
+ if made:
693
+ _MADE_PROFILES[id(browser)] = made
681
694
  before = set(_SEEN_PROFILES)
682
695
  try:
683
696
  await _within(browser.start(), timeout)
@@ -693,6 +706,23 @@ async def _start_one(launch: Dict[str, Any], make: Any, timeout: float) -> Any:
693
706
  # Browsers ForgeQE connected to and did not start (browser.launch: attach): never ended by it.
694
707
  _ATTACHED: set = set()
695
708
 
709
+ def tab_group_args(profile: str, name: Any, *, merged: bool) -> List[str]:
710
+ """
711
+ The flags that load the tab group extension (profilename.py) from a profile folder ForgeQE made, or none when it
712
+ could not be written. `merged`: the starter joins every --disable-features into one (the library does); Playwright
713
+ does not, and a second one would replace its own list, so there Chrome 137 on simply starts without the group.
714
+ """
715
+ from .profilename import TAB_GROUP_FEATURE, profile_name, tab_group_extension
716
+
717
+ ext = tab_group_extension(profile, profile_name(name))
718
+ if not ext:
719
+ return []
720
+ return [f"--load-extension={ext}", *([f"--disable-features={TAB_GROUP_FEATURE}"] if merged else [])]
721
+
722
+
723
+ # Named profile folders ForgeQE made for a direct start (profilename.py), by the Browser: removed once it is closed.
724
+ _MADE_PROFILES: Dict[int, str] = {}
725
+
696
726
  # Browsers whose dialogs (alert, confirm, prompt, leave-page) a person answers: the recorder's. The library answers every
697
727
  # other browser's itself (its popups watchdog: OK, or Cancel for a prompt), which a recording must not do.
698
728
  _PERSON_DIALOGS: set = set()
@@ -1268,6 +1298,9 @@ async def _shutdown_browser_instance(browser: Any) -> None:
1268
1298
  # Browsers that failed starts of this engine left running, found by their profile folders.
1269
1299
  with contextlib.suppress(Exception):
1270
1300
  await asyncio.to_thread(end_left_browsers)
1301
+ made = _MADE_PROFILES.pop(id(browser), None)
1302
+ if made and own_profile(made):
1303
+ await asyncio.to_thread(shutil.rmtree, made, True)
1271
1304
  if left:
1272
1305
  logger.info("closed %d browser%s the library left running", left, "" if left == 1 else "s")
1273
1306
 
@@ -18,7 +18,6 @@ import json
18
18
  import os
19
19
  import shutil
20
20
  import sys
21
- import tempfile
22
21
  from datetime import datetime, timezone
23
22
  from pathlib import Path
24
23
  from typing import Any, Dict, List, Optional, Tuple
@@ -113,12 +112,26 @@ async def launch_with_playwright(launch: Dict[str, Any], *, name: str) -> Tuple[
113
112
  if found is None:
114
113
  raise RuntimeError(f"Failed to start browser: {name}: ForgeQE's Playwright is not installed here.")
115
114
  runtime, entry = found
116
- profile = tempfile.mkdtemp(prefix="forgeqe-pw-")
115
+ from .profilename import named_profile
116
+
117
+ # A fresh profile, shown by the run's name (profilename.py).
118
+ profile = named_profile(launch.get("_profile_name"), prefix="forgeqe-pw-")
117
119
  args: List[str] = []
118
120
  size = launch.get("window_size")
119
121
  if isinstance(size, dict) and size.get("width") and size.get("height"):
120
122
  args.append(f"--window-size={int(size['width'])},{int(size['height'])}")
121
- request: Dict[str, Any] = {"headless": launch.get("headless") is True, "args": args, "userDataDir": profile, "timeoutMs": int(devtools_wait_seconds() * 1000)}
123
+ if launch.get("headless") is not True:
124
+ from .browser import tab_group_args
125
+
126
+ args += tab_group_args(profile, launch.get("_profile_name"), merged=False)
127
+ request: Dict[str, Any] = {
128
+ "headless": launch.get("headless") is True,
129
+ "args": args,
130
+ "userDataDir": profile,
131
+ "timeoutMs": int(devtools_wait_seconds() * 1000),
132
+ # Playwright starts Chrome with --disable-extensions; the tab group's own extension is the one let in.
133
+ "extensions": any(a.startswith("--load-extension=") for a in args),
134
+ }
122
135
  if launch.get("executable_path"):
123
136
  request["executablePath"] = str(launch["executable_path"])
124
137
  elif launch.get("channel") in ("chrome", "msedge"):
@@ -0,0 +1,30 @@
1
+ """Made by scripts/orb-asset.ts from @yogesharc/thinking-orbs 0.1.2 (dist/orb-core.js); run that instead of editing.
2
+
3
+ The thinking orbs' licence:
4
+
5
+ MIT License
6
+
7
+ Copyright (c) 2026 Yogesh
8
+
9
+ Permission is hereby granted, free of charge, to any person obtaining a copy
10
+ of this software and associated documentation files (the "Software"), to deal
11
+ in the Software without restriction, including without limitation the rights
12
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
+ copies of the Software, and to permit persons to whom the Software is
14
+ furnished to do so, subject to the following conditions:
15
+
16
+ The above copyright notice and this permission notice shall be included in all
17
+ copies or substantial portions of the Software.
18
+
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
+ SOFTWARE.
26
+ """
27
+
28
+ ORB_VERSION = "0.1.2"
29
+ ORB_SOURCE_SHA256 = "79d8ec978d20703dd2588d682db937fd76a0d1e7daef574f25ec9895d428748e"
30
+ ORB_JS = "(() => {\n/** One state per thing an agent does, and the looks each comes in, `default` first. */\nconst VARIANTS = {\n idle: [\"default\", \"blink\"],\n working: [\"default\", \"gyro\"],\n reasoning: [\"default\", \"twins\"],\n searching: [\"default\", \"lighthouse\"],\n background: [\"default\", \"spiral\"],\n retrying: [\"default\", \"surge\"],\n compacting: [\"default\", \"squeeze\", \"fuse\"],\n waiting: [\"default\"],\n using: [\"default\", \"tap\", \"scroll\", \"type\", \"zoom\", \"snap\", \"record\"],\n};\nconst TAU = Math.PI * 2;\nconst GOLDEN = Math.PI * (3 - Math.sqrt(5));\nconst ease = (x) => (1 - Math.cos(Math.PI * x)) / 2;\nconst hash = (n) => {\n const s = Math.sin(n * 127.1) * 43758.5453;\n return s - Math.floor(s);\n};\nconst dist2 = (a, b) => (a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 + (a[2] - b[2]) ** 2;\n/**\n * The k points nearest pts[i], nearest first: one pass keeping a short sorted list, not a sort of them all.\n * Plain loops, as it runs once per dot at mount. @internal Shared with `renders.ts`, not part of the API.\n */\nconst nearest = (pts, i, k) => {\n const idx = [], d = [], p = pts[i];\n for (let j = 0; j < pts.length; j++) {\n if (j === i)\n continue;\n const e = dist2(p, pts[j]);\n let at = idx.length;\n if (at === k) {\n if (e >= d[k - 1])\n continue;\n at--;\n }\n while (at > 0 && d[at - 1] > e) {\n idx[at] = idx[at - 1];\n d[at] = d[at - 1];\n at--;\n }\n idx[at] = j;\n d[at] = e;\n }\n return idx;\n};\n/** Time for one full turn, in ms. Retrying's two set their own pace in `yawOf`. */\nconst PERIOD = {\n idle: 6500,\n \"idle-blink\": 13000,\n working: 3000,\n \"working-gyro\": 3000,\n reasoning: 6500,\n \"reasoning-twins\": 6500,\n searching: 13000,\n \"searching-lighthouse\": 13000,\n background: 13000,\n \"background-spiral\": 13000,\n retrying: 13000,\n \"retrying-surge\": 13000,\n compacting: 10000,\n \"compacting-squeeze\": 10000,\n \"compacting-fuse\": 10000,\n waiting: 13000,\n using: 13000,\n \"using-tap\": 13000,\n \"using-scroll\": 13000,\n \"using-type\": 13000,\n \"using-zoom\": 13000,\n \"using-snap\": 13000,\n \"using-record\": 13000,\n};\n/**\n * One clock (ms) per look (state and speed), so every orb of it stays in phase. A frame's gap is\n * capped at 100ms, so a tab coming back from the background, or a look nobody had in view, carries\n * on instead of jumping.\n */\nconst clocks = new Map();\nfunction tick(look, now, speed) {\n let c = clocks.get(look);\n if (!c)\n clocks.set(look, (c = { t: 0, last: now }));\n // A frame's timestamp can predate the performance.now() that started the clock, so never step back.\n if (now > c.last) {\n c.t += Math.min(now - c.last, 100) * speed;\n c.last = now;\n }\n return c.t;\n}\n/**\n * A spring settling from 0 to 1: shoots ~22% past, dips ~5% under, and lands on 1 exactly at\n * x=1. The last term trims the spring's tiny leftover so the next phase starts clean.\n */\nconst spring = (x) => 1 - Math.exp(-4.5 * x) * Math.cos(3 * Math.PI * x) - x * Math.exp(-4.5);\n/**\n * Retrying's spin at `t` for speed `w` (rad/ms), every 3.2s: turns 2s, brakes over 0.2s, springs\n * back 60% of what it turned over 0.8s, then speeds up again over 0.2s. Whole cycles stack, so it never jumps.\n */\nfunction rewind(t, w) {\n const P = 3200, k = Math.floor(t / P), u = t - k * P;\n const back = 0.6 * 2100 * w;\n // Braking and speeding up are each linear over 200ms, so each covers half its span at full speed: 100ms' worth.\n const fwd = (2000 + 100 + 100) * w;\n let a;\n if (u < 2000)\n a = u * w;\n else if (u < 2200) {\n const x = (u - 2000) / 200;\n a = (2000 + 200 * (x - (x * x) / 2)) * w;\n }\n else if (u < 3000)\n a = 2100 * w - back * spring((u - 2200) / 800);\n else {\n const x = (u - 3000) / 200;\n a = 2100 * w - back + 100 * x * x * w;\n }\n return k * (fwd - back) + a;\n}\nfunction yawOf(state, t) {\n // The rewind at double time, at half the rate, so it still averages 4.5s a turn.\n if (state === \"retrying\")\n return rewind(2 * t, TAU / 9000);\n if (state === \"retrying-surge\") {\n // Every turn, at 3.25s, starts fast and eases out, then the next launches straight away.\n const turns = t / 3250, u = turns - Math.floor(turns);\n return (Math.floor(turns) + (1 - (1 - u) ** 3)) * TAU;\n }\n // Scroll rolls instead, so it holds still side to side.\n if (state === \"using-scroll\")\n return 0.4;\n // Snap turns for most of each beat and stops dead for the rest, as the frame is caught.\n if (state === \"using-snap\")\n return ((Math.floor(t / BEAT) * SPIN + Math.min(t % BEAT, SPIN)) / PERIOD[state]) * TAU;\n return (t / PERIOD[state]) * TAU;\n}\n/** Working's ring axis in view space: tipped 30° toward you, then rolled 10° so its right end rides higher. */\nconst RING_AXIS = (() => {\n const tip = (30 * Math.PI) / 180, roll = (10 * Math.PI) / 180;\n return [-Math.sin(roll) * Math.cos(tip), Math.cos(roll) * Math.cos(tip), Math.sin(tip)];\n})();\n/** Gyro and Squeeze: the ends turn up to this far (rad) against the middle, opposite ways. */\nconst TWIST = 1.4;\n/** Lighthouse: its beam leans this far (rad) right, and its trail dies out this far behind it. */\nconst LEAN = (30 * Math.PI) / 180, TRAIL = Math.PI / 2;\n// Searching: a lens hops between spots on the front of the sphere. Each hop is one\n// segment: it glides for the first MOVE of it, then lingers on the spot.\nconst LENS_MS = 1800, MOVE = 0.4;\nconst LENS = 0.6; // angular radius in radians, a bit under half the sphere's width across\n/** The k-th spot, in view space (z toward you). Kept 15–45° off centre, never on the rim. */\nfunction spot(k) {\n const phi = k * 2.45 + hash(k) * 1.5, theta = ((15 + 30 * hash(k + 0.5)) * Math.PI) / 180;\n return [Math.sin(theta) * Math.cos(phi), Math.sin(theta) * Math.sin(phi), Math.cos(theta)];\n}\nfunction lensAt(t) {\n const k = Math.floor(t / LENS_MS), u = t / LENS_MS - k;\n const e = u < MOVE ? (1 - Math.cos((u / MOVE) * Math.PI)) / 2 : 1;\n const a = spot(k), b = spot(k + 1);\n const v = a.map((ai, j) => ai + (b[j] - ai) * e), n = Math.hypot(v[0], v[1], v[2]);\n return v.map((vi) => vi / n);\n}\n// Using: a cursor in view space, like the lens, that glides between spots on the front and acts on them.\n// PTR is its angular radius, PRESS how wide a click dents, and a click's ripple runs out over RIPPLE_MS.\nconst PTR = 0.45, PRESS = 0.5, RIPPLE_MS = 600;\n/** The cursor's k-th resting spot: the lens's spots, further along so the two don't move alike. */\nconst mark = (k) => spot(k + 57);\nconst slide = (a, b, e) => {\n const v = a.map((ai, j) => ai + (b[j] - ai) * e), n = Math.hypot(v[0], v[1], v[2]);\n return v.map((vi) => vi / n);\n};\n/** A dot's weight under a soft disc `w` rad wide, from its angle `ang` off the centre. */\nconst bump = (ang, w) => (ang < w ? (1 - (ang / w) ** 2) ** 2 : 0);\n/** Tap: every TAP ms the cursor glides to the next spot over the first 35%, settles, and clicks halfway. */\nconst TAP = 1400;\nfunction tapAt(t) {\n const k = Math.floor(t / TAP), u = t / TAP - k;\n const at = slide(mark(k), mark(k + 1), u < 0.35 ? ease(u / 0.35) : 1);\n return { at, click: mark(u < 0.5 ? k : k + 1), since: (u < 0.5 ? u + 0.5 : u - 0.5) * TAP };\n}\n/** How far a click is pressed `s` ms after it: in over 60ms, out over the next 240ms. */\nconst pressOf = (s) => (s < 60 ? s / 60 : Math.max(0, 1 - (s - 60) / 240) ** 2);\n/** Using: its cursor, the classic arrow's outline, x right and y down from its tip, scaled to ARROW_H sphere radii tall. */\nconst ARROW_H = 1;\nconst ARROW = [[0, 0], [0, 16], [4, 12], [7, 18], [9, 17], [6, 11], [11, 11]].map(([x, y]) => [(x / 18) * ARROW_H, (y / 18) * ARROW_H]);\n/** Whether (x, y) falls inside `poly`, by counting the edges a ray from it crosses. */\nfunction inside(poly, x, y) {\n let hit = false;\n for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) {\n const [xi, yi] = poly[i], [xj, yj] = poly[j];\n if (yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi)\n hit = !hit;\n }\n return hit;\n}\n/** Using's tip for a cursor spot: pulled in and up-left, so the arrow hanging below it stays on the face. */\nconst HOME = [-0.3, 0.5];\nconst onFace = (x, y) => [x, y, Math.sqrt(Math.max(0, 1 - x * x - y * y))];\nconst tipOf = (p) => onFace(HOME[0] + 0.35 * p[0], HOME[1] + 0.35 * p[1]);\n/** Using given a direction: every AIM ms it glides out from its rest that way, clicks, and comes back. */\nconst AIM = 1800;\nfunction aimAt(t, phi) {\n const u = (t % AIM) / AIM;\n const e = u < 0.3 ? ease(u / 0.3) : u < 0.6 ? 1 : u < 0.85 ? 1 - ease((u - 0.6) / 0.25) : 0;\n const out = (s) => onFace(HOME[0] + 0.3 * s * Math.cos(phi), HOME[1] + 0.3 * s * Math.sin(phi));\n return { at: out(e), click: out(1), since: (u < 0.45 ? u + 0.55 : u - 0.45) * AIM };\n}\n/** Zoom: every ZOOM ms the face swells toward you over a quarter, holds, and eases back. */\nconst ZOOM = 2600;\n/**\n * Using · Snap and Idle · Blink, on one BEAT. Snap spins for SPIN ms of it, then stops dead for the rest, with a\n * flash as it stops. Blink's lids close from top and bottom over 120ms, meet for 60ms, and part\n * over 250ms; it returns how far from the middle they are.\n */\nconst BEAT = 2600, SPIN = 2100;\nfunction snapAt(t) {\n const u = (t % BEAT) - SPIN;\n return u < 0 ? 0 : Math.exp(-u / 220);\n}\nfunction blinkAt(t) {\n const u = t % BEAT;\n return u < 120 ? 1.2 * (1 - ease(u / 120)) : u < 180 ? 0 : u < 430 ? 1.2 * ease((u - 180) / 250) : 1.2;\n}\n/** Record: a recording light's pulse, from 0 (dim and small) to 1 and back every REC ms in straight lines, never resting at either end. */\nconst REC = 1200;\nconst recAt = (t) => Math.abs(1 - 2 * ((t % REC) / REC));\nfunction zoomAt(t) {\n const u = (t % ZOOM) / ZOOM;\n return u < 0.25 ? ease(u / 0.25) : u < 0.5 ? 1 : u < 0.75 ? 1 - ease((u - 0.5) / 0.25) : 0;\n}\n/** Scroll: the sphere rolls up FLING rad a FLICK at a time, fast at first and coasting to a stop. */\nconst FLICK = 1500, FLING = 1.1;\nfunction scrollAt(t) {\n const k = Math.floor(t / FLICK), x = Math.min(1, (t / FLICK - k) / 0.75);\n return { by: (k + 1 - (1 - x) ** 3) * FLING, pace: (1 - x) ** 2 };\n}\n/** The ways Scroll goes, as a page scrolls, by their angle on screen in degrees: right 0, up 90. */\nconst DIRECTIONS = { right: 0, \"up-right\": 45, up: 90, \"up-left\": 135, left: 180, \"down-left\": 225, down: 270, \"down-right\": 315 };\n/** Scroll without a direction: each flick carries the face its own way on screen: up, down, up-right, left, right, down-left. */\nconst PAN = [90, 270, 45, 180, 0, 225].map((deg) => (deg * Math.PI) / 180);\n/** The 3×3 turn (row-major) by `th` rad that carries the front of the sphere `phi` rad round from right on screen. */\nfunction panTurn(phi, th) {\n // The axis lies on screen, square to the way the face moves.\n const ax = -Math.sin(phi), ay = Math.cos(phi), s = Math.sin(th), c = Math.cos(th), v = 1 - c;\n return [c + ax * ax * v, ax * ay * v, ay * s, ax * ay * v, c + ay * ay * v, -ax * s, -ay * s, ax * s, c];\n}\nconst times = (m, n) => m.map((_, i) => m[i - (i % 3)] * n[i % 3] + m[i - (i % 3) + 1] * n[(i % 3) + 3] + m[i - (i % 3) + 2] * n[(i % 3) + 6]);\n/**\n * Type: a short paragraph typed onto the face, held, then cleared. TEXT is its lines, \"x\" a letter\n * and \" \" a space, so words read as bars with gaps between. Each character is a cell CELL wide from\n * LEFT, and lines sit LEAD apart down from TOP, in sphere radii on screen.\n */\nconst TEXT = [\"xxxx xxx xx\", \"xxxxx xx xxxx\", \"xxx xxxxx\"];\nconst CELL = 0.09, LEAD = 0.3, TOP = 0.33, LEFT = -0.5;\n/** Every key in order, with when it lands: 70–130ms a letter, longer after a word, longer still at a line's end. */\nconst KEYS = (() => {\n let at = 0;\n return TEXT.flatMap((line, row) => [...line].map((ch, col) => {\n const key = { row, col, at };\n at += ch === \" \" ? 200 : col === line.length - 1 ? 350 : 70 + 60 * hash(row * 31 + col);\n return key;\n }));\n})();\n/** Which key types each cell, by row then column. */\nconst KEY_OF = TEXT.map((_, row) => KEYS.flatMap((k, i) => (k.row === row ? [i] : [])));\nconst TYPED = KEYS[KEYS.length - 1].at, PARAGRAPH = TYPED + 1300;\nfunction typeAt(t) {\n const c = t % PARAGRAPH;\n let n = 0;\n while (n < KEYS.length && KEYS[n].at <= c)\n n++;\n const since = n ? c - KEYS[n - 1].at : Infinity;\n // The caret waits where the next key lands, or after the last one; it blinks only while idle.\n const next = KEYS[n] ?? { row: TEXT.length - 1, col: TEXT[TEXT.length - 1].length };\n const blink = since < 300 ? 1 : +(Math.floor(c / 450) % 2 === 0);\n return { n, since, blink, caret: [LEFT + next.col * CELL, TOP - next.row * LEAD], fade: c < TYPED + 900 ? 1 : Math.max(0, 1 - (c - TYPED - 900) / 300) };\n}\n/**\n * Reasoning's walk: a hop every HOP ms to one of the REACH nearest dots, with the last TAIL lit\n * and fading. WALK dots of each walk are kept.\n */\nconst HOP = 220, TAIL = 5, REACH = 24, WALK = 16;\n/** The orb's own look: a circle per dot. No dot drops below 0.45px, or it renders as a grey haze. */\nconst DOTS = {\n mount: ({ make, pts }) => {\n const els = pts.map(() => make(\"circle\")), hidden = new Uint8Array(pts.length);\n return {\n dot(i, x, y, r, a) {\n const el = els[i], o = a.toFixed(2);\n // A hidden dot stays hidden wherever it is, so skip it: about a third of a sphere, every frame.\n if (o === \"0.00\" && hidden[i])\n return;\n hidden[i] = +(o === \"0.00\");\n el.setAttribute(\"cx\", x.toFixed(2));\n el.setAttribute(\"cy\", y.toFixed(2));\n el.setAttribute(\"r\", Math.max(0.45, r).toFixed(2));\n el.setAttribute(\"fill-opacity\", o);\n },\n };\n },\n};\n/**\n * Background · Spiral's eight arms, wound pole to pole, turning a radian of longitude per radian of\n * latitude. Toward the poles every other arm stops where they'd crowd, then every other of those,\n * so the caps fill without clotting.\n */\nfunction arms(count) {\n const at = (lat, lon) => [Math.cos(lat) * Math.cos(lon), Math.sin(lat), Math.cos(lat) * Math.sin(lon)];\n const g = Math.sqrt((4 * Math.PI) / count), n = 8, along = 0.6 * g;\n return Array.from({ length: n }, (_, m) => {\n const room = m ? m & -m : n;\n const lim = Math.min((85 * Math.PI) / 180, Math.acos(Math.min(1, (g * n) / (TAU * room))));\n const out = [];\n // Each arm starts at its own offset so the dots don't line up into rings across arms.\n for (let lat = -lim + ((m * 0.618) % 1) * along; lat <= lim; lat += along / Math.sqrt(1 + Math.cos(lat) ** 2))\n out.push(at(lat, (m / n) * TAU - lat));\n return out;\n }).flat();\n}\n/** Where the dots sit: on a unit sphere, a Fibonacci spiral, or for Background · Spiral, eight arms. */\nfunction distribute(state, count, shape) {\n if (shape)\n return shape.points(count, state);\n if (state === \"background-spiral\")\n return arms(count);\n return Array.from({ length: count }, (_, i) => {\n const y = 1 - (2 * (i + 0.5)) / count, r = Math.sqrt(1 - y * y), th = i * GOLDEN;\n return [r * Math.cos(th), y, r * Math.sin(th)];\n });\n}\n/**\n * Draws an orb into `svg` and keeps it moving until `destroy()`; `pause()` holds it on its frame\n * and `play()` carries on. The orb draws in `currentColor`, so the svg's CSS `color` tints it.\n * With reduced motion it holds still. Needs a browser: call it once the svg is on the page.\n */\nfunction mountOrb(svg, { state: asked, variant, size = 20, speed = 1, label, shape, render = DOTS, density = 1, dotSize = 1, tilt = 20, direction } = {}) {\n // A state that doesn't exist (from plain JS, say) falls back to idle, and a variant the state doesn't have to its default.\n // Idle was once called base, so that name still finds it.\n const named = asked === \"base\" ? \"idle\" : asked;\n const which = named && Object.hasOwn(VARIANTS, named) ? named : \"idle\";\n const own = variant !== \"default\" && VARIANTS[which].includes(variant ?? \"\");\n const state = (own ? `${which}-${variant}` : which);\n const attrs = { width: size, height: size, viewBox: `0 0 ${size} ${size}`, fill: \"currentColor\" };\n for (const [k, v] of Object.entries(attrs))\n svg.setAttribute(k, String(v));\n if (label) {\n svg.setAttribute(\"role\", \"img\");\n svg.setAttribute(\"aria-label\", label);\n svg.removeAttribute(\"aria-hidden\");\n }\n else {\n svg.setAttribute(\"aria-hidden\", \"true\");\n svg.removeAttribute(\"role\");\n svg.removeAttribute(\"aria-label\");\n }\n // Background's orb has a quarter of the dots, so each comes out twice the size.\n // Using draws its arrow, and Type its text, in the dots: that takes about 1000 of them, finer, however small the orb.\n const dens = state === \"background\" ? 1 : state === \"using\" || state === \"using-type\" ? Math.max(4, 1000 / size) : 4;\n const count = Math.max(8, Math.round(size * dens * density));\n // Dots shrink as they multiply, so the sphere's coverage holds steady.\n const form = typeof shape === \"function\" ? { points: shape } : shape;\n const c = size / 2, R = c * 0.8 * (form?.scale ?? 1), rs = (size / 64) ** 0.6 * (0.72 * Math.sqrt(4 / dens)) * dotSize;\n const pts = distribute(state, count, form);\n // SVG, not canvas: vectors stay sharp under pinch zoom. One ink blends the same in any order, so no depth sort.\n const make = (tag) => svg.appendChild(document.createElementNS(\"http://www.w3.org/2000/svg\", tag));\n const drawer = render.mount({ make: make, pts, size, radius: rs }), flat = !!render.flat;\n // A walk needs somewhere to go: with under two dots, Reasoning just spins.\n const reasoning = (state === \"reasoning\" || state === \"reasoning-twins\") && pts.length > 1;\n const compacting = state === \"compacting\" || state === \"compacting-fuse\";\n // Reasoning: each dot's REACH nearest neighbours for the walk to hop between, and each walker's walk so far (head last).\n const near = reasoning\n ? pts.map((_, i) => nearest(pts, i, REACH))\n : [];\n const walks = Array.from({ length: state === \"reasoning-twins\" ? 2 : 1 }, () => []);\n let hops = 0;\n // Scroll's whole flicks so far when it pans, so each frame stacks only the new ones.\n let panned = { k: 0, m: [1, 0, 0, 0, 1, 0, 0, 0, 1] };\n const draw = (t) => {\n const period = PERIOD[state], yaw = yawOf(state, t);\n const scroll = state === \"using-scroll\" ? scrollAt(t) : null;\n const way = direction && DIRECTIONS[direction];\n let pan = null;\n if (scroll && way !== undefined) {\n // Given a direction, Scroll keeps to it, and the face moves against it, as a page's content does.\n pan = panTurn((way * Math.PI) / 180 + Math.PI, scroll.by);\n }\n else if (scroll) {\n // Without one it pans: the flicks so far, stacked up once each, then the one under way on top.\n const k = Math.floor(t / FLICK);\n if (k < panned.k)\n panned = { k: 0, m: [1, 0, 0, 0, 1, 0, 0, 0, 1] };\n for (; panned.k < k; panned.k++)\n panned.m = times(panTurn(PAN[panned.k % PAN.length], FLING), panned.m);\n pan = times(panTurn(PAN[k % PAN.length], scroll.by - k * FLING), panned.m);\n }\n // Working · Gyro's axis circles every 5s like a spinning top's, tipping ±10° toward you and leaning ±12° side to side.\n const gyro = state === \"working-gyro\" ? (t / 5000) * TAU : null;\n const pitch = (((flat ? 0 : tilt) + (form?.tip ?? 0) + (gyro === null ? 0 : 10 * Math.cos(gyro))) * Math.PI) / 180;\n const roll = gyro === null ? 0 : ((12 * Math.sin(gyro)) * Math.PI) / 180, sr = Math.sin(roll), cr = Math.cos(roll);\n const sy = Math.sin(yaw), cy = Math.cos(yaw), st = Math.sin(pitch), ct = Math.cos(pitch);\n // How far a dot faces you right now, which the walk steers by.\n const facing = (k) => pts[k][1] * st + (-pts[k][0] * sy + pts[k][2] * cy) * ct;\n // Reasoning: how lit each dot on the walk's tail is, the head brightest.\n const lit = new Map();\n if (reasoning) {\n const s = t / HOP, n = Math.floor(s), f = s - n;\n if (!walks[0].length) {\n // The first walker starts at the dot facing you most; a second, at a front dot well away from it.\n const first = [...pts.keys()].reduce((b, k) => (facing(k) > facing(b) ? k : b), 0);\n const apart = (k) => facing(k) + dist2(pts[k], pts[first]);\n walks.forEach((walk, w) => walk.push(w ? [...pts.keys()].reduce((b, k) => (apart(k) > apart(b) ? k : b), 0) : first));\n }\n hops = Math.max(hops, n - WALK);\n for (; hops < n; hops++) {\n walks.forEach((walk, w) => {\n // Hop to the neighbour that faces you most, with a little chance mixed in so it wanders.\n const recent = walk.slice(-8), from = walk[walk.length - 1];\n let best = -1, score = -Infinity;\n // With two walkers, each also pushes away from the other's head, up to ~45° apart.\n const other = state === \"reasoning-twins\" ? walks[1 - w].at(-1) : undefined;\n near[from].forEach((k, j) => {\n const apart = other === undefined ? 0 : 1.2 * Math.min(Math.sqrt(dist2(pts[k], pts[other])), 0.8);\n const sc = facing(k) + 0.35 * hash(hops * 31 + j + w * 977) + apart;\n if (!recent.includes(k) && sc > score) {\n score = sc;\n best = k;\n }\n });\n // With only a handful of dots every neighbour can be recent, so it hops back to the nearest.\n walk.push(best < 0 ? near[from][0] : best);\n if (walk.length > WALK)\n walk.shift();\n });\n }\n const light = (k, v) => k !== undefined && lit.set(k, Math.max(lit.get(k) ?? 0, v));\n for (const walk of walks)\n for (let j = TAIL - 1; j >= 0; j--)\n light(walk[walk.length - 1 - j], j === 0 ? ease(Math.min(1, f * 2)) : 1 - (j - 1 + f) / TAIL);\n }\n // Waiting: a comet's head runs round a lap every 2s on screen, spiralling from 70° north to\n // 70° south every 6s. `ahead` is how fast it moves over the sphere's own surface, in rad/ms.\n const head = (t / 2000) * TAU + yaw, ahead = TAU / 2000 + TAU / period;\n const headLat = (tt) => ((70 * Math.PI) / 180) * (1 - 2 * ((tt % 6000) / 6000));\n // It fades in and out over the first and last ~10% of each descent, so the jump back to the top doesn't show.\n const glow = Math.min(1, 3 * Math.sin(Math.PI * ((t % 6000) / 6000)));\n // The lens lives in view space, so it searches the face you see while the sphere turns under it.\n const lens = state === \"searching\" ? lensAt(t) : null;\n // Gyro and Squeeze twist back and forth every 2.6s, Gyro at half the twist.\n const tw = state === \"working-gyro\" ? 0.5 * Math.sin((t / 2600) * TAU) : state === \"compacting-squeeze\" ? Math.sin((t / 2600) * TAU) : 0;\n // Compacting: a line crosses left to right over 2s, packing what it's passed, then all lets go\n // over 0.8s. Compacting springs back past loose; Fuse burns out like a firework, with no bounce.\n let sweep = null;\n if (compacting) {\n const u = (t % 2800) / 2800, s = (u - 0.7) / 0.3;\n const release = state === \"compacting-fuse\"\n ? (1 - s) ** 3\n : s < 0.45\n ? 1 - 1.25 * ease(s / 0.45)\n : s < 0.7\n ? -0.25 * (1 - (s - 0.45) / 0.25) ** 2\n : 0;\n sweep = { at: -1.15 + 2.3 * Math.min(1, u / 0.7), hold: u < 0.7 ? 1 : release };\n }\n let tap = null;\n if (state === \"using-tap\")\n tap = tapAt(t);\n // Using's cursor is an arrow drawn in the dots under it.\n const outline = state === \"using\";\n if (outline) {\n // Given a direction it keeps clicking that side; without one it wanders the face.\n const p = way === undefined ? tapAt(t) : null;\n tap = p ? { ...p, at: tipOf(p.at), click: tipOf(p.click) } : aimAt(t, ((way ?? 0) * Math.PI) / 180);\n }\n // The arrow shrinks toward its tip as a click presses.\n const k = outline && tap ? 1 - 0.15 * pressOf(tap.since) : 1;\n const type = state === \"using-type\" ? typeAt(t) : null;\n const zoom = state === \"using-zoom\" ? zoomAt(t) : null;\n const flash = state === \"using-snap\" ? snapAt(t) : null;\n const lids = state === \"idle-blink\" ? blinkAt(t) : null;\n const rec = state === \"using-record\" ? recAt(t) : null;\n pts.forEach(([x, y, z], i) => {\n // Twist turns each dot by an angle that grows with its height: top and bottom opposite ways.\n const turn = yaw + TWIST * tw * y;\n const [ly, lc] = tw ? [Math.sin(turn), Math.cos(turn)] : [sy, cy];\n const z1 = -x * ly + z * lc;\n let vx = x * lc + z * ly, vy = y * ct - z1 * st;\n // Which way the spin carries this dot across the screen, for renders that draw along it.\n const sx = z1, sy2 = vx * st;\n let vz = y * st + z1 * ct;\n if (pan)\n [vx, vy, vz] = [0, 3, 6].map((j) => pan[j] * vx + pan[j + 1] * vy + pan[j + 2] * vz);\n const d = (vz + 1) / 2;\n let r = (0.5 + 1.4 * d) * rs;\n // Opacity ramps from 0 just behind the rim to 1 at the front, so the back fades instead of leaving a haze.\n let a = Math.max(0, (d - 0.3) / 0.7);\n if (lens) {\n // By direction, not position: a solid's dots sit at different distances from the centre.\n const ang = Math.acos(Math.min(1, (vx * lens[0] + vy * lens[1] + vz * lens[2]) / Math.hypot(vx, vy, vz)));\n const w = ang < LENS ? (1 - (ang / LENS) ** 2) ** 2 : 0;\n // Dim what's outside the lens. At 24px and under, dots are ~1px and growth alone barely reads, so it enlarges harder.\n a *= 1 - 0.55 * (1 - w);\n if (size <= 24)\n r *= 1 + 0.5 * w;\n if (w) {\n // Swell out of the surface, then spread away from the lens centre like a magnifier, and enlarge.\n vx *= 1 + 0.12 * w;\n vy *= 1 + 0.12 * w;\n vx += (vx - lens[0]) * 0.35 * w;\n vy += (vy - lens[1]) * 0.35 * w;\n r *= 1 + 0.9 * w;\n a += (1 - a) * w;\n }\n }\n if (sweep) {\n // Packed dots pull in and shrink, fully once the line is 0.2 past them: Compacting by 30%\n // and 45%, Fuse by 20% and 30%, fading them to half as well.\n const q = vx, w = Math.min(1, Math.max(0, (sweep.at - q) / 0.2)) * sweep.hold;\n const k = state === \"compacting\" ? 1.5 : 1;\n vx *= 1 - 0.2 * k * w;\n vy *= 1 - 0.2 * k * w;\n r *= 1 - 0.3 * k * w;\n if (state === \"compacting-fuse\") {\n a *= 1 - 0.5 * w;\n // Fuse's line burns on the near half only, dots at it growing and lighting up.\n const g = Math.exp(-(((q - sweep.at) / 0.08) ** 2)) * Math.max(0, sweep.hold) * Math.min(1, d / 0.5);\n r *= 1 + 0.8 * g;\n a += (1 - a) * g;\n }\n }\n if (state === \"working\") {\n // Every 1.7s a ring of light runs down the sphere over 1.2s, through the back as well as the\n // front. What it's passed pulls in 8% and shrinks 15%, then lets go over 0.5s.\n const u = t % 1700, at = 1.3 - 2.6 * ease(Math.min(1, u / 1200));\n // Halftone and Lines are flat pictures, so there the ring runs straight down rather than leaning into depth.\n const q = flat ? vy : vx * RING_AXIS[0] + vy * RING_AXIS[1] + vz * RING_AXIS[2];\n const g = u < 1200 ? Math.exp(-(((q - at) / 0.2) ** 2)) : 0;\n r *= 1 + 0.6 * g;\n a += (1 - a) * g;\n const w = Math.min(1, Math.max(0, (q - at) / 0.2)) * (u < 1200 ? 1 : 1 - Math.min(1, 1.6 * ((u - 1200) / 800)));\n vx *= 1 - 0.08 * w;\n vy *= 1 - 0.08 * w;\n r *= 1 - 0.15 * w;\n }\n if (state === \"searching-lighthouse\") {\n // A beam leaning 30° right circles the axis, a lap every 2.5s, crossing the face left to\n // right, with a trail dying out 90° behind it. It's full on the near half and a quarter\n // behind, over a sphere resting at 50%.\n a *= 0.5;\n const lr = Math.sin(LEAN), lc = Math.cos(LEAN);\n const across = vx * lc - vy * lr, toward = -st * (vx * lr + vy * lc) + ct * vz;\n const off = Math.atan2(across, toward) - (((t / 2500) % 1) * TAU - Math.PI);\n const dphi = ((((off + Math.PI) % TAU) + TAU) % TAU) - Math.PI;\n const beam = dphi < 0 ? Math.max(0, 1 + dphi / TRAIL) : Math.exp(-((dphi / 0.45) ** 2));\n const g = beam * (0.25 + 0.75 * Math.min(1, Math.max(0, (d - 0.4) / 0.3)));\n r *= 1 + 0.6 * g;\n a += (1 - a) * g;\n }\n if (reasoning) {\n // The sphere rests at 50%, so only the walk reaches full.\n const spark = lit.get(i) ?? 0;\n a *= 0.5;\n if (spark) {\n r *= 1 + 0.8 * spark;\n a += (1 - a) * spark;\n }\n }\n if (state === \"waiting\") {\n // A sharp head and a long fading tail, lit round the back too, over a sphere at 50%.\n // Its width is measured along the surface, so it keeps its size away from the equator.\n const lat = Math.asin(y / (Math.hypot(x, y, z) || 1)), lon = Math.atan2(z, x);\n const off = Math.atan2(Math.sin(lon - head), Math.cos(lon - head)), along = off * Math.cos(lat);\n const g = Math.exp(-(((lat - headLat(t + off / ahead)) / 0.28) ** 2)) * Math.exp(-((along / (off * ahead > 0 ? 0.12 : 1)) ** 2));\n const w = glow * g ** 0.6;\n a = a * 0.5 + (1 - a * 0.5) * w;\n r *= 1 + 1.1 * w;\n }\n if (tap) {\n // The angle off a view-space direction, by direction like the lens.\n const n = Math.hypot(vx, vy, vz) || 1;\n const off = (p) => Math.acos(Math.min(1, Math.max(-1, (vx * p[0] + vy * p[1] + vz * p[2]) / n)));\n // Using rests darker, so the arrow stands out where its dots crowd together at small sizes.\n a *= outline ? 0.25 : 0.5;\n // A click dents what's under it for 300ms, and a ring runs out from it, fading.\n const s = tap.since, ptr = outline ? 0 : bump(off(tap.at), PTR), ak = off(tap.click);\n const press = pressOf(s), pw = press * bump(ak, PRESS);\n const run = Math.min(1, s / RIPPLE_MS);\n const ring = Math.exp(-(((ak - (0.15 + 1.3 * (1 - (1 - run) ** 2))) / 0.18) ** 2)) * (1 - run) ** 2;\n vx *= 1 - 0.14 * pw;\n vy *= 1 - 0.14 * pw;\n r *= (1 - 0.35 * pw) * (1 + 0.7 * Math.max(ring, ptr * (1 - press)));\n a += (1 - a) * Math.max(ptr, ring);\n if (outline && inside(ARROW, (vx - tap.at[0]) / k, (tap.at[1] - vy) / k)) {\n // The dots inside the arrow light up, on the near side only. They barely grow, or they'd blur its edge.\n const lit = Math.min(1, Math.max(0, (d - 0.5) / 0.2));\n r *= 1 + 0.15 * lit;\n a += (1 - a) * lit;\n }\n }\n if (type) {\n // The paragraph lights cell by cell as it's typed, the newest letter brightest, spaces left\n // dark. The caret is an upright bar where the next key lands. The rest sits dark, like Using.\n a *= 0.25;\n const row = Math.round((TOP - vy) / LEAD), col = Math.floor((vx - LEFT) / CELL), key = KEY_OF[row]?.[col];\n let g = 0;\n if (key !== undefined && key < type.n && TEXT[row][col] === \"x\" && Math.abs(TOP - row * LEAD - vy) < 0.085)\n g = 0.75 + (key === type.n - 1 ? 0.25 * Math.exp(-type.since / 120) : 0);\n const [cx, cy] = type.caret;\n if (Math.abs(vy - cy) < 0.1)\n g = Math.max(g, type.blink * Math.exp(-(((vx - cx) / 0.04) ** 2)));\n a += (1 - a) * g * type.fade * Math.min(1, Math.max(0, (d - 0.5) / 0.2));\n }\n if (zoom) {\n // The front swells out toward the rim and its dots grow, as if you'd moved closer. Past the rim they fade.\n const w = zoom * Math.max(0, vz);\n vx *= 1 + 0.45 * w;\n vy *= 1 + 0.45 * w;\n r *= 1 + 0.8 * w;\n a *= Math.min(1, Math.max(0, (1.05 - Math.hypot(vx, vy)) / 0.1));\n }\n // Scroll brightens with its pace, so a flick reads as a burst and the coast as settling.\n if (scroll)\n a *= 0.55 + 0.45 * scroll.pace;\n if (flash !== null) {\n // A sphere at 55% lights up as it stops, and dims back while it holds.\n a *= 0.55;\n r *= 1 + 0.25 * flash;\n a += (1 - a) * flash;\n }\n if (lids !== null) {\n // Shut beyond the lids, with their edges lit as they close and part.\n const edge = Math.exp(-(((Math.abs(vy) - lids) / 0.06) ** 2)) * (lids < 1.2 ? 1 : 0);\n a *= Math.min(1, Math.max(0, (lids - Math.abs(vy)) / 0.08));\n r *= 1 + 0.4 * edge;\n a += (1 - a) * edge * Math.min(1, Math.max(0, (d - 0.4) / 0.3));\n }\n if (rec !== null) {\n // The whole orb pulses like a recording light, dropping to a third and 8% smaller at its low.\n vx *= 0.92 + 0.08 * rec;\n vy *= 0.92 + 0.08 * rec;\n a *= 0.3 + 0.7 * rec;\n }\n if (roll)\n [vx, vy] = [vx * cr - vy * sr, vx * sr + vy * cr];\n drawer.dot(i, c + vx * R, c - vy * R, r, a, sx, -sy2);\n });\n drawer.frame?.();\n };\n const look = `${state}@${speed}`;\n draw(tick(look, performance.now(), speed));\n const still = matchMedia(\"(prefers-reduced-motion: reduce)\").matches;\n // Only orbs on screen redraw, and only they move their look's clock on. So an orb starts from its\n // first frame when it first comes into view, rather than partway through, and picks up where it\n // left off when it comes back. The observer reports at once, so it starts out unseen.\n let visible = false, raf = 0, dead = false;\n const io = new IntersectionObserver((es) => (visible = es[es.length - 1].isIntersecting));\n io.observe(svg);\n function frame(now) {\n if (visible)\n draw(tick(look, now, speed));\n raf = requestAnimationFrame(frame);\n }\n // Paused, it stops ticking too: alone it picks up where it stopped, and beside others of its look it rejoins them in step.\n const pause = () => {\n cancelAnimationFrame(raf);\n raf = 0;\n };\n const play = () => {\n if (!raf && !still && !dead)\n raf = requestAnimationFrame(frame);\n };\n play();\n return {\n pause,\n play,\n destroy() {\n dead = true;\n pause();\n io.disconnect();\n svg.replaceChildren();\n },\n };\n}\n\nreturn { mountOrb, VARIANTS };\n})()"
@@ -0,0 +1,168 @@
1
+ """
2
+ The name Chrome (or Edge) shows for the browser ForgeQE drives: each start still gets a fresh, temporary profile folder,
3
+ seeded before the browser opens with a profile name and avatar, so the window says whose it is ("Checkout
4
+ smoke test", "Priya", "ForgeQE") instead of an unnamed profile next to the person's own.
5
+
6
+ The name comes from the run (its test case's title, the persona's name, else the first words of the request), which can
7
+ come from a tracker or a model, so it is kept only as plain words: letters, digits, spaces and a few marks, one line,
8
+ `MAX_NAME` characters at most, else `DEFAULT_NAME`. Nothing else of the run goes into the folder.
9
+
10
+ Chrome prints a profile's name on its toolbar only beside other profiles, so a visible window also puts its tabs in a
11
+ tab group of that name (`tab_group_extension`), as Claude's browser does: a two-file extension written into the same
12
+ temporary folder, with no host permissions and no content script, so it never reaches a page. Chrome 137 on loads it
13
+ only with DisableLoadExtensionCommandLineSwitch turned off (`TAB_GROUP_FEATURE`); where it is not loaded, the run goes
14
+ on without the group.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import os
20
+ import re
21
+ import tempfile
22
+ import unicodedata
23
+ from pathlib import Path
24
+ from typing import Any, Optional
25
+
26
+ DEFAULT_NAME = "ForgeQE"
27
+ MAX_NAME = 32
28
+ # The library's own prefix: a folder named so is never copied again by it (profile.py) and is found again as one of
29
+ # ForgeQE's temporary profiles (browser.own_profile), so a browser left on it is closed.
30
+ PREFIX = "browser-use-user-data-dir-"
31
+ # Chrome's built-in avatar of a stylised figure (IDR_PROFILE_AVATAR_26). No colour of ForgeQE's: the library starts
32
+ # Chrome with its own theme (--install-autogenerated-theme), and Chrome stops at start when the profile names another.
33
+ AVATAR_INDEX = 26
34
+
35
+ # The extension's folder inside the profile folder, and the Chrome feature that, on, refuses --load-extension.
36
+ TAB_GROUP_DIR = "forgeqe-tab-group"
37
+ TAB_GROUP_FEATURE = "DisableLoadExtensionCommandLineSwitch"
38
+ TAB_GROUP_COLOR = "blue"
39
+
40
+ _KEEP = re.compile(r"[^\w .,'&()+\-#:]", re.UNICODE)
41
+ _SPACES = re.compile(r"\s+")
42
+
43
+
44
+ def profile_name(*candidates: Any) -> str:
45
+ """The first candidate that holds plain words, cleaned and capped; DEFAULT_NAME when none does."""
46
+ for raw in candidates:
47
+ if not isinstance(raw, str):
48
+ continue
49
+ # Only the first line, so a request's later lines (steps, pasted text) never reach the title bar.
50
+ line = raw.strip().splitlines()[0] if raw.strip() else ""
51
+ # Compatibility forms folded (full-width letters), and every control, format or bidi character dropped.
52
+ text = "".join(c for c in unicodedata.normalize("NFKC", line) if unicodedata.category(c)[0] != "C")
53
+ text = _SPACES.sub(" ", _KEEP.sub(" ", text)).strip(" .,:-")
54
+ if not re.search(r"\w", text):
55
+ continue
56
+ if len(text) > MAX_NAME:
57
+ cut = text[:MAX_NAME]
58
+ text = (cut.rsplit(" ", 1)[0] if " " in cut[MAX_NAME // 2 :] else cut).rstrip(" .,:-") + "…"
59
+ return text
60
+ return DEFAULT_NAME
61
+
62
+
63
+ def seed_profile(folder: Any, name: str) -> None:
64
+ """Write the profile's name and avatar into an empty profile folder, before the browser starts on it."""
65
+ root = Path(folder)
66
+ name = profile_name(name)
67
+ local_state = {
68
+ "profile": {
69
+ "last_used": "Default",
70
+ "info_cache": {
71
+ "Default": {
72
+ "name": name,
73
+ "is_using_default_name": False,
74
+ "avatar_icon": f"chrome://theme/IDR_PROFILE_AVATAR_{AVATAR_INDEX}",
75
+ "is_using_default_avatar": False,
76
+ },
77
+ },
78
+ },
79
+ }
80
+ prefs = {"profile": {"name": name, "avatar_index": AVATAR_INDEX, "using_default_name": False, "using_default_avatar": False}}
81
+ default = root / "Default"
82
+ default.mkdir(parents=True, exist_ok=True)
83
+ _write_new(root / "Local State", local_state)
84
+ _write_new(default / "Preferences", prefs)
85
+
86
+
87
+ def _write_new(path: Path, data: Any) -> None:
88
+ """A file that must not exist yet, never through a link (the folder was just made for this start): JSON, or text."""
89
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
90
+ fd = os.open(str(path), flags, 0o600)
91
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
92
+ if isinstance(data, str):
93
+ fh.write(data)
94
+ else:
95
+ json.dump(data, fh)
96
+
97
+
98
+ # Puts every tab of each normal window in one group named NAME. Only the tabs and tabGroups APIs: no page is read.
99
+ _WORKER_JS = """const NAME = __NAME__;
100
+ const COLOR = __COLOR__;
101
+ let busy = false;
102
+ async function gather() {
103
+ if (busy) return;
104
+ busy = true;
105
+ try {
106
+ for (const w of await chrome.windows.getAll({ windowTypes: ['normal'] })) {
107
+ const tabs = await chrome.tabs.query({ windowId: w.id });
108
+ const loose = tabs.filter((t) => t.groupId === -1).map((t) => t.id);
109
+ if (!loose.length) continue;
110
+ const have = tabs.find((t) => t.groupId !== -1);
111
+ const groupId = await chrome.tabs.group(have ? { groupId: have.groupId, tabIds: loose } : { tabIds: loose, createProperties: { windowId: w.id } });
112
+ await chrome.tabGroups.update(groupId, { title: NAME, color: COLOR, collapsed: false });
113
+ }
114
+ } catch (_) {
115
+ } finally {
116
+ busy = false;
117
+ }
118
+ }
119
+ chrome.runtime.onStartup.addListener(gather);
120
+ chrome.runtime.onInstalled.addListener(gather);
121
+ chrome.tabs.onCreated.addListener(gather);
122
+ chrome.tabs.onAttached.addListener(gather);
123
+ chrome.tabs.onUpdated.addListener(gather);
124
+ gather();
125
+ """
126
+
127
+
128
+ def _js_string(value: str) -> str:
129
+ """A JS string literal of plain text: JSON with <, > and the line separators escaped, so it never ends a script."""
130
+ out = json.dumps(value)
131
+ for ch, esc in (("<", "\\u003c"), (">", "\\u003e"), ("\u2028", "\\u2028"), ("\u2029", "\\u2029")):
132
+ out = out.replace(ch, esc)
133
+ return out
134
+
135
+
136
+ def tab_group_extension(folder: Any, name: str) -> Optional[str]:
137
+ """
138
+ Write the tab group extension into a profile folder ForgeQE just made; its folder, or None when it could not be
139
+ written. The name is cleaned again here (`profile_name`) and goes into the script only as a string literal.
140
+ """
141
+ root = Path(folder) / TAB_GROUP_DIR
142
+ try:
143
+ root.mkdir(mode=0o700)
144
+ manifest = {
145
+ "manifest_version": 3,
146
+ "name": "ForgeQE tab group",
147
+ "description": "Groups the tabs ForgeQE drives under the run's name.",
148
+ "version": "1.0",
149
+ "permissions": ["tabGroups"],
150
+ "background": {"service_worker": "worker.js"},
151
+ }
152
+ _write_new(root / "manifest.json", manifest)
153
+ worker = _WORKER_JS.replace("__COLOR__", _js_string(TAB_GROUP_COLOR)).replace("__NAME__", _js_string(profile_name(name)))
154
+ _write_new(root / "worker.js", worker)
155
+ except OSError:
156
+ return None
157
+ return str(root)
158
+
159
+
160
+ def named_profile(name: Optional[str], *, prefix: str = PREFIX) -> str:
161
+ """A new temporary profile folder seeded with this name; its path."""
162
+ folder = tempfile.mkdtemp(prefix=prefix)
163
+ try:
164
+ seed_profile(folder, name or DEFAULT_NAME)
165
+ except OSError:
166
+ # A profile without a name still starts; the browser is what matters.
167
+ pass
168
+ return folder
@@ -1,6 +1,6 @@
1
1
  // Starts a browser through Playwright for the ForgeQE engine (browser.launch: playwright, or auto after a direct start
2
2
  // failed). The engine runs it with an argument list: <node or bun> pwlaunch.mjs <playwright-core index.mjs>.
3
- // stdin, one JSON line: {executablePath?, channel?, headless, args, userDataDir, timeoutMs}.
3
+ // stdin, one JSON line: {executablePath?, channel?, headless, args, userDataDir, timeoutMs, extensions?}.
4
4
  // stdout, one JSON line: {port} once the browser's DevTools port is known, or {error}.
5
5
  // The browser is closed when stdin ends (the engine closes it, or the engine has gone).
6
6
  import { existsSync, readFileSync } from "node:fs"
@@ -32,7 +32,8 @@ async function start(line) {
32
32
  // The same browser as a direct start, as a site sees it: no --enable-automation (navigator.webdriver true and the
33
33
  // "controlled by automated test software" bar), and Chrome's sandbox kept on, which Playwright turns off unless
34
34
  // told; on Linux as root Chrome cannot start with it, as a direct start finds too.
35
- ignoreDefaultArgs: ["--enable-automation"],
35
+ // extensions: the engine loads its tab group extension (profilename.py), which --disable-extensions would refuse.
36
+ ignoreDefaultArgs: ["--enable-automation", ...(req.extensions === true ? ["--disable-extensions"] : [])],
36
37
  chromiumSandbox: !(process.platform === "linux" && typeof process.getuid === "function" && process.getuid() === 0),
37
38
  // Port 0: the browser picks a free one and writes it to DevToolsActivePort in its profile folder.
38
39
  // Playwright drives the browser over --remote-debugging-pipe, which makes Chrome report itself automated
@@ -30,9 +30,11 @@ from .replay import ReplayOutcome, handoff_task, replay_flow
30
30
  from .observe import check_key, checkable, checks_for_flow
31
31
  from . import persona as personas
32
32
  from .proceed import ANSWERS
33
+ from .profilename import profile_name
33
34
  from .settings import (
34
35
  _truthy_env,
35
36
  _browser_use_agent_tuning_kwargs,
37
+ step_timeout_seconds,
36
38
  resolve_browser_headless,
37
39
  build_default_browser_login_system_extension,
38
40
  )
@@ -166,6 +168,8 @@ class RunRequest:
166
168
  persona: Optional[Dict[str, Any]] = None
167
169
  # A person can be asked (proceed.py): at its step or time limit the run asks to carry on instead of ending.
168
170
  ask_to_continue: bool = False
171
+ # What the browser's profile is called (profilename.py): the run's test case, agent or persona; else the goal's words.
172
+ run_name: str = ""
169
173
 
170
174
  @classmethod
171
175
  def from_dict(cls, d: Dict[str, Any]) -> "RunRequest":
@@ -202,6 +206,7 @@ class RunRequest:
202
206
  skills_max_chars=int(d["skills_max_chars"]) if str(d.get("skills_max_chars") or "").isdigit() else 6000,
203
207
  persona=personas.parse_persona(d.get("persona")),
204
208
  ask_to_continue=d.get("ask_to_continue") is True,
209
+ run_name=str(d.get("run_name") or "")[:500],
205
210
  )
206
211
 
207
212
 
@@ -1092,7 +1097,7 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1092
1097
  userlike.install()
1093
1098
  headless = resolve_browser_headless(req.headed)
1094
1099
  timeout_sec = float(os.getenv("BROWSER_USE_TIMEOUT_SECONDS", "600"))
1095
- step_timeout = int(os.getenv("BROWSER_USE_STEP_TIMEOUT", "180"))
1100
+ step_timeout = step_timeout_seconds()
1096
1101
 
1097
1102
  try:
1098
1103
  llm = _build_llm(req.llm)
@@ -1147,6 +1152,7 @@ async def run_browser_task(req: RunRequest, emit: Emit, cancel_event: asyncio.Ev
1147
1152
  # Installed Chrome first; when it closes before it can be driven (a company policy, security software), Edge,
1148
1153
  # then Playwright's Chromium, the one a plain Playwright script starts.
1149
1154
  extra = {k: v for k, v in browser_kw.items() if k not in ("channel", "executable_path")}
1155
+ extra["_profile_name"] = profile_name(req.run_name, (req.persona or {}).get("name"), task_goal(req))
1150
1156
 
1151
1157
  def _fell_back(failed: Dict[str, Any], nxt: Dict[str, Any], reason: str) -> None:
1152
1158
  emit({"type": "log", "level": "warn", "text": f"{browser_name(failed)} did not start ({reason}); trying {browser_name(nxt)}"})
@@ -43,6 +43,23 @@ When the user goal involves **logging in**, **sign in**, **authentication**, or
43
43
  Prefer fields labeled Email, Username, or Login together with Password. Submit the form and wait for a successful post-login state before continuing. If the page already shows a signed-in session, do not re-enter credentials unless the flow requires re-auth.""".strip()
44
44
 
45
45
 
46
+ DEFAULT_STEP_TIMEOUT_S = 180
47
+ # What a step needs beside its model call: the page read before it and the actions after it.
48
+ STEP_MARGIN_S = 60
49
+
50
+
51
+ def step_timeout_seconds() -> int:
52
+ """How long one agent step may take. BROWSER_USE_STEP_TIMEOUT set by the person wins; otherwise it is the default,
53
+ or longer when the model call alone may take longer (BROWSER_USE_LLM_TIMEOUT, which ForgeQE raises for Copilot):
54
+ the step wraps that call, so a step limit below it stopped every slow call before its own limit was reached."""
55
+ raw = (os.getenv("BROWSER_USE_STEP_TIMEOUT") or "").strip()
56
+ if raw.isdigit() and int(raw) > 0:
57
+ return int(raw)
58
+ llm_raw = (os.getenv("BROWSER_USE_LLM_TIMEOUT") or "").strip()
59
+ llm = max(30, int(llm_raw)) if llm_raw.isdigit() else 0
60
+ return max(DEFAULT_STEP_TIMEOUT_S, llm + STEP_MARGIN_S if llm else 0)
61
+
62
+
46
63
  def _browser_use_agent_tuning_kwargs() -> Dict[str, Any]:
47
64
  """
48
65
  Library 0.12+ defaults (planning, thinking, judge, vision) add large per-step latency