copilot-operator 0.1.85 → 0.1.90

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 (58) hide show
  1. package/dist/src/api/operator.controller.js +89 -3
  2. package/dist/src/api/operator.service.js +200 -2
  3. package/dist/src/api/server.js +5 -1
  4. package/dist/src/cli.js +6 -0
  5. package/dist/src/config/live.js +1 -1
  6. package/dist/src/config/schema.js +27 -0
  7. package/dist/src/orchestrator/kerriganRunner.js +3 -1
  8. package/dist/src/orchestrator/leadRunner.js +3 -1
  9. package/dist/src/orchestrator/taskRunner.js +64 -32
  10. package/dist/src/plan/systemGuide.js +193 -4
  11. package/dist/src/session/compose.js +5 -1
  12. package/dist/src/session/locatorFailures.js +55 -0
  13. package/dist/src/transport/chatTransport.js +6 -2
  14. package/dist/src/transport/copilotTransport.js +519 -59
  15. package/dist/src/transport/keptWindow.js +250 -0
  16. package/dist/src/transport/locators.js +140 -9
  17. package/dist/src/transport/pageHtml.js +62 -0
  18. package/dist/web/404.html +2 -2
  19. package/dist/web/_next/static/chunks/1077.1cc6d439e3dd0fa9.js +1 -0
  20. package/dist/web/_next/static/chunks/1548.3de9dc874e47558e.js +1 -0
  21. package/dist/web/_next/static/chunks/2163.66458fb9c54fb52d.js +1 -0
  22. package/dist/web/_next/static/chunks/714.cffed2b87154be0f.js +1 -0
  23. package/dist/web/_next/static/chunks/7220.30b6a3e1bd41e51a.js +1 -0
  24. package/dist/web/_next/static/chunks/7921-d3a4a261e08950e0.js +1 -0
  25. package/dist/web/_next/static/chunks/8584.36422ed19d6c43e9.js +1 -0
  26. package/dist/web/_next/static/chunks/9067.e579f97591576de2.js +1 -0
  27. package/dist/web/_next/static/chunks/9747.11247f0e21542f6d.js +1 -0
  28. package/dist/web/_next/static/chunks/app/layout-7b5fa7c74ecd6939.js +1 -0
  29. package/dist/web/_next/static/chunks/app/page-b71841852e6b9ff5.js +1 -0
  30. package/dist/web/_next/static/chunks/app/queue/{page-317151444eda8115.js → page-7909ba7c9e3d4c2d.js} +1 -1
  31. package/dist/web/_next/static/chunks/app/settings/page-7651920337bbb580.js +1 -0
  32. package/dist/web/_next/static/chunks/{webpack-13ccb80d7b7094ca.js → webpack-78ec62098b09e4a0.js} +1 -1
  33. package/dist/web/_next/static/css/{6e2b8656501f0dd7.css → d74aa18c98dacdb4.css} +1 -1
  34. package/dist/web/defaults.html +2 -2
  35. package/dist/web/defaults.txt +8 -8
  36. package/dist/web/index.html +3 -3
  37. package/dist/web/index.txt +9 -9
  38. package/dist/web/queue.html +2 -2
  39. package/dist/web/queue.txt +9 -9
  40. package/dist/web/settings.html +2 -2
  41. package/dist/web/settings.txt +9 -9
  42. package/dist/web/system.html +2 -2
  43. package/dist/web/system.txt +9 -9
  44. package/package.json +4 -2
  45. package/dist/web/_next/static/chunks/1077.06fe73b2c16f8f49.js +0 -1
  46. package/dist/web/_next/static/chunks/1548.b38c5d8d00ab2a72.js +0 -1
  47. package/dist/web/_next/static/chunks/2163.ba933c9a506302ca.js +0 -1
  48. package/dist/web/_next/static/chunks/714.575273a189d030fe.js +0 -1
  49. package/dist/web/_next/static/chunks/7220.988dfd28e00f407c.js +0 -1
  50. package/dist/web/_next/static/chunks/7921-65dd56d87144bd44.js +0 -1
  51. package/dist/web/_next/static/chunks/8584.2221587201bc2fa2.js +0 -1
  52. package/dist/web/_next/static/chunks/9067.8d94a08830c3d1da.js +0 -1
  53. package/dist/web/_next/static/chunks/9747.8671194406acd839.js +0 -1
  54. package/dist/web/_next/static/chunks/app/layout-127e5af1ebf21876.js +0 -1
  55. package/dist/web/_next/static/chunks/app/page-76139370c7ca3715.js +0 -1
  56. package/dist/web/_next/static/chunks/app/settings/page-116da78c83f0c5c9.js +0 -1
  57. /package/dist/web/_next/static/{aCQe1FDhYTj4zGeI5ueVq → 3VkK1sxEugkae88HSFR-i}/_buildManifest.js +0 -0
  58. /package/dist/web/_next/static/{aCQe1FDhYTj4zGeI5ueVq → 3VkK1sxEugkae88HSFR-i}/_ssgManifest.js +0 -0
@@ -16,9 +16,10 @@ 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, fillLocator, Label, Model, ModelPicking, pageQuery, playwrightSelector, Rename, resolveChatLocators, resolvePickerLocators, Signal, Surface, Upload, 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';
22
23
  /**
23
24
  * The chat did not finish a reply within `copilot.replyTimeoutSec`.
24
25
  *
@@ -38,7 +39,6 @@ export class ReplyTimeoutError extends Error {
38
39
  export function isReplyTimeout(e) {
39
40
  return e instanceof ReplyTimeoutError || (e instanceof Error && e.name === 'ReplyTimeoutError' && typeof e.seconds === 'number');
40
41
  }
41
- const ORIGIN = 'https://m365.cloud.microsoft';
42
42
  /**
43
43
  * Which Copilot an address is, by its host — not by whether the text appears anywhere in it: the
44
44
  * consumer Copilot and a sign-in page carry the work chat's address in their query (`ru=`,
@@ -62,6 +62,21 @@ export function surfaceOfUrl(url) {
62
62
  return 'work';
63
63
  return 'unknown';
64
64
  }
65
+ /** Whether an address is the work Copilot's chat — a new chat, a conversation, the list of chats — on either of its hosts. */
66
+ export function isWorkChatAddress(url) {
67
+ if (surfaceOfUrl(url) !== 'work')
68
+ return false;
69
+ const path = new URL(url).pathname.replace(/\/+$/, '');
70
+ return path === '/chat' || path.startsWith('/chat/');
71
+ }
72
+ /**
73
+ * Whether an address is another page of the work Copilot, not its chat: its home page
74
+ * (`copilot.cloud.microsoft/home?es=SSR&redirfrom=mcmToCcm`, where the work machine's start ended on 2026-11-17), or any
75
+ * other of its own. Signed in, then — a sign-in page is on Microsoft's sign-in host — and only away from the chat.
76
+ */
77
+ export function isCopilotOtherPage(url) {
78
+ return surfaceOfUrl(url) === 'work' && !isWorkChatAddress(url);
79
+ }
65
80
  /**
66
81
  * The operator's locators for a model, from the templates in force and where the list read from the page found it
67
82
  * (operator, 2026-10-24): a model of the main menu by the template for those; one in a provider's menu by the
@@ -140,6 +155,13 @@ export class WindowClosed extends Error {
140
155
  this.name = 'WindowClosed';
141
156
  }
142
157
  }
158
+ /** Said when a window closed under the work cannot be put back on its conversation: it had no address yet. */
159
+ export const NO_ADDRESS_YET = 'the browser window was closed before its conversation had an address, so it could not be found again; nothing more was sent';
160
+ /** How many times Edge is started again on the profile when a window is reopened, and the pause between (see `reopen`). */
161
+ const REOPEN_TRIES = 10;
162
+ const REOPEN_PAUSE_MS = 1_500;
163
+ /** How long the box is waited for on the work Copilot's host before the page is said not to be its chat. */
164
+ const SURFACE_WAIT_MS = 5_000;
143
165
  /**
144
166
  * The window had left the conversation the bot put it on, and could not be put back (operator, 2026-11-09; see
145
167
  * `ensureOnChat`): the conversation does not open again, or the sign-in the page asked for first was not done in time.
@@ -255,6 +277,26 @@ export const CLIPBOARD_GUARD = `(() => {
255
277
  };
256
278
  } catch (e) { /* as above */ }
