copilot-operator 0.1.92 → 0.1.93

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 (36) hide show
  1. package/dist/src/api/operator.controller.js +26 -0
  2. package/dist/src/api/operator.service.js +34 -8
  3. package/dist/src/plan/systemGuide.js +5 -13
  4. package/dist/src/session/chatbotFile.js +117 -0
  5. package/dist/src/transport/copilotTransport.js +74 -10
  6. package/dist/src/transport/locators.js +53 -0
  7. package/dist/src/transport/pageHtml.js +36 -2
  8. package/dist/web/404.html +2 -2
  9. package/dist/web/_next/static/chunks/{1077.922b5f1492f6e0dd.js → 1077.626a11362f53d35c.js} +1 -1
  10. package/dist/web/_next/static/chunks/{1548.4a09f12e23d369ec.js → 1548.79f05ff765581b0a.js} +1 -1
  11. package/dist/web/_next/static/chunks/{2163.14e7879a45ae9748.js → 2163.09f1212655504f3a.js} +1 -1
  12. package/dist/web/_next/static/chunks/{714.2daeede6dd07ee60.js → 714.acea3698b6af7a61.js} +1 -1
  13. package/dist/web/_next/static/chunks/{7220.260579c8dbfa2c30.js → 7220.1eba10bd9d449cea.js} +1 -1
  14. package/dist/web/_next/static/chunks/7921-29256ac683ea4bc5.js +1 -0
  15. package/dist/web/_next/static/chunks/{8584.01e3a7f9f14f0b4f.js → 8584.b5aac5354f124d4b.js} +1 -1
  16. package/dist/web/_next/static/chunks/{9067.75d4fdcf47f62fd1.js → 9067.177163495f3bd8fa.js} +1 -1
  17. package/dist/web/_next/static/chunks/{9747.f1bdfbefaba61f8b.js → 9747.5b9d763e89abc7e4.js} +1 -1
  18. package/dist/web/_next/static/chunks/app/layout-1b7d13f7b2efd008.js +1 -0
  19. package/dist/web/_next/static/chunks/app/settings/page-c92548f9c6318962.js +1 -0
  20. package/dist/web/_next/static/chunks/{webpack-abd1f09115b96456.js → webpack-33252b1a0a7d93ba.js} +1 -1
  21. package/dist/web/defaults.html +2 -2
  22. package/dist/web/defaults.txt +7 -7
  23. package/dist/web/index.html +3 -3
  24. package/dist/web/index.txt +8 -8
  25. package/dist/web/queue.html +2 -2
  26. package/dist/web/queue.txt +8 -8
  27. package/dist/web/settings.html +2 -2
  28. package/dist/web/settings.txt +8 -8
  29. package/dist/web/system.html +2 -2
  30. package/dist/web/system.txt +8 -8
  31. package/package.json +1 -1
  32. package/dist/web/_next/static/chunks/7921-1de1f08d23145c0d.js +0 -1
  33. package/dist/web/_next/static/chunks/app/layout-f5681fae8247797b.js +0 -1
  34. package/dist/web/_next/static/chunks/app/settings/page-7d343eecdd9c7500.js +0 -1
  35. /package/dist/web/_next/static/{n7rfXOWgaCFmATod4Q6hp → ZrEcjGdZEXe66UUxUqine}/_buildManifest.js +0 -0
  36. /package/dist/web/_next/static/{n7rfXOWgaCFmATod4Q6hp → ZrEcjGdZEXe66UUxUqine}/_ssgManifest.js +0 -0
@@ -202,6 +202,23 @@ let OperatorController = class OperatorController {
202
202
  failText(res, e);
203
203
  }
204
204
  }
