copilot-operator 0.1.88 → 0.1.92

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 (47) hide show
  1. package/dist/src/api/operator.controller.js +66 -3
  2. package/dist/src/api/operator.service.js +156 -0
  3. package/dist/src/api/server.js +5 -1
  4. package/dist/src/cli.js +9 -0
  5. package/dist/src/config/live.js +6 -3
  6. package/dist/src/config/schema.js +35 -0
  7. package/dist/src/orchestrator/taskRunner.js +33 -4
  8. package/dist/src/plan/systemGuide.js +373 -0
  9. package/dist/src/session/chatNotice.js +4 -1
  10. package/dist/src/session/events.js +5 -1
  11. package/dist/src/session/locatorFailures.js +56 -0
  12. package/dist/src/transport/chatSteps.js +74 -0
  13. package/dist/src/transport/copilotTransport.js +514 -76
  14. package/dist/src/transport/keptWindow.js +7 -0
  15. package/dist/src/transport/locators.js +174 -5
  16. package/dist/src/transport/pageHtml.js +62 -0
  17. package/dist/web/404.html +2 -2
  18. package/dist/web/_next/static/chunks/{1077.26ca37faa3726fff.js → 1077.922b5f1492f6e0dd.js} +1 -1
  19. package/dist/web/_next/static/chunks/{1548.f5790cd11a91309f.js → 1548.4a09f12e23d369ec.js} +1 -1
  20. package/dist/web/_next/static/chunks/{2163.aa9d9b82fcde6caa.js → 2163.14e7879a45ae9748.js} +1 -1
  21. package/dist/web/_next/static/chunks/{714.b7dbce98ba0b59a8.js → 714.2daeede6dd07ee60.js} +1 -1
  22. package/dist/web/_next/static/chunks/{7220.0ca53eefec5d01ea.js → 7220.260579c8dbfa2c30.js} +1 -1
  23. package/dist/web/_next/static/chunks/7921-1de1f08d23145c0d.js +1 -0
  24. package/dist/web/_next/static/chunks/{8584.9f3b058a8f67d3d7.js → 8584.01e3a7f9f14f0b4f.js} +1 -1
  25. package/dist/web/_next/static/chunks/{9067.107f6164157e0aa1.js → 9067.75d4fdcf47f62fd1.js} +1 -1
  26. package/dist/web/_next/static/chunks/{9747.984a86f70f9cd973.js → 9747.f1bdfbefaba61f8b.js} +1 -1
  27. package/dist/web/_next/static/chunks/app/layout-f5681fae8247797b.js +1 -0
  28. package/dist/web/_next/static/chunks/app/queue/{page-317151444eda8115.js → page-7909ba7c9e3d4c2d.js} +1 -1
  29. package/dist/web/_next/static/chunks/app/settings/page-7d343eecdd9c7500.js +1 -0
  30. package/dist/web/_next/static/chunks/{webpack-c015bbeb103c0856.js → webpack-abd1f09115b96456.js} +1 -1
  31. package/dist/web/_next/static/css/{0c5d6d5914aa3824.css → 6b92f118889ca88b.css} +1 -1
  32. package/dist/web/defaults.html +2 -2
  33. package/dist/web/defaults.txt +8 -8
  34. package/dist/web/index.html +3 -3
  35. package/dist/web/index.txt +9 -9
  36. package/dist/web/queue.html +2 -2
  37. package/dist/web/queue.txt +9 -9
  38. package/dist/web/settings.html +2 -2
  39. package/dist/web/settings.txt +9 -9
  40. package/dist/web/system.html +2 -2
  41. package/dist/web/system.txt +9 -9
  42. package/package.json +3 -2
  43. package/dist/web/_next/static/chunks/7921-8f6503aba840928a.js +0 -1
  44. package/dist/web/_next/static/chunks/app/layout-127e5af1ebf21876.js +0 -1
  45. package/dist/web/_next/static/chunks/app/settings/page-95069cb94d79e909.js +0 -1
  46. /package/dist/web/_next/static/{hLBBsG7Kn4vd0p_J-47BJ → n7rfXOWgaCFmATod4Q6hp}/_buildManifest.js +0 -0
  47. /package/dist/web/_next/static/{hLBBsG7Kn4vd0p_J-47BJ → n7rfXOWgaCFmATod4Q6hp}/_ssgManifest.js +0 -0
@@ -16,9 +16,11 @@ import { mkdir, writeFile } from 'node:fs/promises';
16
16
  import { join } from 'node:path';
17
17
  import { findRecentCrash, describeCrash } from './edgeCrash.js';
18
18
  import { landed } from './acceptance.js';
19
- import { Blocker, Css, fillLocator, Label, Model, ModelPicking, pageQuery, playwrightSelector, Rename, resolvePickerLocators, Sidebar, Signal, Surface, TestId, Upload, Url, } from './locators.js';
19
+ import { Blocker, CHAT_ID, CHAT_LOCATOR_KEYS, ChatLocatorGroupOf, ChatLocatorWhat, Css, DefaultChatLocators, fillFileLocator, fillLocator, Label, Model, ModelPicking, pageQuery, playwrightSelector, Rename, resolveChatLocators, resolvePickerLocators, Signal, Surface, Url, } from './locators.js';
20
20
  import { acquireProfileLock } from './profileLock.js';
21
21
  import { chatNameForms, parseChatId } from './chatSession.js';
22
+ import { strippedPageHtml } from './pageHtml.js';
23
+ import { DefaultBuiltInSteps, stepKey, usableSteps } from './chatSteps.js';
22
24
  /**
23
25
  * The chat did not finish a reply within `copilot.replyTimeoutSec`.
24
26
  *
@@ -276,6 +278,28 @@ export const CLIPBOARD_GUARD = `(() => {
276
278
  };
277
279
  } catch (e) { /* as above */ }
