copilot-operator 0.1.92 → 0.1.94

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 (53) hide show
  1. package/README.md +640 -625
  2. package/dist/src/api/operator.controller.js +26 -0
  3. package/dist/src/api/operator.service.js +117 -25
  4. package/dist/src/exec/readOnly.js +27 -2
  5. package/dist/src/orchestrator/kerriganRunner.js +9 -2
  6. package/dist/src/orchestrator/taskRunner.js +14 -3
  7. package/dist/src/plan/kerrigan.js +263 -243
  8. package/dist/src/plan/systemGuide.js +125 -85
  9. package/dist/src/session/chatbotFile.js +117 -0
  10. package/dist/src/session/compose.js +13 -0
  11. package/dist/src/session/locatorFailures.js +8 -5
  12. package/dist/src/transport/copilotTransport.js +94 -12
  13. package/dist/src/transport/locators.js +53 -0
  14. package/dist/src/transport/pageHtml.js +36 -2
  15. package/dist/src/vcs/newBranch.js +46 -0
  16. package/dist/web/404.html +2 -2
  17. package/dist/web/_next/static/chunks/1077.b7df9cb8ca810075.js +1 -0
  18. package/dist/web/_next/static/chunks/1548.417c17b63c371f00.js +1 -0
  19. package/dist/web/_next/static/chunks/2163.469367b8fbcc862d.js +1 -0
  20. package/dist/web/_next/static/chunks/714.72112704f3cb8127.js +1 -0
  21. package/dist/web/_next/static/chunks/{7220.260579c8dbfa2c30.js → 7220.8bd897c7ddfee701.js} +1 -1
  22. package/dist/web/_next/static/chunks/7921-25d1755799107ea7.js +1 -0
  23. package/dist/web/_next/static/chunks/8584.f87df7324303ab75.js +1 -0
  24. package/dist/web/_next/static/chunks/9067.67a7c7cf3b019b5c.js +1 -0
  25. package/dist/web/_next/static/chunks/9747.a87dbd4acd45e39d.js +1 -0
  26. package/dist/web/_next/static/chunks/app/layout-1b7d13f7b2efd008.js +1 -0
  27. package/dist/web/_next/static/chunks/app/{page-b71841852e6b9ff5.js → page-7eae1e8848525e1d.js} +1 -1
  28. package/dist/web/_next/static/chunks/app/settings/page-c92548f9c6318962.js +1 -0
  29. package/dist/web/_next/static/chunks/{webpack-abd1f09115b96456.js → webpack-91b2de9c3da6f8b9.js} +1 -1
  30. package/dist/web/_next/static/css/{6b92f118889ca88b.css → 523d11041085f836.css} +1 -1
  31. package/dist/web/defaults.html +2 -2
  32. package/dist/web/defaults.txt +8 -8
  33. package/dist/web/index.html +3 -3
  34. package/dist/web/index.txt +9 -9
  35. package/dist/web/queue.html +2 -2
  36. package/dist/web/queue.txt +9 -9
  37. package/dist/web/settings.html +2 -2
  38. package/dist/web/settings.txt +9 -9
  39. package/dist/web/system.html +2 -2
  40. package/dist/web/system.txt +9 -9
  41. package/package.json +2 -1
  42. package/dist/web/_next/static/chunks/1077.922b5f1492f6e0dd.js +0 -1
  43. package/dist/web/_next/static/chunks/1548.4a09f12e23d369ec.js +0 -1
  44. package/dist/web/_next/static/chunks/2163.14e7879a45ae9748.js +0 -1
  45. package/dist/web/_next/static/chunks/714.2daeede6dd07ee60.js +0 -1
  46. package/dist/web/_next/static/chunks/7921-1de1f08d23145c0d.js +0 -1
  47. package/dist/web/_next/static/chunks/8584.01e3a7f9f14f0b4f.js +0 -1
  48. package/dist/web/_next/static/chunks/9067.75d4fdcf47f62fd1.js +0 -1
  49. package/dist/web/_next/static/chunks/9747.f1bdfbefaba61f8b.js +0 -1
  50. package/dist/web/_next/static/chunks/app/layout-f5681fae8247797b.js +0 -1
  51. package/dist/web/_next/static/chunks/app/settings/page-7d343eecdd9c7500.js +0 -1
  52. /package/dist/web/_next/static/{n7rfXOWgaCFmATod4Q6hp → UNygvDtRnBVZrGJt53IE4}/_buildManifest.js +0 -0
  53. /package/dist/web/_next/static/{n7rfXOWgaCFmATod4Q6hp → UNygvDtRnBVZrGJt53IE4}/_ssgManifest.js +0 -0