205
+ /**
206
+ * The one file for a chatbot (2026-11-18): everything it needs to give the right locator, the piece of the page and
207
+ * the whole page included (see `session/chatbotFile.ts`). A download, like the HTML; `lang` is the language the
208
+ * chatbot is told to speak to the operator in.
209
+ */
210
+ async locatorFailureChatbotFile(key, lang, res) {
211
+ try {
212
+ const { fileName, content } = await this.ops.locatorFailureChatbotFile(key, typeof lang === 'string' ? lang.slice(0, 8) : undefined);
213
+ res.type('application/octet-stream');
214
+ res.setHeader('content-disposition', contentDisposition(fileName));
215
+ res.setHeader('x-content-type-options', 'nosniff');
216
+ res.send(Buffer.from(content, 'utf8'));
217
+ }
218
+ catch (e) {
219
+ failText(res, e);
220
+ }
221
+ }
205
222
  /**
206
223
  * "Check the locators" (2026-11-17): the Copilot window opened, each of the chat's locators looked for, and what each
207
224
  * found. Takes as long as the window takes to open, a sign-in included.
@@ -717,6 +734,15 @@ __decorate([
717
734
  __metadata("design:paramtypes", [String, Object]),
718
735
  __metadata("design:returntype", Promise)
719
736
  ], OperatorController.prototype, "locatorFailureHtml", null);
737
+ __decorate([
738
+ Get('locators/failures/:key/chatbot'),
739
+ __param(0, Param('key')),
740
+ __param(1, Query('lang')),
741
+ __param(2, Res()),
742
+ __metadata("design:type", Function),
743
+ __metadata("design:paramtypes", [String, Object, Object]),
744
+ __metadata("design:returntype", Promise)
745
+ ], OperatorController.prototype, "locatorFailureChatbotFile", null);
720
746
  __decorate([
721
747
  Post('locators/check'),
722
748
  __metadata("design:type", Function),
@@ -18,6 +18,7 @@ import { existsSync } from 'node:fs';
18
18
  import { isAbsolute, relative } from 'node:path';
19
19
  import { readFile as readFileText } from 'node:fs/promises';
20
20
  import { LocatorFailures } from '../session/locatorFailures.js';
21
+ import { chatbotFile } from '../session/chatbotFile.js';
21
22
  import { CHAT_LOCATOR_KEYS, locatorPrompt, resolveChatLocators } from '../transport/locators.js';
22
23
  import { LocatorMissing } from '../transport/copilotTransport.js';
23
24
  import { isStepKey, stepKey, stepPrompt } from '../transport/chatSteps.js';
@@ -898,6 +899,8 @@ let OperatorService = class OperatorService {
898
899
  const html = str(detail.html);
899
900
  const picture = str(detail.picture);
900
901
  const url = str(detail.url);
902
+ const piece = str(detail.piece);
903
+ const around = str(detail.around);
901
904
  void this.locatorFailures
902
905
  .record({
903
906
  key: key,
@@ -909,6 +912,7 @@ let OperatorService = class OperatorService {
909
912
  ...(html ? { html } : {}),
910
913
  ...(picture ? { picture } : {}),
911
914
  ...(url ? { url } : {}),
915
+ ...(piece ? { piece, ...(around ? { around } : {}) } : {}),
912
916
  })
913
917
  .catch(() => undefined);
914
918
  }
@@ -922,7 +926,7 @@ let OperatorService = class OperatorService {
922
926
  const inForce = resolveChatLocators(cfg.copilot.chatLocators).locators;
923
927
  // A step's (2026-11-17): changed when its locator is, or it is switched off, made not required, or gone.
924
928
  const steps = new Map(cfg.copilot.extraSteps.map((s) => [stepKey(s.id), s]));
925
- return (await this.locatorFailures.list()).map(({ html, picture: _picture, ...f }) => {
929
+ return (await this.locatorFailures.list()).map(({ html, picture: _picture, piece: _piece, around: _around, ...f }) => {
926
930
  const step = isStepKey(f.key) ? steps.get(f.key) : undefined;
927
931
  return {
928
932
  ...f,
@@ -938,19 +942,41 @@ let OperatorService = class OperatorService {
938
942
  const f = await this.locatorFailures.get(key);
939
943
  if (!f?.html)
940
944
  throw new Error(`No HTML is kept for the "${key}" locator.`);
945
+ const content = await this.keptFailureFile(key, f.html, 'HTML');
946
+ const stamp = f.at.replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
947
+ // A step's key holds a colon, which a Windows file name cannot.
948
+ return { fileName: `copilot-page-${key.replace(/[^\w-]/g, '-')}-${stamp}.html`, content };
949
+ }
950
+ /**
951
+ * The one file for a chatbot (operator, 2026-11-18: "everything in one file; the user takes it and sends it to the
952
+ * chat, and that is all"): what to do, the goal, what failed, the old locator, the piece of the page where the element
953
+ * most likely is, the whole page, and how to find it by hand when it is in neither. See `session/chatbotFile.ts`.
954
+ * Made from what is kept, also for a failure kept before the piece was (then without it).
955
+ */
956
+ async locatorFailureChatbotFile(key, lang) {
957
+ const f = await this.locatorFailures.get(key);
958
+ if (!f)
959
+ throw new Error(`No failure is kept for the "${key}" locator.`);
960
+ const page = f.html ? await this.keptFailureFile(key, f.html, 'HTML').catch(() => '') : '';
961
+ const piece = f.piece ? await this.keptFailureFile(key, f.piece, 'piece of HTML').catch(() => '') : '';
962
+ const cfg = await this.settings.load();
963
+ const step = isStepKey(f.key) ? cfg.copilot.extraSteps.find((s) => stepKey(s.id) === f.key) : undefined;
964
+ const content = chatbotFile({ failure: f, step, piece, page, ...(lang ? { lang } : {}) });
965
+ const stamp = f.at.replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
966
+ return { fileName: `for-chatbot-${key.replace(/[^\w-]/g, '-')}-${stamp}.txt`, content };
967
+ }
968
+ /** A file kept with a failure, read: only one in the bot's runs folder. */
969
+ async keptFailureFile(key, path, what) {
941
970
  const cfg = await this.settings.load();
942
971
  const runs = resolve(cfg.resolved.runsDir);
943
- const file = resolve(f.html);
972
+ const file = resolve(path);
944
973
  const inside = relative(runs, file);
945
974
  if (!inside || inside.startsWith('..') || isAbsolute(inside)) {
946
- throw new Error(`The HTML kept for the "${key}" locator is not in the bot's runs folder.`);
975
+ throw new Error(`The ${what} kept for the "${key}" locator is not in the bot's runs folder.`);
947
976
  }
948
- const content = await readFileText(file, 'utf8').catch(() => {
949
- throw new Error(`The HTML kept for the "${key}" locator is gone (${file}).`);
977
+ return await readFileText(file, 'utf8').catch(() => {
978
+ throw new Error(`The ${what} kept for the "${key}" locator is gone (${file}).`);
950
979
  });
951
- const stamp = f.at.replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
952
- // A step's key holds a colon, which a Windows file name cannot.
953
- return { fileName: `copilot-page-${key.replace(/[^\w-]/g, '-')}-${stamp}.html`, content };
954
980
  }
955
981
  async startFailureReport(id) {
956
982
  await this.init();
@@ -206,20 +206,12 @@ export const SYSTEM_GUIDE = [
206
206
  doesBg: 'На всяка страница, когато локатор на чата не е намерил нищо (2026-11-17): отваря Settings → „Локатори на чата“ на полето на този локатор, в червено, с курсора в него. Провал, спрял работата, го отваря веднъж сам.',
207
207
  },
208
208
  {
209
- key: 'chatloc.html',
209
+ key: 'chatloc.file',
210
210
  kind: 'link',
211
- en: 'Download the HTML',
212
- bg: 'Изтегли HTML',
213
- doesEn: 'The page\'s HTML at the moment the locator found nothing, scripts, styles and the sidebar\'s conversation names taken out: the file to give a chatbot with "Copy for a chatbot", which answers with the right locator.',
214
- doesBg: 'HTML-ът на страницата в момента, в който локаторът не е намерил нищо, без скриптове, стилове и имената на разговорите от страничната лента: файлът, който се дава на чатбот заедно с „Копирай за чатбот“, и той отговаря с правилния локатор.',
215
- },
216
- {
217
- key: 'chatloc.prompt',
218
- kind: 'button',
219
- en: 'Copy for a chatbot',
220
- bg: 'Копирай за чатбот',
221
- doesEn: 'Copies the text that asks a chatbot, given the HTML file, for the locator of this element: what it is, the locator that stopped finding it, and what a good locator uses.',
222
- doesBg: 'Копира текста, който пита чатбот, получил HTML файла, за локатора на този елемент: какъв е, локаторът, който е спрял да го намира, и какво ползва добрият локатор.',
211
+ en: 'Download the file for a chatbot',
212
+ bg: 'Изтегли файл за чатбота',
213
+ doesEn: 'One file with all a chatbot needs to give the right locator (2026-11-18): what to do and why, what failed and when, the old locator, the part of the page where the element most likely is (around an element near it that was found), the whole page without scripts, styles and conversation names, and how the chatbot walks you through finding it in Edge (F12) when it is in neither. Attach it to Copilot or any other chatbot and send it, with nothing else to write; the chatbot speaks the interface\'s language.',
214
+ doesBg: 'Един файл с всичко, което е нужно на чатбот, за да даде правилния локатор (2026-11-18): какво да направи и защо, какво се е провалило и кога, старият локатор, частта от страницата, където елементът най-вероятно е (около близък елемент, който е намерен), цялата страница без скриптове, стилове и имена на разговори, и как чатботът да ви преведе през търсенето в Edge (F12), ако го няма в нито една от тях. Прикачете го в Copilot или друг чатбот и го пратете, без да пишете нищо друго; чатботът говори на езика на интерфейса.',
223
215
  },
224
216
  {
225
217
  key: 'chatloc.dismiss',
@@ -0,0 +1,117 @@
1
+ import { CHAT_ID, ChatLocatorShows, ChatLocatorWhat, ChatPlaceholder, FILE_NAME, FILE_STEM } from '../transport/locators.js';
2
+ const LANGUAGE_NAMES = {
3
+ en: 'English',
4
+ bg: 'Bulgarian',
5
+ de: 'German',
6
+ es: 'Spanish',
7
+ fr: 'French',
8
+ pt: 'Portuguese',
9
+ ja: 'Japanese',
10
+ ko: 'Korean',
11
+ ar: 'Arabic',
12
+ };
13
+ /** The language the chatbot speaks to the operator in: the interface's, English when it is not one of its. */
14
+ export function languageName(code) {
15
+ return LANGUAGE_NAMES[(code ?? '').toLowerCase()] ?? 'English';
16
+ }
17
+ /** The whole page is cut at this length: what is past it is rarely read by a chatbot, and the file stays small to attach. */
18
+ export const PAGE_CAP = 600_000;
19
+ /** A fence longer than any run of backticks in the text, so the HTML never closes its own code block. */
20
+ function fenced(text, lang) {
21
+ const longest = Math.max(0, ...Array.from(text.matchAll(/`+/g), (m) => m[0].length));
22
+ const fence = '`'.repeat(Math.max(3, longest + 1));
23
+ return `${fence}${lang}\n${text}\n${fence}`;
24
+ }
25
+ /** What the element is, said for the chatbot. */
26
+ function elementOf(failure, step) {
27
+ if (!failure.key.startsWith('step:'))
28
+ return ChatLocatorWhat[failure.key];
29
+ const action = step?.action ?? 'click';
30
+ const what = action === 'click' ? 'the element the program clicks at this point'
31
+ : action === 'press' ? `the element whose presence means the key ${step?.key ?? ''} is to be pressed`
32
+ : action === 'appear' ? 'the element that shows when the page is ready for this step'
33
+ : 'the element that shows while the page is not ready yet (a spinner, a banner, a dialog)';
34
+ return `${what}. The user describes it as: "${step?.name || failure.name || '(no description)'}"`;
35
+ }
36
+ /** When the element is on the screen, for the person to bring it there by hand. */
37
+ function showsWhen(failure, step) {
38
+ if (!failure.key.startsWith('step:'))
39
+ return ChatLocatorShows[failure.key];
40
+ const when = (step?.when ?? 'message') === 'open' ? 'right after the chat opens' : 'just before a message is sent';
41
+ return `bring the page to where the program meets it, ${when} (the user knows the step: "${step?.name || failure.name || ''}")`;
42
+ }
43
+ /** The file's text (Markdown, kept as .txt so every chatbot takes it as an attachment). */
44
+ export function chatbotFile({ failure, step, piece, page, lang }) {
45
+ const isStep = failure.key.startsWith('step:');
46
+ const where = isStep ? 'Settings → "Steps to the chat", the step\'s row in red' : 'Settings → "The chat\'s locators", the field in red';
47
+ const placeholder = isStep ? undefined : ChatPlaceholder[failure.key];
48
+ const language = languageName(lang);
49
+ const cutPage = page.length > PAGE_CAP ? `${page.slice(0, PAGE_CAP)}\n<!-- … the rest of the page is cut here (it is ${page.length} characters long) -->` : page;
50
+ const lines = [
51
+ '# For the chatbot: find a locator on the Microsoft 365 Copilot page',
52
+ '',
53
+ 'Read this whole file before you answer. The user attached it and may have written nothing else: start at once.',
54
+ `Speak to the user in ${language}. Keep every locator exactly as it must be typed, in a code block.`,
55
+ '',
56
+ '## What this is about',
57
+ '',
58
+ 'The user runs copilot-operator, a program that drives the Microsoft 365 Copilot chat page in Microsoft Edge (with Playwright).',
59
+ 'It finds each element it needs on that page by a locator: a CSS selector, an XPath, or a Playwright selector.',
60
+ 'Copilot\'s page changed, and one of those locators now finds nothing.',
61
+ '',
62
+ `**Your goal:** give the user ONE new locator that finds exactly this element, and only it. The user pastes it into the program (${where}), and the program finds the element again.`,
63
+ '',
64
+ '## What failed',
65
+ '',
66
+ `- **The element:** ${elementOf(failure, step)}.`,
67
+ `- **Its name in the program:** ${isStep ? `the step "${step?.name || failure.name || failure.key.slice(5)}"` : `"${failure.key}"`}`,
68
+ `- **The old locator, which now finds nothing:** \`${failure.locator}\``,
69
+ `- **When and what the program was doing:** ${failure.at}: ${isStep ? failure.why : `it found nothing ${failure.why}`}`,
70
+ `- **The work:** ${failure.stopped ? 'stopped there' : 'went on without it, more slowly or with something left undone'}`,
71
+ ...(failure.url ? [`- **The page's address:** ${failure.url}`] : []),
72
+ '',
73
+ '## Rules for the new locator',
74
+ '',
75
+ '- A CSS selector; an XPath (starting with /) only when CSS cannot say it. The program also takes Playwright\'s :text-is("…"), :has-text("…"), :has(…) and role=button[name="…"].',
76
+ '- Use what stays the same between versions of the page: id, role, aria-label, data-testid, data-test-id and other data-* attributes, the tag, the visible text.',
77
+ '- Do not use class names made of random letters (like azFuQXgw or ___1x5usfw): they change with every new version of the page.',
78
+ '- Before you give it, check it against the HTML below: it must match exactly one element (for elements the page shows many of, like the conversation\'s messages, it must match each of them and nothing else).',
79
+ ...(placeholder === CHAT_ID ? [`- Keep ${CHAT_ID} in it where the conversation's id goes: the program puts the id there.`] : []),
80
+ ...(placeholder === FILE_NAME
81
+ ? [`- Keep ${FILE_NAME} in it where the file's name goes (the HTML shows message-01-in-full.txt or the like), or ${FILE_STEM} for the name without its extension (message-01-in-full): the program puts the name there.`]
82
+ : []),
83
+ '',
84
+ '## How to answer',
85
+ '',
86
+ '1. The locator alone, in a code block.',
87
+ '2. One line on why it is that element.',
88
+ `3. Tell the user to paste it into the program: ${where}.`,
89
+ '4. Tell the user how to check it on the real page: in Edge on the Copilot page, press F12, open "Elements", press Ctrl+F, paste the locator: it must show "1 of 1". (Ctrl+F there takes CSS and XPath, not Playwright\'s :text-is() or role=…: for those, the program\'s own "Check the locators" in Settings does the check.) If it shows "0 of 0" or more than one, the user tells you, and you look again.',
90
+ '',
91
+ '## Where to look',
92
+ '',
93
+ piece
94
+ ? `Look first in **Part 1**: the piece of the page the program took from around ${failure.around ?? 'where the element was looked for'}. The element is most likely in it: beside it, above it or inside it. If it is not there, look in **Part 2**, the whole page.`
95
+ : 'Look in **Part 2**, the whole page. (The program could not tell which part of the page the element is most likely in, so there is no Part 1.)',
96
+ 'The page was saved without its scripts, styles and picture data, and without the names of the user\'s conversations.',
97
+ '',
98
+ '## If the element is in neither part',
99
+ '',
100
+ 'This is rare: the page may not have been showing it when it was saved. Do not guess a locator. Walk the user through finding it, one step at a time, and wait for their answer after each:',
101
+ `1. In Edge, open the Copilot page and bring the element onto the screen: ${showsWhen(failure, step)}.`,
102
+ '2. Press F12 (the developer tools), then Ctrl+Shift+C, and click the element on the page. Its line in "Elements" is now highlighted.',
103
+ '3. Right-click that highlighted line → Copy → Copy outerHTML, and paste it to you. Then the same for the line of its parent (the line above it, one step to the left), and paste that too.',
104
+ '4. From what they paste, give the locator as above.',
105
+ 'If the user cannot bring the element onto the screen at all, it may no longer exist on the page: say so, and ask them to describe or send a picture of what the page shows at that moment instead, and find with them what replaced it.',
106
+ '',
107
+ '## Part 1: the piece of the page where the element most likely is',
108
+ '',
109
+ piece ? fenced(piece, 'html') : '(none: see Part 2)',
110
+ '',
111
+ '## Part 2: the whole page',
112
+ '',
113
+ cutPage ? fenced(cutPage, 'html') : '(The page itself was not saved: help the user find the element in the browser, as said above.)',
114
+ '',
115
+ ];
116
+ return lines.join('\n');
117
+ }
@@ -16,7 +16,7 @@ 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, 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';
19
+ import { Blocker, CHAT_ID, CHAT_LOCATOR_KEYS, ChatLocatorGroupOf, ChatLocatorNear, ChatLocatorWhat, Css, DefaultChatLocators, fillFileLocator, fillLocator, Label, Model, NearPlaces, ModelPicking, pageQuery, playwrightSelector, Rename, resolveChatLocators, resolvePickerLocators, Signal, StepNear, Surface, Url, } from './locators.js';
20
20
  import { acquireProfileLock } from './profileLock.js';
21
21
  import { chatNameForms, parseChatId } from './chatSession.js';
22
22
  import { strippedPageHtml } from './pageHtml.js';
@@ -668,16 +668,24 @@ export class CopilotTransport {
668
668
  async locatorMissing(key, why, opts = {}) {
669
669
  const stopped = opts.stopped ?? true;
670
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 } : {}) });
671
+ const { picture, html, url, piece, around } = await this.keepPage(`locator-${key}-${Date.now()}`, ChatLocatorGroupOf[key] === 'conversations', {
672
+ near: ChatLocatorNear[key],
673
+ ...(opts.chatId ? { chatId: opts.chatId } : {}),
674
+ ...(opts.file ? { file: opts.file } : {}),
675
+ });
676
+ this.emit('locator-missing', { key, locator, why, stopped, ...(html ? { html } : {}), ...(picture ? { picture } : {}), ...(url ? { url } : {}), ...(piece ? { piece, around } : {}) });
673
677
  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
678
  const message = opts.message?.(files) ??
675
679
  `Not found on Copilot's page: ${ChatLocatorWhat[key]}. The "${key}" locator found nothing ${why}. In force: ${locator} ` +
676
680
  `(Settings → "The chat's locators"). ${files}`.trim();
677
681
  return new LocatorMissing(key, locator, message, html, picture);
678
682
  }
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) {
683
+ /**
684
+ * A picture of the page and its HTML for a chatbot (see `pageHtml.ts`), in the failures folder; where the page was.
685
+ * With `near` (2026-11-18), also the piece of the page where the element not found most likely is: around the first
686
+ * of those that finds something (`ChatLocatorNear`), and what that was (`around`).
687
+ */
688
+ async keepPage(tag, keepSidebar, near) {
681
689
  if (!this.page || this.page.isClosed())
682
690
  return {};
683
691
  const dir = join(this.opts.transportDir, '..', 'failures');
@@ -686,12 +694,51 @@ export class CopilotTransport {
686
694
  const png = join(dir, `${tag}.png`);
687
695
  if (await this.p.screenshot({ path: png, fullPage: true }).then(() => true, () => false))
688
696
  out.picture = png;
689
- const text = await this.p.evaluate(strippedPageHtml, keepSidebar).catch(() => '');
697
+ const anchor = near ? await this.nearAnchor(near).catch(() => null) : null;
698
+ const kept = await this.p.evaluate(strippedPageHtml, { keepSidebar, anchor: anchor?.handle ?? null, cap: 40_000 }).catch(() => ({ page: '', piece: '' }));
699
+ await anchor?.handle.dispose().catch(() => undefined);
690
700
  const file = join(dir, `${tag}.html`);
691
- if (text && (await writeFile(file, text, 'utf8').then(() => true, () => false)))
701
+ if (kept.page && (await writeFile(file, kept.page, 'utf8').then(() => true, () => false)))
692
702
  out.html = file;
703
+ const pieceFile = join(dir, `${tag}.piece.html`);
704
+ if (anchor && kept.piece && (await writeFile(pieceFile, kept.piece, 'utf8').then(() => true, () => false))) {
705
+ out.piece = pieceFile;
706
+ out.around = anchor.what;
707
+ }
693
708
  return out;
694
709
  }
710
+ /** The first of `near` that finds something on the page: the element (the newest of a conversation's), and what it is. */
711
+ async nearAnchor(near) {
712
+ for (const n of near.near) {
713
+ const place = NearPlaces[n];
714
+ const key = place ? null : n;
715
+ let found;
716
+ if (place)
717
+ found = this.p.locator(place.selector);
718
+ else if (key === 'attachment' || key === 'attachmentUploaded') {
719
+ if (!near.file)
720
+ continue;
721
+ found = this.fileEl(key, near.file);
722
+ }
723
+ else if (key === 'chatMore') {
724
+ if (!near.chatId)
725
+ continue;
726
+ found = this.el(key, near.chatId);
727
+ }
728
+ else
729
+ found = this.el(key);
730
+ const newest = key === 'answer' || key === 'turn' || key === 'userMessage' || key === 'copy';
731
+ // One that shows first; a hidden one (the file input) only when none shows.
732
+ for (const which of [found.filter({ visible: true }), found]) {
733
+ if ((await which.count().catch(() => 0)) === 0)
734
+ continue;
735
+ const handle = await (newest ? which.last() : which.first()).elementHandle({ timeout: 1_000 }).catch(() => null);
736
+ if (handle)
737
+ return { handle, what: place ? place.what : `the element the "${key}" locator finds: ${ChatLocatorWhat[key]}` };
738
+ }
739
+ }
740
+ return null;
741
+ }
695
742
  /**
696
743
  * The operator's own steps for `when` (2026-11-17, see `chatSteps.ts`), in their order: "if this is on the page, do
697
744
  * this". One that must be there and is not, within its seconds, stops the work like a locator that found nothing,
@@ -748,9 +795,9 @@ export class CopilotTransport {
748
795
  /** One of the operator's own steps that must be there and is not: said like a locator that found nothing. */
749
796
  async stepMissing(step, why, stopped = true) {
750
797
  const key = stepKey(step.id);
751
- const { picture, html, url } = await this.keepPage(`step-${step.id}-${Date.now()}`, false);
798
+ const { picture, html, url, piece, around } = await this.keepPage(`step-${step.id}-${Date.now()}`, false, { near: StepNear });
752
799
  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 } : {}) });
800
+ this.emit('locator-missing', { key, name: step.name, locator: step.locator, why: `${when}: ${why}`, stopped, ...(html ? { html } : {}), ...(picture ? { picture } : {}), ...(url ? { url } : {}), ...(piece ? { piece, around } : {}) });
754
801
  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
802
  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
803
  `(Settings → "Steps to the chat"; switch the step off there, or make it not required, to go on without it). ${files}`.trim(), html, picture);
@@ -1475,6 +1522,20 @@ Current URL: ${url}`);
1475
1522
  const refused = [];
1476
1523
  for (const form of chatNameForms(name)) {
1477
1524
  await input.fill(form);
1525
+ /*
1526
+ * Its Save not found (work, 2026-11-18: role=button[name="Save"] found nothing, and the dialog was left open
1527
+ * over the chat): said, with the dialog's HTML while it is still open, and the name given with Enter, which
1528
+ * such a field takes. Once only: a dialog that takes no Enter is closed with Cancel below.
1529
+ */
1530
+ if (!(await save.waitFor({ state: 'visible', timeout: 3_000 }).then(() => true, () => false))) {
1531
+ await this.warnLocator('renameSave', `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
1532
+ await input.press('Enter').catch(() => undefined);
1533
+ if (await this.renameTaken(input, save))
1534
+ wanted = form;
1535
+ else
1536
+ refused.push(form);
1537
+ break;
1538
+ }
1478
1539
  await this.press(save);