278
280
  })();`;
281
+ /**
282
+ * A locator of the chat that found nothing where the bot needed it (operator, 2026-11-17: "a mechanism that detects
283
+ * which locator exactly the bot failed on, so we can easily see which locator has to be updated"): which one, as it
284
+ * was in force, and the page's HTML and picture kept for finding the right one. The runner says it like any other
285
+ * error; the transport has said it already (`locator-missing`), which the API keeps for Settings (`LocatorFailures`).
286
+ */
287
+ export class LocatorMissing extends Error {
288
+ key;
289
+ locator;
290
+ html;
291
+ picture;
292
+ constructor(
293
+ /** A chat locator's key, or `step:<id>` for one of the operator's own steps (see `chatSteps.ts`). */
294
+ key, locator, message, html, picture) {
295
+ super(message);
296
+ this.key = key;
297
+ this.locator = locator;
298
+ this.html = html;
299
+ this.picture = picture;
300
+ this.name = 'LocatorMissing';
301
+ }
302
+ }
279
303
  export class CopilotTransport {
280
304
  opts;
281
305
  context = null;
@@ -293,6 +317,18 @@ export class CopilotTransport {
293
317
  gone = false;
294
318
  /** The model menu's locators in force: Settings' own, else the defaults (see `resolvePickerLocators`). */
295
319
  locators;
320
+ /** The chat page's locators in force — the box to write in: Settings' own, else the default (see `resolveChatLocators`). */
321
+ chatLocators;
322
+ /** The bot's own steps as Settings switch them, the operator's own steps taken, and why one saved is not (2026-11-17). */
323
+ builtIn;
324
+ steps;
325
+ stepProblems;
326
+ /** A picture at each step of choosing a model (Settings' `pickerSteps`). */
327
+ stepShots;
328
+ /** Said once a window: the conversation is not named (its step switched off); a step passed over that is not required. */
329
+ nameOffSaid = false;
330
+ /** Why a chat locator saved in Settings is not used; said once, when the chat is first opened. */
331
+ chatLocatorProblems;
296
332
  /** Why a locator saved in Settings is not used; said once, at the first choice or reading of the models. */
297
333
  locatorProblems;
298
334
  /** Whether the rows' locator has been said not to work in the page (see `readMenuRows`). */
@@ -320,13 +356,53 @@ export class CopilotTransport {
320
356
  settleMs = 2_000;
321
357
  /** How long another page of the work Copilot is given to turn into its chat on its own before the bot opens the chat. */
322
358
  otherPageMs = 3_000;
359
+ /** How long the answer is waited for with not one message of the conversation found, before the `turn` locator is said. */
360
+ turnsGraceMs = 20_000;
361
+ /** How long Copilot's newest answer may stand still, not written and not finished, before its locator is said. */
362
+ answerStillMs = 60_000;
363
+ /** The locators said already in this window, where the work went on without them: said once. */
364
+ warned = new Set();
365
+ /** How long Send is waited for once the message is in the box. */
366
+ sendWaitMs = 20_000;
367
+ /** How long a message sent is waited for in the conversation before it is taken as not accepted. */
368
+ acceptMs = 30_000;
323
369
  constructor(opts) {
324
370
  this.opts = opts;
325
371
  const { locators, problems } = resolvePickerLocators(opts.pickerLocators);
326
372
  this.locators = locators;
373
+ const chat = resolveChatLocators(opts.chatLocators);
374
+ this.chatLocators = chat.locators;
375
+ this.chatLocatorProblems = chat.problems;
327
376
  this.locatorProblems = problems;
377
+ this.builtIn = { ...DefaultBuiltInSteps, ...(opts.builtInSteps ?? {}) };
378
+ const own = usableSteps(opts.extraSteps);
379
+ this.steps = own.steps;
380
+ this.stepProblems = own.problems;
381
+ this.stepShots = !!opts.modelStepShots;
328
382
  this.chatOrigin = surfaceOfUrl(opts.chatUrl) === 'work' ? new URL(opts.chatUrl).origin : Url.origin;
329
383
  }
384
+ /**
385
+ * Settings saved since this window opened (2026-11-17): the locators, the model menu's and the chat's, and the steps
386
+ * on the way to the chat. The chat's window is kept open between messages, and a locator fixed in Settings went on
387
+ * being looked for as it was until the window closed; each message's run hands the window what Settings say now, and
388
+ * a save while a message is at work does the same. What cannot be used is said as when a window opens.
389
+ */
390
+ takeSettings(o) {
391
+ const picker = resolvePickerLocators(o.pickerLocators);
392
+ this.locators = picker.locators;
393
+ this.locatorProblems = picker.problems;
394
+ const chat = resolveChatLocators(o.chatLocators);
395
+ if (JSON.stringify(chat.locators) !== JSON.stringify(this.chatLocators))
396
+ this.warned.clear();
397
+ this.chatLocators = chat.locators;
398
+ this.chatLocatorProblems = chat.problems;
399
+ this.builtIn = { ...DefaultBuiltInSteps, ...(o.builtInSteps ?? {}) };
400
+ const own = usableSteps(o.extraSteps);
401
+ this.steps = own.steps;
402
+ this.stepProblems = own.problems;
403
+ this.stepShots = !!o.modelStepShots;
404
+ this.emit('settings-taken', { steps: this.steps.length, builtIn: this.builtIn });
405
+ }
330
406
  /** Says, once, which locators saved in Settings could not be used and why. */
331
407
  sayLocatorProblems() {
332
408
  for (const problem of this.locatorProblems)
@@ -555,8 +631,249 @@ export class CopilotTransport {
555
631
  return false;
556
632
  }
557
633
  }
634
+ /**
635
+ * The box to write in, by the chat's locator in force (Settings' own, else the default; 2026-11-17). What it finds is
636
+ * taken if it can be written in, else the first box inside it that can: a locator copied from the page's inspector for
637
+ * an element around the box (the operator's of 2026-11-17 named the box's wrapper, `data-chat-input-pill`) finds it all
638
+ * the same.
639
+ */
558
640
  composer() {
559
- return this.p.locator(Css.composer).first();
641
+ return this.p
642
+ .locator(this.sel('composer'))
643
+ .first()
644
+ .locator("xpath=descendant-or-self::*[(@contenteditable and @contenteditable != 'false') or self::textarea]")
645
+ .first();
646
+ }
647
+ /** What the message says when the box is not found: its locator in force, and where Settings has it. */
648
+ composerHint() {
649
+ return (`If the picture shows the chat with its box to write in, the box's locator does not find it: ${this.chatLocators.composer} ` +
650
+ '(Settings → "The chat\'s locators" → "Box to write in").');
651
+ }
652
+ /** A chat locator in force, as Playwright takes it; `chatId` goes where a template has its place. */
653
+ sel(key, chatId) {
654
+ const s = this.chatLocators[key];
655
+ return playwrightSelector(chatId === undefined ? s : s.split(CHAT_ID).join(chatId));
656
+ }
657
+ /** What a chat locator in force finds in the page. */
658
+ el(key, chatId) {
659
+ return this.p.locator(this.sel(key, chatId));
660
+ }
661
+ /**
662
+ * A locator that found nothing where the bot needed it (2026-11-17): a picture of the page and its HTML for a chatbot
663
+ * to find the right one in (scripts, styles and the sidebar out — see `pageHtml.ts`), kept in the failures folder, and
664
+ * said (`locator-missing`, which the API keeps so Settings can show the field in red). The error to throw when the
665
+ * work cannot go on without it; `stopped: false` when it goes on (a conversation's name). `message` is given the
666
+ * sentence naming the files.
667
+ */
668
+ async locatorMissing(key, why, opts = {}) {
669
+ const stopped = opts.stopped ?? true;
670
+ const locator = this.chatLocators[key];
671
+ const { picture, html, url } = await this.keepPage(`locator-${key}-${Date.now()}`, ChatLocatorGroupOf[key] === 'conversations');
672
+ this.emit('locator-missing', { key, locator, why, stopped, ...(html ? { html } : {}), ...(picture ? { picture } : {}), ...(url ? { url } : {}) });
673
+ const files = [picture ? `A picture of the page: ${picture}.` : '', html ? `The page's HTML, for a chatbot to find the right locator in: ${html}.` : ''].filter(Boolean).join(' ');
674
+ const message = opts.message?.(files) ??
675
+ `Not found on Copilot's page: ${ChatLocatorWhat[key]}. The "${key}" locator found nothing ${why}. In force: ${locator} ` +
676
+ `(Settings → "The chat's locators"). ${files}`.trim();
677
+ return new LocatorMissing(key, locator, message, html, picture);
678
+ }
679
+ /** A picture of the page and its HTML for a chatbot (see `pageHtml.ts`), in the failures folder; where the page was. */
680
+ async keepPage(tag, keepSidebar) {
681
+ if (!this.page || this.page.isClosed())
682
+ return {};
683
+ const dir = join(this.opts.transportDir, '..', 'failures');
684
+ await mkdir(dir, { recursive: true }).catch(() => undefined);
685
+ const out = { url: whereIs(this.p.url()) };
686
+ const png = join(dir, `${tag}.png`);
687
+ if (await this.p.screenshot({ path: png, fullPage: true }).then(() => true, () => false))
688
+ out.picture = png;
689
+ const text = await this.p.evaluate(strippedPageHtml, keepSidebar).catch(() => '');
690
+ const file = join(dir, `${tag}.html`);
691
+ if (text && (await writeFile(file, text, 'utf8').then(() => true, () => false)))
692
+ out.html = file;
693
+ return out;
694
+ }
695
+ /**
696
+ * The operator's own steps for `when` (2026-11-17, see `chatSteps.ts`), in their order: "if this is on the page, do
697
+ * this". One that must be there and is not, within its seconds, stops the work like a locator that found nothing,
698
+ * said by its name; one that need not be is passed over.
699
+ */
700
+ async runSteps(when, signal) {
701
+ for (const problem of this.stepProblems.splice(0))
702
+ this.emit('chat-step-not-used', { problem });
703
+ for (const step of this.steps) {
704
+ if (step.when !== when)
705
+ continue;
706
+ if (signal?.aborted)
707
+ throw new StoppedByOperator('stopped by the operator during a step on the way to the chat');
708
+ await this.runStep(step);
709
+ }
710
+ }
711
+ async runStep(step) {
712
+ const ms = Math.max(0, step.waitSec ?? 2) * 1000;
713
+ const shown = this.p.locator(playwrightSelector(step.locator)).filter({ visible: true }).first();
714
+ const said = { id: step.id, name: step.name, when: step.when, action: step.action };
715
+ if (step.action === 'gone') {
716
+ // Waited for to go, when it is there: a spinner, a banner that leaves by itself.
717
+ if ((await shown.count().catch(() => 0)) === 0)
718
+ return this.emit('chat-step', { ...said, did: 'not-there' });
719
+ const went = ms > 0 && (await shown.waitFor({ state: 'hidden', timeout: ms }).then(() => true, () => false));
720
+ if (went)
721
+ return this.emit('chat-step', { ...said, did: 'gone' });
722
+ if (step.must)
723
+ throw await this.stepMissing(step, `was still on the page after ${Math.round(ms / 1000)} s`);
724
+ return this.emit('chat-step', { ...said, did: 'still-there' });
725
+ }
726
+ // 0 seconds: only a look at the page as it is (a wait of no time would see nothing, even what is there).
727
+ const there = ms === 0
728
+ ? (await shown.count().catch(() => 0)) > 0
729
+ : await shown.waitFor({ state: 'visible', timeout: ms }).then(() => true, () => false);
730
+ if (!there) {
731
+ if (step.must)
732
+ throw await this.stepMissing(step, `found nothing within ${Math.round(ms / 1000)} s`);
733
+ return this.emit('chat-step', { ...said, did: 'not-there' });
734
+ }
735
+ try {
736
+ if (step.action === 'click')
737
+ await shown.click({ timeout: 10_000 });
738
+ else if (step.action === 'press')
739
+ await this.p.keyboard.press((step.key ?? '').trim());
740
+ this.emit('chat-step', { ...said, did: step.action === 'appear' ? 'appeared' : step.action === 'press' ? 'pressed' : 'clicked' });
741
+ }
742
+ catch (e) {
743
+ if (step.must)
744
+ throw await this.stepMissing(step, `was found, and ${step.action === 'press' ? 'the key could not be pressed' : 'could not be clicked'}: ${e.message.split('\n')[0]}`);
745
+ this.emit('chat-step', { ...said, did: 'failed', error: e.message.split('\n')[0] });
746
+ }
747
+ }
748
+ /** One of the operator's own steps that must be there and is not: said like a locator that found nothing. */
749
+ async stepMissing(step, why, stopped = true) {
750
+ const key = stepKey(step.id);
751
+ const { picture, html, url } = await this.keepPage(`step-${step.id}-${Date.now()}`, false);
752
+ const when = step.when === 'open' ? 'when the chat opened' : 'before a message';
753
+ this.emit('locator-missing', { key, name: step.name, locator: step.locator, why: `${when}: ${why}`, stopped, ...(html ? { html } : {}), ...(picture ? { picture } : {}), ...(url ? { url } : {}) });
754
+ const files = [picture ? `A picture of the page: ${picture}.` : '', html ? `The page's HTML, for a chatbot to find the right locator in: ${html}.` : ''].filter(Boolean).join(' ');
755
+ return new LocatorMissing(key, step.locator, `Your step "${step.name || step.locator}" must be there, and ${when} its locator ${why}. In force: ${step.locator} ` +
756
+ `(Settings → "Steps to the chat"; switch the step off there, or make it not required, to go on without it). ${files}`.trim(), html, picture);
757
+ }
758
+ /** A locator that found nothing where the work goes on without it (a conversation's name): said once a window. */
759
+ async warnLocator(key, why, chatId) {
760
+ if (this.warned.has(key) || !this.page || this.page.isClosed())
761
+ return;
762
+ if ((await this.el(key, chatId).count().catch(() => 1)) > 0)
763
+ return;
764
+ this.warned.add(key);
765
+ await this.locatorMissing(key, why, { stopped: false, ...(chatId ? { chatId } : {}) });
766
+ }
767
+ /**
768
+ * Looks for each of the chat's locators in force in the page (operator, 2026-11-17: "make the 'Check the locators'
769
+ * button too"), and says for each what it found. Only reads and looks:
770
+ * - the chat as it was opened: its box, and its Send (one letter typed and taken out again, if Send shows only with
771
+ * text; nothing is sent);
772
+ * - the sidebar;
773
+ * - the newest conversation in it, opened by its address: its messages, its answers, their Copy;
774
+ * - its "More" button, whose menu is opened and closed again with Escape, for "Rename".
775
+ * The rename dialog is not opened, and Stop shows only while Copilot writes: those are said as not on the page then.
776
+ * One that finds nothing is said as a failure the work went on without (`locator-missing`, its HTML kept), so its
777
+ * field goes red in Settings.
778
+ */
779
+ async checkLocators() {
780
+ const out = new Map();
781
+ const why = 'when the locators were checked ("Check the locators" in Settings)';
782
+ const count = async (key, chatId) => await this.el(key, chatId).count().catch(() => 0);
783
+ const record = async (key, n, chatId, note) => {
784
+ out.set(key, { key, status: n > 0 ? 'found' : 'none', count: n, ...(note ? { note } : {}) });
785
+ if (n === 0)
786
+ await this.locatorMissing(key, why, { stopped: false, ...(chatId ? { chatId } : {}) }).catch(() => undefined);
787
+ return n;
788
+ };
789
+ const look = async (key, chatId) => await record(key, await count(key, chatId), chatId);
790
+ const notHere = (key, note) => {
791
+ out.set(key, { key, status: 'not-here', count: 0, note });
792
+ };
793
+ // The chat as it was opened: its box, and its Send.
794
+ const box = await look('composer');
795
+ let send = await count('send');
796
+ if (send === 0 && box > 0) {
797
+ // Send shown only once the box holds text: one letter, taken out again. Nothing is sent.
798
+ await this.composer().fill('x').catch(() => undefined);
799
+ await this.p.waitForTimeout(500);
800
+ send = await count('send');
801
+ await this.composer().fill('').catch(() => undefined);
802
+ }
803
+ await record('send', send);
804
+ // The box's file input (hidden: counted, not looked at). An attached file shows only once one is, and none is here.
805
+ await look('uploadInput');
806
+ notHere('attachment', 'attach');
807
+ notHere('attachmentUploaded', 'attach');
808
+ // Stop shows only while Copilot writes.
809
+ const stop = await count('stop');
810
+ if (stop > 0)
811
+ out.set('stop', { key: 'stop', status: 'found', count: stop });
812
+ else
813
+ notHere('stop', 'writing');
814
+ // The sidebar, and the newest conversation in it, opened by its address: only read.
815
+ const links = await look('conversationLink');
816
+ const href = links > 0 ? await this.el('conversationLink').first().getAttribute('href').catch(() => null) : null;
817
+ const chatId = href ? parseChatId(href) : null;
818
+ const opened = chatId ? await this.openConversation(chatId).catch(() => false) : false;
819
+ if (opened && chatId) {
820
+ for (const key of ['turn', 'userMessage', 'answer', 'copy'])
821
+ await look(key);
822
+ // Its "More" button: by the locator; at its default and finding nothing, by its name in the row, as the bot does.
823
+ let more = this.el('chatMore', chatId).first();
824
+ let found = await count('chatMore', chatId);
825
+ let note;
826
+ if (found === 0 && this.chatLocators.chatMore === DefaultChatLocators.chatMore) {
827
+ const row = this.el('conversationLink').and(this.p.locator(`[href*="${chatId}"]`)).first();
828
+ const byName = row.locator('xpath=ancestor-or-self::*[self::li or self::div][1]').getByRole('button', { name: Rename.moreButtonLabel, exact: true });
829
+ const n = await byName.count().catch(() => 0);
830
+ if (n > 0) {
831
+ more = byName.first();
832
+ found = n;
833
+ note = 'byName';
834
+ }
835
+ }
836
+ await record('chatMore', found, chatId, note);
837
+ if (found > 0) {
838
+ await this.press(more).catch(() => undefined);
839
+ await this.el('renameItem').first().waitFor({ state: 'visible', timeout: 3_000 }).catch(() => undefined);
840
+ await look('renameItem');
841
+ await this.dismissOpenMenu().catch(() => undefined);
842
+ }
843
+ else
844
+ notHere('renameItem', 'noMenu');
845
+ }
846
+ else {
847
+ for (const key of ['turn', 'userMessage', 'answer', 'copy', 'chatMore', 'renameItem'])
848
+ notHere(key, 'noConversation');
849
+ }
850
+ // The rename dialog is not opened: renaming is not this check's to do.
851
+ notHere('renameInput', 'dialog');
852
+ notHere('renameSave', 'dialog');
853
+ // The operator's own steps (2026-11-17): what each finds now; one required not found is in red, the rest as they are.
854
+ const ownSteps = [];
855
+ for (const step of this.steps) {
856
+ const key = stepKey(step.id);
857
+ const n = await this.p.locator(playwrightSelector(step.locator)).filter({ visible: true }).count().catch(() => 0);
858
+ if (n > 0)
859
+ ownSteps.push({ key, status: 'found', count: n });
860
+ else if (step.action === 'gone')
861
+ ownSteps.push({ key, status: 'not-here', count: 0, note: 'gone' });
862
+ else if (step.must) {
863
+ ownSteps.push({ key, status: 'none', count: 0 });
864
+ await this.stepMissing(step, 'found nothing when the locators were checked', false).catch(() => undefined);
865
+ }
866
+ else
867
+ ownSteps.push({ key, status: 'not-here', count: 0, note: 'optional' });
868
+ }
869
+ for (const c of ownSteps)
870
+ out.set(c.key, c);
871
+ this.emit('locators-checked', { found: [...out.values()].filter((c) => c.status === 'found').length, none: [...out.values()].filter((c) => c.status === 'none').map((c) => c.key) });
872
+ return [...CHAT_LOCATOR_KEYS.map((k) => out.get(k) ?? { key: k, status: 'not-here', count: 0 }), ...ownSteps];
873
+ }
874
+ /** Whether the box to write in is empty: a message clicked away with Send leaves it so. */
875
+ async boxIsEmpty() {
876
+ return ((await this.composer().innerText({ timeout: 2_000 }).catch(() => 'unread')) ?? '').trim() === '';
560
877
  }
