copilot-operator 0.1.45 → 0.1.46

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 (41) hide show
  1. package/dist/src/api/operator.controller.js +1 -0
  2. package/dist/src/api/operator.service.js +17 -3
  3. package/dist/src/api/server.js +6 -4
  4. package/dist/src/config/schema.js +3 -1
  5. package/dist/src/orchestrator/taskRunner.js +81 -21
  6. package/dist/src/transport/copilotTransport.js +92 -18
  7. package/dist/web/404.html +2 -2
  8. package/dist/web/_next/static/chunks/{549-13aab16a40600608.js → 549-8732dd2c1339bc5d.js} +1 -1
  9. package/dist/web/_next/static/chunks/867-7fb52be342fa64e5.js +1 -0
  10. package/dist/web/_next/static/chunks/app/defaults/page-614be29d185a2947.js +1 -0
  11. package/dist/web/_next/static/chunks/app/layout-485ce9395cb17998.js +1 -0
  12. package/dist/web/_next/static/chunks/app/page-ed6a5a2ff1b6285e.js +1 -0
  13. package/dist/web/_next/static/chunks/app/sessions/view/page-835d3533fdc63082.js +1 -0
  14. package/dist/web/appearance.html +2 -2
  15. package/dist/web/appearance.txt +9 -9
  16. package/dist/web/defaults.html +2 -2
  17. package/dist/web/defaults.txt +9 -9
  18. package/dist/web/history.html +2 -2
  19. package/dist/web/history.txt +9 -9
  20. package/dist/web/import.html +2 -2
  21. package/dist/web/import.txt +9 -9
  22. package/dist/web/index.html +2 -2
  23. package/dist/web/index.txt +9 -9
  24. package/dist/web/level1.html +2 -2
  25. package/dist/web/level1.txt +9 -9
  26. package/dist/web/presets.html +2 -2
  27. package/dist/web/presets.txt +9 -9
  28. package/dist/web/sessions/view.html +2 -2
  29. package/dist/web/sessions/view.txt +9 -9
  30. package/dist/web/sessions.html +2 -2
  31. package/dist/web/sessions.txt +9 -9
  32. package/dist/web/system.html +2 -2
  33. package/dist/web/system.txt +9 -9
  34. package/package.json +1 -1
  35. package/dist/web/_next/static/chunks/867-88233b4570638286.js +0 -1
  36. package/dist/web/_next/static/chunks/app/defaults/page-56134fbb8cc7554f.js +0 -1
  37. package/dist/web/_next/static/chunks/app/layout-12f138ee04d33c1e.js +0 -1
  38. package/dist/web/_next/static/chunks/app/page-b51630404f5eba03.js +0 -1
  39. package/dist/web/_next/static/chunks/app/sessions/view/page-afc235a9171535d8.js +0 -1
  40. /package/dist/web/_next/static/{L6g_c8hW3p_AUNzreQ3Sj → uAYbk9CSKPZe3-jWXmPOP}/_buildManifest.js +0 -0
  41. /package/dist/web/_next/static/{L6g_c8hW3p_AUNzreQ3Sj → uAYbk9CSKPZe3-jWXmPOP}/_ssgManifest.js +0 -0
@@ -549,6 +549,7 @@ let OperatorController = class OperatorController {
549
549
  text: body.text,
550
550
  ...(typeof body.threadId === 'string' && body.threadId ? { threadId: body.threadId } : {}),
551
551
  ...(typeof body.model === 'string' && body.model.trim() ? { model: body.model } : {}),
552
+ ...(body.manualModel === true ? { manualModel: true } : {}),
552
553
  })
553
554
  .catch(fail);
554
555
  }
@@ -429,6 +429,7 @@ let OperatorService = class OperatorService {
429
429
  throw new Error('This session is running; its status can be changed once it has stopped.');
430
430
  }
