@floless/app 0.150.0 → 0.152.0

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.
@@ -0,0 +1,1313 @@
1
+ /*
2
+ * The Guide (#2046): FloLess's built-in onboarding agent in AI Chat.
3
+ *
4
+ * This file owns everything the person sees of it outside the conversation itself: the first-launch question (with a
5
+ * preview of exactly what would be sent), the ways in ("Guide" in the ≡ menu, "Ask the Guide" on the empty Workflows
6
+ * and Workspaces pages), Turn off and Delete Guide history, and the next-move cards AI Chat shows in a Guide
7
+ * conversation. The server decides everything that matters (consent, what is sent, whether a turn may go); this file
8
+ * only shows it and relays the person's answers. Plan: docs/superpowers/specs/2026-10-07-2046-guide-agent-PLAN.md.
9
+ */
10
+ (function () {
11
+ 'use strict';
12
+
13
+ const PROVIDER_LABEL = { claude: 'Claude', codex: 'Codex' };
14
+ const PAGE_LABEL = {
15
+ workspaces: 'Workspaces', workflows: 'Workflows', agents: 'Agents', routines: 'Routines', tools: 'Tools',
16
+ discover: 'Discover Local Tools', integrations: 'Integrations', requests: 'Requests',
17
+ };
18
+ const SECTION_LABEL = {
19
+ apps: 'Installed programs', running: 'Open now', recentFiles: 'Recent files', accounts: 'Connected accounts',
20
+ };
21
+ const FLOLESS_LABEL = { projects: 'Projects', workflows: 'Workflows', agents: 'Agents', routines: 'Routines', tools: 'Tools' };
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
+
26
+ const state = {
27
+ sessionReady: false,
28
+ status: null,
29
+ preview: null,
30
+ previewError: '',
31
+ share: { windowTitles: true, recentFiles: true },
32
+ provider: null,
33
+ mode: 'consent', // 'consent' | 'start' | 'folder'
34
+ busy: false,
35
+ banner: '',
36
+ returnFocus: null,
37
+ lookSeq: 0,
38
+ closeSeq: 0, // bumped when the question closes; a Turn on in progress checks it between steps
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)
48
+ };
49
+
50
+ for (const type of ['pointerdown', 'keydown']) document.addEventListener(type, () => { state.lastInteractionAt = Date.now(); }, true);
51
+
52
+ const $modal = document.getElementById('guide-agent-modal');
53
+ const $title = document.getElementById('guide-modal-title');
54
+ let guideFlo = null; // #2140: the Guide's face, mounted on first opening
55
+ const $sub = document.getElementById('guide-modal-sub');
56
+ const $body = document.getElementById('guide-modal-body');
57
+ const $live = document.getElementById('guide-modal-live');
58
+ const $foot = document.getElementById('guide-modal-foot');
59
+ const $secondary = document.getElementById('guide-modal-secondary');
60
+ const $primary = document.getElementById('guide-modal-primary');
61
+
62
+ // ── talking to the server ─────────────────────────────────────────────────────────────────────────────────────
63
+ async function ensureSession() {
64
+ if (state.sessionReady) return;
65
+ let response;
66
+ try { response = await fetch('/api/chat/session', { credentials: 'same-origin' }); }
67
+ catch { throw new Error('FloLess could not be reached. Make sure it is still running, then try again.'); }
68
+ if (!response.ok) throw new Error('FloLess could not open AI Chat’s session, so the Guide could not load. Reload FloLess and try again.');
69
+ state.sessionReady = true;
70
+ }
71
+
72
+ async function api(path, body, retried = false) {
73
+ await ensureSession();
74
+ const init = { credentials: 'same-origin', method: body ? 'POST' : 'GET' };
75
+ if (body) { init.body = JSON.stringify(body); init.headers = { 'content-type': 'application/json' }; }
76
+ if (typeof AbortSignal?.timeout === 'function') init.signal = AbortSignal.timeout(60_000);
77
+ let response;
78
+ try { response = await fetch(path, init); }
79
+ catch (error) {
80
+ throw new Error(error?.name === 'TimeoutError'
81
+ ? 'FloLess took too long to answer, most likely because it is busy. Try again in a moment.'
82
+ : 'FloLess could not be reached. Make sure it is still running, then try again.');
83
+ }
84
+ let data = null;
85
+ try { data = await response.json(); } catch { data = null; }
86
+ if (response.status === 401 && data?.code === 'chat-session-required' && !retried) {
87
+ state.sessionReady = false;
88
+ return api(path, body, true);
89
+ }
90
+ if (!response.ok) {
91
+ const failure = new Error(data?.error || 'FloLess couldn’t do that just now. Try again; if it keeps happening, restart FloLess.');
92
+ failure.code = data?.code || null; failure.body = data;
93
+ throw failure;
94
+ }
95
+ return data;
96
+ }
97
+
98
+ const toast = (message, kind) => (typeof showToast === 'function' ? showToast(message, kind) : console.warn('[guide]', message));
99
+
100
+ async function loadStatus() {
101
+ const body = await api('/api/chat/guide');
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);
105
+ return state.status;
106
+ }
107
+
108
+ /** AIs the person can choose: ready ones, and ones FloLess could not finish checking (a busy computer). */
109
+ function readyProviders() {
110
+ return (state.status?.providers || []).filter((row) => row.ready || row.state === 'unknown').map((row) => row.provider);
111
+ }
112
+
113
+ function providerUnchecked(provider) {
114
+ return (state.status?.providers || []).some((row) => row.provider === provider && row.state === 'unknown');
115
+ }
116
+
117
+ function chooseProvider() {
118
+ const ready = readyProviders();
119
+ const current = window.flolessChat?.currentProvider?.() || null;
120
+ if (state.provider && ready.includes(state.provider)) return state.provider;
121
+ if (current && ready.includes(current)) return current;
122
+ return ready[0] || current || 'claude';
123
+ }
124
+
125
+ // ── opening the Guide conversation ────────────────────────────────────────────────────────────────────────────
126
+ async function openGuideChat(chatId) {
127
+ const chat = window.flolessChat;
128
+ if (!chat?.openConversation) { toast('AI Chat isn’t ready yet. Try again in a moment.', 'warn'); return false; }
129
+ try {
130
+ await chat.openConversation(chatId, { owner: { kind: 'workspace' } });
131
+ return true;
132
+ } catch (error) {
133
+ toast(error?.message || 'FloLess couldn’t open the Guide conversation. Try again.', 'warn');
134
+ return false;
135
+ }
136
+ }
137
+
138
+ /**
139
+ * The one way in, from every entry point. Signed out → says so. Guide on with a conversation → opens it. Anything
140
+ * else → the question (a click is never an unprompted ask, so it asks again after Not now or Turn off).
141
+ */
142
+ async function open(options = {}) {
143
+ state.returnFocus = options.returnFocus || (document.activeElement instanceof HTMLElement ? document.activeElement : null);
144
+ let status;
145
+ try { status = await loadStatus(); }
146
+ catch (error) { toast(error.message, 'warn'); return; }
147
+ if (!status.signedIn) { toast('Sign in to FloLess first. The Guide belongs to your FloLess account, so it starts once you are signed in.', 'warn'); return; }
148
+ if (status.consent?.choice === 'on' && status.activeChatId) { await openGuideChat(status.activeChatId); return; }
149
+ await showModal(status.consent?.choice === 'on' ? 'start' : 'consent');
150
+ }
151
+
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
+ */
160
+ async function maybeAskOnLaunch() {
161
+ if (state.launchAsked) return;
162
+ state.launchAsked = true;
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);
182
+ }
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
+ }
187
+ }
188
+
189
+ // ── the modal ─────────────────────────────────────────────────────────────────────────────────────────────────
190
+ function el(tag, className, text) {
191
+ const node = document.createElement(tag);
192
+ if (className) node.className = className;
193
+ if (text !== undefined) node.textContent = text;
194
+ return node;
195
+ }
196
+
197
+ function sectionList(items, render) {
198
+ const list = el('ul', 'guide-preview-list');
199
+ for (const item of items) list.append(el('li', '', render(item)));
200
+ return list;
201
+ }
202
+
203
+ function previewSection(label, section, render, extra) {
204
+ const details = el('details', 'guide-preview-section');
205
+ const summary = el('summary');
206
+ summary.dataset.commandId = `shell.guide-preview-section#${label}`;
207
+ const count = section?.items?.length || 0;
208
+ const omitted = section?.omitted || 0;
209
+ summary.textContent = `${label} · ${section?.problem ? 'couldn’t read' : omitted ? `${count} of ${count + omitted}` : count}`;
210
+ details.append(summary);
211
+ if (section?.problem) {
212
+ details.append(el('p', 'guide-preview-problem', `${section.problem} Only this note goes to the AI for this part.`));
213
+ } else if (extra) {
214
+ details.append(extra);
215
+ } else if (!count) {
216
+ details.append(el('p', 'guide-preview-empty', 'Nothing here.'));
217
+ } else {
218
+ details.append(sectionList(section.items, render));
219
+ }
220
+ if (omitted && !section?.problem) details.append(el('p', 'guide-preview-cut', `…and ${omitted} more not included.`));
221
+ return details;
222
+ }
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
+
238
+ function renderPreview() {
239
+ const wrap = el('div', 'guide-preview');
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
+ }
250
+ if (!look) {
251
+ const line = el('p', 'guide-preview-loading');
252
+ line.textContent = state.previewError || 'Looking at this computer… this takes a few seconds.';
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];
256
+ if (state.previewError) {
257
+ const again = el('button', '', 'Try again');
258
+ again.type = 'button';
259
+ again.dataset.commandId = 'shell.guide-preview-retry';
260
+ again.dataset.tip = 'Looks at this computer again.';
261
+ again.addEventListener('click', () => { void takeLook(state.lookBecause); });
262
+ parts.push(again);
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);
266
+ return wrap;
267
+ }
268
+ const counts = look.recentFiles?.countsByType || {};
269
+ const countLine = Object.keys(counts).length
270
+ ? el('p', 'guide-preview-empty', `Only counts: ${Object.entries(counts).map(([type, n]) => `${n} × .${type}`).join(', ')}. No names or folders.`)
271
+ : null;
272
+ const flo = look.floless || {};
273
+ const floBlock = el('div');
274
+ for (const key of Object.keys(FLOLESS_LABEL)) {
275
+ const section = flo[key];
276
+ const line = el('p', 'guide-preview-empty');
277
+ line.textContent = section?.problem
278
+ ? `${FLOLESS_LABEL[key]}: couldn’t read`
279
+ : `${FLOLESS_LABEL[key]}: ${(section?.items || []).length ? section.items.join(', ') : 'none'}`;
280
+ floBlock.append(line);
281
+ }
282
+ const summary = el('p', 'guide-preview-summary');
283
+ const part = (section, count, noun) => (section?.problem ? `${noun}: couldn’t read` : `${count} ${noun}`);
284
+ summary.textContent = `Looks like: ${part(look.apps, look.apps?.items?.length || 0, 'programs')} · ${part(look.running, look.running?.items?.length || 0, 'open')} · `
285
+ + `${part(look.recentFiles, state.share.recentFiles ? (look.recentFiles?.items?.length || 0) : Object.values(counts).reduce((a, b) => a + b, 0), 'recent files')} · `
286
+ + `${part(look.accounts, look.accounts?.items?.length || 0, 'accounts')}.`;
287
+ const region = el('div', 'guide-preview-scroll');
288
+ region.setAttribute('role', 'region');
289
+ region.setAttribute('aria-label', 'Preview of what will be sent');
290
+ region.tabIndex = 0;
291
+ region.append(
292
+ previewSection(SECTION_LABEL.apps, look.apps, (app) => (app.version ? `${app.name} (${app.version})` : app.name)),
293
+ previewSection(SECTION_LABEL.running, look.running, (row) => (row.title ? `${row.name} — ${row.title}` : row.name)),
294
+ previewSection(SECTION_LABEL.recentFiles, look.recentFiles, (file) => `${file.name} — ${file.folder}`, state.share.recentFiles ? null : countLine),
295
+ previewSection(SECTION_LABEL.accounts, look.accounts, (row) => `${row.service}: ${row.status}`),
296
+ (() => {
297
+ const details = el('details', 'guide-preview-section');
298
+ const holds = el('summary', '', 'What FloLess holds');
299
+ holds.dataset.commandId = 'shell.guide-preview-section#What FloLess holds';
300
+ details.append(holds, floBlock);
301
+ return details;
302
+ })(),
303
+ );
304
+ const disclosure = previewDisclosure(region,
305
+ el('p', 'guide-preview-foot', 'Sent as plain facts, marked as data — never as instructions.'));
306
+ wrap.append(summary, disclosure);
307
+ return wrap;
308
+ }
309
+
310
+ function switchRow(id, label, help, key) {
311
+ const row = el('div', 'guide-switch');
312
+ const toggle = el('label', 'rtn-toggle');
313
+ const input = document.createElement('input');
314
+ input.type = 'checkbox'; input.id = id; input.setAttribute('role', 'switch');
315
+ input.checked = state.share[key];
316
+ input.dataset.commandId = `shell.guide-share-${key === 'windowTitles' ? 'window-titles' : 'recent-files'}`;
317
+ input.setAttribute('aria-describedby', `${id}-help`);
318
+ input.addEventListener('change', () => { state.share = { ...state.share, [key]: input.checked }; relook(); });
319
+ toggle.append(input, el('span', 'rtn-toggle-track'));
320
+ const text = el('div', 'guide-switch-text');
321
+ const name = el('label', 'guide-switch-label', label); name.htmlFor = id;
322
+ const note = el('div', 'guide-switch-help', help); note.id = `${id}-help`;
323
+ text.append(name, note);
324
+ row.append(toggle, text);
325
+ return row;
326
+ }
327
+
328
+ function providerChoice() {
329
+ const ready = readyProviders();
330
+ const wrap = el('div', 'guide-provider');
331
+ if (ready.length === 2) {
332
+ const group = el('div', 'guide-provider-group');
333
+ group.setAttribute('role', 'radiogroup');
334
+ group.setAttribute('aria-label', 'Which AI reads this?');
335
+ group.append(el('span', 'guide-switch-label', 'Which AI reads this?'));
336
+ for (const provider of ready) {
337
+ const option = el('label', 'guide-provider-option');
338
+ const radio = document.createElement('input');
339
+ radio.type = 'radio'; radio.name = 'guide-provider'; radio.value = provider;
340
+ radio.checked = provider === state.provider;
341
+ radio.dataset.commandId = `shell.guide-provider#${PROVIDER_LABEL[provider]}`;
342
+ radio.addEventListener('change', () => { state.provider = provider; relook(); });
343
+ option.append(radio, document.createTextNode(` ${PROVIDER_LABEL[provider]}`));
344
+ group.append(option);
345
+ }
346
+ wrap.append(group);
347
+ } else if (ready.length === 1) {
348
+ wrap.append(el('p', 'guide-switch-help', providerUnchecked(ready[0])
349
+ ? `Sent to ${PROVIDER_LABEL[ready[0]]}. FloLess couldn’t finish checking it just now; the Guide will try anyway, and says so if it can’t start.`
350
+ : `Sent to ${PROVIDER_LABEL[ready[0]]}, the AI you’re signed in with.`));
351
+ } else {
352
+ wrap.append(el('p', 'guide-switch-help', 'No AI is signed in yet. You can still turn the Guide on; it starts once you sign in to Claude Code or Codex in AI Chat.'));
353
+ }
354
+ return wrap;
355
+ }
356
+
357
+ /**
358
+ * Repaint the question. A repaint replaces the controls, so a focused one is gone and focus would fall to the page
359
+ * behind, out of reach of the dialog's own keys (independent QA, #2046). When focus WAS in the question, it goes back
360
+ * to the control with the same id, else the title. When it was elsewhere (a dialog opened over the Guide), it is left
361
+ * there.
362
+ */
363
+ function paint() {
364
+ const active = document.activeElement;
365
+ const wasInside = Boolean(active && active !== document.body && $modal.contains(active));
366
+ const focusedId = wasInside && active.id ? active.id : null;
367
+ paintBody();
368
+ if (!wasInside || !$modal.classList.contains('show')) return;
369
+ const again = focusedId ? document.getElementById(focusedId) : null;
370
+ if (again && $modal.contains(again)) again.focus();
371
+ else $title.focus();
372
+ }
373
+
374
+ function paintBody() {
375
+ const providerName = PROVIDER_LABEL[state.provider] || 'the AI you chose';
376
+ $body.replaceChildren();
377
+ $foot.textContent = '';
378
+ if (state.mode === 'folder') {
379
+ $title.textContent = 'Let the Guide show you around?';
380
+ $sub.textContent = 'First, choose where your projects live.';
381
+ $body.append(el('p', 'guide-copy', 'The Guide keeps its conversation in your projects folder, next to your work. Choose it now; you can change it later in ≡ → Workspace directory.'));
382
+ $primary.textContent = 'Choose folder…';
383
+ $primary.dataset.commandId = 'shell.guide-choose-folder';
384
+ $secondary.textContent = 'Not now';
385
+ $secondary.dataset.commandId = 'shell.guide-not-now';
386
+ $foot.textContent = 'You can turn the Guide on later: ≡ menu → Guide.';
387
+ return;
388
+ }
389
+ const off = state.status?.consent?.choice === 'off';
390
+ $title.textContent = state.mode === 'start' ? 'Start the Guide' : off ? 'Turn the Guide back on?' : 'Let the Guide show you around?';
391
+ $sub.textContent = state.mode === 'start'
392
+ ? 'The Guide takes a fresh look at this computer and starts its conversation in AI Chat. Here is what it would send.'
393
+ : 'The Guide is an assistant in AI Chat. It looks at what you work with on this computer, tells you what it sees, and suggests what to set up next.';
394
+ if (state.mode === 'consent') {
395
+ const reads = el('div', 'guide-block');
396
+ reads.append(el('h3', 'guide-heading', 'What it looks at'));
397
+ reads.append(sectionList([
398
+ 'Programs installed on this computer, and which ones are open right now.',
399
+ 'Files you opened recently — names and folders; FloLess doesn’t read inside them.',
400
+ 'The accounts you’ve connected in FloLess — their names and whether they work, never passwords.',
401
+ 'Email and Teams only if you later turn on your own connectors in the Guide chat. Claude asks before each use; Codex asks too, except for tools that declare themselves read-only.',
402
+ 'While you talk, the Guide may open more files or folders to answer you.',
403
+ ], (line) => line));
404
+ const lock = el('div', 'guide-callout');
405
+ lock.append(el('strong', '', 'It only reads — but read-only isn’t a lock. '),
406
+ document.createTextNode('The Guide is told never to change anything, and every change is a button you press. That is a rule the AI follows, not a lock: the AI program can open any folder you can.'));
407
+ const where = el('p', 'guide-copy');
408
+ where.textContent = `What the Guide sees is sent to ${providerName} under your own subscription, and kept in this conversation’s history on this computer. You can turn the Guide off or delete its history at any time; whatever ${providerName} already received stays under its own rules.`;
409
+ const gives = el('p', 'guide-copy', 'You get a short briefing on what you seem to be working on, then suggested next moves as buttons.');
410
+ $body.append(reads, lock, where, gives);
411
+ }
412
+ $body.append(
413
+ switchRow('guide-share-titles', 'Window titles', 'Shows what is open inside each running program. Off: program names only.', 'windowTitles'),
414
+ switchRow('guide-share-files', 'Recent file names', 'Off: only counts, such as “12 drawings, 3 models”. No names or folders.', 'recentFiles'),
415
+ providerChoice(),
416
+ renderPreview(),
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());
420
+ if (state.banner) {
421
+ const banner = el('p', 'guide-banner', state.banner);
422
+ banner.setAttribute('role', 'status');
423
+ $body.append(banner);
424
+ }
425
+ $primary.textContent = state.busy ? 'Starting…' : state.mode === 'start' ? 'Start the Guide' : 'Turn on the Guide';
426
+ $primary.dataset.commandId = state.mode === 'start' ? 'shell.guide-start' : 'shell.guide-turn-on';
427
+ $primary.setAttribute('aria-busy', String(state.busy));
428
+ $secondary.textContent = state.mode === 'start' ? 'Cancel' : 'Not now';
429
+ $secondary.dataset.commandId = state.mode === 'start' ? 'shell.dialog-cancel#the Guide' : 'shell.guide-not-now';
430
+ if (state.mode === 'consent') $foot.textContent = 'You can turn the Guide on later: ≡ menu → Guide.';
431
+ }
432
+
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) {
438
+ const seq = ++state.lookSeq;
439
+ state.lookBecause = because;
440
+ state.preview = null; state.previewError = '';
441
+ paint();
442
+ let landed = false;
443
+ try {
444
+ const body = await api('/api/chat/guide/preview', { provider: state.provider, share: state.share, because });
445
+ if (seq !== state.lookSeq) return false;
446
+ state.preview = body.preview;
447
+ landed = true;
448
+ $live.textContent = 'Preview updated.';
449
+ } catch (error) {
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}`;
454
+ }
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);
462
+ }
463
+
464
+ let keyHandler = null;
465
+ async function showModal(mode) {
466
+ // One question at a time: a second ask while it is open (two clicks, the launch question racing ≡ → Guide) changes
467
+ // nothing, and never adds a second key listener.
468
+ if ($modal.classList.contains('show')) return;
469
+ if (keyHandler) { $modal.removeEventListener('keydown', keyHandler); keyHandler = null; }
470
+ state.provider = chooseProvider();
471
+ state.share = state.status?.consent?.share ? { ...state.status.consent.share } : { windowTitles: true, recentFiles: true };
472
+ state.banner = ''; state.busy = false; state.preview = null; state.previewError = ''; state.briefingAsk = false;
473
+ state.lookBecause = null; state.previewOpen = false;
474
+ state.mode = !state.status?.workspace ? 'folder' : mode;
475
+ paint();
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
+ }
483
+ $title.focus();
484
+ keyHandler = (event) => {
485
+ if (event.key === 'Escape') { event.preventDefault(); void dismiss(); }
486
+ if (event.key === 'Tab') {
487
+ const focusable = [...$modal.querySelectorAll('button, input, summary, [tabindex="0"]')].filter((node) => !node.disabled && node.offsetParent !== null);
488
+ if (!focusable.length) return;
489
+ const first = focusable[0]; const last = focusable[focusable.length - 1];
490
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
491
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
492
+ }
493
+ };
494
+ // Heard on the dialog only: Esc pressed in a dialog opened over the Guide belongs to that dialog.
495
+ $modal.addEventListener('keydown', keyHandler);
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');
499
+ }
500
+
501
+ function closeModal() {
502
+ $modal.classList.remove('show');
503
+ if (keyHandler) $modal.removeEventListener('keydown', keyHandler);
504
+ keyHandler = null;
505
+ state.lookSeq += 1;
506
+ state.closeSeq += 1; // a Turn on still in progress stops before its next step (#2054 review)
507
+ const back = state.returnFocus?.isConnected ? state.returnFocus : document.getElementById('menu-btn');
508
+ back?.focus?.();
509
+ }
510
+
511
+ /** Not now (or Esc): remembered for a first-launch question; Cancel in start mode changes nothing. */
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; }
515
+ const asking = state.mode !== 'start' && state.status?.consent?.choice !== 'off' && state.status?.consent?.choice !== 'on';
516
+ closeModal();
517
+ if (!asking) return;
518
+ try { await api('/api/chat/guide/consent', { choice: 'not-now', share: state.share }); }
519
+ catch (error) { toast(error.message, 'warn'); }
520
+ }
521
+
522
+ async function chooseFolder() {
523
+ if (typeof openWorkspaceRoot !== 'function') { toast('Open ≡ → Workspace directory to choose where your projects live, then open the Guide again.', 'warn'); return; }
524
+ closeModal();
525
+ await openWorkspaceRoot();
526
+ // The folder chooser is its own dialog; when it closes with a folder set, this question continues.
527
+ const until = Date.now() + 10 * 60 * 1000;
528
+ while (Date.now() < until && document.querySelector('.modal-backdrop.show')) await new Promise((resolve) => setTimeout(resolve, 500));
529
+ try { await loadStatus(); }
530
+ catch (error) { toast(`FloLess couldn’t continue to the Guide: ${error.message} Open it again from ≡ → Guide.`, 'warn'); return; }
531
+ if (state.status?.workspace) await showModal('consent');
532
+ }
533
+
534
+ async function confirm() {
535
+ if (state.mode === 'folder') { await chooseFolder(); return; }
536
+ if (state.busy) 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
+ }
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
+ }
557
+ try {
558
+ const agreed = state.status?.consent?.share;
559
+ const changed = !agreed || agreed.windowTitles !== state.share.windowTitles || agreed.recentFiles !== state.share.recentFiles;
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;
563
+ if (state.mode === 'consent' || changed) {
564
+ const answer = await api('/api/chat/guide/consent', { choice: 'on', share: state.share, previewId: state.preview.previewId, ...(briefing ? { provider: state.provider, briefing } : {}) });
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;
579
+ }
580
+ if (!readyProviders().includes(state.provider)) {
581
+ closeModal();
582
+ toast(`The Guide is on. It starts once you sign in to ${PROVIDER_LABEL[state.provider] || 'Claude Code or Codex'} in AI Chat — then open it from ≡ → Guide.`, 'info');
583
+ return;
584
+ }
585
+ const started = await api('/api/chat/guide/start', {
586
+ provider: state.provider, previewId: state.preview.previewId, submissionId: crypto.randomUUID(),
587
+ });
588
+ closeModal();
589
+ await openGuideChat(started.chatId);
590
+ } catch (error) {
591
+ if (error.code === 'guide-preview-needed' && error.body?.preview) {
592
+ // Something changed since the person looked: show the fresh look; the next press sends that one.
593
+ state.mode = 'start';
594
+ state.preview = error.body.preview;
595
+ // The switches show exactly what this fresh preview was taken with.
596
+ if (error.body.preview.share) state.share = { ...error.body.preview.share };
597
+ state.banner = 'Something changed since you looked (or it’s been a while), so here is a fresh preview. Check it, then press Start the Guide.';
598
+ } else {
599
+ state.banner = error.message;
600
+ }
601
+ state.busy = false;
602
+ paint();
603
+ }
604
+ }
605
+
606
+ $primary?.addEventListener('click', () => { void confirm(); });
607
+ $secondary?.addEventListener('click', () => { void dismiss(); });
608
+
609
+ // ── Turn off / Delete (AI Chat's settings in a Guide conversation) ────────────────────────────────────────────
610
+ async function turnOff() {
611
+ try {
612
+ const body = await api('/api/chat/guide/consent', { choice: 'off' });
613
+ if (body.notStopped) {
614
+ toast('The Guide is off, but an answer it was writing could not be stopped. Press Stop in AI Chat to end it.', 'warn');
615
+ } else {
616
+ // Only this projects folder's answers can be stopped from here; one still running in another folder finishes
617
+ // the answer it is writing, and nothing more is sent to it (plan §1, as built). Say so rather than promise more.
618
+ const elsewhere = ' An answer it may still be writing for another projects folder finishes on its own; nothing more is sent to it.';
619
+ toast((body.stopped ? 'The Guide is off, and its work in progress here was stopped.' : 'The Guide is off. It won’t look at this computer again until you turn it on (≡ → Guide).') + elsewhere, 'info');
620
+ }
621
+ await loadStatus().catch(() => null);
622
+ return true;
623
+ } catch (error) { toast(error.message, 'warn'); return false; }
624
+ }
625
+
626
+ async function deleteHistory() {
627
+ const ok = await confirmDelete();
628
+ if (!ok) return false;
629
+ try {
630
+ const body = await api('/api/chat/guide/delete', {});
631
+ if (body.failed) {
632
+ toast(`${body.deleted ? `Deleted ${body.deleted} Guide conversation${body.deleted === 1 ? '' : 's'}, but` : 'FloLess couldn’t delete'} ${body.failed} ${body.failed === 1 ? 'is' : 'are'} still busy or locked. Stop any answer in AI Chat, then delete again.`, 'warn');
633
+ } else {
634
+ toast(body.deleted ? 'Guide history deleted.' : 'There was no Guide history here to delete.', 'info');
635
+ }
636
+ await window.flolessChat?.refreshScope?.(true);
637
+ return true;
638
+ } catch (error) { toast(error.message, 'warn'); return false; }
639
+ }
640
+
641
+ function confirmDelete() {
642
+ return new Promise((resolve) => {
643
+ const $confirm = document.getElementById('guide-delete-modal');
644
+ const cancel = document.getElementById('guide-delete-cancel');
645
+ const go = document.getElementById('guide-delete-confirm');
646
+ const back = document.activeElement instanceof HTMLElement ? document.activeElement : null;
647
+ const done = (value) => {
648
+ $confirm.classList.remove('show');
649
+ $confirm.removeEventListener('keydown', onKey);
650
+ cancel.removeEventListener('click', onCancel); go.removeEventListener('click', onGo);
651
+ back?.focus?.();
652
+ resolve(value);
653
+ };
654
+ const onKey = (event) => { if (event.key === 'Escape') { event.preventDefault(); done(false); } };
655
+ const onCancel = () => done(false);
656
+ const onGo = () => done(true);
657
+ $confirm.addEventListener('keydown', onKey);
658
+ cancel.addEventListener('click', onCancel); go.addEventListener('click', onGo);
659
+ $confirm.classList.add('show');
660
+ cancel.focus();
661
+ });
662
+ }
663
+
664
+ // ── next-move cards ───────────────────────────────────────────────────────────────────────────────────────────
665
+ function moveText(move) {
666
+ switch (move?.kind) {
667
+ case 'install-tool': return { title: `Install ${move.toolName}`, action: 'Review and install…' };
668
+ case 'create-workflow': return { title: `Create a workflow: ${move.name}`, action: 'Start this workflow…', detail: move.purpose };
669
+ case 'create-agent': return { title: `Set up an agent: ${move.name}`, action: 'Review this agent…' };
670
+ case 'create-routine': return { title: `Run ${move.target?.name || 'it'} on a schedule`, action: 'Set up the schedule…' };
671
+ case 'open': return { title: `Open ${PAGE_LABEL[move.page] || 'this page'}`, action: `Open ${PAGE_LABEL[move.page] || 'it'}` };
672
+ default: return null;
673
+ }
674
+ }
675
+
676
+ /** Opens the existing flow for a move; true when it opened. Nothing is done from here. */
677
+ async function openFlow(move) {
678
+ const bridge = window.flolessBridge;
679
+ switch (move.kind) {
680
+ case 'install-tool':
681
+ if (typeof openLibrary !== 'function') return false;
682
+ openLibrary(move.toolId, { tab: 'available' }); return true; // not installed yet: where its Install button is
683
+ case 'create-workflow':
684
+ if (typeof bridge?.newWorkflow !== 'function') return false;
685
+ await bridge.newWorkflow({ name: move.name }); return true;
686
+ case 'create-agent':
687
+ return Boolean(await window.flolessAgents?.newDraft?.({ name: move.name, instructions: move.instructions }));
688
+ case 'create-routine':
689
+ if (move.target?.kind === 'agent') { await window.flolessRoutines?.editForAgent?.(move.target.id); return Boolean(window.flolessRoutines); }
690
+ await window.flolessRoutines?.editForWorkflow?.(move.target?.id); return Boolean(window.flolessRoutines?.editForWorkflow);
691
+ case 'open':
692
+ if (['workspaces', 'workflows', 'agents'].includes(move.page)) { await window.flolessWorkspaces?.setMode?.(move.page); return Boolean(window.flolessWorkspaces); }
693
+ if (move.page === 'routines' && typeof openRoutines === 'function') { openRoutines(); return true; }
694
+ if (move.page === 'tools' && typeof openLibrary === 'function') { openLibrary(); return true; }
695
+ if (move.page === 'integrations' && typeof openIntegrations === 'function') { openIntegrations(); return true; }
696
+ // Discover Local Tools answers the same ≡-menu action the Tools window's button uses (web/local-discovery.js).
697
+ if (move.page === 'discover' && typeof handleMenuAction === 'function') { handleMenuAction('discover-local'); return Boolean(document.querySelector('#local-discovery-modal.show')); }
698
+ if (move.page === 'requests' && typeof bridge?.openRequest === 'function') { await bridge.openRequest(null); return true; }
699
+ return false;
700
+ default: return false;
701
+ }
702
+ }
703
+
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;
751
+ }
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);
795
+ }
796
+
797
+ /** A next-move event as a card. Its text is the AI's: textContent only. */
798
+ function renderNextMove(event) {
799
+ const payload = event.payload || {};
800
+ const move = payload.move;
801
+ const text = moveText(move);
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 : '';
804
+ if (!text) return null;
805
+ ensureSetAsideLoaded();
806
+ const card = el('section', 'ai-chat-filter-card ai-chat-connection-card guide-move-card');
807
+ card.dataset.eventId = event.eventId;
808
+ card.dataset.eventSequence = String(event.sequence);
809
+ card.setAttribute('role', 'group');
810
+ card.setAttribute('aria-label', `Suggestion: ${text.title}`);
811
+ const status = el('p', 'ai-chat-filter-note guide-move-status');
812
+ status.setAttribute('role', 'status');
813
+ const paintCard = () => {
814
+ const focusBack = card.contains(document.activeElement);
815
+ card.replaceChildren();
816
+ const aside = setAsideFor(moveKey, move);
817
+ if (aside) {
818
+ moveKey = aside.key;
819
+ const line = el('div', 'ai-chat-connection-collapsed');
820
+ const undo = el('button', '', 'Undo');
821
+ undo.type = 'button';
822
+ undo.dataset.commandId = 'shell.guide-move-undo';
823
+ undo.dataset.commandInstanceLabel = text.title;
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
+ });
830
+ line.append(el('span', '', `Not now: ${text.title}`), undo);
831
+ card.append(line, status);
832
+ if (focusBack) undo.focus();
833
+ return;
834
+ }
835
+ const head = el('div', 'ai-chat-filter-card-head');
836
+ head.append(el('span', 'guide-move-eyebrow', 'Suggested'), el('strong', '', text.title));
837
+ card.append(head);
838
+ const why = typeof payload.why === 'string' ? payload.why.trim() : '';
839
+ if (text.detail) card.append(el('p', 'ai-chat-filter-why', text.detail));
840
+ if (why) card.append(el('p', 'ai-chat-filter-why', why));
841
+ const actions = el('div', 'ai-chat-filter-actions');
842
+ const go = el('button', 'ai-chat-filter-apply', text.action);
843
+ go.type = 'button';
844
+ go.dataset.commandId = `shell.guide-move-open#${move.kind}`;
845
+ go.dataset.commandInstanceLabel = text.title;
846
+ go.dataset.tip = 'Opens the place to do this. Nothing happens until you confirm there.';
847
+ go.addEventListener('click', async () => {
848
+ go.disabled = true; go.setAttribute('aria-busy', 'true'); go.textContent = 'Checking…';
849
+ status.textContent = '';
850
+ try {
851
+ const { check } = await api('/api/chat/guide/next-moves/recheck', { move });
852
+ if (!check.ok) { status.textContent = check.message; return; }
853
+ const opened = await openFlow(move);
854
+ if (!opened) status.textContent = 'FloLess couldn’t open that from here. Open it from the ≡ menu instead.';
855
+ } catch (error) {
856
+ status.textContent = error.message;
857
+ } finally {
858
+ go.disabled = false; go.removeAttribute('aria-busy'); go.textContent = text.action;
859
+ }
860
+ });
861
+ const later = el('button', '', 'Not now');
862
+ later.type = 'button';
863
+ later.dataset.commandId = 'shell.guide-move-not-now';
864
+ later.dataset.commandInstanceLabel = text.title;
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
+ });
876
+ actions.append(go, later);
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();
879
+ };
880
+ cardPainters.set(card, paintCard);
881
+ unplacedCards.add(card);
882
+ if (unplacedCards.size > 100) unplacedCards.delete(unplacedCards.values().next().value);
883
+ paintCard();
884
+ return card;
885
+ }
886
+
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 };
1308
+
1309
+ // Ask once, after AI Chat is ready and the app has settled.
1310
+ // #2053: and, once settled, whether a morning briefing is ready or needs an answer.
1311
+ const askLater = () => setTimeout(() => { void maybeAskOnLaunch(); void refreshBriefing(); }, 2500);
1312
+ if (window.flolessChat) askLater(); else window.addEventListener('floless:chat-ready', askLater, { once: true });
1313
+ })();