@floless/app 0.151.0 → 0.152.1

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.
package/dist/web/guide.js CHANGED
@@ -20,6 +20,9 @@
20
20
  };
21
21
  const FLOLESS_LABEL = { projects: 'Projects', workflows: 'Workflows', agents: 'Agents', routines: 'Routines', tools: 'Tools' };
22
22
 
23
+ // A click or key press this recently means the person is mid-action: the launch question waits.
24
+ const QUIET_AFTER_INTERACTION_MS = 4000;
25
+
23
26
  const state = {
24
27
  sessionReady: false,
25
28
  status: null,
@@ -32,11 +35,23 @@
32
35
  banner: '',
33
36
  returnFocus: null,
34
37
  lookSeq: 0,
38
+ closeSeq: 0, // bumped when the question closes; a Turn on in progress checks it between steps
35
39
  launchAsked: false,
40
+ lastInteractionAt: 0,
41
+ briefing: null, // #2053: the morning briefing as the server sees it
42
+ briefingAsk: false, // #2053: the question's "Also brief me each morning" switch (off by default)
43
+ // #2054: the look is taken only for something the person did — opened the preview, pressed Turn on, or opened Start
44
+ // the Guide once it is on. Until then nothing is looked at; `lookBecause` is the reason given, reused for a re-look.
45
+ lookBecause: null, // null | 'opened-preview' | 'turning-on' | 'starting'
46
+ previewOpen: false, // the "Preview exactly what will be sent" disclosure, kept open across repaints
47
+ setAside: [], // #2054: next moves this account set aside with Not now (the server remembers them)
36
48
  };
37
49
 
50
+ for (const type of ['pointerdown', 'keydown']) document.addEventListener(type, () => { state.lastInteractionAt = Date.now(); }, true);
51
+
38
52
  const $modal = document.getElementById('guide-agent-modal');
39
53
  const $title = document.getElementById('guide-modal-title');
54
+ let guideFlo = null; // #2140: the Guide's face, mounted on first opening
40
55
  const $sub = document.getElementById('guide-modal-sub');
41
56
  const $body = document.getElementById('guide-modal-body');
42
57
  const $live = document.getElementById('guide-modal-live');
@@ -85,6 +100,8 @@
85
100
  async function loadStatus() {
86
101
  const body = await api('/api/chat/guide');
87
102
  state.status = body.guide;
103
+ if (body.guide && 'briefing' in body.guide) setBriefing(body.guide.briefing);
104
+ if (Array.isArray(body.guide?.setAside)) setSetAside(body.guide.setAside);
88
105
  return state.status;
89
106
  }
90
107
 
@@ -132,31 +149,41 @@
132
149
  await showModal(status.consent?.choice === 'on' ? 'start' : 'consent');
133
150
  }
134
151
 
135
- /** First launch: ask once, after boot, never over another dialog. Not now and Turn off are never asked again here. */
152
+ /**
153
+ * First launch: ask once, after boot, never over another dialog. Not now and Turn off are never asked again here.
154
+ *
155
+ * One loop, no give-up: read the answer; if the person is busy, wait and read it AGAIN; ask only straight after a
156
+ * fresh read that finds them free. Busy means a dialog is up, the page has lost focus (a native file picker takes
157
+ * it while it is open, and no dialog exists yet at that moment) or the person just clicked or typed. A failed
158
+ * read is not an answer, so it is retried rather than spent, and a long wait never uses the question up.
159
+ */
136
160
  async function maybeAskOnLaunch() {
137
161
  if (state.launchAsked) return;
138
162
  state.launchAsked = true;
139
- let status;
140
- try { status = await loadStatus(); }
141
- catch (error) {
142
- // Not this time: the next start of FloLess asks again.
143
- console.warn('[guide] could not check whether to ask about the Guide:', error);
144
- state.launchAsked = false;
145
- return;
146
- }
147
- if (!status.signedIn || !status.ask) return;
148
- const waitForQuiet = async () => {
149
- for (let tries = 0; tries < 120; tries += 1) {
150
- if (!document.querySelector('.modal-backdrop.show')) return true;
151
- await new Promise((resolve) => setTimeout(resolve, 1000));
163
+ const busy = () => Boolean(document.querySelector('.modal-backdrop.show'))
164
+ || (typeof document.hasFocus === 'function' && !document.hasFocus())
165
+ || Date.now() - state.lastInteractionAt < QUIET_AFTER_INTERACTION_MS;
166
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
167
+ let finished = false;
168
+ try {
169
+ for (;;) {
170
+ let status;
171
+ try { status = await loadStatus(); }
172
+ catch (error) {
173
+ console.warn('[guide] could not check whether to ask about the Guide; trying again shortly:', error);
174
+ await sleep(30_000);
175
+ continue;
176
+ }
177
+ // Signed out, or answered meanwhile (≡ → Guide, Ask the Guide): nothing more to ask.
178
+ if (!status.signedIn || !status.ask || $modal.classList.contains('show')) { finished = true; return; }
179
+ // Free right after the read: ask now. Otherwise wait for quiet and read the answer again.
180
+ if (!busy()) { finished = true; await showModal('consent'); return; }
181
+ while (busy()) await sleep(1000);
152
182
  }
153
- return false;
154
- };
155
- if (!(await waitForQuiet())) return;
156
- // The person may have answered meanwhile (≡ → Guide, Ask the Guide): never ask again after an answer.
157
- try { status = await loadStatus(); } catch { return; }
158
- if (!status.signedIn || !status.ask || $modal.classList.contains('show')) return;
159
- await showModal('consent');
183
+ } finally {
184
+ // Only an unexpected failure leaves the question unspent; every normal exit has answered or asked it.
185
+ if (!finished) state.launchAsked = false;
186
+ }
160
187
  }
161
188
 
162
189
  // ── the modal ─────────────────────────────────────────────────────────────────────────────────────────────────
@@ -194,22 +221,48 @@
194
221
  return details;
195
222
  }
196
223
 