257
279
  })();`;
280
+ /**
281
+ * A locator of the chat that found nothing where the bot needed it (operator, 2026-11-17: "a mechanism that detects
282
+ * which locator exactly the bot failed on, so we can easily see which locator has to be updated"): which one, as it
283
+ * was in force, and the page's HTML and picture kept for finding the right one. The runner says it like any other
284
+ * error; the transport has said it already (`locator-missing`), which the API keeps for Settings (`LocatorFailures`).
285
+ */
286
+ export class LocatorMissing extends Error {
287
+ key;
288
+ locator;
289
+ html;
290
+ picture;
291
+ constructor(key, locator, message, html, picture) {
292
+ super(message);
293
+ this.key = key;
294
+ this.locator = locator;
295
+ this.html = html;
296
+ this.picture = picture;
297
+ this.name = 'LocatorMissing';
298
+ }
299
+ }
258
300
  export class CopilotTransport {
259
301
  opts;
260
302
  context = null;
@@ -272,6 +314,10 @@ export class CopilotTransport {
272
314
  gone = false;
273
315
  /** The model menu's locators in force: Settings' own, else the defaults (see `resolvePickerLocators`). */
274
316
  locators;
317
+ /** The chat page's locators in force — the box to write in: Settings' own, else the default (see `resolveChatLocators`). */
318
+ chatLocators;
319
+ /** Why a chat locator saved in Settings is not used; said once, when the chat is first opened. */
320
+ chatLocatorProblems;
275
321
  /** Why a locator saved in Settings is not used; said once, at the first choice or reading of the models. */
276
322
  locatorProblems;
277
323
  /** Whether the rows' locator has been said not to work in the page (see `readMenuRows`). */
@@ -289,11 +335,35 @@ export class CopilotTransport {
289
335
  chatNames = new Map();
290
336
  /** How long a page is given to show the composer before it is taken to be asking for a sign-in. */
291
337
  firstLookMs = 15_000;
338
+ /**
339
+ * The host the chat was last found on, which the chat's addresses are opened on (2026-11-17): the address set in
340
+ * Settings when it is the work Copilot's, else the old host, until the chat is found on the new one. Going through
341
+ * the old host's redirect is what ended the work machine's start on Copilot's home page.
342
+ */
343
+ chatOrigin;
344
+ /** How long the box to write in must stay before the page is taken for the chat: one that showed on its way elsewhere is not. */
345
+ settleMs = 2_000;
346
+ /** How long another page of the work Copilot is given to turn into its chat on its own before the bot opens the chat. */
347
+ otherPageMs = 3_000;
348
+ /** How long the answer is waited for with not one message of the conversation found, before the `turn` locator is said. */
349
+ turnsGraceMs = 20_000;
350
+ /** How long Copilot's newest answer may stand still, not written and not finished, before its locator is said. */
351
+ answerStillMs = 60_000;
352
+ /** The locators said already in this window, where the work went on without them: said once. */
353
+ warned = new Set();
354
+ /** How long Send is waited for once the message is in the box. */
355
+ sendWaitMs = 20_000;
356
+ /** How long a message sent is waited for in the conversation before it is taken as not accepted. */
357
+ acceptMs = 30_000;
292
358
  constructor(opts) {
293
359
  this.opts = opts;
294
360
  const { locators, problems } = resolvePickerLocators(opts.pickerLocators);
295
361
  this.locators = locators;
362
+ const chat = resolveChatLocators(opts.chatLocators);
363
+ this.chatLocators = chat.locators;
364
+ this.chatLocatorProblems = chat.problems;
296
365
  this.locatorProblems = problems;
366
+ this.chatOrigin = surfaceOfUrl(opts.chatUrl) === 'work' ? new URL(opts.chatUrl).origin : Url.origin;
297
367
  }
298
368
  /** Says, once, which locators saved in Settings could not be used and why. */
299
369
  sayLocatorProblems() {
@@ -396,6 +466,41 @@ export class CopilotTransport {
396
466
  closedOutside() {
397
467
  return this.gone;
398
468
  }
469
+ /**
470
+ * The window again, after it was closed under the work (operator, 2026-11-13: "if I close the browser with the chat by
471
+ * accident, the bot should carry the task on from where it got to"). Edge is started again on the same profile, and
472
+ * the window put back on the conversation it was on: by its address, after a sign-in when the page asks for one, or by
473
+ * its name in the sidebar (see `ensureOnChat`). The Edge that was closed may still be on its way out and holding the
474
+ * profile, so the start is tried again for a while. A conversation that had no address yet — closed before its first
475
+ * answer — cannot be found again: `WindowClosed`, with the new window open on nothing. When and how often this is done
476
+ * is the runner's (`KeptWindow` in keptWindow.ts); this only does it.
477
+ */
478
+ async reopen(opts = {}) {
479
+ // What `close` leaves alone, kept: the conversation the window was on, and the names given to conversations.
480
+ const want = this.onChat;
481
+ await this.close();
482
+ for (let tries = 1;; tries += 1) {
483
+ try {
484
+ await this.open();
485
+ break;
486
+ }
487
+ catch (e) {
488
+ await this.close().catch(() => undefined);
489
+ const busy = /already running with this profile|already in use by copilot-operator/i.test(e.message);
490
+ if (!busy || tries >= REOPEN_TRIES || opts.signal?.aborted)
491
+ throw e;
492
+ await new Promise((r) => setTimeout(r, REOPEN_PAUSE_MS));
493
+ }
494
+ }
495
+ this.onChat = want;
496
+ if (!want || want === 'new')
497
+ throw new WindowClosed(NO_ADDRESS_YET);
498
+ await this.p.goto(this.chatAddress(Url.conversationPath(want.id)), { waitUntil: 'domcontentloaded' }).catch(() => undefined);
499
+ // On it, as nearly always: waited for until its box is there to write in. Elsewhere (a sign-in): `ensureOnChat`.
500
+ if (parseChatId(this.p.url()) === want.id)
501
+ await this.composerWithin(this.firstLookMs, opts.signal, 'stopped by the operator while the window was opened again');
502
+ return await this.ensureOnChat(opts);
503
+ }
399
504
  /**
400
505
  * A card over the chat's page with one button that takes it away (2026-10-19: "when the chat is done, let the
401
506
  * browser show a message — the task has finished — and an OK under it"). The window of the workbench's chat is
@@ -488,8 +593,163 @@ export class CopilotTransport {
488
593
  return false;
489
594
  }
490
595
  }
596
+ /**
597
+ * The box to write in, by the chat's locator in force (Settings' own, else the default; 2026-11-17). What it finds is
598
+ * taken if it can be written in, else the first box inside it that can: a locator copied from the page's inspector for
599
+ * an element around the box (the operator's of 2026-11-17 named the box's wrapper, `data-chat-input-pill`) finds it all
600
+ * the same.
601
+ */
491
602
  composer() {
492
- return this.p.locator(Css.composer).first();
603
+ return this.p
604
+ .locator(this.sel('composer'))
605
+ .first()
606
+ .locator("xpath=descendant-or-self::*[(@contenteditable and @contenteditable != 'false') or self::textarea]")
607
+ .first();
608
+ }
609
+ /** What the message says when the box is not found: its locator in force, and where Settings has it. */
610
+ composerHint() {
611
+ return (`If the picture shows the chat with its box to write in, the box's locator does not find it: ${this.chatLocators.composer} ` +
612
+ '(Settings → "The chat\'s locators" → "Box to write in").');
613
+ }
614
+ /** A chat locator in force, as Playwright takes it; `chatId` goes where a template has its place. */
615
+ sel(key, chatId) {
616
+ const s = this.chatLocators[key];
617
+ return playwrightSelector(chatId === undefined ? s : s.split(CHAT_ID).join(chatId));
618
+ }
619
+ /** What a chat locator in force finds in the page. */
620
+ el(key, chatId) {
621
+ return this.p.locator(this.sel(key, chatId));
622
+ }
623
+ /**
624
+ * A locator that found nothing where the bot needed it (2026-11-17): a picture of the page and its HTML for a chatbot
625
+ * to find the right one in (scripts, styles and the sidebar out — see `pageHtml.ts`), kept in the failures folder, and
626
+ * said (`locator-missing`, which the API keeps so Settings can show the field in red). The error to throw when the
627
+ * work cannot go on without it; `stopped: false` when it goes on (a conversation's name). `message` is given the
628
+ * sentence naming the files.
629
+ */
630
+ async locatorMissing(key, why, opts = {}) {
631
+ const stopped = opts.stopped ?? true;
632
+ const locator = this.chatLocators[key];
633
+ const open = !!this.page && !this.page.isClosed();
634
+ const dir = join(this.opts.transportDir, '..', 'failures');
635
+ const tag = `locator-${key}-${Date.now()}`;
636
+ let picture;
637
+ let html;
638
+ if (open) {
639
+ await mkdir(dir, { recursive: true }).catch(() => undefined);
640
+ const png = join(dir, `${tag}.png`);
641
+ if (await this.p.screenshot({ path: png, fullPage: true }).then(() => true, () => false))
642
+ picture = png;
643
+ const text = await this.p.evaluate(strippedPageHtml, ChatLocatorGroupOf[key] === 'conversations').catch(() => '');
644
+ const file = join(dir, `${tag}.html`);
645
+ if (text && (await writeFile(file, text, 'utf8').then(() => true, () => false)))
646
+ html = file;
647
+ }
648
+ const url = open ? whereIs(this.p.url()) : undefined;
649
+ this.emit('locator-missing', { key, locator, why, stopped, ...(html ? { html } : {}), ...(picture ? { picture } : {}), ...(url ? { url } : {}) });
650
+ 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(' ');
651
+ const message = opts.message?.(files) ??
652
+ `Not found on Copilot's page: ${ChatLocatorWhat[key]}. The "${key}" locator found nothing ${why}. In force: ${locator} ` +
653
+ `(Settings → "The chat's locators"). ${files}`.trim();
654
+ return new LocatorMissing(key, locator, message, html, picture);
655
+ }
656
+ /** A locator that found nothing where the work goes on without it (a conversation's name): said once a window. */
657
+ async warnLocator(key, why, chatId) {
658
+ if (this.warned.has(key) || !this.page || this.page.isClosed())
659
+ return;
660
+ if ((await this.el(key, chatId).count().catch(() => 1)) > 0)
661
+ return;
662
+ this.warned.add(key);
663
+ await this.locatorMissing(key, why, { stopped: false, ...(chatId ? { chatId } : {}) });
664
+ }
665
+ /**
666
+ * Looks for each of the chat's locators in force in the page (operator, 2026-11-17: "make the 'Check the locators'
667
+ * button too"), and says for each what it found. Only reads and looks:
668
+ * - the chat as it was opened: its box, and its Send (one letter typed and taken out again, if Send shows only with
669
+ * text; nothing is sent);
670
+ * - the sidebar;
671
+ * - the newest conversation in it, opened by its address: its messages, its answers, their Copy;
672
+ * - its "More" button, whose menu is opened and closed again with Escape, for "Rename".
673
+ * The rename dialog is not opened, and Stop shows only while Copilot writes: those are said as not on the page then.
674
+ * One that finds nothing is said as a failure the work went on without (`locator-missing`, its HTML kept), so its
675
+ * field goes red in Settings.
676
+ */
677
+ async checkLocators() {
678
+ const out = new Map();
679
+ const why = 'when the locators were checked ("Check the locators" in Settings)';
680
+ const count = async (key, chatId) => await this.el(key, chatId).count().catch(() => 0);
681
+ const record = async (key, n, chatId, note) => {
682
+ out.set(key, { key, status: n > 0 ? 'found' : 'none', count: n, ...(note ? { note } : {}) });
683
+ if (n === 0)
684
+ await this.locatorMissing(key, why, { stopped: false, ...(chatId ? { chatId } : {}) }).catch(() => undefined);
685
+ return n;
686
+ };
687
+ const look = async (key, chatId) => await record(key, await count(key, chatId), chatId);
688
+ const notHere = (key, note) => {
689
+ out.set(key, { key, status: 'not-here', count: 0, note });
690
+ };
691
+ // The chat as it was opened: its box, and its Send.
692
+ const box = await look('composer');
693
+ let send = await count('send');
694
+ if (send === 0 && box > 0) {
695
+ // Send shown only once the box holds text: one letter, taken out again. Nothing is sent.
696
+ await this.composer().fill('x').catch(() => undefined);
697
+ await this.p.waitForTimeout(500);
698
+ send = await count('send');
699
+ await this.composer().fill('').catch(() => undefined);
700
+ }
701
+ await record('send', send);
702
+ // Stop shows only while Copilot writes.
703
+ const stop = await count('stop');
704
+ if (stop > 0)
705
+ out.set('stop', { key: 'stop', status: 'found', count: stop });
706
+ else
707
+ notHere('stop', 'writing');
708
+ // The sidebar, and the newest conversation in it, opened by its address: only read.
709
+ const links = await look('conversationLink');
710
+ const href = links > 0 ? await this.el('conversationLink').first().getAttribute('href').catch(() => null) : null;
711
+ const chatId = href ? parseChatId(href) : null;
712
+ const opened = chatId ? await this.openConversation(chatId).catch(() => false) : false;
713
+ if (opened && chatId) {
714
+ for (const key of ['turn', 'userMessage', 'answer', 'copy'])
715
+ await look(key);
716
+ // Its "More" button: by the locator; at its default and finding nothing, by its name in the row, as the bot does.
717
+ let more = this.el('chatMore', chatId).first();
718
+ let found = await count('chatMore', chatId);
719
+ let note;
720
+ if (found === 0 && this.chatLocators.chatMore === DefaultChatLocators.chatMore) {
721
+ const row = this.el('conversationLink').and(this.p.locator(`[href*="${chatId}"]`)).first();
722
+ const byName = row.locator('xpath=ancestor-or-self::*[self::li or self::div][1]').getByRole('button', { name: Rename.moreButtonLabel, exact: true });
723
+ const n = await byName.count().catch(() => 0);
724
+ if (n > 0) {
725
+ more = byName.first();
726
+ found = n;
727
+ note = 'byName';
728
+ }
729
+ }
730
+ await record('chatMore', found, chatId, note);
731
+ if (found > 0) {
732
+ await this.press(more).catch(() => undefined);
733
+ await this.el('renameItem').first().waitFor({ state: 'visible', timeout: 3_000 }).catch(() => undefined);
734
+ await look('renameItem');
735
+ await this.dismissOpenMenu().catch(() => undefined);
736
+ }
737
+ else
738
+ notHere('renameItem', 'noMenu');
739
+ }
740
+ else {
741
+ for (const key of ['turn', 'userMessage', 'answer', 'copy', 'chatMore', 'renameItem'])
742
+ notHere(key, 'noConversation');
743
+ }
744
+ // The rename dialog is not opened: renaming is not this check's to do.
745
+ notHere('renameInput', 'dialog');
746
+ notHere('renameSave', 'dialog');
747
+ 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) });
748
+ return CHAT_LOCATOR_KEYS.map((k) => out.get(k) ?? { key: k, status: 'not-here', count: 0 });
749
+ }
750
+ /** Whether the box to write in is empty: a message clicked away with Send leaves it so. */
751
+ async boxIsEmpty() {
752
+ return ((await this.composer().innerText({ timeout: 2_000 }).catch(() => 'unread')) ?? '').trim() === '';
493
753
  }