@@ -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
+ }
@@ -164,6 +164,19 @@ export function composeOpening(input) {
164
164
  const instruction = input.instruction?.text.trim() ? input.instruction : undefined;
165
165
  if (input.continuing && input.contractAlreadySent) {
166
166
  const title = input.taskTitle.trim() || 'untitled';
167
+ /*
168
+ * Carried on with no plan approved yet, in plan mode (2026-11-18): not "carry on from your plan" — there is none the
169
+ * operator approved — but plan first, as the plan-mode note says, and nothing changes until the plan is approved.
170
+ */
171
+ if (input.planNote) {
172
+ const message = `Continue task ${input.taskNumber}: ${title}, in this same conversation. ${whyItStopped(input.continuing)} ` +
173
+ `Its plan was not approved yet, so the work does not go on from where it stopped: plan first, as below — look at ` +
174
+ `what is there now, changing nothing — and send the plan for approval. Step numbering restarts at 1.\n\n` +
175
+ `${input.planNote}\n\n` +
176
+ (instruction ? `${instructionSection(instruction.text)}\n\n` : '') +
177
+ `${runnerBlock(input)}`.trimEnd();
178
+ return { messages: [message], firstMessage: message };
179
+ }
167
180
  /*
168
181
  * After a failure, with the operator's new prompt: told how it ended and why, that its files are
169
182
  * there, and what to do now — not "carry on from your plan", which is the plan that failed.
@@ -4,7 +4,8 @@
4
4
  * each. Kept in the data folder, so a failure seen before a restart is still shown; read by the banner on every page
5
5
  * and by Settings, where the locator's field is in red, until the locator is changed there or the operator closes it.
6
6
  */
7
- import { readFile, rename, writeFile } from 'node:fs/promises';
7
+ import { readFile } from 'node:fs/promises';
8
+ import { writeFileAtomically } from './store.js';
8
9
  import { CHAT_LOCATOR_KEYS } from '../transport/locators.js';
9
10
  import { isStepKey } from '../transport/chatSteps.js';
10
11
  const isKey = (k) => typeof k === 'string' && (CHAT_LOCATOR_KEYS.includes(k) || isStepKey(k));
@@ -42,12 +43,14 @@ export class LocatorFailures {
42
43
  });
43
44
  return had;
44
45
  }
46
+ /*
47
+ * Through the store's own atomic write, which tries again when Windows refuses the rename for a moment (2026-11-18:
48
+ * a failure recorded while the banner, polling every few seconds, was reading the file was lost without a word: the
49
+ * rename onto a file open for reading was refused, and the error swallowed).
50
+ */
45
51
  async change(edit) {
46
52
  const run = async () => {
47
- const next = edit(await this.list());
48
- const tmp = `${this.file}.tmp`;
49
- await writeFile(tmp, JSON.stringify(next, null, 2), 'utf8');
50
- await rename(tmp, this.file);
53
+ await writeFileAtomically(this.file, async () => JSON.stringify(edit(await this.list()), null, 2));
51
54
  };
52
55
  const done = this.queue.then(run, run);
53
56
  this.queue = done.catch(() => undefined);
@@ -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);
@@ -1213,9 +1260,25 @@ Current URL: ${url}`);
1213
1260
  let at = await this.arrive(Url.newChatPath, opts.signal, stoppedHere);
1214
1261
  if (at === 'no-box') {
1215
1262
  this.emit('sign-in-required', { url: this.p.url() });
1216
- if (!(await this.composerWithin(this.opts.signInTimeoutMs, opts.signal, stoppedHere))) {
1263
+ /*
1264
+ * On Copilot's own chat page, no sign-in page in sight, and still no box after a while (2026-11-18): most likely the
1265
+ * box's locator, which finds nothing on a page Copilot changed — and the bot waited the whole sign-in time (15
1266
+ * minutes by default) and then said "the sign-in was not completed", with no locator named. Said once, then, as the
1267
+ * box's locator, the page's file for a chatbot kept; the wait for a sign-in goes on, since Copilot may also ask for
1268
+ * one on its own page.
1269
+ */
1270
+ const firstLook = Math.min(this.boxSuspectMs, this.opts.signInTimeoutMs);
1271
+ const soon = await this.composerWithin(firstLook, opts.signal, stoppedHere);
1272
+ if (!soon && isWorkChatAddress(this.p.url()) && !this.warned.has('composer')) {
1273
+ this.warned.add('composer');
1274
+ await this.locatorMissing('composer', `on ${whereIs(this.p.url())}, Copilot's own chat page and not a sign-in page, for ${Math.round(firstLook / 1000)} s: if you are signed in, the box's locator is the one to fix (the bot goes on waiting for a sign-in meanwhile)`, { stopped: false }).catch(() => undefined);
1275
+ }
1276
+ if (!soon && !(await this.composerWithin(Math.max(1, this.opts.signInTimeoutMs - firstLook), opts.signal, stoppedHere))) {
1217
1277
  throw new Error(`The sign-in was not completed within ${Math.round(this.opts.signInTimeoutMs / 1000)} s (Settings → copilot.signInTimeoutSec). ` +
1218
- 'Sign in in the open Edge window, then start again.');
1278
+ 'Sign in in the open Edge window, then start again.' +
1279
+ (this.warned.has('composer') && isWorkChatAddress(this.p.url())
1280
+ ? ` If you were signed in, the box to write in was not found on Copilot's chat page: fix "Box to write in" in Settings → "The chat's locators" (its notice has the file for a chatbot). In force: ${this.chatLocators.composer}`
1281
+ : ''));
1219
1282
  }