224
+ /** The preview's one disclosure. Opening it is what asks FloLess to look, the first time (#2054). */
225
+ function previewDisclosure(...content) {
226
+ const disclosure = el('details', 'guide-preview-disclosure');
227
+ const open = el('summary', '', 'Preview exactly what will be sent');
228
+ open.dataset.commandId = 'shell.guide-preview-open';
229
+ disclosure.append(open, ...content);
230
+ disclosure.open = state.previewOpen || Boolean(state.banner);
231
+ disclosure.addEventListener('toggle', () => {
232
+ state.previewOpen = disclosure.open;
233
+ if (disclosure.open && !state.lookBecause) void takeLook('opened-preview');
234
+ });
235
+ return disclosure;
236
+ }
237
+
197
238
  function renderPreview() {
198
239
  const wrap = el('div', 'guide-preview');
199
240
  const look = state.preview?.look;
241
+ if (!look && !state.lookBecause) {
242
+ // #2054: nothing has been looked at yet, and nothing is until the person opens this or presses Turn on.
243
+ const pending = el('p', 'guide-switch-help guide-preview-pending', 'FloLess hasn’t looked at anything yet. It only looks when you open the preview or turn the Guide on.');
244
+ pending.id = 'guide-preview-pending';
245
+ const disclosure = previewDisclosure();
246
+ disclosure.querySelector('summary').setAttribute('aria-describedby', pending.id);
247
+ wrap.append(pending, disclosure);
248
+ return wrap;
249
+ }
200
250
  if (!look) {
201
251
  const line = el('p', 'guide-preview-loading');
202
252
  line.textContent = state.previewError || 'Looking at this computer… this takes a few seconds.';
203
- if (!state.previewError) line.prepend(el('span', 'ws-source-spin'));
204
- wrap.append(line);
253
+ if (state.previewError) line.setAttribute('role', 'alert');
254
+ else { line.prepend(el('span', 'ws-source-spin')); wrap.setAttribute('aria-busy', 'true'); }
255
+ const parts = [line];
205
256
  if (state.previewError) {
206
257
  const again = el('button', '', 'Try again');
207
258
  again.type = 'button';
208
259
  again.dataset.commandId = 'shell.guide-preview-retry';
209
260
  again.dataset.tip = 'Looks at this computer again.';
210
- again.addEventListener('click', () => { void takeLook(); });
211
- wrap.append(again);
261
+ again.addEventListener('click', () => { void takeLook(state.lookBecause); });
262
+ parts.push(again);
212
263
  }
264
+ // Opened by the person: the progress shows where they asked for it. Taken for Turn on with it closed: shown above it.
265
+ if (state.previewOpen) wrap.append(previewDisclosure(...parts)); else wrap.append(...parts);
213
266
  return wrap;
214
267
  }
215
268
  const counts = look.recentFiles?.countsByType || {};
@@ -248,12 +301,8 @@
248
301
  return details;
249
302
  })(),
250
303
  );
251
- const disclosure = el('details', 'guide-preview-disclosure');
252
- const open = el('summary', '', 'Preview exactly what will be sent');
253
- open.dataset.commandId = 'shell.guide-preview-open';
254
- disclosure.append(open, region,
304
+ const disclosure = previewDisclosure(region,
255
305
  el('p', 'guide-preview-foot', 'Sent as plain facts, marked as data — never as instructions.'));
256
- if (state.banner) disclosure.open = true;
257
306
  wrap.append(summary, disclosure);
258
307
  return wrap;
259
308
  }
@@ -266,7 +315,7 @@
266
315
  input.checked = state.share[key];
267
316
  input.dataset.commandId = `shell.guide-share-${key === 'windowTitles' ? 'window-titles' : 'recent-files'}`;
268
317
  input.setAttribute('aria-describedby', `${id}-help`);
269
- input.addEventListener('change', () => { state.share = { ...state.share, [key]: input.checked }; void takeLook(); });
318
+ input.addEventListener('change', () => { state.share = { ...state.share, [key]: input.checked }; relook(); });
270
319
  toggle.append(input, el('span', 'rtn-toggle-track'));
271
320
  const text = el('div', 'guide-switch-text');
272
321
  const name = el('label', 'guide-switch-label', label); name.htmlFor = id;
@@ -290,7 +339,7 @@
290
339
  radio.type = 'radio'; radio.name = 'guide-provider'; radio.value = provider;
291
340
  radio.checked = provider === state.provider;
292
341
  radio.dataset.commandId = `shell.guide-provider#${PROVIDER_LABEL[provider]}`;
293
- radio.addEventListener('change', () => { state.provider = provider; void takeLook(); });
342
+ radio.addEventListener('change', () => { state.provider = provider; relook(); });
294
343
  option.append(radio, document.createTextNode(` ${PROVIDER_LABEL[provider]}`));
295
344
  group.append(option);
296
345
  }
@@ -366,6 +415,8 @@
366
415
  providerChoice(),
367
416
  renderPreview(),
368
417
  );
418
+ // #2053: one more switch, off by default, close to the button that agrees to it. Not shown once it is already on.
419
+ if (state.briefing?.on !== true) $body.append(briefingAskRow());
369
420
  if (state.banner) {
370
421
  const banner = el('p', 'guide-banner', state.banner);
371
422
  banner.setAttribute('role', 'status');
@@ -379,20 +430,35 @@
379
430
  if (state.mode === 'consent') $foot.textContent = 'You can turn the Guide on later: ≡ menu → Guide.';
380
431
  }
381
432
 
382
- async function takeLook() {
433
+ /**
434
+ * Take the look, for the reason the person gave by what they did (#2054). Resolves true when this look landed; false
435
+ * when it failed (the reason is shown where the preview goes) or a newer look replaced it.
436
+ */
437
+ async function takeLook(because) {
383
438
  const seq = ++state.lookSeq;
439
+ state.lookBecause = because;
384
440
  state.preview = null; state.previewError = '';
385
441
  paint();
442
+ let landed = false;
386
443
  try {
387
- const body = await api('/api/chat/guide/preview', { provider: state.provider, share: state.share });
388
- if (seq !== state.lookSeq) return;
444
+ const body = await api('/api/chat/guide/preview', { provider: state.provider, share: state.share, because });
445
+ if (seq !== state.lookSeq) return false;
389
446
  state.preview = body.preview;
447
+ landed = true;
390
448
  $live.textContent = 'Preview updated.';
391
449
  } catch (error) {
392
- if (seq !== state.lookSeq) return;
393
- state.previewError = `FloLess couldn’t look at this computer: ${error.message}`;
450
+ if (seq !== state.lookSeq) return false;
451
+ // Pressed Turn on and the look failed: say what that means for the Guide, not only what went wrong.
452
+ const off = because === 'turning-on' && state.mode === 'consent' ? ' The Guide is still off. Try again, or turn it on later from ≡ → Guide.' : '';
453
+ state.previewError = `FloLess couldn’t look at this computer: ${error.message}${off}`;
394
454
  }
395
455
  if ($modal.classList.contains('show')) paint();
456
+ return landed;
457
+ }
458
+
459
+ /** A switch or the AI changed: look again only if the person already asked for a look; otherwise nothing is taken. */
460
+ function relook() {
461
+ if (state.lookBecause) void takeLook(state.lookBecause);
396
462
  }
397
463
 
398
464
  let keyHandler = null;
@@ -403,10 +469,17 @@
403
469
  if (keyHandler) { $modal.removeEventListener('keydown', keyHandler); keyHandler = null; }
404
470
  state.provider = chooseProvider();
405
471
  state.share = state.status?.consent?.share ? { ...state.status.consent.share } : { windowTitles: true, recentFiles: true };
406
- state.banner = ''; state.busy = false; state.preview = null;
472
+ state.banner = ''; state.busy = false; state.preview = null; state.previewError = ''; state.briefingAsk = false;
473
+ state.lookBecause = null; state.previewOpen = false;
407
474
  state.mode = !state.status?.workspace ? 'folder' : mode;
408
475
  paint();
409
476
  $modal.classList.add('show');
477
+ // #2140: Flo, the Guide's face, tips its hat beside the title as the dialog opens, then holds still. It never sits
478
+ // beside the choice: this is a question about what is sent to the AI, and a mascot by "Turn on" would lean on it.
479
+ if (typeof floAvatar === 'function') {
480
+ if (guideFlo) guideFlo.play();
481
+ else guideFlo = floAvatar(document.getElementById('guide-flo'), { size: 32, mood: 'hello', hat: true, once: 0.9 });
482
+ }
410
483
  $title.focus();
411
484
  keyHandler = (event) => {
412
485
  if (event.key === 'Escape') { event.preventDefault(); void dismiss(); }
@@ -420,7 +493,9 @@
420
493
  };
421
494
  // Heard on the dialog only: Esc pressed in a dialog opened over the Guide belongs to that dialog.
422
495
  $modal.addEventListener('keydown', keyHandler);
423
- if (state.mode !== 'folder') await takeLook();
496
+ // #2054: the question asks first — no look until the person opens the preview or presses Turn on. Start the Guide is
497
+ // different: it opens only once the Guide is on, so the person has agreed, and it shows the look it would send.
498
+ if (state.mode === 'start') await takeLook('starting');
424
499
  }