494
754
  /** Whether the composer shows within `ms`, looked for a second at a time; a Stop ends the wait with `StoppedByOperator`. */
495
755
  async composerWithin(ms, signal, stopped) {
@@ -510,6 +770,118 @@ export class CopilotTransport {
510
770
  }
511
771
  }
512
772
  }
773
+ /** One of the chat's addresses (`Url.newChatPath`, `Url.conversationPath`) on the host the chat was last found on. */
774
+ chatAddress(path) {
775
+ return `${this.chatOrigin}${path}`;
776
+ }
777
+ /**
778
+ * Keeps the host the chat was found on — its box there, and staying — when it is the work Copilot's: the chat's
779
+ * addresses are opened there from then on. Whatever the path: on 2026-11-17 the work machine's chat was at `/home`.
780
+ */
781
+ learnChatOrigin() {
782
+ const url = this.p.url();
783
+ if (surfaceOfUrl(url) === 'work')
784
+ this.chatOrigin = new URL(url).origin;
785
+ }
786
+ /** Whether the box to write in is still there, on the same page, after `settleMs`: one that showed on the way elsewhere is not. */
787
+ async boxStays() {
788
+ const at = whereIs(this.p.url());
789
+ await this.p.waitForTimeout(this.settleMs);
790
+ return whereIs(this.p.url()) === at && (await this.composer().isVisible().catch(() => false));
791
+ }
792
+ /**
793
+ * After the window was sent to the chat (`path`, one of its addresses): whether it got there. Operator, 2026-11-17:
794
+ * the start ended on "The page is not the Microsoft 365 Copilot chat" at
795
+ * `copilot.cloud.microsoft/home?es=SSR&redirfrom=mcmToCcm` — the box to write in had shown, and a few seconds later the
796
+ * page was Copilot's home page, with none, and the bot neither waited nor went to the chat from there.
797
+ *
798
+ * - `chat`: the box is there and stays (`boxStays`). The host it is on is the chat's from then on (`learnChatOrigin`).
799
+ * - `elsewhere`: the page is another of the work Copilot's own (`isCopilotOtherPage`), and stayed one after the chat
800
+ * was opened from it — by `path` on the page's own host, then, for a new chat, by the page's link to its chat. It
801
+ * is not a sign-in, and is not waited on as one.
802
+ * - `no-box`: anything else with no box within `firstLookMs` — a sign-in page, the consumer Copilot, a chat slow to
803
+ * load — left to the caller, as before.
804
+ *
805
+ * Looked at a second at a time, so a Stop ends it at once; another of Copilot's pages is given `otherPageMs` to turn
806
+ * into the chat on its own, not the whole first look.
807
+ */
808
+ async arrive(path, signal, stopped) {
809
+ for (let move = 0;; move += 1) {
810
+ const until = Date.now() + this.firstLookMs;
811
+ let otherSince = 0;
812
+ for (;;) {
813
+ if ((await this.composerWithin(Math.max(1, Math.min(1_000, until - Date.now())), signal, stopped)) && (await this.boxStays())) {
814
+ this.learnChatOrigin();
815
+ return 'chat';
816
+ }
817
+ const other = isCopilotOtherPage(this.p.url());
818
+ otherSince = other ? otherSince || Date.now() : 0;
819
+ if (other && Date.now() - otherSince >= this.otherPageMs)
820
+ break;
821
+ if (Date.now() >= until) {
822
+ if (other)
823
+ break;
824
+ return 'no-box';
825
+ }
826
+ }
827
+ if (move >= 2)
828
+ return 'elsewhere';
829
+ const found = whereIs(this.p.url());
830
+ if (move === 0) {
831
+ const to = `${new URL(this.p.url()).origin}${path}`;
832
+ this.emit('chat-page-elsewhere', { found, by: 'address', to: whereIs(to) });
833
+ await this.p.goto(to, { waitUntil: 'domcontentloaded' });
834
+ }
835
+ else {
836
+ // A conversation's address is the only way to it: a link to the chat would open a new one.
837
+ if (path !== Url.newChatPath)
838
+ return 'elsewhere';
839
+ const link = await this.chatLink();
840
+ if (!link)
841
+ return 'elsewhere';
842
+ this.emit('chat-page-elsewhere', { found, by: 'link', to: whereIs(link.href) });
843
+ await link.at.click({ timeout: 5_000 }).catch(() => undefined);
844
+ }
845
+ }
846
+ }
847
+ /**
848
+ * The page's own link to its chat, for another of Copilot's pages that the chat's address did not get past: an anchor
849
+ * on the page's host to `/chat`, shown, and opening in this window. Nothing else on the page is clicked.
850
+ */
851
+ async chatLink() {
852
+ const found = await this.p
853
+ .evaluate(() => {
854
+ const links = [...document.querySelectorAll('a[href]')];
855
+ const i = links.findIndex((a) => {
856
+ let u;
857
+ try {
858
+ u = new URL(a.href);
859
+ }
860
+ catch {
861
+ return false;
862
+ }
863
+ const box = a.getBoundingClientRect();
864
+ const shown = box.width > 0 && box.height > 0 && getComputedStyle(a).visibility !== 'hidden';
865
+ return u.origin === location.origin && u.pathname.replace(/\/+$/, '') === '/chat' && (!a.target || a.target === '_self') && shown;
866
+ });
867
+ return i < 0 ? null : { i, href: links[i].href };
868
+ })
869
+ .catch(() => null);
870
+ return found ? { at: this.p.locator('a[href]').nth(found.i), href: found.href } : null;
871
+ }
872
+ /**
873
+ * The error for a window that would not go to the chat from another of Copilot's pages (`arrive`'s `elsewhere`), with
874
+ * a picture of the page — a screenshot always, its HTML when Settings keep it — so the next look is at what it showed.
875
+ */
876
+ async notTheChat() {
877
+ const url = this.p.url();
878
+ // Most likely the box itself (2026-11-17: Copilot's chat was at /home, its box changed): said as the box's locator.
879
+ return await this.locatorMissing('composer', `on ${whereIs(url)}, which did not turn into the chat`, {
880
+ message: (files) => `Copilot showed its page ${whereIs(url)} instead of the chat, and the chat did not open from there ` +
881
+ `(by its address on that host, nor by a link to it on the page). Nothing was sent. ${files} ${this.composerHint()}
882
+ Current URL: ${url}`,
883
+ });
884
+ }
513
885
  /**
514
886
  * Which Copilot we actually landed on.
515
887
  *
@@ -523,7 +895,8 @@ export class CopilotTransport {
523
895
  const where = surfaceOfUrl(this.p.url());
524
896
  if (where !== 'work')
525
897
  return where;
526
- const hasWorkComposer = (await this.p.locator(Surface.workMarkers[0]).count()) > 0;
898
+ // The box by the chat's locator in force (2026-11-17: the work page's box changed, and Settings may name it).
899
+ const hasWorkComposer = (await this.composer().count().catch(() => 0)) > 0;
527
900
  return hasWorkComposer ? 'work' : 'unknown';
528
901
  }
529
902
  /**
@@ -579,9 +952,17 @@ export class CopilotTransport {
579
952
  this.onChat = null;
580
953
  await this.p.goto(target.toString(), { waitUntil: 'domcontentloaded' });
581
954
  }
582
- /** Throws with an explanation when the profile is not on the work Copilot. */
955
+ /**
956
+ * Throws with an explanation when the profile is not on the work Copilot. On the work Copilot's host with no box to
957
+ * write in, the box is waited for a few seconds rather than looked for once (2026-11-17: the page was changing); a
958
+ * page that is still not the chat leaves a picture of itself, since its address alone does not say what it showed.
959
+ */
583
960
  async assertWorkSurface() {
584
- const where = await this.surface();
961
+ let where = await this.surface();
962
+ if (where === 'unknown' && surfaceOfUrl(this.p.url()) === 'work') {
963
+ await this.composerWithin(SURFACE_WAIT_MS, undefined, '');
964
+ where = await this.surface();
965
+ }
585
966
  if (where === 'work')
586
967
  return;
587
968
  const url = this.p.url();
@@ -592,6 +973,10 @@ export class CopilotTransport {
592
973
  'sign-in': 'The profile is signed out. Run "cop login".',
593
974
  unknown: 'The page is not the Microsoft 365 Copilot chat.',
594
975
  };
976
+ if (where === 'unknown') {
977
+ throw await this.locatorMissing('composer', `on ${whereIs(url)}`, { message: (files) => `${explain.unknown} ${files} ${this.composerHint()}
978
+ Current URL: ${url}` });
979
+ }
595
980
  throw new Error(`${explain[where] ?? explain.unknown}
596
981
  Current URL: ${url}`);
597
982
  }
