@capagents/forgeqe 3.2.6 → 3.2.7

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 (166) hide show
  1. package/HOW_TO_USE.md +4 -1
  2. package/dist/docs-site/CREDITS.md +3 -3
  3. package/dist/docs-site/{LICENSE.dm-sans.txt → LICENSE.geist.txt} +1 -1
  4. package/dist/docs-site/app-look.css +72 -32
  5. package/dist/docs-site/architecture-map/arch-theme.css +31 -40
  6. package/dist/docs-site/docs/app-theme.css +109 -108
  7. package/dist/docs-site/docs/area-api/index.html +3 -3
  8. package/dist/docs-site/docs/area-browser/index.html +2 -0
  9. package/dist/docs-site/docs/area-setup/index.html +1 -0
  10. package/dist/docs-site/docs/search.js +1 -1
  11. package/dist/docs-site/docs/web-app/index.html +2 -2
  12. package/dist/docs-site/security/security-theme.css +66 -69
  13. package/dist/forgeqe.js +1870 -1847
  14. package/dist/web/THIRD_PARTY_NOTICES.md +0 -101
  15. package/dist/web/assets/{3d-force-graph-CNVqakzA.js → 3d-force-graph-CUGt_TSW.js} +1 -1
  16. package/dist/web/assets/Agent-DiX8ljlC.js +8 -0
  17. package/dist/web/assets/AgentWork-BpfMY_xu.js +2 -0
  18. package/dist/web/assets/ApiTests-4jfzlfVd.js +15 -0
  19. package/dist/web/assets/Browse-ByDemInL.js +1 -0
  20. package/dist/web/assets/Chat-C3wKV0CI.js +3 -0
  21. package/dist/web/assets/CommandPalette-CKJHtRjo.js +1 -0
  22. package/dist/web/assets/Compare-DtW2g-qb.js +1 -0
  23. package/dist/web/assets/Cost-DW-kVEL8.js +1 -0
  24. package/dist/web/assets/Data--HGneNun.js +6 -0
  25. package/dist/web/assets/Desktop-DQf5gv7D.js +1 -0
  26. package/dist/web/assets/DesktopReview-BaPYt0kl.js +2 -0
  27. package/dist/web/assets/DeviceScreen-DzVNfMwl.js +1 -0
  28. package/dist/web/assets/Evidence-CxRMnZch.js +1 -0
  29. package/dist/web/assets/Explore-ChpAuezG.js +2 -0
  30. package/dist/web/assets/Features-VsLb8QTH.js +1 -0
  31. package/dist/web/assets/Flags-Do-pvmCF.js +2 -0
  32. package/dist/web/assets/Flaky-CyhTszAg.js +1 -0
  33. package/dist/web/assets/Impact-BWBAXRuw.js +3 -0
  34. package/dist/web/assets/Jobs-C_MjXv0_.js +5 -0
  35. package/dist/web/assets/KindPage-Bb3Kp4-q.js +6 -0
  36. package/dist/web/assets/LiveDevice-OyxEiqBt.js +1 -0
  37. package/dist/web/assets/Migration-C80mGA3h.js +8 -0
  38. package/dist/web/assets/Mobile-C4wVBYfr.js +1 -0
  39. package/dist/web/assets/Observability-DdTOLp2C.js +1 -0
  40. package/dist/web/assets/PageAgent-Bi53-H99.js +1 -0
  41. package/dist/web/assets/Product-0LXndvp-.js +12 -0
  42. package/dist/web/assets/Production-oTXhv40a.js +1 -0
  43. package/dist/web/assets/Quality-CY0CJF9e.js +1 -0
  44. package/dist/web/assets/Readiness-Bv9uTTiI.js +1 -0
  45. package/dist/web/assets/Record-C-kyOkYq.js +1 -0
  46. package/dist/web/assets/Regression-CwKxvG1h.js +5 -0
  47. package/dist/web/assets/RelationGraph-BQl3M4zd.js +1 -0
  48. package/dist/web/assets/Reports-Ck8rc3br.js +2 -0
  49. package/dist/web/assets/Responsive-COmV2NXo.js +3 -0
  50. package/dist/web/assets/RunDiff-BBT1sQLh.js +1 -0
  51. package/dist/web/assets/Settings-7aMk9Sqx.js +21 -0
  52. package/dist/web/assets/Steps-C_vL6-8p.js +3 -0
  53. package/dist/web/assets/TestData-KzMy9N9f.js +2 -0
  54. package/dist/web/assets/TestManagement-BCEhOGB9.js +4 -0
  55. package/dist/web/assets/WhatsNew-DTcaqdOJ.js +1 -0
  56. package/dist/web/assets/agentSettingsSheet-DM1aa237.js +1 -0
  57. package/dist/web/assets/choice-B6z9CWyZ.js +1 -0
  58. package/dist/web/assets/code-DzYywAs5.js +1 -0
  59. package/dist/web/assets/{coverage-xSRsKFL6.js → coverage-BhtF065n.js} +4 -4
  60. package/dist/web/assets/dataParts-BNDVxwFb.js +3 -0
  61. package/dist/web/assets/desktopAppPath-D4hHP56R.js +1 -0
  62. package/dist/web/assets/frame-CNYHTG4T.js +13 -0
  63. package/dist/web/assets/index-B1Q2Dlqw.js +56 -0
  64. package/dist/web/assets/index-sxUpjgyw.css +2 -0
  65. package/dist/web/assets/markdown-BhU7ng6c.js +8 -0
  66. package/dist/web/assets/pageBack-BoSbGSU6.js +3 -0
  67. package/dist/web/assets/palette-BsY8OLxd.js +1 -0
  68. package/dist/web/assets/{paletteCommands-CwHwpVqt.js → paletteCommands-DflHQ05x.js} +1 -1
  69. package/dist/web/assets/parts-C4QMgN_N.js +1 -0
  70. package/dist/web/assets/preload-helper-qorOEK5q.js +1 -0
  71. package/dist/web/assets/productParts-Dxl-TQKY.js +1 -0
  72. package/dist/web/assets/qualityParts-ClGKtjEv.js +1 -0
  73. package/dist/web/assets/radio-DDxnnflQ.js +1 -0
  74. package/dist/web/assets/recordTest-B33rIncn.js +1 -0
  75. package/dist/web/assets/route-D9uPlFWw.js +1 -0
  76. package/dist/web/assets/{sectionList-BlwEtA8S.js → sectionList-e5mFDaS2.js} +1 -1
  77. package/dist/web/assets/stepper-DSDz0uu8.js +1 -0
  78. package/dist/web/index.html +10 -9
  79. package/docs/WEB_APP.md +2 -2
  80. package/docs/user-guide.html +13 -7
  81. package/package.json +1 -1
  82. package/prompts/api-scenarios.md +1 -0
  83. package/prompts/brain.md +1 -0
  84. package/py/forgeqe_desktop/replay.py +3 -1
  85. package/py/forgeqe_desktop/workflow.py +19 -0
  86. package/py/forgeqe_engine/capture.py +19 -4
  87. package/py/forgeqe_engine/cli.py +12 -10
  88. package/py/forgeqe_engine/clientcert.py +28 -0
  89. package/py/forgeqe_engine/d365.py +182 -0
  90. package/py/forgeqe_engine/logins.py +20 -16
  91. package/py/forgeqe_engine/memory.py +9 -3
  92. package/py/forgeqe_engine/recordsession.py +23 -3
  93. package/py/forgeqe_engine/webrecord.py +16 -0
  94. package/py/forgeqe_engine/webrecord_page.py +26 -1
  95. package/py/forgeqe_mobile/appium_driver.py +26 -0
  96. package/py/forgeqe_mobile/maestro.py +2 -1
  97. package/dist/web/assets/Agent-CAp1dIHx.js +0 -8
  98. package/dist/web/assets/AgentWork-DxO8FN6U.js +0 -2
  99. package/dist/web/assets/ApiTests-XQ8wXCBj.js +0 -14
  100. package/dist/web/assets/Browse-BP1oToo4.js +0 -1
  101. package/dist/web/assets/Chat-DjIdHvHj.js +0 -3
  102. package/dist/web/assets/CommandPalette-rNWxEO_C.js +0 -1
  103. package/dist/web/assets/Compare-DwUP21-2.js +0 -1
  104. package/dist/web/assets/Cost-qZ-gGn2T.js +0 -1
  105. package/dist/web/assets/Data-AlbKk5zW.js +0 -6
  106. package/dist/web/assets/Desktop-yGPlxyBz.js +0 -1
  107. package/dist/web/assets/DesktopReview-BlpxN07L.js +0 -2
  108. package/dist/web/assets/DeviceScreen-BQKsJonx.js +0 -1
  109. package/dist/web/assets/Evidence-BCodp0GV.js +0 -1
  110. package/dist/web/assets/Explore-Ck5EEDy7.js +0 -2
  111. package/dist/web/assets/Features-BOQomaU8.js +0 -1
  112. package/dist/web/assets/Flags-DjolLE4S.js +0 -2
  113. package/dist/web/assets/Flaky-D-xnPfil.js +0 -1
  114. package/dist/web/assets/Impact-CoNLaNwy.js +0 -3
  115. package/dist/web/assets/Jobs-_kBd2W3F.js +0 -5
  116. package/dist/web/assets/KindPage-DfnkzpPj.js +0 -6
  117. package/dist/web/assets/LiveDevice-DRAN4Gl4.js +0 -1
  118. package/dist/web/assets/Migration-PETc1Ckc.js +0 -8
  119. package/dist/web/assets/Mobile-B193VBXu.js +0 -1
  120. package/dist/web/assets/Observability-CvdV37XD.js +0 -1
  121. package/dist/web/assets/PageAgent-BJguufGW.js +0 -1
  122. package/dist/web/assets/Product-Cmgcj9fr.js +0 -12
  123. package/dist/web/assets/Production-DM62n03j.js +0 -1
  124. package/dist/web/assets/Quality-DbgAAeel.js +0 -1
  125. package/dist/web/assets/Readiness-CojmD235.js +0 -1
  126. package/dist/web/assets/Record-C4VFM97k.js +0 -1
  127. package/dist/web/assets/Regression-5mma_vyD.js +0 -5
  128. package/dist/web/assets/RelationGraph-bDvvcead.js +0 -1
  129. package/dist/web/assets/Reports-BeSrlzKk.js +0 -2
  130. package/dist/web/assets/Responsive-B4CkMBwF.js +0 -3
  131. package/dist/web/assets/RunDiff-DGThx7bk.js +0 -1
  132. package/dist/web/assets/Settings-IjfPYiuf.js +0 -21
  133. package/dist/web/assets/Steps-BPSNI3aY.js +0 -3
  134. package/dist/web/assets/TestCases-hIuP5BLu.js +0 -1
  135. package/dist/web/assets/TestData-DpAMEMLP.js +0 -2
  136. package/dist/web/assets/TestDebt-D6UjJCpY.js +0 -1
  137. package/dist/web/assets/TestManagement-CTWh-aA8.js +0 -4
  138. package/dist/web/assets/WhatsNew-DMDg1zmv.js +0 -1
  139. package/dist/web/assets/agentSettingsSheet-CUogAKga.js +0 -1
  140. package/dist/web/assets/dataParts-s8iIR3Ad.js +0 -3
  141. package/dist/web/assets/desktopAppPath-CnmfVr-s.js +0 -1
  142. package/dist/web/assets/dm-sans-latin-400-normal-BwCSEQnW.woff +0 -0
  143. package/dist/web/assets/dm-sans-latin-400-normal-CW0RaeGs.woff2 +0 -0
  144. package/dist/web/assets/dm-sans-latin-500-normal-B9HHJjqV.woff2 +0 -0
  145. package/dist/web/assets/dm-sans-latin-500-normal-Dr3UlScf.woff +0 -0
  146. package/dist/web/assets/dm-sans-latin-600-normal-Aqo67rzb.woff2 +0 -0
  147. package/dist/web/assets/dm-sans-latin-600-normal-BmdmIIQ2.woff +0 -0
  148. package/dist/web/assets/dm-sans-latin-ext-400-normal-BjWJ59Pq.woff +0 -0
  149. package/dist/web/assets/dm-sans-latin-ext-400-normal-BtiwyxMk.woff2 +0 -0
  150. package/dist/web/assets/dm-sans-latin-ext-500-normal-BJfUCQsA.woff2 +0 -0
  151. package/dist/web/assets/dm-sans-latin-ext-500-normal-DR84L5F-.woff +0 -0
  152. package/dist/web/assets/dm-sans-latin-ext-600-normal-4vooXBpG.woff2 +0 -0
  153. package/dist/web/assets/dm-sans-latin-ext-600-normal-DRtaDpgU.woff +0 -0
  154. package/dist/web/assets/frame-DNgVKrlp.js +0 -13
  155. package/dist/web/assets/index-BBJ_SKdO.js +0 -56
  156. package/dist/web/assets/index-hysPD6U9.css +0 -2
  157. package/dist/web/assets/input-FbzQKk3L.js +0 -1
  158. package/dist/web/assets/markdown-1z66EzBR.js +0 -8
  159. package/dist/web/assets/pageBack-B6bY6ZUl.js +0 -3
  160. package/dist/web/assets/palette-C5Ok5Zd1.js +0 -1
  161. package/dist/web/assets/parts-Dqq6noWp.js +0 -1
  162. package/dist/web/assets/productParts-DNSo4bn5.js +0 -1
  163. package/dist/web/assets/qualityParts-kh6SukEP.js +0 -1
  164. package/dist/web/assets/recordTest-BCxsm3gC.js +0 -1
  165. package/dist/web/assets/route-D8G-pTdk.js +0 -1
  166. package/dist/web/assets/stepper-ByKrM1LP.js +0 -1