561
878
  /** Whether the composer shows within `ms`, looked for a second at a time; a Stop ends the wait with `StoppedByOperator`. */
562
879
  async composerWithin(ms, signal, stopped) {
@@ -581,10 +898,13 @@ export class CopilotTransport {
581
898
  chatAddress(path) {
582
899
  return `${this.chatOrigin}${path}`;
583
900
  }
584
- /** Keeps the host the page is on when it is one of the chat's addresses: the chat's addresses are opened there from then on. */
901
+ /**
902
+ * Keeps the host the chat was found on — its box there, and staying — when it is the work Copilot's: the chat's
903
+ * addresses are opened there from then on. Whatever the path: on 2026-11-17 the work machine's chat was at `/home`.
904
+ */
585
905
  learnChatOrigin() {
586
906
  const url = this.p.url();
587
- if (isWorkChatAddress(url))
907
+ if (surfaceOfUrl(url) === 'work')
588
908
  this.chatOrigin = new URL(url).origin;
589
909
  }
590
910
  /** Whether the box to write in is still there, on the same page, after `settleMs`: one that showed on the way elsewhere is not. */
@@ -679,12 +999,12 @@ export class CopilotTransport {
679
999
  */
680
1000
  async notTheChat() {
681
1001
  const url = this.p.url();
682
- const dir = join(this.opts.transportDir, '..', 'failures');
683
- const tag = `not-the-chat-${Date.now()}`;
684
- await this.dumpFailure(dir, tag).catch(() => undefined);
685
- return new Error(`Copilot showed its page ${whereIs(url)} instead of the chat, and the chat did not open from there ` +
686
- `(by its address on that host, nor by a link to it on the page). Nothing was sent. A picture of the page: ${join(dir, `${tag}.png`)}
687
- Current URL: ${url}`);
1002
+ // Most likely the box itself (2026-11-17: Copilot's chat was at /home, its box changed): said as the box's locator.
1003
+ return await this.locatorMissing('composer', `on ${whereIs(url)}, which did not turn into the chat`, {
1004
+ message: (files) => `Copilot showed its page ${whereIs(url)} instead of the chat, and the chat did not open from there ` +
1005
+ `(by its address on that host, nor by a link to it on the page). Nothing was sent. ${files} ${this.composerHint()}
1006
+ Current URL: ${url}`,
1007
+ });
688
1008
  }
689
1009
  /**
690
1010
  * Which Copilot we actually landed on.
@@ -699,7 +1019,8 @@ Current URL: ${url}`);
699
1019
  const where = surfaceOfUrl(this.p.url());
700
1020
  if (where !== 'work')
701
1021
  return where;
702
- const hasWorkComposer = (await this.p.locator(Surface.workMarkers[0]).count()) > 0;
1022
+ // The box by the chat's locator in force (2026-11-17: the work page's box changed, and Settings may name it).
1023
+ const hasWorkComposer = (await this.composer().count().catch(() => 0)) > 0;
703
1024
  return hasWorkComposer ? 'work' : 'unknown';
704
1025
  }
705
1026
  /**
@@ -776,14 +1097,11 @@ Current URL: ${url}`);
776
1097
  'sign-in': 'The profile is signed out. Run "cop login".',
777
1098
  unknown: 'The page is not the Microsoft 365 Copilot chat.',
778
1099
  };
779
- let picture = '';
780
1100
  if (where === 'unknown') {
781
- const dir = join(this.opts.transportDir, '..', 'failures');
782
- const tag = `not-the-chat-${Date.now()}`;
783
- await this.dumpFailure(dir, tag).catch(() => undefined);
784
- picture = ` A picture of the page: ${join(dir, `${tag}.png`)}`;
1101
+ throw await this.locatorMissing('composer', `on ${whereIs(url)}`, { message: (files) => `${explain.unknown} ${files} ${this.composerHint()}
1102
+ Current URL: ${url}` });
785
1103
  }
786
- throw new Error(`${explain[where] ?? explain.unknown}${picture}
1104
+ throw new Error(`${explain[where] ?? explain.unknown}
787
1105
  Current URL: ${url}`);
788
1106
  }
789
1107
  /**
@@ -877,6 +1195,9 @@ Current URL: ${url}`);
877
1195
  * types credentials; it only waits for the composer to appear.
878
1196
  */
879
1197
  async ensureSignedIn(url = this.opts.chatUrl, opts = {}) {
1198
+ // A box locator saved in Settings that cannot be used: said once, before the box is looked for with the default.
1199
+ for (const problem of this.chatLocatorProblems.splice(0))
1200
+ this.emit('chat-locator-not-used', { problem });
880
1201
  // Copilot's home page, where no conversation is expected until the run enters one.
881
1202
  this.onChat = null;
882
1203
  await this.p.goto(url, { waitUntil: 'domcontentloaded' });
@@ -908,6 +1229,7 @@ Current URL: ${url}`);
908
1229
  throw await this.notTheChat();
909
1230
  }
910
1231
  await this.assertWorkSurface();
1232
+ await this.runSteps('open', opts.signal);
911
1233
  }
912
1234
  async newChat() {
913
1235
  this.onChat = null;
@@ -915,9 +1237,16 @@ Current URL: ${url}`);
915
1237
  // Another of Copilot's pages instead (2026-11-17): the chat opened from it, and said so when it would not.
916
1238
  if ((await this.arrive(Url.newChatPath, undefined, '')) === 'elsewhere')
917
1239
  throw await this.notTheChat();
918
- // A chat slow to load: the rest of the minute it was always given (the page's default timeout).
919
- await this.composer().waitFor({ state: 'visible', timeout: 45_000 });
1240
+ // A chat slow to load: the rest of the minute it was always given (the page's default timeout); none by then, said.
1241
+ await this.composer()
1242
+ .waitFor({ state: 'visible', timeout: 45_000 })
1243
+ .catch(async (e) => {
1244
+ if (e.name !== 'TimeoutError')
1245
+ throw e;
1246
+ throw await this.locatorMissing('composer', 'on a new chat, within a minute');
1247
+ });
920
1248
  await this.dismissPopups();
1249
+ await this.runSteps('open');
921
1250
  this.onChat = 'new';
922
1251
  }
923
1252
  /** Reopens a conversation by its id. Returns false when it no longer opens. */
@@ -929,13 +1258,15 @@ Current URL: ${url}`);
929
1258
  if (at === 'elsewhere' || (at === 'no-box' && !(await this.isChatReady(5_000))))
930
1259
  return false;
931
1260
  const there = parseChatId(this.p.url()) === chatId;
932
- if (there)
1261
+ if (there) {
933
1262
  this.onChat = { id: chatId };
1263
+ await this.runSteps('open');
1264
+ }
934
1265
  return there;
935
1266
  }
936
1267
  /** Finds a conversation by its exact name in the sidebar. */
937
1268
  async openConversationByName(name) {
938
- const row = this.p.locator(`${Sidebar.conversationLink}[aria-label="${name.replace(/"/g, '\\"')}"]`);
1269
+ const row = this.el('conversationLink').and(this.p.locator(`[aria-label="${name.replace(/"/g, '\\"')}"]`));
939
1270
  if ((await row.count()) === 0)
940
1271
  return false;
941
1272
  // The conversation it is, from the link's own address: the page's follows a moment after the click.
@@ -949,6 +1280,7 @@ Current URL: ${url}`);
949
1280
  this.onChat = { id };
950
1281
  this.chatNames.set(id, name);
951
1282
  }
1283
+ await this.runSteps('open');
952
1284
  return true;
953
1285
  }
954
1286
  async currentChatId() {
@@ -1010,6 +1342,7 @@ Current URL: ${url}`);
1010
1342
  break;