@@ -686,6 +1071,9 @@ Current URL: ${url}`);
686
1071
  * types credentials; it only waits for the composer to appear.
687
1072
  */
688
1073
  async ensureSignedIn(url = this.opts.chatUrl, opts = {}) {
1074
+ // A box locator saved in Settings that cannot be used: said once, before the box is looked for with the default.
1075
+ for (const problem of this.chatLocatorProblems.splice(0))
1076
+ this.emit('chat-locator-not-used', { problem });
689
1077
  // Copilot's home page, where no conversation is expected until the run enters one.
690
1078
  this.onChat = null;
691
1079
  await this.p.goto(url, { waitUntil: 'domcontentloaded' });
@@ -694,29 +1082,54 @@ Current URL: ${url}`);
694
1082
  * ends the wait at once, rather than after the whole sign-in timeout, fifteen minutes by default (2026-10-17).
695
1083
  */
696
1084
  const stoppedHere = 'stopped by the operator while waiting for the sign-in';
697
- if (!(await this.composerWithin(this.firstLookMs, opts.signal, stoppedHere))) {
1085
+ /*
1086
+ * The chat; or another of Copilot's own pages, which the chat is opened from (2026-11-17: Copilot's home page, where
1087
+ * the work machine's start ended); or a page asking for a sign-in, the only one waited on for the operator.
1088
+ */
1089
+ let at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);
1090
+ if (at === 'no-box') {
698
1091
  this.emit('sign-in-required', { url: this.p.url() });
699
1092
  if (!(await this.composerWithin(this.opts.signInTimeoutMs, opts.signal, stoppedHere))) {
700
1093
  throw new Error(`The sign-in was not completed within ${Math.round(this.opts.signInTimeoutMs / 1000)} s (Settings → copilot.signInTimeoutSec). ` +
701
1094
  'Sign in in the open Edge window, then start again.');
702
1095
  }
703
1096
  this.emit('signed-in');
1097
+ // A sign-in may come back to Copilot's home page rather than to its chat.
1098
+ at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);
704
1099
  }