1220
1283
  this.emit('signed-in');
1221
1284
  // A sign-in may come back to Copilot's home page rather than to its chat.
@@ -1475,6 +1538,20 @@ Current URL: ${url}`);
1475
1538
  const refused = [];
1476
1539
  for (const form of chatNameForms(name)) {
1477
1540
  await input.fill(form);
1541
+ /*
1542
+ * Its Save not found (work, 2026-11-18: role=button[name="Save"] found nothing, and the dialog was left open
1543
+ * over the chat): said, with the dialog's HTML while it is still open, and the name given with Enter, which
1544
+ * such a field takes. Once only: a dialog that takes no Enter is closed with Cancel below.
1545
+ */
1546
+ if (!(await save.waitFor({ state: 'visible', timeout: 3_000 }).then(() => true, () => false))) {
1547
+ await this.warnLocator('renameSave', `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
1548
+ await input.press('Enter').catch(() => undefined);
1549
+ if (await this.renameTaken(input, save))
1550
+ wanted = form;
1551
+ else
1552
+ refused.push(form);
1553
+ break;
1554
+ }
1478
1555
  await this.press(save);
1479
1556
  if (await this.renameTaken(input, save)) {
1480
1557
  wanted = form;
@@ -1508,6 +1585,9 @@ Current URL: ${url}`);
1508
1585
  this.emit('chat-name-failed', { chatId, name, error: e.message });
1509
1586
  // The step's locator, when it finds nothing: said (the name is the work's convenience; the work goes on).
1510
1587
  await this.warnLocator(step, `while the conversation was being named "${name}"`, chatId).catch(() => undefined);
1588
+ // A rename dialog it stopped in is not left open over the chat (work, 2026-11-18): closed, after its HTML is kept.
1589
+ if (step === 'renameInput' || step === 'renameSave')
1590
+ await this.p.keyboard.press('Escape').catch(() => undefined);
1511
1591
  return false;
1512
1592
  }
1513
1593
  finally {
@@ -2657,7 +2737,7 @@ Current URL: ${url}`);
2657
2737
  this.emit('attachment-upload-unconfirmed', { name });
2658
2738
  if (!this.warned.has('attachmentUploaded')) {
2659
2739
  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);
2740
+ await this.locatorMissing('attachmentUploaded', `for ${Math.round(this.uploadWaitMs / 1000)} s after the file ${name} was attached`, { stopped: false, file: path }).catch(() => undefined);
2661
2741
  }
2662
2742
  }
2663
2743
  this.emit('attached', { name });