431
431
  return await this.store.updateSession(id, (s) => {
432
+ const before = { model: s.model, manualModel: s.manualModel };
432
433
  if (patch.name !== undefined)
433
434
  s.name = patch.name.trim() || s.name;
434
435
  if (patch.active === true)
@@ -443,6 +444,16 @@ let OperatorService = class OperatorService {
443
444
  // Chosen on the session's page: the operator's own word, which outranks Settings.
444
445
  s.modelSource = s.model ? 'operator' : undefined;
445
446
  }
447
+ if (typeof patch.manualModel === 'boolean') {
448
+ if (patch.manualModel)
449
+ s.manualModel = true;
450
+ else
451
+ delete s.manualModel;
452
+ }
453
+ // Another choice of model: what was set by hand in the conversation is not what is asked for any more.
454
+ if ((patch.model !== undefined || typeof patch.manualModel === 'boolean') && (s.model !== before.model || !!s.manualModel !== !!before.manualModel)) {
455
+ delete s.modelByHand;
456
+ }
446
457
  // The same for the group: clearing it gives this session its conversation back. It does
447
458
  // not move the conversation it is already in; that history is where it is.
448
459
  if (patch.conversationGroup !== undefined)
@@ -1479,8 +1490,9 @@ let OperatorService = class OperatorService {
1479
1490
  await this.store.updateSession(sessionId, (s) => {
1480
1491
  s.status = 'stopping';
1481
1492
  });
1482
- // The running step is cut off, not waited for: said as it is (live run 2026-10-03).
1483
- this.bus.publish({ sessionId, type: 'stop-requested', level: 'warn', message: 'stopping now: nothing more is sent, and a step still running is cut off' });
1493
+ // The running step is cut off, not waited for: said as it is (live run 2026-10-03). An answer the chat is writing
1494
+ // is waited for, so the conversation is left whole; the choice of model and the sign-in end at once (2026-10-17).
1495
+ this.bus.publish({ sessionId, type: 'stop-requested', level: 'warn', message: 'stopping now: nothing more is sent, a step still running is cut off, and an answer Copilot is writing is waited for first' });
1484
1496
  return { stopping: true };
1485
1497
  }
1486
1498
  // --- running several sessions in turn -------------------------------------------------
@@ -2314,7 +2326,9 @@ let OperatorService = class OperatorService {
2314
2326
  s.vcs = { ...(s.vcs ?? DEFAULT_VCS), enabled: false, repoDir: '' };
2315
2327
  s.projectDir = ws.dir;
2316
2328
  // The model chosen in the chat for this conversation: the operator's word, which outranks Settings.
2317
- if (input.model?.trim()) {
2329
+ if (input.manualModel)
2330
+ s.manualModel = true;
2331
+ else if (input.model?.trim()) {
2318
2332
  s.model = input.model.trim();
2319
2333
  s.modelSource = 'operator';
2320
2334
  }
@@ -111,14 +111,16 @@ export async function startApi(opts = {}) {
111
111
  /*
112
112
  * A page whose name is also a folder of pages: `/sessions` is `sessions.html`, and `sessions/` holds
113
113
  * `view.html` (2026-10-14, when the list moved there). The static server finds the folder first and
114
- * redirects to it, where there is no page; the page is served instead.
114
+ * redirects to it, where there is no page; the page is served instead. Named from the interface's own
115
+ * folder: a whole path is refused (404) when any folder in it starts with a dot, as one under
116
+ * `.claude\worktrees` or pnpm's `node_modules\.pnpm` does (2026-10-17).
115
117
  */
116
118
  const root = webDir;
117
119
  app.use((req, res, next) => {
118
120
  if ((req.method === 'GET' || req.method === 'HEAD') && /^\/[a-z0-9-]+$/i.test(req.path)) {
119
- const page = join(root, `${req.path.slice(1)}.html`);
120
- if (existsSync(page) && existsSync(join(root, req.path.slice(1)))) {
121
- res.sendFile(page);
121
+ const name = req.path.slice(1);
122
+ if (existsSync(join(root, `${name}.html`)) && existsSync(join(root, name))) {
123
+ res.sendFile(`${name}.html`, { root });
122
124
  return;
123
125
  }
124
126
  }
@@ -119,8 +119,10 @@ export const RunConfigSchema = z.object({
119
119
  * Choose the model by hand (operator's workaround, 2026-10-06): at the start of a run, and of a review's
120
120
  * conversation, the runner does not touch the picker; a card in the UI asks the operator to choose the
121
121
  * model in the Copilot window and press "Ready". A conversation already on the model is not asked about.
122
+ * On by default since 2026-10-17 (operator: "leave the automatic choice for now; make it work with the
123
+ * user choosing it by hand, and test the bot itself"); off, the runner chooses the model itself.
122
124
  */
123
- manualModel: z.boolean().default(false),
125
+ manualModel: z.boolean().default(true),
124
126
  replyTimeoutSec: z.number().int().positive().default(900),
125
127
  signInTimeoutSec: z.number().int().positive().default(900),
126
128
  humanWaitSec: z.number().int().positive().default(900),
@@ -13,7 +13,7 @@
13
13
  import { createHash } from 'node:crypto';
14
14
  import { readFile, mkdir, writeFile, appendFile } from 'node:fs/promises';
15
15
  import { join, resolve } from 'node:path';
16
- import { buttonShows } from '../transport/modelMatch.js';
16
+ import { buttonShows, normModel } from '../transport/modelMatch.js';
17
17
  import { createTransport, isReplyTimeout } from '../transport/chatTransport.js';
18
18
  import { buildChatName, chatCode, loadPointer, savePointer } from '../transport/chatSession.js';
19
19
  import { parseReply, formatErrorMessage, findLikelyDamage, damageGuidance } from '../protocol/parser.js';
@@ -313,7 +313,9 @@ export function speakFor(transport, sessionId) {
313
313
  if (speaker)
314
314
  speaker.id = sessionId;
315
315
  }
316
- export async function openBrowser(cfg, bus, transportDir, sessionId) {
316
+ export async function openBrowser(cfg, bus, transportDir, sessionId,
317
+ /** The run's Stop: a sign-in still awaited ends with it. */
318
+ signal) {
317
319
  const speaker = { id: sessionId };
318
320
  const transport = createTransport({
319
321
  profileDir: cfg.resolved.profileDir,
@@ -358,7 +360,7 @@ export async function openBrowser(cfg, bus, transportDir, sessionId) {
358
360
  */
359
361
  try {
360
362
  await transport.open();
361
- await transport.ensureSignedIn();
363
+ await transport.ensureSignedIn(undefined, { signal });
362
364
  }
363
365
  catch (e) {
364
366
  await transport.close().catch(() => undefined);
@@ -500,8 +502,8 @@ async function joinGroupConversation(store, session, bus) {
500
502
  return updated;
501
503
  }
502
504
  /** The old shape, kept for the terminal path: open a browser and enter the conversation. */
503
- export async function openSessionTransport(cfg, session, bus, runsDir) {
504
- const transport = await openBrowser(cfg, bus, join(runsDir, '_browser'), session.id);
505
+ export async function openSessionTransport(cfg, session, bus, runsDir, signal) {
506
+ const transport = await openBrowser(cfg, bus, join(runsDir, '_browser'), session.id, signal);
505
507
  await enterSessionConversation(transport, session, { closeOnFailure: true });
506
508
  return transport;
507
509
  }
@@ -529,14 +531,32 @@ export async function openSessionTransport(cfg, session, bus, runsDir) {
529
531
  */
530
532
  export function effectiveModels(session, cfg) {
531
533
  const pick = (own, source, settings) => own && source === 'operator' ? [own, 'session'] : settings ? [settings, 'settings'] : own ? [own, 'plan'] : ['', 'none'];
532
- const [model, modelFrom] = pick((session.model ?? '').trim(), session.modelSource, (cfg.copilot.defaultModel ?? '').trim());
534
+ // Set by hand in the Copilot window: no name is asked for, neither the session's nor the one in Settings.
535
+ const [model, modelFrom] = session.manualModel ? ['', 'none'] : pick((session.model ?? '').trim(), session.modelSource, (cfg.copilot.defaultModel ?? '').trim());
533
536
  const [reviewModel, reviewModelFrom] = pick((session.review?.model ?? '').trim(), session.reviewModelSource, (cfg.copilot.defaultReviewModel ?? '').trim());
534
537
  return { model, reviewModel, modelFrom, reviewModelFrom };
535
538
  }
536
- async function applySessionModel(transport, session, bus, cfg, store, hooks) {
539
+ /**
540
+ * Whether the model of this session's conversation is chosen by hand in the Copilot window: Settings say so for
541
+ * every run, the session says so ("Set the model by hand" in the chat's picker), or it is a chat that names no
542
+ * model and has none from Settings either — its picker shows "by hand" for that, and what it shows is what happens.
543
+ */
544
+ export function modelByHand(session, cfg) {
545
+ if (cfg.copilot.manualModel || session.manualModel)
546
+ return true;
547
+ return session.kind === 'chat' && !effectiveModels(session, cfg).model;
548
+ }
549
+ async function applySessionModel(transport, session, bus, cfg, store, hooks,
550
+ /** Whether the conversation was opened new for this run, rather than one the session already had. */
551
+ fresh = true,
552
+ /** The run's Stop: the picker's waits end with it, and nothing is sent. */
553
+ signal) {
554
+ const stopped = { refused: 'Stopped by the operator while the model was being chosen. Nothing was sent; the tasks stay queued.' };
555
+ if (signal?.aborted)
556
+ return stopped;
537
557
  const { model: wanted, modelFrom } = effectiveModels(session, cfg);
538
558
  const fromSettings = modelFrom === 'settings';
539
- const manual = !!cfg.copilot.manualModel && !!hooks?.askHelp;
559
+ const manual = modelByHand(session, cfg) && !!hooks?.askHelp;
540
560
  if (!wanted && !manual)
541
561
  return {};
542
562
  let result;
@@ -546,18 +566,42 @@ async function applySessionModel(transport, session, bus, cfg, store, hooks) {
546
566
  * on the model — the chat keeps its model — is not asked about; otherwise the card asks for it.
547
567
  */
548
568
  const shown = await transport.currentModel().catch(() => null);
569
+ /*
570
+ * The conversation is "on the model" when the operator set it by hand in it before, for the same name or for
571
+ * none: asked once, at its first run, not at every one (2026-10-17) — the picker button's text could not be
572
+ * relied on at work to say so. A new conversation is asked again, and so is another name asked for.
573
+ */
574
+ const setBefore = session.modelByHand;
575
+ if (!fresh && setBefore && normModel(setBefore.asked ?? '') === normModel(wanted)) {
576
+ bus.publish({ sessionId: session.id, type: 'model-kept-by-hand', level: 'info',
577
+ message: `model: set by hand in this conversation (the picker shows "${shown ?? 'nothing'}"); not asked again`,
578
+ data: { shown, setAt: setBefore.at, shownThen: setBefore.shown, asked: wanted } });
579
+ await store?.updateSession(session.id, (s) => { s.modelInUse = shown ?? undefined; }).catch(() => undefined);
580
+ return { current: shown ?? undefined };
581
+ }
582
+ const why = cfg.copilot.manualModel ? 'Settings ask for the model to be chosen by hand' : 'the session asks for the model to be set by hand';
549
583
  const hand = wanted && buttonShows(shown, wanted)
550
584
  ? { result: { ok: true, current: wanted, by: 'already' }, goOnAsItIs: false }
551
- : await withOperatorHand(transport, wanted, { ok: false, current: shown, reason: 'Settings ask for the model to be chosen by hand' }, hooks, session.id, bus, true);
585
+ : await withOperatorHand(transport, wanted, { ok: false, current: shown, reason: why }, hooks, session.id, bus, true);
552
586
  if (!wanted) {
553
587
  const now = await transport.currentModel().catch(() => null);
554
588
  if (hand.result.ok || hand.goOnAsItIs) {
555
- await store?.updateSession(session.id, (s) => { s.modelInUse = now ?? undefined; }).catch(() => undefined);
589
+ await store
590
+ ?.updateSession(session.id, (s) => {
591
+ s.modelInUse = now ?? undefined;
592
+ s.modelByHand = { at: new Date().toISOString(), shown: now };
593
+ })
594
+ .catch(() => undefined);
556
595
  return { current: now ?? undefined };
557
596
  }
558
597
  return { refused: 'The model was to be chosen by hand, and the operator stopped the run. Nothing was sent.' };
559
598
  }
560
599
  result = hand.result;
600
+ // Set by hand in this conversation: the next run that comes back to it is not asked again.
601
+ if (result.ok || hand.goOnAsItIs) {
602
+ const now = await transport.currentModel().catch(() => null);
603
+ await store?.updateSession(session.id, (s) => { s.modelByHand = { at: new Date().toISOString(), shown: now, asked: wanted }; }).catch(() => undefined);
604
+ }
561
605
  if (hand.goOnAsItIs) {
562
606
  bus.publish({ sessionId: session.id, type: 'model-selected', level: 'warn', message: `model: ${result.current ?? 'unknown'} (chosen by hand; not "${wanted}")`, data: { asked: wanted, current: result.current, ok: false, by: 'hand' } });
563
607
  return { current: result.current ?? undefined };
@@ -565,11 +609,16 @@ async function applySessionModel(transport, session, bus, cfg, store, hooks) {
565
609
  }
566
610
  else {
567
611
  const locator = await hooks?.locate?.(wanted).catch(() => undefined);
568
- result = await transport.selectModel(wanted, { locator }).catch((e) => ({
612
+ result = await transport.selectModel(wanted, { locator, signal }).catch((e) => ({
569
613
  ok: false,
570
614
  current: null,
571
615
  reason: e.message,
572
616
  }));
617
+ // Not put to the operator on a card: they asked for the run to stop.
618
+ if (signal?.aborted) {
619
+ bus.publish({ sessionId: session.id, type: 'model-not-selected', level: 'info', message: `stopped by the operator while "${wanted}" was being chosen; nothing was sent`, data: { asked: wanted, stopped: true } });
620
+ return stopped;
621
+ }
573
622
  }
574
623
  const hand = await withOperatorHand(transport, wanted, result, hooks, session.id, bus, false);
575
624
  result = hand.result;
@@ -1433,7 +1482,7 @@ export async function runTask(transport, session, task, deps) {
1433
1482
  * record would go on naming the model the session asked for. Applied again here, as the
1434
1483
  * fresh-chat retry in `runSession` does for the same reason.
1435
1484
  */
1436
- const modelNow = await applySessionModel(transport, session, bus, cfg, store, deps.models);
1485
+ const modelNow = await applySessionModel(transport, session, bus, cfg, store, deps.models, !chat, deps.signal);
1437
1486
  if (effectiveModels(session, cfg).model) {
1438
1487
  await store.updateSession(session.id, (s) => {
1439
1488
  s.modelInUse = modelNow.current;
@@ -1923,7 +1972,7 @@ export async function runTask(transport, session, task, deps) {
1923
1972
  }
1924
1973
  else {
1925
1974
  const reviewLocator = await deps.models?.locate?.(model).catch(() => undefined);
1926
- picked = await transport.selectModel(model, { locator: reviewLocator }).catch((e) => ({ ok: false, current: null, reason: e.message }));
1975
+ picked = await transport.selectModel(model, { locator: reviewLocator, signal }).catch((e) => ({ ok: false, current: null, reason: e.message }));
1927
1976
  }
1928
1977
  const renamed = await followPageModels('review', model, picked, session, store, deps.models, effectiveModels(session, cfg).reviewModelFrom);
1929
1978
  if (renamed)
@@ -2935,19 +2984,21 @@ export async function runSession(sessionId, deps) {
2935
2984
  }
2936
2985
  else {
2937
2986
  await deps.beforeBrowser?.();
2938
- transport = await openSessionTransport(cfg, session, bus, sessionRunsDir);
2987
+ transport = await openSessionTransport(cfg, session, bus, sessionRunsDir, deps.signal);
2939
2988
  }
2940
2989
  const chat = transport;
2941
2990
  // The picker belongs to the conversation, so the session's choice is applied once, here,
2942
- // before the first task goes out. What the chat ended up on is recorded either way.
2943
- const modelInUse = await applySessionModel(chat, session, bus, cfg, store, deps.models);
2991
+ // before the first task goes out. What the chat ended up on is recorded either way. A conversation
2992
+ // the session already had was reopened above; one it did not have was opened new.
2993
+ const modelInUse = await applySessionModel(chat, session, bus, cfg, store, deps.models, !session.chat, deps.signal);
2944
2994
  if (effectiveModels(session, cfg).model) {
2945
2995
  await store.updateSession(sessionId, (s) => {
2946
2996
  s.modelInUse = modelInUse.current;
2947
2997
  });
2948
2998
  }
2949
- // Refused before a task is marked started: its tasks stay queued, and the run says why.
2950
- if (modelInUse.refused)
2999
+ // Refused before a task is marked started: its tasks stay queued, and the run says why. Stopped, the loop
3000
+ // below ends before its first task.
3001
+ if (modelInUse.refused && !deps.signal?.aborted)
2951
3002
  throw new Error(modelInUse.refused);
2952
3003
  for (const queuedTask of queued) {
2953
3004
  if (deps.signal?.aborted)
@@ -3063,7 +3114,7 @@ export async function runSession(sessionId, deps) {
3063
3114
  * it was the model the session asked for. The review has always done this for its own
3064
3115
  * fresh conversations a few hundred lines up; this path simply never did.
3065
3116
  */
3066
- const freshModel = await applySessionModel(chat, session, bus, cfg, store, deps.models);
3117
+ const freshModel = await applySessionModel(chat, session, bus, cfg, store, deps.models, true, deps.signal);
3067
3118
  if (effectiveModels(session, cfg).model) {
3068
3119
  session = await store.updateSession(sessionId, (s) => {
3069
3120
  s.modelInUse = freshModel.current;
@@ -3127,8 +3178,17 @@ export async function runSession(sessionId, deps) {
3127
3178
  }
3128
3179
  }
3129
3180
  catch (e) {
3130
- bus.publish({ sessionId, type: 'session-error', level: 'error', message: e.message });
3131
- throw e;
3181
+ /*
3182
+ * Stopped while the browser was opening, the sign-in awaited or the model chosen: what the operator asked for,
3183
+ * not a failure. Said as a stop, and the tasks stay queued (2026-10-17).
3184
+ */
3185
+ if (deps.signal?.aborted && ran === 0) {
3186
+ bus.publish({ sessionId, type: 'session-stopped', level: 'info', message: `stopped by the operator before the first task was sent; the tasks stay queued (${e.message})` });
3187
+ }
3188
+ else {
3189
+ bus.publish({ sessionId, type: 'session-error', level: 'error', message: e.message });
3190
+ throw e;
3191
+ }
3132
3192
  }
3133
3193
  finally {
3134
3194
  // A borrowed window belongs to whoever opened it and stays open for the next session.
@@ -118,6 +118,16 @@ export class SendRejectedError extends Error {
118
118
  this.name = 'SendRejectedError';
119
119
  }
120
120
  }
121
+ /**
122
+ * The run was stopped while the transport was in one of its long waits: the model picker's looks and pauses, or
123
+ * the sign-in. Thrown by `hold` and the sign-in wait, so a Stop is not left waiting minutes for them to end.
124
+ */
125
+ export class StoppedByOperator extends Error {
126
+ constructor(message = 'stopped by the operator') {
127
+ super(message);
128
+ this.name = 'StoppedByOperator';
129
+ }
130
+ }
121
131
  /**
122
132
  * Takes the copy button off the operator's clipboard.
123
133
  *
@@ -205,9 +215,27 @@ export class CopilotTransport {
205
215
  context = null;
206
216
  page = null;
207
217
  lock = null;
218
+ /**
219
+ * The run's Stop, while a choice of model is being made (see `selectModel`). The picker's waits add up to minutes
220
+ * — six attempts, each looking up to twenty seconds for each of its rows, in four ways — and a Stop pressed in them
221
+ * did nothing until they ended (2026-10-17: "the Stop button seems not to work").
222
+ */
223
+ stop = null;
208
224
  constructor(opts) {
209
225
  this.opts = opts;
210
226
  }
227
+ /** A pause of the model picker that ends early, with `StoppedByOperator`, once the run is stopped. */
228
+ async hold(ms) {
229
+ const until = Date.now() + ms;
230
+ for (;;) {
231
+ if (this.stop?.aborted)
232
+ throw new StoppedByOperator();
233
+ const left = until - Date.now();
234
+ if (left <= 0)
235
+ return;
236
+ await this.p.waitForTimeout(Math.min(250, left));
237
+ }
238
+ }
211
239
  emit(event, detail) {
212
240
  this.opts.onEvent?.(event, detail);
213
241
  }
@@ -269,6 +297,25 @@ export class CopilotTransport {
269
297
  composer() {
270
298
  return this.p.locator(Css.composer).first();
271
299
  }
300
+ /** Whether the composer shows within `ms`, looked for a second at a time; a Stop ends the wait with `StoppedByOperator`. */
301
+ async composerWithin(ms, signal, stopped) {
302
+ const until = Date.now() + ms;
303
+ for (;;) {
304
+ if (signal?.aborted)
305
+ throw new StoppedByOperator(stopped);
306
+ try {
307
+ await this.composer().waitFor({ state: 'visible', timeout: Math.max(1, Math.min(1_000, until - Date.now())) });
308
+ return true;
309
+ }
310
+ catch (e) {
311
+ // Only "not yet": a closed window or page ends the wait as it always did, at once.
312
+ if (e.name !== 'TimeoutError')
313
+ throw e;
314
+ if (Date.now() >= until)
315
+ return false;
316
+ }
317
+ }
318
+ }
272
319
  /**
273
320
  * Which Copilot we actually landed on.
274
321
  *
@@ -442,11 +489,19 @@ Current URL: ${url}`);
442
489
  * Opens the chat and, if the tenant has signed us out, waits for the human. The bot never
443
490
  * types credentials; it only waits for the composer to appear.
444
491
  */
445
- async ensureSignedIn(url = this.opts.chatUrl) {
492
+ async ensureSignedIn(url = this.opts.chatUrl, opts = {}) {
446
493
  await this.p.goto(url, { waitUntil: 'domcontentloaded' });
447
- if (!(await this.isChatReady(15_000))) {
494
+ /*
495
+ * Looked for a second at a time, so a Stop pressed while the page loads or the operator has not signed in yet
496
+ * ends the wait at once, rather than after the whole sign-in timeout, fifteen minutes by default (2026-10-17).
497
+ */
498
+ const stoppedHere = 'stopped by the operator while waiting for the sign-in';
499
+ if (!(await this.composerWithin(15_000, opts.signal, stoppedHere))) {
448
500
  this.emit('sign-in-required', { url: this.p.url() });
449
- await this.composer().waitFor({ state: 'visible', timeout: this.opts.signInTimeoutMs });
501
+ if (!(await this.composerWithin(this.opts.signInTimeoutMs, opts.signal, stoppedHere))) {
502
+ throw new Error(`The sign-in was not completed within ${Math.round(this.opts.signInTimeoutMs / 1000)} s (Settings → copilot.signInTimeoutSec). ` +
503
+ 'Sign in in the open Edge window, then start again.');
504
+ }
450
505
  this.emit('signed-in');
451
506
  }
452
507
  await this.clearBlockers();
@@ -600,11 +655,11 @@ Current URL: ${url}`);
600
655
  async dismissOpenMenu() {
601
656
  try {
602
657
  await this.p.keyboard.press('Escape');
603
- await this.p.waitForTimeout(150);
658
+ await this.hold(150);
604
659
  const open = this.p.locator('[role="menu"]');
605
660
  if ((await open.count()) > 0) {
606
661
  await this.p.mouse.click(4, 4);
607
- await this.p.waitForTimeout(150);
662
+ await this.hold(150);
608
663
  }
609
664
  }
610
665
  catch {
@@ -650,7 +705,7 @@ Current URL: ${url}`);
650
705
  const byLabel = this.p.getByRole('button', { name: Model.buttonLabel, exact: false });
651
706
  if ((await byLabel.count().catch(() => 0)) > 0)
652
707
  return byLabel.first();
653
- await this.p.waitForTimeout(500);
708
+ await this.hold(500);
654
709
  } while (Date.now() < deadline);
655
710
  return null;
656
711
  }
@@ -834,7 +889,7 @@ Current URL: ${url}`);
834
889
  const fresh = rows.find((r) => !before.has(r.menuOf) && r.menuOf !== row.elId);
835
890
  if (fresh && (!row.elId || Date.now() - started > 1_500))
836
891
  return fresh.menuOf;
837
- await this.p.waitForTimeout(200);
892
+ await this.hold(200);
838
893
  } while (Date.now() - started < ms);
839
894
  return null;
840
895
  };
@@ -879,7 +934,7 @@ Current URL: ${url}`);
879
934
  }
880
935
  if (first)
881
936
  return first;
882
- await this.p.waitForTimeout(200);
937
+ await this.hold(200);
883
938
  } while (Date.now() < deadline);
884
939
  return null;
885
940
  }
@@ -938,7 +993,7 @@ Current URL: ${url}`);
938
993
  return { ok: true, current: name, by: 'locator' };
939
994
  }
940
995
  await this.press(found.row).catch(() => undefined);
941
- await this.p.waitForTimeout(800);
996
+ await this.hold(800);
942
997
  // Whatever the click did, the menu is not left open over the chat.
943
998
  await this.closeMenu();
944
999
  const again = await this.openToModel(name, group);
@@ -964,7 +1019,7 @@ Current URL: ${url}`);
964
1019
  const before = await this.currentModel();
965
1020
  const textOf = async (el) => (((await el.innerText().catch(() => '')) ?? '').split('\n')[0] ?? '').trim();
966
1021
  // A fixed pause after every opening and every press (see `ModelPicking`); the checks give it less.
967
- const settle = () => this.p.waitForTimeout(this.opts.modelSettleMs ?? ModelPicking.settleMs);
1022
+ const settle = () => this.hold(this.opts.modelSettleMs ?? ModelPicking.settleMs);
968
1023
  const pause = this.opts.modelBeforePressMs ?? ModelPicking.beforePressMs;
969
1024
  const poll = this.opts.modelPollMs ?? ModelPicking.pollMs;
970
1025
  const appear = this.opts.modelAppearMs ?? ModelPicking.appearMs;
@@ -987,7 +1042,7 @@ Current URL: ${url}`);
987
1042
  let el = await find();
988
1043
  while (!el && Date.now() < deadline) {
989
1044
  this.emit('model-step', { step: 'not there yet, waiting', what: label, look: looks, waitMs: poll });
990
- await this.p.waitForTimeout(poll);
1045
+ await this.hold(poll);
991
1046
  looks += 1;
992
1047
  el = await find();
993
1048
  }
@@ -996,7 +1051,7 @@ Current URL: ${url}`);
996
1051
  return null;
997
1052
  }
998
1053
  this.emit('model-step', { step: 'there, pausing before the press', what: label, look: looks, text: await textOf(el), pauseMs: pause });
999
- await this.p.waitForTimeout(pause);
1054
+ await this.hold(pause);
1000
1055
  await picture(`before-${label}`);
1001
1056
  return el;
1002
1057
  };
@@ -1035,7 +1090,7 @@ Current URL: ${url}`);
1035
1090
  return { row };
1036
1091
  }
1037
1092
  this.emit('model-step', { step: 'group not opened', how });
1038
- await this.p.waitForTimeout(pause);
1093
+ await this.hold(pause);
1039
1094
  }
1040
1095
  await this.captureMenu('select-failed', await this.readMenuRows().catch(() => [])).catch(() => undefined);
1041
1096
  return { problem: `"${target.model}" did not appear after opening "${target.group.name}" every way (${target.xpath}); the menu is kept as models-select-failed.html/.png` };
@@ -1083,14 +1138,14 @@ Current URL: ${url}`);
1083
1138
  // The chosen model's own name: "Sonnet" alone would stop at "Sonnet 5.5" when "Sonnet 5" is asked for.
1084
1139
  if (now.radio && (sameModel(line, name) || containsModel(now.text, name))) {
1085
1140
  this.emit('model-step', { step: 'model reached by the keyboard, pausing before Enter', attempt, text: line, presses, pauseMs: pause });
1086
- await this.p.waitForTimeout(pause);
1141
+ await this.hold(pause);
1087
1142
  await picture('before-enter');
1088
1143
  await this.p.keyboard.press('Enter');
1089
1144
  await settle();
1090
1145
  return true;
1091
1146
  }
1092
1147
  await this.p.keyboard.press('ArrowDown');
1093
- await this.p.waitForTimeout(400);
1148
+ await this.hold(400);
1094
1149
  }
1095
1150
  this.emit('model-step', { step: 'model not reached by the keyboard', attempt });
1096
1151
  await this.closeMenu();
@@ -1142,7 +1197,7 @@ Current URL: ${url}`);
1142
1197
  await found.row.evaluate((el) => el.click(), undefined, { timeout: 3_000 }).catch(() => undefined);
1143
1198
  await settle();
1144
1199
  if ((await this.modelMenuOpen()) && !(await checked(found.row))) {
1145
- await this.p.waitForTimeout(pause);
1200
+ await this.hold(pause);
1146
1201
  await found.row.click({ timeout: 3_000 }).catch(() => undefined);
1147
1202
  await settle();
1148
1203
  }
@@ -1239,7 +1294,7 @@ Current URL: ${url}`);
1239
1294
  if (!(await this.modelMenuOpen()))
1240
1295
  return;
1241
1296
  await act().catch(() => undefined);
1242
- await this.p.waitForTimeout(250);
1297
+ await this.hold(250);
1243
1298
  if (!(await this.modelMenuOpen())) {
1244
1299
  if (how !== 'escape')
1245
1300
  this.emit('model-menu-closed', { how });
@@ -1262,7 +1317,7 @@ Current URL: ${url}`);
1262
1317
  return one;
1263
1318
  }
1264
1319
  }
1265
- await this.p.waitForTimeout(250);
1320
+ await this.hold(250);
1266
1321
  }
1267
1322
  return null;
1268
1323
  }
@@ -1277,6 +1332,25 @@ Current URL: ${url}`);
1277
1332
  * caller is told what the chat is actually on.
1278
1333
  */
1279
1334
  async selectModel(name, opts = {}) {
1335
+ if (opts.signal?.aborted)
1336
+ return { ok: false, current: null, reason: 'stopped by the operator' };
1337
+ this.stop = opts.signal ?? null;
1338
+ try {
1339
+ return await this.chooseModel(name, opts);
1340
+ }
1341
+ catch (e) {
1342
+ if (!(e instanceof StoppedByOperator))
1343
+ throw e;
1344
+ this.stop = null;
1345
+ this.emit('model-step', { step: 'stopped by the operator', model: name });
1346
+ await this.closeMenu().catch(() => undefined);
1347
+ return { ok: false, current: await this.currentModel().catch(() => null), reason: 'stopped by the operator' };
1348
+ }
1349
+ finally {
1350
+ this.stop = null;
1351
+ }
1352
+ }
1353
+ async chooseModel(name, opts) {
1280
1354
  const button = await this.resolveModelButton();
1281
1355
  if (!button)
1282
1356
  return { ok: false, current: null, reason: 'This chat does not show a model picker.' };