1100
+ if (at === 'elsewhere')
1101
+ throw await this.notTheChat();
705
1102
  await this.clearBlockers();
1103
+ // The page may have moved on while the blockers were looked at, as the work machine's did: once more to the chat.
1104
+ if ((await this.surface()) !== 'work' && (await this.arrive(Url.newChatPath, opts.signal, stoppedHere)) === 'elsewhere') {
1105
+ throw await this.notTheChat();
1106
+ }
706
1107
  await this.assertWorkSurface();
707
1108
  }
708
1109
  async newChat() {
709
1110
  this.onChat = null;
710
- await this.p.goto(Url.newChat, { waitUntil: 'domcontentloaded' });
711
- await this.composer().waitFor({ state: 'visible' });
1111
+ await this.p.goto(this.chatAddress(Url.newChatPath), { waitUntil: 'domcontentloaded' });
1112
+ // Another of Copilot's pages instead (2026-11-17): the chat opened from it, and said so when it would not.
1113
+ if ((await this.arrive(Url.newChatPath, undefined, '')) === 'elsewhere')
1114
+ throw await this.notTheChat();
1115
+ // A chat slow to load: the rest of the minute it was always given (the page's default timeout); none by then, said.
1116
+ await this.composer()
1117
+ .waitFor({ state: 'visible', timeout: 45_000 })
1118
+ .catch(async (e) => {
1119
+ if (e.name !== 'TimeoutError')
1120
+ throw e;
1121
+ throw await this.locatorMissing('composer', 'on a new chat, within a minute');
1122
+ });
712
1123
  await this.dismissPopups();
713
1124
  this.onChat = 'new';
714
1125
  }