425
500
 
426
501
  function closeModal() {
@@ -428,12 +503,15 @@
428
503
  if (keyHandler) $modal.removeEventListener('keydown', keyHandler);
429
504
  keyHandler = null;
430
505
  state.lookSeq += 1;
506
+ state.closeSeq += 1; // a Turn on still in progress stops before its next step (#2054 review)
431
507
  const back = state.returnFocus?.isConnected ? state.returnFocus : document.getElementById('menu-btn');
432
508
  back?.focus?.();
433
509
  }
434
510
 
435
511
  /** Not now (or Esc): remembered for a first-launch question; Cancel in start mode changes nothing. */
436
512
  async function dismiss() {
513
+ // Closed while Turn on is working: the person pressed Turn on, so this is no Not now; confirm() stops at its next step.
514
+ if (state.busy) { closeModal(); return; }
437
515
  const asking = state.mode !== 'start' && state.status?.consent?.choice !== 'off' && state.status?.consent?.choice !== 'on';
438
516
  closeModal();
439
517
  if (!asking) return;
@@ -456,15 +534,48 @@
456
534
  async function confirm() {
457
535
  if (state.mode === 'folder') { await chooseFolder(); return; }
458
536
  if (state.busy) return;
459
- if (!state.preview) { state.banner = 'Looking first, so you can see what goes. Press again once the preview is shown.'; paint(); return; }
537
+ if (!state.preview && state.lookBecause && !state.previewError) {
538
+ // A look the person already asked for is still on its way: the press waits for it to be shown.
539
+ state.banner = 'Looking first, so you can see what goes. Press again once the preview is shown.'; paint(); return;
540
+ }
460
541
  state.busy = true; paint();
542
+ const opened = state.closeSeq;
543
+ const closed = () => opened !== state.closeSeq;
544
+ if (!state.preview) {
545
+ // #2054: pressing Turn on (or Start) is the person asking FloLess to look now. If it can't, the reason is shown
546
+ // where the preview goes, with Try again, and nothing is turned on.
547
+ const landed = await takeLook(state.mode === 'start' ? 'starting' : 'turning-on');
548
+ if (!landed || !state.preview) {
549
+ state.busy = false;
550
+ // A switch changed while the look was taken: a newer look replaced it. Say so rather than end silently.
551
+ if (!closed() && !state.previewError) state.banner = 'The preview changed while you pressed. Check it, then press again.';
552
+ paint();
553
+ return;
554
+ }
555
+ if (closed()) { state.busy = false; return; }
556
+ }
461
557
  try {
462
558
  const agreed = state.status?.consent?.share;
463
559
  const changed = !agreed || agreed.windowTitles !== state.share.windowTitles || agreed.recentFiles !== state.share.recentFiles;
464
560
  // Turning on, or (already on) a switch changed: the agreement is what the switches now show, with this preview.
561
+ const briefing = state.briefingAsk ? { on: true, time: '08:00', days: 'weekdays' } : undefined;
562
+ let briefed = false;
465
563
  if (state.mode === 'consent' || changed) {
466
- await api('/api/chat/guide/consent', { choice: 'on', share: state.share, previewId: state.preview.previewId });
564
+ const answer = await api('/api/chat/guide/consent', { choice: 'on', share: state.share, previewId: state.preview.previewId, ...(briefing ? { provider: state.provider, briefing } : {}) });
467
565
  if (state.status) state.status = { ...state.status, consent: { choice: 'on', share: { ...state.share } } };
566
+ if (answer && 'briefing' in answer) { setBriefing(answer.briefing); briefed = true; }
567
+ if (answer?.briefingError) { toast(answer.briefingError, 'warn'); briefed = true; }
568
+ }
569
+ if (briefing && !briefed) {
570
+ // The Guide was already on: the briefing is its own step. A failure here never stops the Guide starting.
571
+ try { const answer = await api('/api/chat/guide/briefing', { on: true, provider: state.provider, time: '08:00', days: 'weekdays' }); setBriefing(answer.briefing); }
572
+ catch (error) { toast(`The Guide is starting, but the morning briefing wasn’t turned on: ${error.message}`, 'warn'); }
573
+ }
574
+ if (closed()) {
575
+ // Closed while the Guide was being turned on: it is on, but nothing more happens until the person opens it.
576
+ state.busy = false;
577
+ toast('The Guide is on. Open it from ≡ → Guide when you want it to show you around.', 'info');
578
+ return;
468
579
  }
469
580
  if (!readyProviders().includes(state.provider)) {
470
581
  closeModal();
@@ -590,14 +701,97 @@
590
701
  }
591
702
  }
592
703
 
593
- const SET_ASIDE_KEY = 'floless:guide-moves-set-aside';
594
- function setAside() {
595
- try { return new Set(JSON.parse(localStorage.getItem(SET_ASIDE_KEY) || '[]')); } catch { return new Set(); }
704
+ // #2054: Not now is remembered by the server for the signed-in account, by what the move is about (its key), so the
705
+ // Guide never suggests it again — in a later answer, after a reload, or in another browser — until the person brings
706
+ // it back (Undo on the card, or Bring back in the Guide's settings in AI Chat).
707
+ // A list change repaints every card on the page, and the cards drawn but not yet placed on it (AI Chat builds a card
708
+ // before it inserts it). Placed cards leave the waiting list; the list keeps the newest 100 that never were.
709
+ const cardPainters = new WeakMap();
710
+ const unplacedCards = new Set();
711
+ let statusLoad = null;
712
+ let statusFailedAt = 0;
713
+
714
+ /** A move's identity without its wording, for a card from before #2054 that carries no key: the same fields, sorted. */
715
+ function sameMove(a, b) {
716
+ const canon = (value) => (value && typeof value === 'object'
717
+ ? `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canon(value[key])}`).join(',')}}`
718
+ : JSON.stringify(value));
719
+ return canon(a) === canon(b);
720
+ }
721
+
722
+ /** The set-aside entry for a card: by its key, or (no key) by the move itself. */
723
+ function setAsideFor(moveKey, move) {
724
+ return state.setAside.find((row) => (moveKey ? row.key === moveKey : sameMove(row.move, move))) || null;
725
+ }
726
+
727
+ function setSetAside(rows) {
728
+ state.setAside = Array.isArray(rows) ? rows : [];
729
+ for (const card of document.querySelectorAll('.guide-move-card')) { unplacedCards.delete(card); cardPainters.get(card)?.(); }
730
+ for (const card of unplacedCards) cardPainters.get(card)?.();
731
+ paintSetAside();
732
+ }
733
+
734
+ /** A card drawn before the Guide's status was read (AI Chat opened first): read it once, then repaint the cards. */
735
+ function ensureSetAsideLoaded() {
736
+ // After a failed read, wait half a minute: AI Chat redraws its cards every few seconds and each would ask again.
737
+ if (state.status || statusLoad || Date.now() - statusFailedAt < 30_000) return;
738
+ statusLoad = loadStatus().catch((error) => {
739
+ // Cards stay as drawn; Not now still asks the server, which answers with the account's real list.
740
+ statusFailedAt = Date.now();
741
+ console.warn('[guide] could not read which suggestions were set aside:', error);
742
+ }).finally(() => { statusLoad = null; });
743
+ }
744
+
745
+ async function moveAside(move, on, key) {
746
+ const answer = on
747
+ ? await api('/api/chat/guide/next-moves/not-now', { move })
748
+ : await api('/api/chat/guide/next-moves/bring-back', { key });
749
+ setSetAside(answer.setAside);
750
+ return answer;
596
751
  }
597
- function markSetAside(moveId, on) {
598
- const ids = setAside();
599
- if (on) ids.add(moveId); else ids.delete(moveId);
600
- try { localStorage.setItem(SET_ASIDE_KEY, JSON.stringify([...ids].slice(-200))); } catch { /* private window: this view only */ }
752
+
753
+ /** The set-aside suggestions in a Guide conversation's AI Chat settings, each with Bring back. Hidden when none. */
754
+ function paintSetAside() {
755
+ const host = document.getElementById('chat-guide-set-aside');
756
+ if (!host) return;
757
+ // Only rebuilt when the list changed: AI Chat repaints its settings often, and a rebuild takes focus off Bring back.
758
+ // Kept on the element itself, so a host that is ever replaced is painted afresh.
759
+ const signature = JSON.stringify(state.setAside.map((row) => row.key));
760
+ if (host.dataset.setAsideKeys === signature) return;
761
+ host.dataset.setAsideKeys = signature;
762
+ const rows = state.setAside.map((row) => ({ row, text: moveText(row.move) })).filter((item) => item.text);
763
+ host.replaceChildren();
764
+ host.hidden = rows.length === 0;
765
+ if (!rows.length) return;
766
+ host.append(el('strong', '', 'Suggestions you set aside'),
767
+ el('span', '', 'The Guide doesn’t suggest these again until you bring them back.'));
768
+ const list = el('ul', 'ai-chat-guide-set-aside-list');
769
+ for (const { row, text } of rows.slice().reverse()) {
770
+ const item = el('li', 'ai-chat-guide-set-aside-row');
771
+ const back = el('button', '', 'Bring back');
772
+ back.type = 'button';
773
+ back.dataset.commandId = 'shell.guide-move-bring-back';
774
+ back.dataset.commandInstanceLabel = text.title;
775
+ back.dataset.tip = 'The Guide may suggest this again.';
776
+ back.setAttribute('aria-label', `Bring back: ${text.title}`);
777
+ back.addEventListener('click', async () => {
778
+ back.disabled = true;
779
+ // Focus goes on to the next suggestion in the list (or the one before), never lost to the page.
780
+ const items = [...list.children];
781
+ const at = items.indexOf(item);
782
+ const nextKey = (items[at + 1] || items[at - 1])?.dataset.key;
783
+ try {
784
+ await moveAside(row.move, false, row.key);
785
+ toast(`The Guide may suggest “${text.title}” again.`, 'info');
786
+ const nextButton = nextKey ? [...host.querySelectorAll('li')].find((li) => li.dataset.key === nextKey)?.querySelector('button') : null;
787
+ nextButton?.focus();
788
+ } catch (error) { back.disabled = false; toast(error.message, 'warn'); }
789
+ });
790
+ item.dataset.key = row.key;
791
+ item.append(el('span', '', text.title), back);
792
+ list.append(item);
793
+ }
794
+ host.append(list);
601
795
  }
602
796
 
603
797
  /** A next-move event as a card. Its text is the AI's: textContent only. */
@@ -605,8 +799,10 @@
605
799
  const payload = event.payload || {};
606
800
  const move = payload.move;
607
801
  const text = moveText(move);
608
- const moveId = String(payload.moveId || event.eventId || '');
802
+ // A card from before #2054 has no key: it is matched to the list by its move, and the server returns its key on Not now.
803
+ let moveKey = typeof payload.moveKey === 'string' ? payload.moveKey : '';
609
804
  if (!text) return null;
805
+ ensureSetAsideLoaded();
610
806
  const card = el('section', 'ai-chat-filter-card ai-chat-connection-card guide-move-card');
611
807
  card.dataset.eventId = event.eventId;
612
808
  card.dataset.eventSequence = String(event.sequence);
@@ -615,17 +811,25 @@
615
811
  const status = el('p', 'ai-chat-filter-note guide-move-status');
616
812
  status.setAttribute('role', 'status');
617
813
  const paintCard = () => {
814
+ const focusBack = card.contains(document.activeElement);
618
815
  card.replaceChildren();
619
- if (setAside().has(moveId)) {
816
+ const aside = setAsideFor(moveKey, move);
817
+ if (aside) {
818
+ moveKey = aside.key;
620
819
  const line = el('div', 'ai-chat-connection-collapsed');
621
820
  const undo = el('button', '', 'Undo');
622
821
  undo.type = 'button';
623
822
  undo.dataset.commandId = 'shell.guide-move-undo';
624
823
  undo.dataset.commandInstanceLabel = text.title;
625
- undo.dataset.tip = 'Shows this suggestion again.';
626
- undo.addEventListener('click', () => { markSetAside(moveId, false); paintCard(); });
824
+ undo.dataset.tip = 'Shows this suggestion again. The Guide may also bring it up later.';
825
+ undo.addEventListener('click', async () => {
826
+ undo.disabled = true; status.textContent = '';
827
+ try { await moveAside(move, false, moveKey); }
828
+ catch (error) { undo.disabled = false; status.textContent = error.message; }
829
+ });
627
830
  line.append(el('span', '', `Not now: ${text.title}`), undo);
628
- card.append(line);
831
+ card.append(line, status);
832
+ if (focusBack) undo.focus();
629
833
  return;
630
834
  }
631
835
  const head = el('div', 'ai-chat-filter-card-head');
@@ -658,18 +862,452 @@
658
862
  later.type = 'button';
659
863
  later.dataset.commandId = 'shell.guide-move-not-now';
660
864
  later.dataset.commandInstanceLabel = text.title;
661
- later.dataset.tip = 'Sets this suggestion aside. You can bring it back.';
662
- later.addEventListener('click', () => { markSetAside(moveId, true); paintCard(); });
865
+ later.dataset.tip = 'Sets this suggestion aside, and the Guide won’t suggest it again. You can bring it back.';
866
+ later.addEventListener('click', async () => {
867
+ later.disabled = true; status.textContent = '';
868
+ try {
869
+ const answer = await moveAside(move, true);
870
+ if (answer?.key) { moveKey = answer.key; paintCard(); }
871
+ } catch (error) {
872
+ later.disabled = false;
873
+ status.textContent = error.message;
874
+ }
875
+ });
663
876
  actions.append(go, later);
664
877
  card.append(actions, el('p', 'ai-chat-filter-note', 'Nothing happens until you confirm in the next step.'), status);
878
+ if (focusBack) go.focus();
665
879
  };
880
+ cardPainters.set(card, paintCard);
881
+ unplacedCards.add(card);
882
+ if (unplacedCards.size > 100) unplacedCards.delete(unplacedCards.values().next().value);
666
883
  paintCard();
667
884
  return card;
668
885
  }
669
886
 
670
- window.flolessGuide = { open, maybeAskOnLaunch, turnOff, deleteHistory, renderNextMove, status: loadStatus };
887
+ /** The question's own switch: "Also brief me each morning", off by default; the agreement shows once it is on. */
888
+ function briefingAskRow() {
889
+ const { row, input, text } = briefingToggle('guide-briefing-ask', 'shell.guide-briefing-ask', 'Also brief me each morning',
890
+ 'Weekdays at 08:00. You can change the time later in the Guide’s settings in AI Chat.', state.briefingAsk, (checked) => {
891
+ state.briefingAsk = checked; paint();
892
+ });
893
+ if (state.briefingAsk) {
894
+ const { wrap, leadId } = briefingDisclosure(PROVIDER_LABEL[state.provider] || 'the AI you chose', false, 'shell.guide-briefing-ask-details');
895
+ input.setAttribute('aria-describedby', `${input.id}-help ${leadId}`);
896
+ text.append(wrap);
897
+ }
898
+ row.classList.add('guide-briefing-ask');
899
+ return row;
900
+ }
901
+
902
+ // ── the morning briefing (#2053) ──────────────────────────────────────────────────────────────────────────────
903
+ // Opt-in only (owner ruling 2026-10-07). The server decides everything (when it is due, whether it may go, what it
904
+ // sends); this paints its settings in the Guide conversation's AI Chat settings, the "Also brief me" switch in the
905
+ // Guide question, and one notice per outcome. Plan: docs/superpowers/specs/2026-10-07-2053-guide-morning-briefing-PLAN.md.
906
+ const DAYS_LABEL = { weekdays: 'Weekdays', 'every-day': 'Every day' };
907
+ const NOTICE_SEEN_KEY = 'floless:guide-briefing-notices';
908
+ const NOTICE_STATES = new Set(['ready', 'waiting', 'didnt-go-out', 'didnt-finish']);
909
+ let briefingSignature = '';
910
+ // A control in the block that had focus while it was disabled for a change: it gets focus back on the next paint.
911
+ let briefingFocus = null;
912
+ let briefingBusy = false;
913
+
914
+ function briefingAi(provider) {
915
+ return PROVIDER_LABEL[provider] || PROVIDER_LABEL[window.flolessChat?.currentProvider?.()] || 'your AI';
916
+ }
917
+
918
+ /** The agreement, said where the switch is: one sentence always visible, the rest one step away. */
919
+ function briefingDisclosure(ai, open, commandId = 'shell.guide-briefing-details') {
920
+ const wrap = el('div', 'guide-briefing-disclosure');
921
+ const lead = el('p', 'guide-switch-help', `Each morning FloLess sends ${ai} the same look you previewed, using your sharing switches as they are then, without asking first. The AI may also open other files to understand them.`);
922
+ lead.id = `guide-briefing-lead-${Math.random().toString(36).slice(2, 8)}`;
923
+ const more = el('details', 'guide-preview-disclosure');
924
+ const summary = el('summary', '', 'What the AI can and can’t do');
925
+ summary.dataset.commandId = commandId;
926
+ more.append(summary, el('p', 'guide-switch-help', `While writing, the AI may open more of your files to understand them, as it can in the Guide chat. It is told only to read. Nobody is watching, so anything it asks permission for is declined. You can pause it, turn it off, or delete the Guide history at any time; whatever ${ai} already received stays under its own rules.`));
927
+ if (open) more.open = true;
928
+ wrap.append(lead, more);
929
+ return { wrap, leadId: lead.id };
930
+ }
931
+
932
+ function briefingToggle(id, commandId, label, help, checked, onChange) {
933
+ const row = el('div', 'guide-switch');
934
+ const toggle = el('label', 'rtn-toggle');
935
+ const input = document.createElement('input');
936
+ input.type = 'checkbox'; input.id = id; input.setAttribute('role', 'switch');
937
+ input.checked = checked;
938
+ input.dataset.commandId = commandId;
939
+ input.setAttribute('aria-describedby', `${id}-help`);
940
+ input.addEventListener('change', () => onChange(input.checked, input));
941
+ toggle.append(input, el('span', 'rtn-toggle-track'));
942
+ const text = el('div', 'guide-switch-text');
943
+ const name = el('label', 'guide-switch-label', label); name.htmlFor = id;
944
+ const note = el('div', 'guide-switch-help', help); note.id = `${id}-help`;
945
+ text.append(name, note);
946
+ row.append(toggle, text);
947
+ return { row, input, text };
948
+ }
949
+
950
+ function whenLabel(iso) {
951
+ const due = new Date(iso);
952
+ const time = `${String(due.getHours()).padStart(2, '0')}:${String(due.getMinutes()).padStart(2, '0')}`;
953
+ const today = new Date(); const tomorrow = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);
954
+ if (due.toDateString() === today.toDateString()) return `today at ${time}`;
955
+ if (due.toDateString() === tomorrow.toDateString()) return `tomorrow at ${time}`;
956
+ return `${due.toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' })} at ${time}`;
957
+ }
958
+
959
+ function dateLabel(key) {
960
+ const [y, m, d] = String(key).split('-').map(Number);
961
+ return new Date(y, m - 1, d).toLocaleDateString('en-GB', { weekday: 'short', day: 'numeric', month: 'short' });
962
+ }
963
+
964
+ async function briefingCall(path, body, done) {
965
+ if (briefingBusy) return null;
966
+ briefingBusy = true;
967
+ try {
968
+ const answer = await api(path, body);
969
+ if (answer && 'briefing' in answer) setBriefing(answer.briefing);
970
+ if (answer?.notStopped) toast('The morning briefing it was writing could not be stopped. Press Stop in AI Chat to end it.', 'warn');
971
+ else if (done) toast(done, 'info');
972
+ return answer;
973
+ } catch (error) {
974
+ if (error.body && 'briefing' in error.body) setBriefing(error.body.briefing);
975
+ toast(error.message, 'warn');
976
+ return null;
977
+ } finally {
978
+ briefingBusy = false;
979
+ paintBriefing(true);
980
+ }
981
+ }
982
+
983
+ function setBriefing(briefing) {
984
+ state.briefing = briefing || null;
985
+ if (state.status) state.status = { ...state.status, briefing: state.briefing };
986
+ paintBriefing();
987
+ schedulePoll();
988
+ void maybeNotice();
989
+ }
990
+
991
+ function actionButton(text, commandId, tip, onClick) {
992
+ const button = el('button', '', text);
993
+ button.type = 'button';
994
+ button.dataset.commandId = commandId;
995
+ if (tip) button.dataset.tip = tip;
996
+ button.addEventListener('click', onClick);
997
+ return button;
998
+ }
999
+
1000
+ /** The current slot's line and its choices: Open, or Brief me now / Skip today. */
1001
+ function briefingStatus(briefing) {
1002
+ const wrap = el('div', 'guide-briefing-status');
1003
+ const current = briefing.current;
1004
+ const line = el('p', 'guide-briefing-line');
1005
+ line.setAttribute('role', 'status');
1006
+ const actions = el('div', 'ai-chat-guide-actions');
1007
+ if (current && NOTICE_STATES.has(current.state)) {
1008
+ line.textContent = current.message;
1009
+ for (const button of briefingChoices(current, 'settings')) actions.append(button);
1010
+ } else if (current && (current.state === 'preparing' || current.state === 'being-written')) {
1011
+ line.textContent = current.message;
1012
+ }
1013
+ const next = el('p', 'guide-switch-help');
1014
+ if (briefing.pausedUntil) next.textContent = `Paused until ${dateLabel(briefing.pausedUntil)}.`;
1015
+ else if (briefing.next) next.textContent = `Next: ${whenLabel(briefing.next)}.`;
1016
+ if (line.textContent) wrap.append(line);
1017
+ if (actions.childElementCount) wrap.append(actions);
1018
+ if (next.textContent) wrap.append(next);
1019
+ return wrap;
1020
+ }
1021
+
1022
+ /** `where` is 'settings' or 'notice': the same choices, each carrier with its own command (Instructor says where it is). */
1023
+ function briefingChoices(current, where, after) {
1024
+ const done = () => { if (typeof after === 'function') after(); };
1025
+ // Another change still going: say so and keep the notice, rather than closing it on a click that does nothing.
1026
+ const free = () => {
1027
+ if (!briefingBusy) return true;
1028
+ toast('Still working on your last change to the morning briefing. Try again in a moment.', 'info');
1029
+ return false;
1030
+ };
1031
+ const id = (name) => (where === 'notice' ? `shell.guide-briefing-notice-${name}` : `shell.guide-briefing-${name}`);
1032
+ if (current.state === 'ready') {
1033
+ return [actionButton('Open', id('open'), 'Opens the Guide conversation with this morning’s briefing.', async () => {
1034
+ done(); if (current.chatId) await openGuideChat(current.chatId);
1035
+ })];
1036
+ }
1037
+ return [
1038
+ actionButton('Brief me now', id('now'), 'Takes a fresh look now and sends this morning’s briefing.', async () => {
1039
+ if (!free()) return;
1040
+ done(); await briefingCall('/api/chat/guide/briefing/now', { slotKey: current.slotKey }, 'Your morning briefing is on its way.');
1041
+ }),
1042
+ actionButton('Skip today', id('skip'), 'No briefing this morning. The next one comes as usual.', async () => {
1043
+ if (!free()) return;
1044
+ done(); await briefingCall('/api/chat/guide/briefing/skip', { slotKey: current.slotKey }, 'No briefing this morning. The next one comes as usual.');
1045
+ }),
1046
+ ];
1047
+ }
1048
+
1049
+ // The time pair lives in index.html: the themed combobox markup (.sel-combo, so the app's outside-click closes it),
1050
+ // with no native select behind it — AI Chat carries none. It is moved into the block when the briefing is on.
1051
+ const $briefingTime = document.getElementById('chat-guide-briefing-time');
1052
+ /** One part of the time: a trigger showing the value and a listbox of choices. */
1053
+ function timePart(id, count, step) {
1054
+ const trigger = document.getElementById(id);
1055
+ if (!trigger) return null;
1056
+ const box = trigger.closest('.sel-combo');
1057
+ const popover = box.querySelector('[role="listbox"]');
1058
+ const list = popover.querySelector('.fm-select-list');
1059
+ const label = trigger.querySelector('.fm-select-label');
1060
+ const values = [];
1061
+ for (let i = 0; i < count; i += step) values.push(String(i).padStart(2, '0'));
1062
+ let value = values[0];
1063
+ let hi = -1;
1064
+ const rows = () => [...list.children];
1065
+ const paint = () => {
1066
+ label.textContent = value;
1067
+ // A value set elsewhere (a minute not on the five-minute list) is still shown and selectable.
1068
+ const all = values.includes(value) ? values : [...values, value].sort();
1069
+ list.replaceChildren(...all.map((v) => {
1070
+ const row = document.createElement('div');
1071
+ row.className = 'wf-option' + (v === value ? ' selected' : '');
1072
+ row.setAttribute('role', 'option'); row.setAttribute('aria-selected', String(v === value));
1073
+ row.id = `${id}-option-${v}`; row.dataset.value = v; row.tabIndex = -1;
1074
+ const name = document.createElement('span'); name.className = 'wf-option-name'; name.textContent = v;
1075
+ row.append(name);
1076
+ return row;
1077
+ }));
1078
+ hi = -1;
1079
+ };
1080
+ const highlight = (i) => {
1081
+ const all = rows();
1082
+ hi = Math.max(0, Math.min(all.length - 1, i));
1083
+ all.forEach((row, n) => row.classList.toggle('highlighted', n === hi));
1084
+ trigger.setAttribute('aria-activedescendant', all[hi]?.id || '');
1085
+ all[hi]?.scrollIntoView?.({ block: 'nearest' });
1086
+ };
1087
+ const close = (focus) => {
1088
+ popover.hidden = true; trigger.classList.remove('open'); trigger.setAttribute('aria-expanded', 'false');
1089
+ trigger.removeAttribute('aria-activedescendant'); hi = -1;
1090
+ if (focus) trigger.focus();
1091
+ };
1092
+ const open = () => {
1093
+ if (trigger.disabled) return;
1094
+ // One open list at a time, like every other themed combobox.
1095
+ document.querySelectorAll('.sel-combo').forEach((other) => {
1096
+ if (other === box) return;
1097
+ const pop = other.querySelector('.fm-select-popover');
1098
+ if (pop && !pop.hidden) { pop.hidden = true; const t = other.querySelector('.fm-select-trigger'); t?.classList.remove('open'); t?.setAttribute('aria-expanded', 'false'); }
1099
+ });
1100
+ paint();
1101
+ // A highlight left from a list closed elsewhere (an outside click) never carries over.
1102
+ trigger.removeAttribute('aria-activedescendant');
1103
+ popover.hidden = false; trigger.classList.add('open'); trigger.setAttribute('aria-expanded', 'true');
1104
+ list.querySelector('.wf-option.selected')?.scrollIntoView?.({ block: 'nearest' });
1105
+ };
1106
+ const choose = (v) => {
1107
+ close(true);
1108
+ if (v === value) return;
1109
+ value = v; paint();
1110
+ changeTime();
1111
+ };
1112
+ trigger.addEventListener('click', (event) => { event.stopPropagation(); popover.hidden ? open() : close(false); });
1113
+ list.addEventListener('click', (event) => {
1114
+ const row = event.target.closest('.wf-option');
1115
+ if (row) { event.stopPropagation(); choose(row.dataset.value); }
1116
+ });
1117
+ // Keys stay inside the combo: Escape must close the list, not the settings around it.
1118
+ box.addEventListener('keydown', (event) => {
1119
+ const key = event.key;
1120
+ if (popover.hidden) {
1121
+ if (key === 'ArrowDown' || key === 'ArrowUp' || key === 'Enter' || key === ' ') { event.preventDefault(); open(); }
1122
+ return;
1123
+ }
1124
+ if (key === 'ArrowDown' || key === 'ArrowUp') {
1125
+ event.preventDefault(); event.stopPropagation();
1126
+ const start = hi < 0 ? rows().findIndex((row) => row.dataset.value === value) : hi;
1127
+ highlight(start + (key === 'ArrowDown' ? 1 : -1));
1128
+ } else if (key === 'Enter' || key === ' ') {
1129
+ event.preventDefault(); event.stopPropagation();
1130
+ if (hi >= 0) choose(rows()[hi].dataset.value); else close(true);
1131
+ } else if (key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(true); }
1132
+ else if (key === 'Tab') close(false);
1133
+ });
1134
+ paint();
1135
+ return {
1136
+ trigger,
1137
+ get value() { return value; },
1138
+ /** Shows a stored value without treating it as the person's change. */
1139
+ set(v) { if (v !== value) { value = v; paint(); } },
1140
+ set disabled(flag) { trigger.disabled = flag; if (flag) close(false); },
1141
+ };
1142
+ }
1143
+ const changeTime = () => {
1144
+ const time = `${briefingHour.value}:${briefingMinute.value}`;
1145
+ if (time === state.briefing?.time) return;
1146
+ void briefingCall('/api/chat/guide/briefing', { on: true, time }, `Morning briefing moved to ${time}.`);
1147
+ };
1148
+ const briefingHour = timePart('chat-guide-briefing-hour', 24, 1);
1149
+ const briefingMinute = timePart('chat-guide-briefing-minute', 60, 5);
1150
+
1151
+ /** Paints the briefing block in a Guide conversation's AI Chat settings. Only rebuilt when something changed. */
1152
+ function paintBriefing(force) {
1153
+ paintSetAside(); // #2054: the same settings panel lists the suggestions set aside
1154
+ const host = document.getElementById('chat-guide-briefing');
1155
+ if (!host) return;
1156
+ const signature = JSON.stringify([state.briefing, state.status?.consent?.choice, window.flolessChat?.currentProvider?.(), briefingBusy]);
1157
+ if (!force && signature === briefingSignature && host.childElementCount) return;
1158
+ briefingSignature = signature;
1159
+ const active = document.activeElement;
1160
+ const nowhere = !active || active === document.body;
1161
+ const focusedId = (active && host.contains(active) ? active.id : null) || (nowhere ? briefingFocus : null);
1162
+ briefingFocus = null;
1163
+ host.replaceChildren();
1164
+ const briefing = state.briefing;
1165
+ const on = briefing?.on === true;
1166
+ const ai = briefingAi(briefing?.provider);
1167
+ const { row, input, text } = briefingToggle('chat-guide-briefing-on', 'shell.guide-briefing-toggle', 'Morning briefing',
1168
+ `A short Guide note each morning, written by ${ai}.`, on, (checked) => {
1169
+ void briefingCall('/api/chat/guide/briefing', { on: checked, provider: window.flolessChat?.currentProvider?.() || undefined },
1170
+ checked ? null : 'The morning briefing is off.');
1171
+ });
1172
+ input.disabled = briefingBusy;
1173
+ host.append(row);
1174
+ const { wrap, leadId } = briefingDisclosure(ai, false);
1175
+ input.setAttribute('aria-describedby', `${input.id}-help ${leadId}`);
1176
+ text.append(wrap);
1177
+ if (on) {
1178
+ const [hour, minute] = String(briefing.time || '08:00').split(':');
1179
+ const when = el('div', 'guide-briefing-when');
1180
+ const label = el('span', 'guide-briefing-at', 'At');
1181
+ briefingHour.set(hour);
1182
+ briefingMinute.set(minute);
1183
+ $briefingTime.hidden = false;
1184
+ briefingHour.disabled = briefingBusy; briefingMinute.disabled = briefingBusy;
1185
+ const days = el('div', 'guide-provider-group guide-briefing-days');
1186
+ days.setAttribute('role', 'radiogroup'); days.setAttribute('aria-label', 'Which days');
1187
+ for (const key of Object.keys(DAYS_LABEL)) {
1188
+ const option = el('label', 'guide-provider-option');
1189
+ const radio = document.createElement('input');
1190
+ radio.type = 'radio'; radio.name = 'chat-guide-briefing-days'; radio.value = key; radio.id = `chat-guide-briefing-days-${key}`;
1191
+ radio.checked = briefing.days === key;
1192
+ radio.dataset.commandId = `shell.guide-briefing-days#${DAYS_LABEL[key]}`;
1193
+ radio.addEventListener('change', () => { void briefingCall('/api/chat/guide/briefing', { on: true, days: key }, `Morning briefing: ${DAYS_LABEL[key].toLowerCase()}.`); });
1194
+ option.append(radio, document.createTextNode(` ${DAYS_LABEL[key]}`));
1195
+ days.append(option);
1196
+ }
1197
+ when.append(label, $briefingTime, days);
1198
+ const controls = el('div', 'ai-chat-guide-actions');
1199
+ controls.append(briefing.pausedUntil
1200
+ ? actionButton('Resume', 'shell.guide-briefing-resume', 'Starts the morning briefing again from its next time. Paused mornings are not caught up.', () => {
1201
+ void briefingCall('/api/chat/guide/briefing/pause', { pause: false }, 'The morning briefing is back on.');
1202
+ })
1203
+ : actionButton('Pause for a week', 'shell.guide-briefing-pause', 'No briefing for the next seven days. Paused mornings are not caught up.', () => {
1204
+ void briefingCall('/api/chat/guide/briefing/pause', { pause: true }, 'The morning briefing is paused for a week.');
1205
+ }));
1206
+ host.append(when, controls, briefingStatus(briefing));
1207
+ } else if ($briefingTime) {
1208
+ // Kept in the block (hidden) so it is never lost from the page.
1209
+ $briefingTime.hidden = true;
1210
+ host.append($briefingTime);
1211
+ }
1212
+ const again = focusedId ? document.getElementById(focusedId) : null;
1213
+ if (again && host.contains(again)) {
1214
+ again.focus();
1215
+ // Disabled while the change is saved, so it cannot take focus yet: keep it for the paint after.
1216
+ if (document.activeElement !== again) briefingFocus = focusedId;
1217
+ }
1218
+ }
1219
+
1220
+ // ── the notice: one per outcome, never over a dialog, never stealing focus ──────────────────────────────────
1221
+ function seenNotices() {
1222
+ try { return new Set(JSON.parse(localStorage.getItem(NOTICE_SEEN_KEY) || '[]')); } catch { return new Set(); }
1223
+ }
1224
+ function markNotice(key) {
1225
+ const seen = seenNotices(); seen.add(key);
1226
+ try { localStorage.setItem(NOTICE_SEEN_KEY, JSON.stringify([...seen].slice(-50))); } catch { /* private window: this view only */ }
1227
+ }
1228
+
1229
+ let noticeShowing = false;
1230
+ async function maybeNotice() {
1231
+ const current = state.briefing?.current;
1232
+ if (!current || !NOTICE_STATES.has(current.state) || noticeShowing) return;
1233
+ if (seenNotices().has(current.noticeKey)) return;
1234
+ if (document.querySelector('.modal-backdrop.show')) return; // asked again at the next refresh
1235
+ noticeShowing = true;
1236
+ try { showNotice(current); } finally { noticeShowing = false; }
1237
+ }
1238
+
1239
+ function showNotice(current) {
1240
+ const container = document.getElementById('toast-container');
1241
+ if (!container) return;
1242
+ markNotice(current.noticeKey);
1243
+ // A newer outcome for the same morning replaces the one already on screen.
1244
+ for (const old of container.querySelectorAll('.guide-notice')) if (old.dataset.slot === current.slotKey) old.remove();
1245
+ const ready = current.state === 'ready';
1246
+ const notice = el('div', `toast ${ready ? 'ok' : 'warn'} guide-notice`);
1247
+ notice.dataset.group = 'In the morning briefing notice';
1248
+ notice.dataset.slot = current.slotKey;
1249
+ notice.setAttribute('role', ready ? 'status' : 'alert');
1250
+ const body = el('div', 'guide-notice-body');
1251
+ body.append(el('span', 'toast-msg', ready ? 'Your morning briefing is ready.' : current.message));
1252
+ const actions = el('div', 'guide-notice-actions');
1253
+ const close = () => notice.remove();
1254
+ for (const button of briefingChoices(current, 'notice', close)) actions.append(button);
1255
+ if (!ready) {
1256
+ actions.append(actionButton('Turn off', 'shell.guide-briefing-notice-off', 'Turns the morning briefing off. You can turn it back on in the Guide’s settings in AI Chat.', async () => {
1257
+ if (briefingBusy) { toast('Still working on your last change to the morning briefing. Try again in a moment.', 'info'); return; }
1258
+ close();
1259
+ await briefingCall('/api/chat/guide/briefing', { on: false }, 'The morning briefing is off. You can turn it back on in the Guide’s settings in AI Chat.');
1260
+ }));
1261
+ }
1262
+ body.append(actions);
1263
+ const x = el('button', 'toast-close', '×');
1264
+ x.type = 'button';
1265
+ x.setAttribute('aria-label', 'Dismiss');
1266
+ x.dataset.commandId = 'shell.guide-briefing-notice-dismiss';
1267
+ x.addEventListener('click', close);
1268
+ notice.append(body, x);
1269
+ container.append(notice);
1270
+ if (ready) setTimeout(close, 12_000);
1271
+ }
1272
+
1273
+ // ── keeping it current: on launch, on focus, and every minute while it is on and FloLess is in view ──────────
1274
+ let pollTimer = null;
1275
+ async function refreshBriefing() {
1276
+ try {
1277
+ const body = await api('/api/chat/guide/briefing');
1278
+ briefingUnknown = false; failedChecks = 0;
1279
+ setBriefing(body.briefing);
1280
+ } catch (error) {
1281
+ // Not this time (FloLess still starting, a busy moment): keep asking every minute until one check answers, so a
1282
+ // briefing that is ready or needs an answer is never left unsaid. A signed-out FloLess has no briefing to show.
1283
+ if (error.code !== 'guide-signed-out') console.warn('[guide] could not check the morning briefing:', error);
1284
+ briefingUnknown = error.code !== 'guide-signed-out';
1285
+ failedChecks = briefingUnknown ? failedChecks + 1 : 0;
1286
+ if (failedChecks === 3 && state.briefing?.on) {
1287
+ toast('FloLess couldn’t check your morning briefing for a few minutes. It keeps trying; if this goes on, restart FloLess.', 'warn');
1288
+ }
1289
+ schedulePoll();
1290
+ }
1291
+ }
1292
+ let briefingUnknown = false;
1293
+ let failedChecks = 0;
1294
+ function schedulePoll() {
1295
+ const wanted = state.briefing?.on === true || briefingUnknown;
1296
+ if (wanted && !pollTimer) {
1297
+ pollTimer = setInterval(() => { if (document.visibilityState === 'visible') void refreshBriefing(); }, 60_000);
1298
+ } else if (!wanted && pollTimer) { clearInterval(pollTimer); pollTimer = null; }
1299
+ }
1300
+ let lastFocusCheck = 0;
1301
+ window.addEventListener('focus', () => {
1302
+ if ((!state.briefing?.on && !briefingUnknown) || Date.now() - lastFocusCheck < 10_000) return;
1303
+ lastFocusCheck = Date.now();
1304
+ void refreshBriefing();
1305
+ });
1306
+
1307
+ window.flolessGuide = { open, maybeAskOnLaunch, turnOff, deleteHistory, renderNextMove, status: loadStatus, paintBriefing, refreshBriefing };
671
1308
 
672
1309
  // Ask once, after AI Chat is ready and the app has settled.
673
- const askLater = () => setTimeout(() => { void maybeAskOnLaunch(); }, 2500);
1310
+ // #2053: and, once settled, whether a morning briefing is ready or needs an answer.
1311
+ const askLater = () => setTimeout(() => { void maybeAskOnLaunch(); void refreshBriefing(); }, 2500);
674
1312
  if (window.flolessChat) askLater(); else window.addEventListener('floless:chat-ready', askLater, { once: true });
675
1313
  })();