1011
1343
  this.onChat = want;
1012
1344
  await this.dismissPopups().catch(() => undefined);
1345
+ await this.runSteps('open', opts.signal);
1013
1346
  this.emit('chat-returned', { chatId: want.id, by: 'address', signedIn, from });
1014
1347
  return { at: 'returned', chatId: want.id, from, by: 'address', signedIn };
1015
1348
  }
@@ -1051,6 +1384,9 @@ Current URL: ${url}`);
1051
1384
  * something else entirely.
1052
1385
  */
1053
1386
  async dismissPopups() {
1387
+ // Switched off in Settings → "Steps to the chat" (2026-11-17).
1388
+ if (!this.builtIn.popups)
1389
+ return;
1054
1390
  for (const name of ['Got it', 'Close', 'Dismiss', 'No thanks', 'Skip', 'Set later', 'Not now', 'Maybe later', 'Reject All', 'Reject all']) {
1055
1391
  const b = this.p.getByRole('button', { name, exact: true });
1056
1392
  if ((await b.count()) > 0 && (await b.first().isVisible().catch(() => false))) {
@@ -1068,7 +1404,14 @@ Current URL: ${url}`);
1068
1404
  * of it when Copilot's dialog refused that one (see `chatNameForms`) — or false when it could not be renamed.