715
1126
  /** Reopens a conversation by its id. Returns false when it no longer opens. */
716
1127
  async openConversation(chatId) {
717
1128
  this.onChat = null;
718
- await this.p.goto(Url.conversation(chatId), { waitUntil: 'domcontentloaded' });
719
- if (!(await this.isChatReady(20_000)))
1129
+ const path = Url.conversationPath(chatId);
1130
+ await this.p.goto(this.chatAddress(path), { waitUntil: 'domcontentloaded' });
1131
+ const at = await this.arrive(path, undefined, '');
1132
+ if (at === 'elsewhere' || (at === 'no-box' && !(await this.isChatReady(5_000))))
720
1133
  return false;
721
1134
  const there = parseChatId(this.p.url()) === chatId;
722
1135
  if (there)
@@ -725,7 +1138,7 @@ Current URL: ${url}`);
725
1138
  }
726
1139
  /** Finds a conversation by its exact name in the sidebar. */
727
1140
  async openConversationByName(name) {
728
- const row = this.p.locator(`${Sidebar.conversationLink}[aria-label="${name.replace(/"/g, '\\"')}"]`);
1141
+ const row = this.el('conversationLink').and(this.p.locator(`[aria-label="${name.replace(/"/g, '\\"')}"]`));
729
1142
  if ((await row.count()) === 0)
730
1143
  return false;
731
1144
  // The conversation it is, from the link's own address: the page's follows a moment after the click.
@@ -788,9 +1201,14 @@ Current URL: ${url}`);
788
1201
  this.emit('chat-left', { chatId: want.id, found: from });
789
1202
  const stopped = 'stopped by the operator while waiting for the sign-in';
790
1203
  let signedIn = false;
1204
+ const path = Url.conversationPath(want.id);
791
1205
  for (let tries = 0; tries < 3; tries += 1) {
792
- await this.p.goto(Url.conversation(want.id), { waitUntil: 'domcontentloaded' });
793
- if (await this.composerWithin(this.firstLookMs, opts.signal, stopped)) {
1206
+ await this.p.goto(this.chatAddress(path), { waitUntil: 'domcontentloaded' });
1207
+ // Another of Copilot's pages, the conversation's address not getting past it (2026-11-17): by its name, not a sign-in.
1208
+ const at = await this.arrive(path, opts.signal, stopped);
1209
+ if (at === 'elsewhere')
1210
+ break;
1211
+ if (at === 'chat') {
794
1212
  if (parseChatId(this.p.url()) !== want.id)
795
1213
  break;
796
1214
  this.onChat = want;
@@ -853,7 +1271,7 @@ Current URL: ${url}`);
853
1271
  * of it when Copilot's dialog refused that one (see `chatNameForms`) — or false when it could not be renamed.
854
1272
  */
855
1273
  async nameChat(chatId, name, opts = {}) {
856
- const row = this.p.locator(`${Sidebar.conversationLink}[href*="${chatId}"]`).first();
1274
+ const row = this.el('conversationLink').and(this.p.locator(`[href*="${chatId}"]`)).first();
857
1275
  // Waited for, like everything below: a new chat's row appears in the sidebar some seconds after the
858
1276
  // reply, and `count()` read it as missing and returned without a word (live run 2026-10-03). The run
859
1277
  // tries again later when it is still not there (see `nameIfStillUnnamed` in taskRunner.ts).
@@ -863,6 +1281,8 @@ Current URL: ${url}`);
863
1281
  }
864
1282
  catch {
865
1283
  this.emit('chat-name-failed', { chatId, name, error: `the conversation did not appear in the sidebar within ${Math.round(waitMs / 1000)} s` });
1284
+ // Not one conversation in the sidebar by its locator: the locator's, said; this one not there yet is not.
1285
+ await this.warnLocator('conversationLink', 'in the sidebar, while the conversation was to be named').catch(() => undefined);
866
1286
  return false;
867
1287
  }
868
1288
  /*
@@ -875,6 +1295,8 @@ Current URL: ${url}`);
875
1295
  * own auto-generated titles instead of the name this runner gave them.
876
1296
  */
877
1297
  let opened = false;