@@ -729,7 +729,7 @@ page). To use one model instead, pick it on <strong>Settings › Models</strong>
729
729
  <li>Pick the model. The row then says who is signed in and with which model.</li>
730
730
  </ol>
731
731
  <p><strong>Terminal</strong></p>
732
- <pre><code class="language-bash">forgeqe auth login copilot # sign in; ForgeQE then uses auto
732
+ <pre><code class="language-bash">forgeqe auth login copilot # sign in; ForgeQE then uses auto, and adds a copilot-&lt;model&gt; profile per seat model
733
733
  forgeqe auth # the Copilot line shows the sign-in
734
734
  </code></pre>
735
735
  <p><strong>GitHub Enterprise Cloud</strong> (a <code>ghe.com</code> address, with data residency). In the web app press <strong>Enterprise</strong>; in the
@@ -786,9 +786,12 @@ request carrying a browser screenshot; ForgeQE then sends the next screenshots s
786
786
  across), and if those do not get through either, none at all (the browser agent works from the page's text). It says so
787
787
  in the run, keeps it for an hour in <code>~/.forgeqe/copilot/model-health.json</code>, and then tries full screenshots again. To get
788
788
  full screenshots back, ask IT to allow uploads to that address.</p>
789
- <p><strong>Behind a company proxy.</strong> ForgeQE reaches Copilot over plain HTTPS. Copilot can use WebSockets for some models, which
790
- many company proxies break, leaving requests unanswered; ForgeQE turns them off, as each request is a new Copilot
791
- session anyway. To turn them on, set <code>FORGEQE_COPILOT_WEBSOCKETS=1</code>.</p>
789
+ <p><strong>Behind a company proxy.</strong> ForgeQE reaches Copilot over WebSockets first. Many company proxies break them, which
790
+ leaves requests unanswered rather than failing, so until WebSockets have answered once on this computer, a request that
791
+ hears nothing from Copilot within 45 seconds (or fails on the connection) is sent again over plain HTTPS, and HTTPS is
792
+ kept: for that ForgeQE and, in <code>~/.forgeqe/copilot/transport.json</code>, for a week, before WebSockets are tried again.
793
+ <code>copilot-gateway.log</code> says when it switched. Set <code>FORGEQE_COPILOT_WEBSOCKETS=0</code> to always use HTTPS, or <code>=1</code> to always
794
+ use WebSockets with no fallback.</p>
792
795
  <p><strong>Choosing the model.</strong> Your seat's models each show whether they take screenshots, their premium requests per call (0
793
796
  is included in your plan) and the profiles that use them.</p>