@@ -2667,6 +2747,8 @@ Current URL: ${url}`);
2667
2747
  inputWaitMs = 10_000;
2668
2748
  attachWaitMs = 30_000;
2669
2749
  uploadWaitMs = 120_000;
2750
+ /** How long Copilot's own chat page may show no box before its locator is said as the likely cause (a field, for the checks). */
2751
+ boxSuspectMs = 30_000;
2670
2752
  /** An attached file's locator in force, with the file's name put in its place (see `fillFileLocator`). */
2671
2753
  fileEl(key, file) {
2672
2754
  return this.p.locator(playwrightSelector(fillFileLocator(this.chatLocators[key], file)));
@@ -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
  }
@@ -177,6 +177,52 @@ async function keepUncommitted(dir, head, branch, message, author) {
177
177
  await rm(index, { force: true });
178
178
  }
179
179
  }
180
+ /**
181
+ * What is not committed in the folder, put aside as "New branch from main" puts it aside: one commit on a branch of its
182
+ * own (`<prefix>saved/<when>`, never pushed), checked whole, and only then taken out of the folder, which is left clean
183
+ * on the branch it is on. Nothing is deleted. Null when there was nothing to put aside.
184
+ *
185
+ * For the queue (2026-11-18): a task that works on "the folder as it is" leaves its changes uncommitted, and the next
186
+ * task with a branch of its own was refused for them ("There are uncommitted changes … Commit or stash them first"), the
187
+ * tasks depending on it skipped, in a queue nobody was watching.
188
+ */
189
+ export async function setAsideUncommitted(folder, why, prefix = 'cop/') {
190
+ const top = await git(folder, ['rev-parse', '--show-toplevel']);
191
+ const repoDir = top.ok && top.stdout ? resolve(top.stdout) : folder;
192
+ const changed = porcelainPaths((await git(repoDir, ['status', '--porcelain', '--untracked-files=no'])).stdout);
193
+ const untracked = lines((await git(repoDir, ['ls-files', '--others', '--exclude-standard'])).stdout);
194
+ if (changed.length === 0 && untracked.length === 0)
195
+ return null;
196
+ const head = (await git(repoDir, ['rev-parse', '--verify', '--quiet', 'HEAD'])).stdout;
197
+ if (!head)
198
+ return { problem: 'the repository has no commit yet to keep the changes on top of' };
199
+ const here = (await git(repoDir, ['symbolic-ref', '--quiet', '--short', 'HEAD'])).stdout || null;
200
+ const saved = await freeBranchName(repoDir, `${branchNameFrom(['saved'], prefix)}/${stamp()}`);
201
+ const message = [
202
+ 'Keep uncommitted work',
203
+ '',
204
+ `Everything that was not committed in the folder on ${here ?? 'a detached HEAD'} (${short(head)}), kept here: ${why}`,
205
+ 'To take a file back: git restore --source <this branch> -- <path>',
206
+ '',
207
+ ...[...changed.map((p) => `- changed: ${p}`), ...untracked.map((p) => `- new: ${p}`)].slice(0, 300),
208
+ '',
209
+ 'Committed by copilot-operator. Not pushed.',
210
+ '',
211
+ ].join('\n');
212
+ const kept = await keepUncommitted(repoDir, head, saved, message);
213
+ if ('problem' in kept)
214
+ return { problem: kept.problem };
215
+ // Kept whole: now out of the folder — the tracked changes put back, the new files kept on the branch taken out.
216
+ const restored = await git(repoDir, ['restore', '--staged', '--worktree', '--source', 'HEAD', '--', '.'], 300_000);
217
+ if (!restored.ok)
218
+ return { problem: `the changes are kept on ${saved}, but could not be taken out of the folder: ${restored.stderr}` };
219
+ for (let i = 0; i < untracked.length; i += 100) {
220
+ const cleaned = await git(repoDir, ['--literal-pathspecs', 'clean', '-fd', '--quiet', '--', ...untracked.slice(i, i + 100)], 300_000);
221
+ if (!cleaned.ok)
222
+ return { problem: `the new files are kept on ${saved}, but could not be taken out of the folder: ${cleaned.stderr}` };
223
+ }
224
+ return { saved, commit: kept.commit, files: changed.length + untracked.length };
225
+ }
180
226
  /** The bot's own name on a commit. */
181
227
  const BOT_AUTHOR = ['-c', 'user.name=copilot-operator', '-c', `user.email=${RUNNER_EMAIL}`];
182
228
  /** The commit message when the operator wrote none. */