1298
+ // Which locator the step under way looks for: the one said when it finds nothing.
1299
+ let step = 'chatMore';
878
1300
  try {
879
1301
  await row.scrollIntoViewIfNeeded().catch(() => undefined);
880
1302
  // Briefly: a hover the sidebar takes waits out the page's whole timeout otherwise.
@@ -885,20 +1307,24 @@ Current URL: ${url}`);
885
1307
  * section header — and Playwright retried for the whole minute (live 2026-10-05), so `press` clicks
886
1308
  * the element itself when the mouse cannot reach it.
887
1309
  */
888
- const byChat = this.p.locator(Rename.moreButtonForChat(chatId)).first();
889
- const more = (await byChat.count()) > 0
1310
+ const byChat = this.el('chatMore', chatId).first();
1311
+ // Through the row by its name only while the locator is the default: one set in Settings is the one used.
1312
+ const more = (await byChat.count()) > 0 || this.chatLocators.chatMore !== DefaultChatLocators.chatMore
890
1313
  ? byChat
891
1314
  : row.locator('xpath=ancestor-or-self::*[self::li or self::div][1]').getByRole('button', { name: Rename.moreButtonLabel, exact: true }).first();
892
1315
  await more.waitFor({ state: 'attached', timeout: 5_000 });
893
1316
  await this.press(more);
894
1317
  opened = true;
895
- const item = this.p.getByRole('menuitem', { name: Rename.menuItem, exact: true }).first();
1318
+ step = 'renameItem';
1319
+ const item = this.el('renameItem').first();
896
1320
  await item.waitFor({ state: 'visible', timeout: 5_000 });
897
1321
  await this.press(item);
898
1322
  opened = false;
899
- const input = this.p.locator(Rename.input);
1323
+ step = 'renameInput';
1324
+ const input = this.el('renameInput').first();
900
1325
  await input.waitFor({ state: 'visible', timeout: 10_000 });
901
- const save = this.p.getByRole('button', { name: Rename.saveText, exact: true }).first();
1326
+ step = 'renameSave';
1327
+ const save = this.el('renameSave').first();
902
1328
  /*
903
1329
  * Offered in shorter forms until the dialog takes one. Copilot refuses a name it counts as longer than 50
904
1330
  * characters, by a count that is not always ours, and its dialog then stays open over the chat (2026-10-17: "the
@@ -940,6 +1366,8 @@ Current URL: ${url}`);
940
1366
  }