1479
1540
  if (await this.renameTaken(input, save)) {
1480
1541
  wanted = form;
@@ -1508,6 +1569,9 @@ Current URL: ${url}`);
1508
1569
  this.emit('chat-name-failed', { chatId, name, error: e.message });
1509
1570
  // The step's locator, when it finds nothing: said (the name is the work's convenience; the work goes on).
1510
1571
  await this.warnLocator(step, `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
1572
+ // A rename dialog it stopped in is not left open over the chat (work, 2026-11-18): closed, after its HTML is kept.
1573
+ if (step === 'renameInput' || step === 'renameSave')
1574
+ await this.p.keyboard.press('Escape').catch(() => undefined);
1511
1575
  return false;
1512
1576
  }
1513
1577
  finally {
@@ -2657,7 +2721,7 @@ Current URL: ${url}`);
2657
2721
  this.emit('attachment-upload-unconfirmed', { name });
2658
2722
  if (!this.warned.has('attachmentUploaded')) {
2659
2723
  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);
2724
+ await this.locatorMissing('attachmentUploaded', `for ${Math.round(this.uploadWaitMs / 1000)} s after the file ${name} was attached`, { stopped: false, file: path }).catch(() => undefined);
2661
2725
  }
2662
2726
  }
2663
2727
  this.emit('attached', { name });
@@ -298,6 +298,59 @@ export const ChatLocatorWhat = {
298
298
  attachment: `the file attached to the message, as the box shows it before Send (a card with the file's name); ${FILE_NAME} is where the file's name goes (message-01-in-full.txt), ${FILE_STEM} the name without its extension (message-01-in-full)`,
299
299
  attachmentUploaded: `the same attached file once it has finished uploading (no spinner or progress on it any more); ${FILE_NAME} is where the file's name goes, ${FILE_STEM} the name without its extension`,
300
300
  };
301
+ /**
302
+ * Places on the page an element that is not found is most likely near, when none of the chat's own locators finds
303
+ * something beside it (operator, 2026-11-18: "the piece of code where the new locator probably is").
304
+ */
305
+ export const NearPlaces = {
306
+ wrapper: { selector: '[data-test-id="chat-input-wrapper"], [data-testid="chat-input-wrapper"]', what: 'the area around the box where a message is typed' },
307
+ dialog: { selector: '[role="dialog"], [role="alertdialog"], [aria-modal="true"], dialog[open]', what: 'the dialog open on the page' },
308
+ menu: { selector: '[role="menu"], [role="listbox"]', what: 'the menu open on the page' },
309
+ main: { selector: 'main, [role="main"]', what: 'the main part of the page, where the conversation is' },
310
+ sidebar: { selector: 'nav, [role="navigation"], aside', what: 'the sidebar with the list of conversations' },
311
+ };
312
+ /**
313
+ * Where to look for each element that was not found, nearest first: another of the chat's locators that finds
314
+ * something beside it (the box for its Send, the rename dialog's field for its Save), or a place (`NearPlaces`). The
315
+ * first that finds something gives the piece of the page handed to a chatbot.
316
+ */
317
+ export const ChatLocatorNear = {
318
+ composer: ['wrapper', 'send', 'uploadInput', 'main'],
319
+ send: ['composer', 'wrapper', 'uploadInput'],
320
+ userMessage: ['turn', 'answer', 'main'],
321
+ turn: ['userMessage', 'answer', 'main'],
322
+ answer: ['turn', 'copy', 'userMessage', 'main'],
323
+ copy: ['answer', 'turn', 'main'],
324
+ stop: ['composer', 'send', 'wrapper', 'answer'],
325
+ conversationLink: ['sidebar'],
326
+ chatMore: ['conversationLink', 'sidebar'],
327
+ renameItem: ['menu', 'chatMore', 'sidebar'],
328
+ renameInput: ['dialog', 'renameSave', 'sidebar'],
329
+ renameSave: ['renameInput', 'dialog'],
330
+ uploadInput: ['composer', 'wrapper', 'send'],
331
+ attachment: ['composer', 'wrapper', 'uploadInput'],
332
+ attachmentUploaded: ['attachment', 'composer', 'wrapper'],
333
+ };
334
+ /** For one of the operator's own steps, whose element can be anywhere: a dialog first (most are), then the box's area. */
335
+ export const StepNear = ['dialog', 'wrapper', 'composer', 'main'];
336
+ /** When each one is on the screen, for a person to bring it there and find it by hand in the browser's developer tools. */
337
+ export const ChatLocatorShows = {
338
+ composer: 'open Copilot\'s chat: the box is at the bottom of the page',
339
+ send: 'type a word in the box at the bottom of the chat: the Send button is beside it (do not send it)',
340
+ userMessage: 'open a conversation that has messages: each message the user sent is shown in it',
341
+ turn: 'open a conversation that has messages',
342
+ answer: 'open a conversation in which Copilot has answered',
343
+ copy: 'open a conversation in which Copilot has answered, and point the mouse at an answer: the Copy button is in the row of small buttons under it',
344
+ stop: 'send Copilot a question that takes a long answer, and while it is still writing, the Stop button shows (near the box at the bottom)',
345
+ conversationLink: 'open the sidebar with the list of conversations (the button at the top left, if it is closed)',
346
+ chatMore: 'in the sidebar, point the mouse at a conversation: its "More" button (three dots) shows on its row',
347
+ renameItem: 'in the sidebar, click a conversation\'s "More" button (three dots): the menu with "Rename" opens',
348
+ renameInput: 'in the sidebar, click a conversation\'s "More" button (three dots), then "Rename": the dialog with the field opens',
349
+ renameSave: 'in the sidebar, click a conversation\'s "More" button (three dots), then "Rename": the dialog opens; its button that saves the name is the one wanted (do not click it)',
350
+ uploadInput: 'it is never on the screen: it is the hidden <input type="file"> near the box at the bottom, found in Elements with Ctrl+F and input[type="file"]',
351
+ attachment: 'attach a file to the message with the box\'s attach button (a paper clip or a "+"): its card shows in the box',
352
+ attachmentUploaded: 'attach a file to the message with the box\'s attach button (a paper clip or a "+") and wait until it has finished uploading (no spinner or progress on its card): the card as it is then is wanted',
353
+ };
301
354
  /** The placeholder a template must hold; the others hold none. An attached file's: its name, or its name without the extension. */
302
355
  export const ChatPlaceholder = { chatMore: CHAT_ID, attachment: FILE_NAME, attachmentUploaded: FILE_NAME };
303
356
  /** Whether a template holds its placeholder (for a file's, either of the two). */
@@ -6,12 +6,30 @@
6
6
  * failed is one of the sidebar's own: it holds the names of all the operator's conversations. When it is kept, those
7
7
  * names are put out ("chat title") and only the structure, the ids and the labels of its buttons stay.
8
8
  *
9
+ * And the piece of it where the element that was not found most likely is (operator, 2026-11-18: "the piece of code
10
+ * where the new locator probably is"): around `anchor`, an element near it that was found (the box for its Send, the
11
+ * rename dialog's field for its Save), the largest part around it of at most `cap` characters, taken out of the same
12
+ * copy. The element is most likely beside it, above it or in it.
13
+ *
9
14
  * Run in the page (`page.evaluate`), on a copy of the document: the page itself is not touched. No function is named
10
15
  * inside it: the checks run the source through tsx, which wraps a named one in `__name(…)`, and the page has no
11
16
  * `__name` — the HTML was not kept at all until this was so.
12
17
  */
13
- export function strippedPageHtml(keepSidebar) {
18
+ export function strippedPageHtml(arg) {
19
+ const keepSidebar = arg.keepSidebar;
20
+ // Where the anchor is, by each element's place among its parent's children: the same place in the copy.
21
+ const path = [];
22
+ for (let n = arg.anchor ?? null; n && n !== document.documentElement; n = n.parentElement) {
23
+ if (!n.parentElement) {
24
+ path.length = 0;
25
+ break;
26
+ }
27
+ path.unshift(Array.prototype.indexOf.call(n.parentElement.children, n));
28
+ }
14
29
  const doc = document.documentElement.cloneNode(true);
30
+ let anchor = arg.anchor ? doc : null;
31
+ for (const i of path)
32
+ anchor = anchor?.children[i] ?? null;
15
33
  const noise = 'script, style, noscript, template, link[rel="stylesheet"], link[rel="preload"], link[rel="prefetch"], link[rel="modulepreload"], meta, iframe';
16
34
  for (const el of Array.from(doc.querySelectorAll(noise)))
17
35
  el.remove();
@@ -58,5 +76,21 @@ export function strippedPageHtml(keepSidebar) {
58
76
  gone.push(n);
59
77
  for (const n of gone)
60
78
  n.parentNode?.removeChild(n);
61
- return `<!doctype html>\n${doc.outerHTML.replace(/\n\s*\n+/g, '\n')}`;
79
+ // No function is named here, an arrow kept in a const included (see above): the blank lines go in each place.
80
+ const BLANK = /\n\s*\n+/g;
81
+ // The piece: the largest part around the anchor within the cap; the anchor alone, cut, when even it is longer.
82
+ let piece = '';
83
+ if (anchor && anchor !== doc && doc.contains(anchor)) {
84
+ const cap = arg.cap ?? 40_000;
85
+ let best = null;
86
+ for (let n = anchor; n; n = n.parentElement) {
87
+ if (n.outerHTML.replace(BLANK, '\n').length > cap)
88
+ break;
89
+ best = n;
90
+ }
91
+ piece = best
92
+ ? best.outerHTML.replace(BLANK, '\n')
93
+ : `${anchor.outerHTML.replace(BLANK, '\n').slice(0, cap)}\n<!-- … cut here: the element is longer than ${cap} characters -->`;
94
+ }
95
+ return { page: `<!doctype html>\n${doc.outerHTML.replace(BLANK, '\n')}`, piece };
62
96
  }