1069
1405
  */
1070
1406
  async nameChat(chatId, name, opts = {}) {
1071
- const row = this.p.locator(`${Sidebar.conversationLink}[href*="${chatId}"]`).first();
1407
+ // Switched off in Settings → "Steps to the chat" (2026-11-17): the conversation keeps Copilot's own title.
1408
+ if (!this.builtIn.nameChat) {
1409
+ if (!this.nameOffSaid)
1410
+ this.emit('chat-name-off', { chatId, name });
1411
+ this.nameOffSaid = true;
1412
+ return false;
1413
+ }
1414
+ const row = this.el('conversationLink').and(this.p.locator(`[href*="${chatId}"]`)).first();
1072
1415
  // Waited for, like everything below: a new chat's row appears in the sidebar some seconds after the
1073
1416
  // reply, and `count()` read it as missing and returned without a word (live run 2026-10-03). The run
1074
1417
  // tries again later when it is still not there (see `nameIfStillUnnamed` in taskRunner.ts).
@@ -1078,6 +1421,8 @@ Current URL: ${url}`);
1078
1421
  }
1079
1422
  catch {
1080
1423
  this.emit('chat-name-failed', { chatId, name, error: `the conversation did not appear in the sidebar within ${Math.round(waitMs / 1000)} s` });
1424
+ // Not one conversation in the sidebar by its locator: the locator's, said; this one not there yet is not.
1425
+ await this.warnLocator('conversationLink', 'in the sidebar, while the conversation was to be named').catch(() => undefined);
1081
1426
  return false;
1082
1427
  }
1083
1428
  /*
@@ -1090,6 +1435,8 @@ Current URL: ${url}`);
1090
1435
  * own auto-generated titles instead of the name this runner gave them.