941
1367
  catch (e) {
942
1368
  this.emit('chat-name-failed', { chatId, name, error: e.message });
1369
+ // The step's locator, when it finds nothing: said (the name is the work's convenience; the work goes on).
1370
+ await this.warnLocator(step, `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
943
1371
  return false;
944
1372
  }
945
1373
  finally {
@@ -1882,8 +2310,8 @@ Current URL: ${url}`);
1882
2310
  * counted, with the rendered count as the fallback for a page that does not carry it.
1883
2311
  */
1884
2312
  async turnCount() {
1885
- return await this.p.evaluate((turnSel) => {
1886
- const nodes = Array.from(document.querySelectorAll(turnSel));
2313
+ // By the `turn` locator in force (2026-11-17), whatever its kind: CSS, XPath or Playwright's own.
2314
+ return await this.el('turn').evaluateAll((nodes) => {
1887
2315
  let size = 0;
1888
2316
  for (const n of nodes) {
1889
2317
  const carrier = n.matches('[aria-setsize]') ? n : (n.querySelector('[aria-setsize]') ?? n.closest('[aria-setsize]'));
@@ -1892,17 +2320,13 @@ Current URL: ${url}`);
1892
2320
  size = v;
1893
2321
  }
1894
2322
  return size > 0 ? size : nodes.length;
1895
- }, `[data-testid="${TestId.turn}"]`);
2323
+ });
1896
2324
  }
1897
2325
  /** The newest user message as shown, for telling "landed but not counted" from "not sent". */
1898
2326
  async lastUserTurnText() {
1899
- return await this.p
1900
- .evaluate(() => {
1901
- const nodes = document.querySelectorAll('[id^="user-message-"]');
1902
- const last = nodes[nodes.length - 1];
1903
- return last ? last.innerText : '';
1904
- })
1905
- .catch(() => '');
2327
+ const all = this.el('userMessage');
2328
+ const n = await all.count().catch(() => 0);
2329
+ return n > 0 ? ((await all.nth(n - 1).innerText({ timeout: 2_000 }).catch(() => '')) ?? '') : '';
1906
2330
  }
1907
2331
  /** Puts text in the composer and clicks Send. Enter is not used: it does not submit. */
1908
2332
  async send(text, attachments = []) {
@@ -1913,10 +2337,17 @@ Current URL: ${url}`);
1913
2337
  if (attachments.length > 0)
1914
2338
  await this.attach(attachments);
1915
2339
  const composer = this.composer();
2340
+ // The box, before it is clicked: none, its locator is said, rather than a minute's wait on the click.
2341
+ if (!(await this.composerWithin(10_000, undefined, '')))
2342
+ throw await this.locatorMissing('composer', 'when a message was to be written in it');
1916
2343
  await composer.click();
1917
2344
  await composer.fill(text);
1918
2345
  const send = await this.sendButton();
1919
- await send.waitFor({ state: 'visible', timeout: 20_000 });
2346
+ await send.waitFor({ state: 'visible', timeout: this.sendWaitMs }).catch(async (e) => {
2347
+ if (e.name !== 'TimeoutError')
2348
+ throw e;
2349
+ throw await this.locatorMissing('send', `after the message was written in the box, within ${Math.round(this.sendWaitMs / 1000)} s`);
2350
+ });
1920
2351
  await send.click();
1921
2352
  this.emit('message-sent', { chars: text.length, attachments: attachments.length });
1922
2353
  }
@@ -1930,9 +2361,9 @@ Current URL: ${url}`);
1930
2361
  * change here is the attribute name rather than the button.
1931
2362
  */
1932
2363
  async sendButton() {
1933
- const wrapper = this.p.locator(Css.composerWrapper);
1934
- if ((await wrapper.count()) > 0) {
1935
- return wrapper.first().getByRole('button', { name: Label.send, exact: true }).first();
2364
+ // Settings' own; or the default — the Send in the box's wrapper — wherever the wrapper is on the page.
2365
+ if (this.chatLocators.send !== DefaultChatLocators.send || (await this.p.locator(Css.composerWrapper).count()) > 0) {
2366
+ return this.el('send').first();
1936
2367
  }
1937
2368
  const submit = this.p.locator(Css.composerSendSubmit);
1938
2369
  if ((await submit.count()) > 0) {
@@ -1991,12 +2422,22 @@ Current URL: ${url}`);
1991
2422
  this.retryBaselineTurns = before;
1992
2423
  }
1993
2424
  await this.send(text, attachments);
1994
- const accepted = await this.waitForAccepted(before, 30_000, text, shownBefore);
2425
+ const accepted = await this.waitForAccepted(before, this.acceptMs, text, shownBefore);
1995
2426
  if (accepted)
1996
2427
  return before;
1997
2428
  const found = await this.detectBlocker();
1998
2429
  lastProblem = found.kind === 'none' ? 'the message did not appear in the chat' : `${found.kind}: ${found.reason}`;
1999
2430
  this.emit('send-not-accepted', { attempt, problem: lastProblem });
2431
+ /*
2432
+ * Sent — the box is empty — and neither a message of the conversation nor the one sent is found: the locators, not
2433
+ * the chat (2026-11-17). Said, and not sent again: a message that did land would be in the chat twice.
2434
+ */
2435
+ if (found.kind === 'none' &&
2436
+ (await this.boxIsEmpty()) &&
2437
+ (await this.el('turn').count().catch(() => 0)) === 0 &&
2438
+ (await this.el('userMessage').count().catch(() => 0)) === 0) {
2439
+ 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)");
2440
+ }
2000
2441
  if (found.kind !== 'none') {
2001
2442
  const cleared = await this.handleBlocker(found);
2002
2443
  if (!cleared) {
@@ -2070,29 +2511,25 @@ Current URL: ${url}`);
2070
2511
  async waitForReply(previousTurns) {
2071
2512
  const startedAt = Date.now();
2072
2513
  const deadline = startedAt + this.opts.replyTimeoutMs;
2073
- const state = async () => await this.p.evaluate(({ turnSel, stopLabel, wrapperSel, copySel }) => {
2074
- // The conversation's size as the app reports it, not the rendered count: see turnCount.
2075
- const nodes = Array.from(document.querySelectorAll(turnSel));
2076
- let size = 0;
2077
- for (const n of nodes) {
2078
- const carrier = n.matches('[aria-setsize]') ? n : (n.querySelector('[aria-setsize]') ?? n.closest('[aria-setsize]'));
2079
- const v = carrier ? Number(carrier.getAttribute('aria-setsize')) : NaN;
2080
- if (!Number.isNaN(v) && v > size)
2081
- size = v;
2082
- }
2083
- const turns = size > 0 ? size : nodes.length;
2084
- const streaming = Array.from(document.querySelectorAll('button')).some((b) => b.getAttribute('aria-label') === stopLabel);
2085
- const wrappers = document.querySelectorAll(wrapperSel);
2086
- const last = wrappers[wrappers.length - 1];
2087
- return { turns, streaming, finished: !streaming && !!last && !!last.querySelector(copySel) };
2088
- }, {
2089
- turnSel: `[data-testid="${TestId.turn}"]`,
2090
- stopLabel: Label.stopGenerating,
2091
- wrapperSel: Signal.answerWrapper,
2092
- copySel: Signal.copyButtonInAnswer,
2093
- });
2514
+ /*
2515
+ * Through the chat's locators in force (2026-11-17: each can be set in Settings): the conversation's size as the app
2516
+ * reports it (see turnCount), whether Copilot is still writing, and whether its newest answer is finished — its Copy
2517
+ * button there — with how long that answer's text is, to tell one standing still.
2518
+ */
2519
+ const state = async () => {
2520
+ const turns = await this.turnCount();
2521
+ const streaming = (await this.el('stop').count()) > 0;
2522
+ const answers = this.el('answer');
2523
+ const n = await answers.count();
2524
+ const newest = n > 0 ? answers.nth(n - 1) : null;
2525
+ const chars = newest ? await newest.evaluate((el) => (el.textContent ?? '').length).catch(() => 0) : 0;
2526
+ const finished = !streaming && !!newest && (await newest.locator(this.sel('copy')).count()) > 0;
2527
+ return { turns, streaming, finished, answers: n, chars };
2528
+ };
2094
2529
  let sawNewTurn = false;
2095
- let last = { turns: previousTurns, streaming: false, finished: false };
2530
+ let last = { turns: previousTurns, streaming: false, finished: false, answers: 0, chars: 0 };
2531
+ // Since when Copilot's newest answer has stood still, not written and not finished (see below).
2532
+ let still = { since: Date.now(), chars: -1, answers: -1 };
2096
2533
  while (Date.now() < deadline) {
2097
2534
  if (this.p.isClosed()) {
2098
2535
  throw new Error('The browser window was closed while waiting for a reply. If you did not close it, ' +
@@ -2116,6 +2553,29 @@ Current URL: ${url}`);
2116
2553
  sawNewTurn = true;
2117
2554
  if (sawNewTurn && last.finished)
2118
2555
  break;
2556
+ /*
2557
+ * What a locator that no longer finds its element looks like (2026-11-17), said rather than waiting out the whole
2558
+ * reply time: not one message of the conversation found, though the message sent is in it; or Copilot's answer
2559
+ * begun, then standing still — not written any more, never finished — with no answer found at all, or no Copy
2560
+ * button anywhere on the page. A Copy missing from the newest answer alone is Copilot's, not the locator's.
2561
+ */
2562
+ if (last.turns === 0 && Date.now() - startedAt >= this.turnsGraceMs) {
2563
+ 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');
2564
+ }
2565
+ if (sawNewTurn && !last.streaming) {
2566
+ if (last.chars !== still.chars || last.answers !== still.answers)
2567
+ still = { since: Date.now(), chars: last.chars, answers: last.answers };
2568
+ else if (Date.now() - still.since >= this.answerStillMs) {
2569
+ if (last.answers === 0) {
2570
+ 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`);
2571
+ }
2572
+ if ((await this.el('copy').count().catch(() => 1)) === 0) {
2573
+ 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`);
2574
+ }
2575
+ }
2576
+ }
2577
+ else
2578
+ still = { since: Date.now(), chars: -1, answers: -1 };
2119
2579
  // Only look for blockers while nothing is streaming, so the check stays cheap.
2120
2580
  if (!last.streaming) {
2121
2581
  const blocker = await this.detectBlocker();
@@ -2178,7 +2638,7 @@ Current URL: ${url}`);
2178
2638
  * all reachable from one locator.
2179
2639
  */
2180
2640
  lastAnswer() {
2181
- return this.p.getByTestId(TestId.assistantMessage).last();
2641
+ return this.el('answer').last();
2182
2642
  }
2183
2643
  async lastMessageText() {
2184
2644
  return (await this.lastAnswer().innerText().catch(() => '')) ?? '';
@@ -2213,7 +2673,7 @@ Current URL: ${url}`);
2213
2673
  * as degraded, because that text is known to be lossy.
2214
2674
  */
2215
2675
  async copyLastReply() {
2216
- const copy = this.lastAnswer().getByTestId(TestId.copyResponse).first();
2676
+ const copy = this.lastAnswer().locator(this.sel('copy')).first();
2217
2677
  try {
2218
2678
  /*
2219
2679
  * Two guards around one click, both about the neighbours.