794
797
  <p><strong>Web app</strong></p>
@@ -2341,6 +2344,8 @@ forgeqe record --case SHOP-12 # record a test case
2341
2344
  <li><strong>A CAPTCHA</strong> (reCAPTCHA, hCaptcha, Turnstile, Arkose, GeeTest) is one step for a person, never its clicks. A replay in a visible browser waits up to 3 minutes for you to solve it; a headless one fails and says to turn it off in the test environment (the provider's test keys, or a bypass).</li>
2342
2345
  <li><strong>The browser's own sign-in box</strong> (basic auth): only the site is kept, with the saved login whose <code>domains</code> cover it. A replay signs in there with that login's variables. With no such login, the recording says to save one.</li>
2343
2346
  <li><strong>Browser permissions</strong> you allowed (location, notifications, clipboard, camera, microphone) are granted to that site in a replay.</li>
2347
+ <li><strong>Dynamics 365</strong> (a <code>*.crm*.dynamics.com</code> site, or any page with D365's <code>#ApplicationShell</code>): elements are recorded by D365's own attributes, as the <code>dynamics-365</code> skills name them. An app tile is <code>div[data-type=&quot;app-title&quot;][title=&quot;&lt;app&gt;&quot;]</code> and a field or command is its <code>data-id</code>. The ids D365 makes from a control's position (<code>AppModuleTileSec_1_Item_1</code>) are never relied on. A replay waits after each step until D365 says it is idle (<code>UCWorkBlockTracker.isAppIdle()</code>).</li>
2348
+ <li><strong>Chrome's &quot;Select a certificate&quot; box</strong>, which Entra ID's device sign-in (<code>device.login.microsoftonline.com</code>) brings up on a computer joined to Entra: pick the certificate in Chrome as usual. The recording keeps one step for it. Nothing in a replay can answer that box, so Chrome must pick the certificate by itself. Run <code>forgeqe doctor certificate</code> and install the policy it writes, once, with administrator rights. On macOS that is a configuration profile, on Linux a policy file, and on Windows a <code>.reg</code> file. ForgeQE never installs it. The policy makes Chrome pick the certificate issued by <code>MS-Organization-Access</code> on that host only. Without it, a replay stops at the sign-in and says so. A device certificate stays on the computer it was issued to, so a CI agent needs a test user that the tenant does not ask for a managed device.</li>
2344
2349
  </ul>
2345
2350
  <p><strong>Passwords and files.</strong></p>
2346
2351
  <ul>
@@ -3574,6 +3579,7 @@ Signing in stays <code>/auth</code> and <code>forgeqe login</code>; <code>forgeq
3574
3579
  <tr><td><code>forgeqe doctor</code></td><td>Whether this computer and the network (proxy, inspected HTTPS, firewall) let ForgeQE reach what it needs</td></tr>
3575
3580
  <tr><td><code>forgeqe doctor --packages</code></td><td>Every package ForgeQE installs on this computer, and which are missing or out of date</td></tr>
3576
3581
  <tr><td><code>forgeqe doctor browser [--headless]</code></td><td>Start the local browser each way ForgeQE can, and write a report of what stops it</td></tr>
3582
+ <tr><td><code>forgeqe doctor certificate</code></td><td>Write Chrome's policy that picks this computer's Entra device certificate, for you to install</td></tr>
3577
3583
  <tr><td><code>forgeqe models</code></td><td>List the profiles in <code>llms.json</code> and the active one</td></tr>
3578
3584
  <tr><td><code>forgeqe models --routes [--profile-models]</code></td><td>The model each area of work gets (<code>llm.routing</code>) and why; <code>--profile-models</code> checks and rates the models again (see <a href="#doc-docs-model_routing-model-routing-the-right-configured-model-for-each-task">docs/MODEL_ROUTING.md</a>)</td></tr>
3579
3585
  <tr><td><code>forgeqe features</code></td><td>What ForgeQE can do, and what each capability still needs in this setup (works without a model)</td></tr>
@@ -10288,12 +10294,12 @@ DevOps test case's Associated Automation when write-back is on.</li>
10288
10294
  </article>
10289
10295
  <article class="spec feat" id="cap-api-calls">
10290
10296
  <div class="hd"><span class="mono">API</span><h3>An API's calls and collections</h3></div>
10291
- <p class="ds">Keeps an API's calls as a set on the API tests Workbench: finds an API and its calls, adds calls (from the code, cURL or a description), imports a Postman collection, renames, moves and deletes them, and signs in to the API with a saved login, never a credential on a call.</p>
10297
+ <p class="ds">Keeps an API's calls as a set on the API tests Workbench: finds an API and its calls, adds calls (from the code, cURL or a description) and changes the ones it has in place, imports a Postman collection, renames, moves and deletes them, and signs in to the API with a saved login, never a credential on a call.</p>
10292
10298
  <div class="facts">
10293
- <div class="fact"><span class="mono">Ask it</span><ul class="asks"><li>Import our Postman collection and send its calls</li><li>Add these cURL calls to the shop API</li><li>Delete the old orders API from the Workbench</li><li>Send the shop API calls signed in with the admin login</li></ul></div>
10299
+ <div class="fact"><span class="mono">Ask it</span><ul class="asks"><li>Import our Postman collection and send its calls</li><li>Add these cURL calls to the shop API</li><li>Add query parameters to the existing API call in the shop API</li><li>Delete the old orders API from the Workbench</li><li>Send the shop API calls signed in with the admin login</li></ul></div>
10294
10300
  <div class="fact"><span class="mono">What it needs</span><p class="muted">Nothing beyond ForgeQE itself.</p></div>
10295
10301
  <div class="fact"><span class="mono">Limits</span><ul class="plainlist"><li>Calls that change data run only when the user allows them, on a test environment, never production.</li><li>Deleting an API asks the user first.</li></ul></div>
10296
- <div class="fact"><span class="mono">Tools</span><p class="tools"><code>api_find_calls</code> <code>api_new_set</code> <code>api_add_calls</code> <code>api_rename_folder</code> <code>api_move_calls</code> <code>api_delete_set</code> <code>api_sign_in</code> <code>api_import_collection</code></p></div>
10302
+ <div class="fact"><span class="mono">Tools</span><p class="tools"><code>api_find_calls</code> <code>api_new_set</code> <code>api_add_calls</code> <code>api_edit_call</code> <code>api_rename_folder</code> <code>api_move_calls</code> <code>api_delete_set</code> <code>api_sign_in</code> <code>api_import_collection</code></p></div>
10297
10303
  </div>
10298
10304
  <div class="detail"><span class="mono">In detail</span>
10299
10305
  <p class="see">See <a href="#doc-how_to_use-api-and-contract-tests">API and contract tests</a>.</p>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capagents/forgeqe",
3
- "version": "3.2.6",
3
+ "version": "3.2.7",
4
4
  "description": "ForgeQE: a browser agent CLI that runs goals and test cases in local Chrome or Chromium, or BrowserStack and TestMu AI/LambdaTest when configured, and turns passing runs into tests in your repo",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -30,6 +30,7 @@ Values:
30
30
  - Data that the scenario creates MUST be new on each run. Put {{$unique}} in emails, usernames, names, and references.
31
31
  - You MAY also use {{$uuid}}, {{$now}}, and {{$randomInt}}.
32
32
  - You MUST use the test data of the case, such as a product or a coupon code, as the case gives it.
33
+ - When the case or the text gives a request body, you MUST send each of its fields exactly as given, {{$unique}} and other {{expressions}} included. You MUST NOT keep the example call's value for a field it gives.
33
34
 
34
35
  Checks:
35
36
  - Each step MUST expect the status that the operation gives on success.
package/prompts/brain.md CHANGED
@@ -460,6 +460,7 @@ For REST, GraphQL, SOAP, and gRPC:
460
460
  - When the calls are not in a set yet, make the set first: api_contracts from run for browser runs, or api_new_set and api_add_calls for calls in the code. Then use write_api_tests with that set.
461
461
  - To run API tests that are already in the repository, you MUST use find_tests, then run_tests. You MUST NOT run them with the shell.
462
462
  - Before api_new_set or api_add_calls, and whenever a set id is not in the conversation (a conversation picked up again), you MUST look for the API and the call with api_find_calls and reuse what is there. You MUST NOT make a second API or call with the same method and path; when you cannot tell which API is meant, ask the user.
463
+ - To change a call the API already has (add query parameters, change headers, body, name, folder or the answer it expects), you MUST use api_edit_call with its set id and call id (api_find_calls finds them, and api_add_calls returns already_there for it). It changes the call in place. You MUST NOT add it again, and MUST NOT tell the user to edit it on the Workbench by hand.
463
464
  - To send API calls found in the repository's code, read the code, then use api_new_set and api_add_calls. To make tests of them, use write_api_tests.
464
465
  - To delete an API (a set, a folder on the API tests Workbench), you MUST use api_delete_set with its set id (api_find_calls finds it); ForgeQE asks the user to confirm. You MUST NOT open the Workbench in a browser to delete, rename or change an API. When api_delete_set cannot delete it, tell the user why and stop.
465
466
 
@@ -18,7 +18,7 @@ from dataclasses import dataclass, field
18
18
  from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Protocol
19
19
 
20
20
  from .apps import AppSpec, resolve_app
21
- from .workflow import MAX_PICK, MOBILE_FORMAT, MOBILE_RETRY_OPS, RETRY_OPS, WorkflowError, env_secret, fill, fill_targets, parse_chord, secret_names, validate
21
+ from .workflow import MAX_PICK, MOBILE_FORMAT, new_run_unique, MOBILE_RETRY_OPS, RETRY_OPS, WorkflowError, env_secret, fill, fill_targets, parse_chord, secret_names, validate
22
22
 
23
23
 
24
24
  class ControlNotFound(LookupError):
@@ -113,6 +113,8 @@ def replay(
113
113
  open_link: Optional[Callable[[str, float], None]] = None,
114
114
  ) -> ReplayResult:
115
115
  wf = validate(dict(workflow))
116
+ # A {{$unique}} of its own for each replay (each row of a data file too).
117
+ new_run_unique()
116
118
  spec = resolve_app(wf["app"], apps, must_exist=must_exist)
117
119
  allowed = {str(n) for n in allowed_secrets}
118
120
  values: Dict[str, Any] = {**wf["variables"], **dict(variables or {})}
@@ -119,6 +119,23 @@ _MONTHS = ("January", "February", "March", "April", "May", "June", "July", "Augu
119
119
  _DAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
120
120
 
121
121
 
122
+ # {{$unique}}: a part new on each replay (an email or a name that must not repeat), the same everywhere in one replay.
123
+ _UNIQUE: List[str] = []
124
+
125
+
126
+ def new_run_unique() -> str:
127
+ """A fresh {{$unique}} for the replay that starts now: base 36 of the time and a few random letters."""
128
+ import secrets as _secrets
129
+
130
+ digits = "0123456789abcdefghijklmnopqrstuvwxyz"
131
+ n, out = int(time.time() * 1000), ""
132
+ while n:
133
+ n, r = divmod(n, 36)
134
+ out = digits[r] + out
135
+ _UNIQUE[:] = [out + "".join(_secrets.choice(digits) for _ in range(4))]
136
+ return _UNIQUE[0]
137
+
138
+
122
139
  def date_text(days: int, fmt: str, today: Optional["date"] = None) -> str:
123
140
  """The date ``days`` from ``today`` in ``fmt``: %Y %m %d, %e the day without a zero, %o its ending, month and day names."""
124
141
  from datetime import date, timedelta
@@ -444,6 +461,8 @@ def fill(text: str, variables: Mapping[str, Any], secret: Callable[[str], Option
444
461
 
445
462
  def one(m: "re.Match[str]") -> str:
446
463
  ref = m.group(1)
464
+ if ref == "$unique":
465
+ return _UNIQUE[0] if _UNIQUE else new_run_unique()
447
466
  if ref.startswith("$date:"):
448
467
  when = _DATE_REF.match(ref)
449
468
  if not when:
@@ -19,6 +19,7 @@ from typing import Any, Dict, List, Optional
19
19
  from browser_use import ActionResult, BrowserSession
20
20
 
21
21
  from . import userlike
22
+ from .d365 import clean_facts as d365_clean_facts, page_config as d365_page_config
22
23
  from .memory import BASE, KEPT_ATTRS, candidate_locators, confidence, has_icons, looks_generated, playwright_role_ok, state_class
23
24
 
24
25
  logger = logging.getLogger("forgeqe_engine.capture")
@@ -253,7 +254,8 @@ _VERIFY_FN = r"""function(locs) {
253
254
  if (!all) return null;
254
255
  // Every match, hidden ones too: Playwright's strict mode counts them, so a locator with a hidden copy (a
255
256
  // consent tool's second "Accept all" in a closed menu) throws on click though one match shows.
256
- return { count: all.length, target: all.length === 1 && (all[0] === el || within(el, all[0])) };
257
+ // `up` (d365.py): a locator of the D365 control the element is inside (an app tile, for a click on its name).
258
+ return { count: all.length, target: all.length === 1 && (all[0] === el || within(el, all[0]) || (l.up === true && within(all[0], el))) };
257
259
  } catch (e) { return { count: -1, target: false }; }
258
260
  });
259
261
  // What Playwright's getByRole reads for the element's role: its tag, href and role attribute.
@@ -384,10 +386,21 @@ async def _contains(cdp: Any, object_id: str, backend_node_id: int) -> bool:
384
386
 
385
387
 
386
388
  # Facts (as memory.element_facts gives them) for an element reached through CDP rather than the agent's element list.
387
- _FACTS_FN = r"""function(kept) {
389
+ _FACTS_FN = r"""function(kept, d365) {
388
390
  const el = this;
389
391
  const attrs = {};
390
392
  for (const k of kept) { const v = el.getAttribute(k); if (v) attrs[k] = v; }
393
+ // A Dynamics 365 page (d365.py, ADO 3529): its own attributes, and the D365 control the element is inside.
394
+ let site = '', d365Up = null;
395
+ try { if (d365 && (new RegExp(d365.host, 'i').test(location.hostname) || document.getElementById(d365.shell))) site = 'd365'; } catch (e) {}
396
+ const d365Attrs = (x) => { const a = {}; for (const k of d365.attrs) { const v = x.getAttribute(k); if (v) a[k] = v.slice(0, 200); } if (a['data-type'] && a['data-type'] !== 'app-title') delete a['data-type']; return a; };
397
+ if (site) {
398
+ Object.assign(attrs, d365Attrs(el));
399
+ for (let x = el.parentElement, i = 0; x && i < d365.up && x !== document.body; x = x.parentElement, i++) {
400
+ const a = d365Attrs(x);
401
+ if (Object.keys(a).length) { const t = x.getAttribute('title'); if (t) a.title = t.slice(0, 200); d365Up = { tag: x.tagName.toLowerCase(), attributes: a }; break; }
402
+ }
403
+ }
391
404
  // None inside a shadow root: an XPath cannot reach into one, so it would find nothing when the test runs.
392
405
  const xp = (e) => e.getRootNode() !== document ? '' : xpFrom(e);
393
406
  const xpFrom = (e) => { const parts = []; for (; e && e.nodeType === 1; e = e.parentElement) { let i = 1; for (let s = e.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === e.tagName) i++; parts.unshift(e.tagName.toLowerCase() + '[' + i + ']'); } return parts.join('/'); };
@@ -408,6 +421,7 @@ _FACTS_FN = r"""function(kept) {
408
421
  const out = { tag: el.tagName.toLowerCase(), attributes: attrs, classes, xpath: xp(el), text: String(el.innerText || el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 120) };
409
422
  if (scope) out.scope = scope;
410
423
  if (frame) out.frame = frame;
424
+ if (site) { out.site = site; if (d365Up) out.d365_up = d365Up; }
411
425
  // Icon characters drawn by CSS (an icon font's ::before): Playwright counts them in the name, the browser's own
412
426
  // accessibility tree drops them. Only characters of the private use area, a few.
413
427
  let icons = '';
@@ -428,9 +442,10 @@ async def element_facts_cdp(session: Any, backend_node_id: int) -> Optional[Dict
428
442
  return None
429
443
  res = await _send(
430
444
  cdp, "Runtime", "callFunctionOn",
431
- {"objectId": object_id, "functionDeclaration": _FACTS_FN, "arguments": [{"value": list(KEPT_ATTRS)}], "returnByValue": True},
445
+ {"objectId": object_id, "functionDeclaration": _FACTS_FN, "arguments": [{"value": list(KEPT_ATTRS)}, {"value": d365_page_config()}], "returnByValue": True},
432
446
  )
433
- facts = (res.get("result") or {}).get("value") or {}
447
+ # Read as untrusted: D365's parts only in their shapes, and only on a D365 page (d365.clean_facts).
448
+ facts = d365_clean_facts((res.get("result") or {}).get("value") or {})
434
449
  # Build-generated class names (b87c397a13, css-1x2y3z) change with the site's next deploy.
435
450
  facts["classes"] = [c for c in facts.get("classes") or [] if not looks_generated(c) and not state_class(c)]
436
451
  ax = await _send(cdp, "Accessibility", "getPartialAXTree", {"backendNodeId": backend_node_id, "fetchRelatives": False})
@@ -8,7 +8,7 @@ Engine process protocol, used by the Bun CLI:
8
8
  stderr engine logs
9
9
 
10
10
  python -m forgeqe_engine run
11
- python -m forgeqe_engine login (stdin: {url, logins}, then "save")
11
+ python -m forgeqe_engine login (stdin: {url, logins}, then "save" until saved, or "stop")
12
12
  python -m forgeqe_engine record (stdin: {start_url, out_dir, ...}, then commands; "stop" or EOF ends it)
13
13
  python -m forgeqe_engine code (stdin: {login, since}; prints {"type": "done", "result": {success, code | error}})
14
14
  python -m forgeqe_engine doctor
@@ -147,7 +147,10 @@ def _run(out: TextIO) -> int:
147
147
 
148
148
 
149
149
  def _login(out: TextIO) -> int:
150
- """stdin line 1: {url, logins: [login]}; then "save" saves the session, "stop" or EOF cancels."""
150
+ """
151
+ stdin line 1: {url, logins: [login]}; then each "save" tries to save the session (the browser stays open while
152
+ there is nothing of the login's sites to save yet), and "stop" or EOF cancels.
153
+ """
151
154
  from .logins import interactive_login
152
155
 
153
156
  line = sys.stdin.readline()
@@ -159,21 +162,20 @@ def _login(out: TextIO) -> int:
159
162
 
160
163
  async def main() -> int:
161
164
  loop = asyncio.get_running_loop()
162
- finished = asyncio.Event()
165
+ commands: "asyncio.Queue[str]" = asyncio.Queue()
163
166
 
164
167
  def watch_stdin() -> None:
165
168
  for cmd in sys.stdin:
166
- if cmd.strip().lower() == "save":
167
- loop.call_soon_threadsafe(finished.set)
168
- return
169
- if cmd.strip().lower() == "stop":
169
+ word = cmd.strip().lower()
170
+ if word == "save":
171
+ loop.call_soon_threadsafe(commands.put_nowait, "save")
172
+ elif word == "stop":
170
173
  break
171
- payload["cancelled"] = True
172
- loop.call_soon_threadsafe(finished.set)
174
+ loop.call_soon_threadsafe(commands.put_nowait, "stop")
173
175
 
174
176
  threading.Thread(target=watch_stdin, daemon=True).start()
175
177
  try:
176
- result = await interactive_login(payload, emit, finished)
178
+ result = await interactive_login(payload, emit, commands.get)
177
179
  except Exception as e:
178
180
  result = {"success": False, "error": str(e)}
179
181
  emit({"type": "done", "result": result})
@@ -0,0 +1,28 @@
1
+ """
2
+ A host that asks the browser for a client certificate while recording (ADO 3529).
3
+
4
+ Entra ID's device sign-in (device.login.microsoftonline.com) asks Chrome for the computer's device certificate, and
5
+ Chrome shows its own "Select a certificate" box: no page script or DevTools event sees it. The request to that host
6
+ is what the recorder sees, so the recording keeps one `client_certificate` step for it, by host and the issuer of the
7
+ certificate that answers, both fixed here (never a value from the page). A replay gets past it only when the
8
+ computer's Chrome policy picks the certificate (src/engine/certpolicy.ts, `forgeqe doctor certificate`).
9
+ """
10
+ from __future__ import annotations
11
+
12
+ from typing import Optional
13
+ from urllib.parse import urlparse
14
+
15
+ # Kept in step with CLIENT_CERT_HOSTS in src/engine/certpolicy.ts.
16
+ CLIENT_CERT_HOSTS = {"device.login.microsoftonline.com": "MS-Organization-Access"}
17
+
18
+
19
+ def client_cert_host(url: str) -> Optional[str]:
20
+ """The host of CLIENT_CERT_HOSTS a request goes to over https, exactly; else None."""
21
+ try:
22
+ p = urlparse(url or "")
23
+ host = (p.hostname or "").lower()
24
+ except Exception:
25
+ return None
26
+ if p.scheme != "https" or p.username or p.password or p.port not in (None, 443):
27
+ return None
28
+ return host if host in CLIENT_CERT_HOSTS else None
@@ -0,0 +1,182 @@
1
+ """
2
+ Dynamics 365 / Power Apps model-driven apps, as the recorder sees them (ADO 3529).
3
+
4
+ The browser agent reads the `dynamics-365` skill and the coding agent `dynamics-365-automation`, whose catalogue
5
+ (`skills/dynamics-365-automation/references/elements.md`, from Microsoft's EasyRepro) says how D365 names its
6
+ controls: by its own attributes (`data-id`, `data-lp-id`, `data-type`, `data-control-name`), never by a generated id.
7
+ A hand recording has no model to read a skill, so the same rules are code here, and `tests/engine/test_d365.py`
8
+ checks that every selector shape below is one the skill's catalogue holds.
9
+
10
+ D365 renders ids from where a control sits (`AppModuleTileSec_1_Item_1`: the first tile of the first section of the
11
+ app picker's results; `id-6a1c…-12`, `quickFind_text_1`). They look steady and match on the page they were read from,
12
+ so the recorder ranked them first, and a replay with other results, another order or another session found nothing.
13
+
14
+ What the page gives is untrusted: an attribute is kept only by a name of `ATTRS`, and a value only when it is plain
15
+ (`plain`), so a selector built from it is one attribute test and nothing else.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ from typing import Any, Dict, List
21
+
22
+ SITE = "d365"
23
+
24
+ # Hosts of Dynamics 365 / Dataverse model-driven apps: commercial (crm, crm2…crm21), China, Germany, US government.
25
+ # An app on another host (on-premises) is told by the page itself: `#ApplicationShell`, the UCI's root (elements.md
26
+ # "App shell"); `HOST_JS` and `SHELL_ID` go to the page scripts so both sides decide alike.
27
+ HOST = re.compile(r"(?:^|\.)crm\d*\.(?:dynamics\.com|dynamics\.cn|microsoftdynamics\.de|microsoftdynamics\.us|appsplatform\.us)$", re.I)
28
+ HOST_JS = r"(?:^|\.)crm\d*\.(?:dynamics\.com|dynamics\.cn|microsoftdynamics\.de|microsoftdynamics\.us|appsplatform\.us)$"
29
+ SHELL_ID = "ApplicationShell"
30
+
31
+ # D365's own attributes that name a control (elements.md). Read only on a D365 page.
32
+ ATTRS = ("data-id", "data-lp-id", "data-type", "data-control-name")
33
+ # The only data-type value that names a thing: an app tile on the app landing page (elements.md Nav_UCIAppTile).
34
+ APP_TILE = "app-title"
35
+
36
+ # A D365 id or attribute value made from where the control sits or from a record: a number standing alone between
37
+ # separators (a section, an item, a row index), a GUID, or the Fluent UI ids D365 renders (`id__123`, `id-…`).
38
+ # `emailaddress1`, `address1_line1` keep their digits inside a word, so they stay.
39
+ GENERATED = re.compile(r"(?:^|[_\-.:])\d+(?:$|[_\-.:])|[0-9a-f]{8}-[0-9a-f]{4}-|^id(?:__|-)|^AppModuleTile", re.I)
40
+ GENERATED_JS = r"(?:^|[_\-.:])\d+(?:$|[_\-.:])|[0-9a-f]{8}-[0-9a-f]{4}-|^id(?:__|-)|^AppModuleTile"
41
+
42
+ # Above an id (memory.BASE["id"] 0.90) and a test id: the catalogue's attributes are what D365 keeps across sessions
43
+ # and releases, where its ids are not.
44
+ BASE = 0.95
45
+ MAX_VALUE = 120
46
+ # How far up from the element the recorder looks for the D365 control it belongs to (a tile, a command, a row).
47
+ MAX_UP = 4
48
+ FORM_TAGS = frozenset({"input", "textarea", "select"})
49
+ _TAG = re.compile(r"^[a-z][a-z0-9-]{0,30}$")
50
+
51
+
52
+ def is_d365_url(url: str) -> bool:
53
+ from urllib.parse import urlparse
54
+
55
+ try:
56
+ host = urlparse(url or "").hostname or ""
57
+ except Exception:
58
+ return False
59
+ return bool(host and HOST.search(host))
60
+
61
+
62
+ def plain(value: Any) -> bool:
63
+ """A value that goes into a selector as it is: one line, short, no quote, backslash or angle bracket."""
64
+ return isinstance(value, str) and 0 < len(value) <= MAX_VALUE and not re.search(r"[\"'\\<>\x00-\x1f\x7f]", value)
65
+
66
+
67
+ def generated(value: str) -> bool:
68
+ """A D365 id or attribute made from where the control sits or from a record: it changes on another run."""
69
+ return bool(GENERATED.search(value or ""))
70
+
71
+
72
+ def generated_path(xpath: str) -> bool:
73
+ """A relative XPath the page script built on an id or name D365 renders from position (`//div[@id='AppModuleTileSec_1_Item_1']`)."""
74
+ return any(generated(v) for v in re.findall(r"@(?:id|name)\s*=\s*['\"]([^'\"]*)['\"]", xpath or ""))
75
+
76
+
77
+ def page_config() -> Dict[str, Any]:
78
+ """What the page scripts need to tell a D365 page and read its attributes (webrecord_page.py, capture.py)."""
79
+ return {"host": HOST_JS, "shell": SHELL_ID, "attrs": list(ATTRS), "gen": GENERATED_JS, "up": MAX_UP}
80
+
81
+
82
+ def _attrs(raw: Any) -> Dict[str, str]:
83
+ if not isinstance(raw, dict):
84
+ return {}
85
+ out = {k: raw[k] for k in ATTRS if plain(raw.get(k))}
86
+ if plain(raw.get("title")):
87
+ out["title"] = raw["title"]
88
+ return out
89
+
90
+
91
+ def clean_facts(facts: Dict[str, Any]) -> Dict[str, Any]:
92
+ """
93
+ An element's facts as the page script read them, with D365's parts kept only in their shapes: `site` only "d365",
94
+ its attributes only by a name of `ATTRS` with a plain value, the control it belongs to (`d365_up`) only a tag and
95
+ such attributes. Anything else the page sent is dropped. On a page that is not D365, none of it is kept.
96
+ """
97
+ out = dict(facts)
98
+ attrs = dict(out.get("attributes") or {})
99
+ up = out.pop("d365_up", None)
100
+ if out.get("site") != SITE:
101
+ out.pop("site", None)
102
+ for k in ATTRS:
103
+ attrs.pop(k, None)
104
+ out["attributes"] = attrs
105
+ return out
106
+ for k in ATTRS:
107
+ if k in attrs and not plain(attrs[k]):
108
+ attrs.pop(k)
109
+ out["attributes"] = attrs
110
+ if isinstance(up, dict) and isinstance(up.get("tag"), str) and _TAG.match(up["tag"]):
111
+ a = _attrs(up.get("attributes"))
112
+ if any(k in a for k in ATTRS):
113
+ out["d365_up"] = {"tag": up["tag"], "attributes": a}
114
+ return out
115
+
116
+
117
+ def _q(v: str) -> str:
118
+ return '"' + v + '"'
119
+
120
+
121
+ def _selectors(tag: str, a: Dict[str, str]) -> List[Dict[str, str]]:
122
+ """The catalogue's selector shapes for one element's attributes, steadiest first, each with the attribute it counts by."""
123
+ out: List[Dict[str, str]] = []
124
+ title = a.get("title") or ""
125
+ # App tile: `div[data-type="app-title"][title="<app name>"]` (elements.md Nav_UCIAppTile).
126
+ if a.get("data-type") == APP_TILE and plain(title):
127
+ out.append({"css": f"{tag}[data-type={_q(APP_TILE)}][title={_q(title)}]", "attr": "title", "value": title})
128
+ # `[data-id="<field>.fieldControl-…"]`, `button[data-id*="Mscrm.Form.account.Save"]`, `a[data-id="appBreadCrumb"]`.
129
+ for k in ("data-id", "data-lp-id", "data-control-name"):
130
+ v = a.get(k) or ""
131
+ if plain(v) and not generated(v):
132
+ out.append({"css": f"{tag}[{k}={_q(v)}]", "attr": k, "value": v})
133
+ return out
134
+
135
+
136
+ def locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
137
+ """
138
+ Locators the D365 catalogue gives for an element: on the element itself, then on the D365 control it is inside (a
139
+ click on an app tile's name is a click on the tile), never for a field's input by its container. Each is a `css`
140
+ locator a replay builds as `page.locator(css)`, marked `site: d365`; `up` when it finds the control around it.
141
+ """
142
+ if f.get("site") != SITE:
143
+ return []
144
+ tag = str(f.get("tag") or "")
145
+ if not _TAG.match(tag):
146
+ return []
147
+ out: List[Dict[str, Any]] = []
148
+ seen = set()
149
+
150
+ def add(sel: Dict[str, str], up: bool) -> None:
151
+ if sel["css"] in seen:
152
+ return
153
+ seen.add(sel["css"])
154
+ css = sel["css"]
155
+ loc: Dict[str, Any] = {
156
+ "type": "css", "value": css, "css": css, "playwright": f"page.locator({_js(css)})", "base": BASE, "site": SITE,
157
+ # Counted by the page script at the event through this attribute (recordsession._count): an upper bound, as
158
+ # the selector is narrower than the attribute alone.
159
+ **({"count_attr": sel["attr"]} if not up else {}),
160
+ }
161
+ if up:
162
+ loc["up"] = True
163
+ out.append(loc)
164
+
165
+ for sel in _selectors(tag, f.get("attributes") or {}):
166
+ add(sel, False)
167
+ up = f.get("d365_up")
168
+ if tag not in FORM_TAGS and isinstance(up, dict) and _TAG.match(str(up.get("tag") or "")):
169
+ for sel in _selectors(str(up["tag"]), up.get("attributes") or {}):
170
+ add(sel, True)
171
+ return out
172
+
173
+
174
+ def _js(s: str) -> str:
175
+ import json
176
+
177
+ return json.dumps(s)
178
+
179
+
180
+ def note() -> str:
181
+ """One line for the recording's log, said once when the recorder first sees a D365 page."""
182
+ return "Dynamics 365 page: elements are found by D365's own attributes (data-id, app tiles by name), as the dynamics-365 skill says, never by the ids D365 renders from position."
@@ -318,10 +318,11 @@ def write_session(file: str, state: Dict[str, Any]) -> None:
318
318
  os.replace(tmp, path)
319
319
 
320
320
 
321
- async def interactive_login(payload: Dict[str, Any], emit: Any, finished: Any) -> Dict[str, Any]:
321
+ async def interactive_login(payload: Dict[str, Any], emit: Any, next_command: Any) -> Dict[str, Any]:
322
322
  """
323
323
  Open a visible browser on the login's page with any saved session, let a person sign in, and save the session
324
- when `finished` is set by a "save" line on stdin.
324
+ when `next_command()` gives "save" ("stop" cancels). A "save" pressed before the person signed in (nothing of the
325
+ login's sites to keep yet) leaves the browser open and says so (`not_signed_in`), so it is never closed under them.
325
326
  """
326
327
  from browser_use import Browser
327
328
 
@@ -352,21 +353,24 @@ async def interactive_login(payload: Dict[str, Any], emit: Any, finished: Any) -
352
353
  enroll = (enroll_cdp, await add_authenticator(enroll_cdp))
353
354
  await browser._cdp_navigate(url)
354
355
  if overlay is not None:
355
- await overlay.waiting(f"Sign in to {logins[0].name} here, then press Enter in the terminal to save the session")
356
+ await overlay.waiting(f"Sign in to {logins[0].name} here, then confirm in ForgeQE to save the session")
356
357
  emit({"type": "log", "level": "info", "text": f"Browser open at {url}"})
357
- await finished.wait()
358
- if payload.get("cancelled"):
359
- return {"success": False, "error": "cancelled"}
360
- saved = await save_sessions(browser, logins, {})
361
- if enroll is not None:
362
- from .passkey import read_credentials
363
-
364
- creds = await read_credentials(*enroll)
365
- # The credential is a secret: it goes back to ForgeQE on this pipe only, which keeps it in the credential store.
366
- return {"success": True, "saved": saved, "passkey": creds, "summary": f"{len(creds)} security key{'' if len(creds) == 1 else 's'} registered"}
367
- if not saved:
368
- return {"success": False, "error": f"No cookies or local storage for {', '.join(logins[0].domains)} were found; nothing was saved."}
369
- return {"success": True, "saved": saved, "summary": f"Session saved for {', '.join(saved)}"}
358
+ while True:
359
+ if await next_command() != "save":
360
+ return {"success": False, "error": "cancelled"}
361
+ if enroll is not None:
362
+ from .passkey import read_credentials
363
+
364
+ saved = await save_sessions(browser, logins, {})
365
+ creds = await read_credentials(*enroll)
366
+ # The credential is a secret: it goes back to ForgeQE on this pipe only, which keeps it in the credential store.
367
+ return {"success": True, "saved": saved, "passkey": creds, "summary": f"{len(creds)} security key{'' if len(creds) == 1 else 's'} registered"}
368
+ saved = await save_sessions(browser, logins, {})
369
+ if saved:
370
+ return {"success": True, "saved": saved, "summary": f"Session saved for {', '.join(saved)}"}
371
+ # Nothing to keep yet: the person has not finished signing in (an account picker, a code still open). The
372
+ # browser stays open and ForgeQE asks again.
373
+ emit({"type": "not_signed_in", "text": f"No cookies or local storage for {', '.join(logins[0].domains)} yet: finish signing in in the browser window."})
370
374
  finally:
371
375
  await _shutdown_browser_instance(browser)
372
376
 
@@ -25,6 +25,7 @@ from typing import Any, Dict, Iterable, Iterator, List, Optional, Set, Tuple
25
25
  from urllib.parse import urlparse
26
26
 
27
27
  from . import flowmatch
28
+ from .d365 import SITE as D365_SITE, generated as d365_generated, generated_path as d365_generated_path, locators as d365_locators
28
29
  from .logins import secret_ref, text_envs
29
30
 
30
31
  VERSION = 1
@@ -378,12 +379,17 @@ def candidate_locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
378
379
  a: Dict[str, str] = f.get("attributes") or {}
379
380
  tag = f.get("tag") or "*"
380
381
  role, name = f.get("role") or "", f.get("name") or ""
382
+ # A Dynamics 365 page (d365.py): its own attributes first, as the dynamics-365 skill names its controls, and the ids
383
+ # it renders from where a control sits (AppModuleTileSec_1_Item_1) read down as generated.
384
+ d365 = f.get("site") == D365_SITE
385
+ if d365:
386
+ out.extend(d365_locators(f))
381
387
 
382
388
  def add(kind: str, value: str, playwright: str, **extra: Any) -> None:
383
389
  if not value:
384
390
  return
385
391
  base = BASE[kind]
386
- generated = kind in ("test_id", "id", "name", "href", "css") and looks_generated(value)
392
+ generated = kind in ("test_id", "id", "name", "href", "css") and (looks_generated(value) or (d365 and kind in ("id", "name", "css") and d365_generated(value)))
387
393
  if generated:
388
394
  base *= GENERATED_FACTOR
389
395
  loc = {"type": kind, "value": value, "playwright": playwright, "base": round(base, 3), **extra}
@@ -448,13 +454,13 @@ def candidate_locators(f: Dict[str, Any]) -> List[Dict[str, Any]]:
448
454
  if classes:
449
455
  css = tag + "".join(class_selector(c) for c in classes[:2])
450
456
  add("css", css, f"page.locator({_q(css)})", css=css)
451
- if f.get("scope"):
457
+ if f.get("scope") and not (d365 and d365_generated(str(f["scope"]))):
452
458
  # Within the item it belongs to: one of a control that repeats on every row or card.
453
459
  own = tag + "".join(class_selector(c) for c in classes[:2]) if classes else (f"{tag}[href={_q(href)}]" if tag == "a" and href else tag)
454
460
  css = f"{f['scope']} {own}"
455
461
  add("css", css, f"page.locator({_q(css)})", css=css, scoped=True)
456
462
  rel = str(f.get("rel_xpath") or "")
457
- if rel.startswith("//") and len(rel) <= MAX_REL_XPATH:
463
+ if rel.startswith("//") and len(rel) <= MAX_REL_XPATH and not (d365 and d365_generated_path(rel)):
458
464
  add("xpath_relative", rel, f"page.locator({_q('xpath=' + rel)})")
459
465
  if f.get("xpath"):
460
466
  xp = "/" + str(f["xpath"]).lstrip("/")