1091
1436
  */
1092
1437
  let opened = false;
1438
+ // Which locator the step under way looks for: the one said when it finds nothing.
1439
+ let step = 'chatMore';
1093
1440
  try {
1094
1441
  await row.scrollIntoViewIfNeeded().catch(() => undefined);
1095
1442
  // Briefly: a hover the sidebar takes waits out the page's whole timeout otherwise.
@@ -1100,20 +1447,24 @@ Current URL: ${url}`);
1100
1447
  * section header — and Playwright retried for the whole minute (live 2026-10-05), so `press` clicks
1101
1448
  * the element itself when the mouse cannot reach it.
1102
1449
  */
1103
- const byChat = this.p.locator(Rename.moreButtonForChat(chatId)).first();
1104
- const more = (await byChat.count()) > 0
1450
+ const byChat = this.el('chatMore', chatId).first();
1451
+ // Through the row by its name only while the locator is the default: one set in Settings is the one used.
1452
+ const more = (await byChat.count()) > 0 || this.chatLocators.chatMore !== DefaultChatLocators.chatMore
1105
1453
  ? byChat
1106
1454
  : row.locator('xpath=ancestor-or-self::*[self::li or self::div][1]').getByRole('button', { name: Rename.moreButtonLabel, exact: true }).first();
1107
1455
  await more.waitFor({ state: 'attached', timeout: 5_000 });
1108
1456
  await this.press(more);
1109
1457
  opened = true;
1110
- const item = this.p.getByRole('menuitem', { name: Rename.menuItem, exact: true }).first();
1458
+ step = 'renameItem';
1459
+ const item = this.el('renameItem').first();
1111
1460
  await item.waitFor({ state: 'visible', timeout: 5_000 });
1112
1461
  await this.press(item);
1113
1462
  opened = false;
1114
- const input = this.p.locator(Rename.input);
1463
+ step = 'renameInput';
1464
+ const input = this.el('renameInput').first();
1115
1465
  await input.waitFor({ state: 'visible', timeout: 10_000 });
1116
- const save = this.p.getByRole('button', { name: Rename.saveText, exact: true }).first();
1466
+ step = 'renameSave';
1467
+ const save = this.el('renameSave').first();
1117
1468
  /*
1118
1469
  * Offered in shorter forms until the dialog takes one. Copilot refuses a name it counts as longer than 50
1119
1470
  * characters, by a count that is not always ours, and its dialog then stays open over the chat (2026-10-17: "the
@@ -1155,6 +1506,8 @@ Current URL: ${url}`);
1155
1506
  }
1156
1507
  catch (e) {
1157
1508
  this.emit('chat-name-failed', { chatId, name, error: e.message });
1509
+ // The step's locator, when it finds nothing: said (the name is the work's convenience; the work goes on).
1510
+ await this.warnLocator(step, `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
1158
1511
  return false;
1159
1512
  }
1160
1513
  finally {
@@ -1651,7 +2004,7 @@ Current URL: ${url}`);
1651
2004
  let shot = 0;
1652
2005
  /** With `modelStepShots`, a picture and the menu's HTML at each step, numbered, beside the transport's files. */
1653
2006
  const picture = async (label) => {
1654
- if (!this.opts.modelStepShots)
2007
+ if (!this.stepShots)
1655
2008
  return;
1656
2009
  shot += 1;
1657
2010
  await this.captureMenu(`step-${String(shot).padStart(2, '0')}-${label.replace(/[^A-Za-z0-9._-]+/g, '-').slice(0, 40)}`, await this.readMenuRows().catch(() => [])).catch(() => undefined);
@@ -2097,8 +2450,8 @@ Current URL: ${url}`);
2097
2450
  * counted, with the rendered count as the fallback for a page that does not carry it.
2098
2451
  */
2099
2452
  async turnCount() {
2100
- return await this.p.evaluate((turnSel) => {
2101
- const nodes = Array.from(document.querySelectorAll(turnSel));
2453
+ // By the `turn` locator in force (2026-11-17), whatever its kind: CSS, XPath or Playwright's own.
2454
+ return await this.el('turn').evaluateAll((nodes) => {
2102
2455
  let size = 0;
2103
2456
  for (const n of nodes) {
2104
2457
  const carrier = n.matches('[aria-setsize]') ? n : (n.querySelector('[aria-setsize]') ?? n.closest('[aria-setsize]'));
@@ -2107,17 +2460,13 @@ Current URL: ${url}`);
2107
2460
  size = v;
2108
2461
  }
2109
2462
  return size > 0 ? size : nodes.length;
2110
- }, `[data-testid="${TestId.turn}"]`);
2463
+ });
2111
2464
  }
2112
2465
  /** The newest user message as shown, for telling "landed but not counted" from "not sent". */
2113
2466
  async lastUserTurnText() {
2114
- return await this.p
2115
- .evaluate(() => {
2116
- const nodes = document.querySelectorAll('[id^="user-message-"]');
2117
- const last = nodes[nodes.length - 1];
2118
- return last ? last.innerText : '';
2119
- })
2120
- .catch(() => '');
2467
+ const all = this.el('userMessage');
2468
+ const n = await all.count().catch(() => 0);
2469
+ return n > 0 ? ((await all.nth(n - 1).innerText({ timeout: 2_000 }).catch(() => '')) ?? '') : '';
2121
2470
  }
2122
2471
  /** Puts text in the composer and clicks Send. Enter is not used: it does not submit. */
2123
2472
  async send(text, attachments = []) {
@@ -2125,13 +2474,21 @@ Current URL: ${url}`);
2125
2474
  throw new Error('Refusing to send an empty message: the composer requires text.');
2126
2475
  }
2127
2476
  await this.clearBlockers();
2477
+ await this.runSteps('message');
2128
2478
  if (attachments.length > 0)
2129
2479
  await this.attach(attachments);
2130
2480
  const composer = this.composer();
2481
+ // The box, before it is clicked: none, its locator is said, rather than a minute's wait on the click.
2482
+ if (!(await this.composerWithin(10_000, undefined, '')))
2483
+ throw await this.locatorMissing('composer', 'when a message was to be written in it');
2131
2484
  await composer.click();
2132
2485
  await composer.fill(text);
2133
2486
  const send = await this.sendButton();
2134
- await send.waitFor({ state: 'visible', timeout: 20_000 });
2487
+ await send.waitFor({ state: 'visible', timeout: this.sendWaitMs }).catch(async (e) => {
2488
+ if (e.name !== 'TimeoutError')
2489
+ throw e;
2490
+ throw await this.locatorMissing('send', `after the message was written in the box, within ${Math.round(this.sendWaitMs / 1000)} s`);
2491
+ });
2135
2492
  await send.click();
2136
2493
  this.emit('message-sent', { chars: text.length, attachments: attachments.length });
2137
2494
  }
@@ -2145,9 +2502,9 @@ Current URL: ${url}`);
2145
2502
  * change here is the attribute name rather than the button.
2146
2503
  */
2147
2504
  async sendButton() {
2148
- const wrapper = this.p.locator(Css.composerWrapper);
2149
- if ((await wrapper.count()) > 0) {
2150
- return wrapper.first().getByRole('button', { name: Label.send, exact: true }).first();
2505
+ // Settings' own; or the default — the Send in the box's wrapper — wherever the wrapper is on the page.
2506
+ if (this.chatLocators.send !== DefaultChatLocators.send || (await this.p.locator(Css.composerWrapper).count()) > 0) {
2507
+ return this.el('send').first();
2151
2508
  }
2152
2509
  const submit = this.p.locator(Css.composerSendSubmit);
2153
2510
  if ((await submit.count()) > 0) {
@@ -2168,6 +2525,8 @@ Current URL: ${url}`);
2168
2525
  * scoped now, so the panel being open is untidy rather than fatal.
2169
2526
  */
2170
2527
  async dismissFeedbackPanel() {
2528
+ if (!this.builtIn.feedbackPanel)
2529
+ return;
2171
2530
  const panel = this.p.locator(Css.feedbackPanel);
2172
2531
  if ((await panel.count()) === 0)
2173
2532
  return;
@@ -2206,12 +2565,22 @@ Current URL: ${url}`);
2206
2565
  this.retryBaselineTurns = before;
2207
2566
  }
2208
2567
  await this.send(text, attachments);
2209
- const accepted = await this.waitForAccepted(before, 30_000, text, shownBefore);
2568
+ const accepted = await this.waitForAccepted(before, this.acceptMs, text, shownBefore);
2210
2569
  if (accepted)
2211
2570
  return before;
2212
2571
  const found = await this.detectBlocker();
2213
2572
  lastProblem = found.kind === 'none' ? 'the message did not appear in the chat' : `${found.kind}: ${found.reason}`;
2214
2573
  this.emit('send-not-accepted', { attempt, problem: lastProblem });
2574
+ /*
2575
+ * Sent — the box is empty — and neither a message of the conversation nor the one sent is found: the locators, not
2576
+ * the chat (2026-11-17). Said, and not sent again: a message that did land would be in the chat twice.
2577
+ */
2578
+ if (found.kind === 'none' &&
2579
+ (await this.boxIsEmpty()) &&
2580
+ (await this.el('turn').count().catch(() => 0)) === 0 &&
2581
+ (await this.el('userMessage').count().catch(() => 0)) === 0) {
2582
+ throw await this.locatorMissing('turn', "after a message was sent: the box emptied, and neither the conversation's messages nor the message sent were found (the userMessage locator found nothing either)");
2583
+ }
2215
2584
  if (found.kind !== 'none') {
2216
2585
  const cleared = await this.handleBlocker(found);
2217
2586
  if (!cleared) {
@@ -2256,20 +2625,70 @@ Current URL: ${url}`);
2256
2625
  * prefix, which is the signal that the upload actually finished.
2257
2626
  */
2258
2627
  async attach(paths) {
2259
- await this.p.setInputFiles(Upload.input, paths);
2628
+ /*
2629
+ * By the chat's locators in force (2026-11-17: the work page showed the attached file as a card of its own, and the
2630
+ * old `div.fx-Attachment[aria-label=<name>]`, written in the code, waited two minutes and ended the message with
2631
+ * Playwright's own words). Each can be set in Settings → "The chat's locators" → "Attaching a file"; one that finds
2632
+ * nothing is said by its name, with the page's HTML, like the others.
2633
+ */
2634
+ const input = this.el('uploadInput').first();
2635
+ const there = await input.waitFor({ state: 'attached', timeout: this.inputWaitMs }).then(() => true, () => false);
2636
+ if (!there)
2637
+ throw await this.locatorMissing('uploadInput', 'when a file was to be attached to the message');
2638
+ await input.setInputFiles(paths);
2260
2639
  for (const path of paths) {
2261
2640
  const name = path.split(/[\\/]/).pop();
2262
- const chip = this.p.locator(`${Upload.chip}[aria-label="${name.replace(/"/g, '\\"')}"]`);
2263
- await chip.first().waitFor({ state: 'visible', timeout: 120_000 });
2264
- await this.p
2265
- .waitForFunction(({ sel, prefix }) => {
2266
- const el = document.querySelector(sel);
2267
- return !!el && (el.id || '').startsWith(prefix);
2268
- }, { sel: `${Upload.chip}[aria-label="${name.replace(/"/g, '\\"')}"]`, prefix: Upload.uploadedIdPrefix }, { timeout: 120_000 })
2269
- .catch(() => this.emit('attachment-upload-unconfirmed', { name }));
2641
+ const shown = await this.fileEl('attachment', path)
2642
+ .filter({ visible: true })
2643
+ .first()
2644
+ .waitFor({ state: 'visible', timeout: this.attachWaitMs })
2645
+ .then(() => true, (e) => {
2646
+ if (e.name !== 'TimeoutError')
2647
+ throw e;
2648
+ return false;
2649
+ });
2650
+ if (!shown) {
2651
+ throw await this.locatorMissing('attachment', `after the file ${name} was put in the box's file input, within ${Math.round(this.attachWaitMs / 1000)} s`);
2652
+ }
2653
+ // Uploaded: the locator finds it, and goes on finding it for a moment (a spinner can come a little after the card).
2654
+ const uploaded = await this.holds(async () => (await this.fileEl('attachmentUploaded', path).count().catch(() => 0)) > 0, this.uploadWaitMs, 2_000);
2655
+ if (!uploaded) {
2656
+ // As before: the message goes on (Send waits while it cannot be pressed); what found nothing is said once a window.
2657
+ this.emit('attachment-upload-unconfirmed', { name });
2658
+ if (!this.warned.has('attachmentUploaded')) {
2659
+ this.warned.add('attachmentUploaded');
2660
+ await this.locatorMissing('attachmentUploaded', `for ${Math.round(this.uploadWaitMs / 1000)} s after the file ${name} was attached`, { stopped: false }).catch(() => undefined);
2661
+ }
2662
+ }
2270
2663
  this.emit('attached', { name });
2271
2664
  }
2272
2665
  }
2666
+ /** How long an attached file may take to show in the box, and to finish uploading (fields, for the checks). */
2667
+ inputWaitMs = 10_000;
2668
+ attachWaitMs = 30_000;
2669
+ uploadWaitMs = 120_000;
2670
+ /** An attached file's locator in force, with the file's name put in its place (see `fillFileLocator`). */
2671
+ fileEl(key, file) {
2672
+ return this.p.locator(playwrightSelector(fillFileLocator(this.chatLocators[key], file)));
2673
+ }
2674
+ /** Whether `test` comes true within `ms` and stays true for `steadyMs`, looked at every half second. */
2675
+ async holds(test, ms, steadyMs) {
2676
+ const until = Date.now() + ms;
2677
+ let since = null;
2678
+ while (Date.now() < until) {
2679
+ if (this.p.isClosed())
2680
+ return false;
2681
+ if (await test()) {
2682
+ since ??= Date.now();
2683
+ if (Date.now() - since >= steadyMs)
2684
+ return true;
2685
+ }
2686
+ else
2687
+ since = null;
2688
+ await this.p.waitForTimeout(500);
2689
+ }
2690
+ return false;
2691
+ }
2273
2692
  /**
2274
2693
  * Waits for the answer to finish streaming, then returns its raw markdown.
2275
2694
  *
@@ -2285,29 +2704,25 @@ Current URL: ${url}`);
2285
2704
  async waitForReply(previousTurns) {
2286
2705
  const startedAt = Date.now();
2287
2706
  const deadline = startedAt + this.opts.replyTimeoutMs;
2288
- const state = async () => await this.p.evaluate(({ turnSel, stopLabel, wrapperSel, copySel }) => {
2289
- // The conversation's size as the app reports it, not the rendered count: see turnCount.
2290
- const nodes = Array.from(document.querySelectorAll(turnSel));
2291
- let size = 0;
2292
- for (const n of nodes) {
2293
- const carrier = n.matches('[aria-setsize]') ? n : (n.querySelector('[aria-setsize]') ?? n.closest('[aria-setsize]'));
2294
- const v = carrier ? Number(carrier.getAttribute('aria-setsize')) : NaN;
2295
- if (!Number.isNaN(v) && v > size)
2296
- size = v;
2297
- }
2298
- const turns = size > 0 ? size : nodes.length;
2299
- const streaming = Array.from(document.querySelectorAll('button')).some((b) => b.getAttribute('aria-label') === stopLabel);
2300
- const wrappers = document.querySelectorAll(wrapperSel);
2301
- const last = wrappers[wrappers.length - 1];
2302
- return { turns, streaming, finished: !streaming && !!last && !!last.querySelector(copySel) };
2303
- }, {
2304
- turnSel: `[data-testid="${TestId.turn}"]`,
2305
- stopLabel: Label.stopGenerating,
2306
- wrapperSel: Signal.answerWrapper,
2307
- copySel: Signal.copyButtonInAnswer,
2308
- });
2707
+ /*
2708
+ * Through the chat's locators in force (2026-11-17: each can be set in Settings): the conversation's size as the app
2709
+ * reports it (see turnCount), whether Copilot is still writing, and whether its newest answer is finished — its Copy
2710
+ * button there — with how long that answer's text is, to tell one standing still.
2711
+ */
2712
+ const state = async () => {
2713
+ const turns = await this.turnCount();
2714
+ const streaming = (await this.el('stop').count()) > 0;
2715
+ const answers = this.el('answer');
2716
+ const n = await answers.count();
2717
+ const newest = n > 0 ? answers.nth(n - 1) : null;
2718
+ const chars = newest ? await newest.evaluate((el) => (el.textContent ?? '').length).catch(() => 0) : 0;
2719
+ const finished = !streaming && !!newest && (await newest.locator(this.sel('copy')).count()) > 0;
2720
+ return { turns, streaming, finished, answers: n, chars };
2721
+ };
2309
2722
  let sawNewTurn = false;
2310
- let last = { turns: previousTurns, streaming: false, finished: false };
2723
+ let last = { turns: previousTurns, streaming: false, finished: false, answers: 0, chars: 0 };
2724
+ // Since when Copilot's newest answer has stood still, not written and not finished (see below).
2725
+ let still = { since: Date.now(), chars: -1, answers: -1 };
2311
2726
  while (Date.now() < deadline) {
2312
2727
  if (this.p.isClosed()) {
2313
2728
  throw new Error('The browser window was closed while waiting for a reply. If you did not close it, ' +
@@ -2331,6 +2746,29 @@ Current URL: ${url}`);
2331
2746
  sawNewTurn = true;
2332
2747
  if (sawNewTurn && last.finished)
2333
2748
  break;
2749
+ /*
2750
+ * What a locator that no longer finds its element looks like (2026-11-17), said rather than waiting out the whole
2751
+ * reply time: not one message of the conversation found, though the message sent is in it; or Copilot's answer
2752
+ * begun, then standing still — not written any more, never finished — with no answer found at all, or no Copy
2753
+ * button anywhere on the page. A Copy missing from the newest answer alone is Copilot's, not the locator's.
2754
+ */
2755
+ if (last.turns === 0 && Date.now() - startedAt >= this.turnsGraceMs) {
2756
+ throw await this.locatorMissing('turn', 'while the answer was awaited: not one message of the conversation was found, though the message sent is in it');
2757
+ }
2758
+ if (sawNewTurn && !last.streaming) {
2759
+ if (last.chars !== still.chars || last.answers !== still.answers)
2760
+ still = { since: Date.now(), chars: last.chars, answers: last.answers };
2761
+ else if (Date.now() - still.since >= this.answerStillMs) {
2762
+ if (last.answers === 0) {
2763
+ throw await this.locatorMissing('answer', `while the answer was awaited: Copilot's turn began and, ${Math.round((Date.now() - startedAt) / 1000)} s on, no answer was found`);
2764
+ }
2765
+ if ((await this.el('copy').count().catch(() => 1)) === 0) {
2766
+ throw await this.locatorMissing('copy', `in Copilot's answers: the newest had not changed for ${Math.round(this.answerStillMs / 1000)} s, was not being written, and no answer had a Copy button`);
2767
+ }
2768
+ }
2769
+ }
2770
+ else
2771
+ still = { since: Date.now(), chars: -1, answers: -1 };
2334
2772
  // Only look for blockers while nothing is streaming, so the check stays cheap.
2335
2773
  if (!last.streaming) {
2336
2774
  const blocker = await this.detectBlocker();
@@ -2393,7 +2831,7 @@ Current URL: ${url}`);
2393
2831
  * all reachable from one locator.
2394
2832
  */
2395
2833
  lastAnswer() {
2396
- return this.p.getByTestId(TestId.assistantMessage).last();
2834
+ return this.el('answer').last();
2397
2835
  }
2398
2836
  async lastMessageText() {
2399
2837
  return (await this.lastAnswer().innerText().catch(() => '')) ?? '';
@@ -2428,7 +2866,7 @@ Current URL: ${url}`);
2428
2866
  * as degraded, because that text is known to be lossy.
2429
2867
  */
2430
2868
  async copyLastReply() {
2431
- const copy = this.lastAnswer().getByTestId(TestId.copyResponse).first();
2869
+ const copy = this.lastAnswer().locator(this.sel('copy')).first();
2432
2870
  try {
2433
2871
  /*
2434
2872
  * Two guards around one click, both about the neighbours.