@floless/app 0.160.0 → 0.161.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.
@@ -1,11 +1,12 @@
1
1
  /*
2
2
  * A General project's RFIs step (#2470 R6.6): the project's questions for the engineer, client or architect. Each RFI
3
- * may cite a page of this project's Knowledge or a saved sheet of a project linked on its Modules step; FloLess gives
4
- * the email text to send and keeps what was sent, answered and closed. It sends nothing itself (Gmail is R6.6b).
3
+ * may cite a page of this project's Knowledge or a saved sheet of a project linked on its Modules step; FloLess sends
4
+ * it through the connected Gmail account (R6.6b, the same delivery engine as Steel's) or gives the email text for the
5
+ * person to send, and keeps what was sent, answered and closed.
5
6
  *
6
7
  * It renders GET /api/projects/:id/correspondence-rfis and changes RFIs only through that route family. Every write
7
- * names the Workspace and project it was shown (rootId + project uuid from the read). Spec:
8
- * docs/superpowers/specs/2026-10-23-2470-r6-6-rfis-tab-PLAN.md.
8
+ * names the Workspace and project it was shown (rootId + project uuid from the read). Specs:
9
+ * docs/superpowers/specs/2026-10-23-2470-r6-6-rfis-tab-PLAN.md and 2026-10-26-2470-r6-6b-general-rfis-gmail-PLAN.md (§6).
9
10
  */
10
11
  (() => {
11
12
  const bridge = () => window.flolessBridge || {};
@@ -24,6 +25,26 @@
24
25
  const refused = (error) => !!error?.status && error.status >= 400 && error.status < 500 && typeof error?.body?.error === 'string';
25
26
  const newKey = () => `rfi-${crypto.randomUUID()}`;
26
27
  const MAX_CITES = 5;
28
+ const isAddress = (s) => /^[^\s@<>()",;:]+@[^\s@<>()",;:]+\.[^\s@<>()",;:]+$/.test(String(s || '').trim());
29
+
30
+ // ── Gmail (#2470 R6.6b): readiness, and what each send state says (Steel's meaning, the step's words) ──────────────
31
+
32
+ const READINESS_TEXT = {
33
+ 'connect-google': 'Connect Google Workspace in Integrations before sending from FloLess.',
34
+ 'update-aware': 'Update AWARE before sending from FloLess.',
35
+ 'update-agent': 'Update the Google Workspace integration before sending from FloLess.',
36
+ 'fix-google-access': 'Reconnect Google Workspace with Gmail send access in Integrations.',
37
+ busy: 'Gmail sending is busy with another request. Try again when it finishes.',
38
+ unavailable: 'FloLess couldn’t check the connected Google account just now.',
39
+ };
40
+ /** Readiness that a retry may fix: the person can still try to send beside the sentence. */
41
+ const TRANSIENT = new Set(['busy', 'unavailable']);
42
+ /** Readiness whose fix is in Integrations. */
43
+ const FIX_IN_INTEGRATIONS = new Set(['connect-google', 'fix-google-access', 'update-agent']);
44
+ const readinessText = (r) => (r?.status === 'loading' ? 'Checking the connected Google account…'
45
+ : r?.status === 'ready' ? '' : (r?.message || READINESS_TEXT[r?.status] || 'Gmail sending isn’t available just now.'));
46
+ const unresolved = (d) => d && (d.status === 'prepared' || d.status === 'outcome-unknown');
47
+ const HELD = 'Mark sent, Answer and Close are held back until this is settled, so the RFI’s history stays true.';
27
48
 
28
49
  function ago(iso, now = Date.now()) {
29
50
  const t = Date.parse(iso);
@@ -114,6 +135,42 @@
114
135
  data-command-id="shell.project-rfi-close-note#${esc(rfi.id)}" data-command-instance-label="${id}"${busy}${ro}>${esc(draft.note || '')}</textarea></label>`;
115
136
  primary = 'Close RFI'; break;
116
137
  }
138
+ case 'gmail': {
139
+ const readiness = state.readiness;
140
+ const notReady = readiness?.status !== 'ready';
141
+ const blocking = notReady && !TRANSIENT.has(readiness?.status) && readiness?.status !== 'loading';
142
+ const why = notReady ? `<p class="pm-note pr-readiness" role="status">${esc(readinessText(readiness))}</p>` : '';
143
+ if (blocking) {
144
+ // Not ready, and a send can't work until something is fixed: say what, and offer the other ways — never a dead control.
145
+ const fix = FIX_IN_INTEGRATIONS.has(readiness?.status)
146
+ ? `<button type="button" class="primary" data-pr-gmail-integrations="1" data-command-id="shell.project-rfis-gmail-integrations">Open Integrations</button>` : '';
147
+ return `<div class="pr-form" role="group" aria-label="${esc(`Send ${rfi.id} with Gmail`)}">${why}
148
+ <div class="pm-strip-acts pr-form-acts">
149
+ ${fix}
150
+ <button type="button" class="ghost" data-pr-gmail-recheck="1" data-command-id="shell.project-rfis-gmail-recheck">Check again</button>
151
+ <button type="button" class="ghost" data-pr-copy="${id}" data-command-id="shell.project-rfi-copy#${esc(rfi.id)}" data-command-instance-label="${id}">Copy email text</button>
152
+ ${rfi.verbs.includes('mark-sent') ? `<button type="button" class="ghost" data-pr-verb="mark-sent" data-pr-rfi="${id}" data-command-id="shell.project-rfi-mark-sent#${esc(rfi.id)}" data-command-instance-label="${id}">Mark sent…</button>` : ''}
153
+ <button type="button" class="ghost" data-pr-form-cancel="1" data-command-id="shell.project-rfi-form-cancel#${esc(rfi.id)}" data-command-instance-label="${id}">Cancel</button>
154
+ </div></div>`;
155
+ }
156
+ const frozen = form.busy || form.uncertain ? ' readonly' : '';
157
+ const lineBusy = form.busy ? `<p class="pm-note" role="status">${form.slow ? 'Still waiting for Gmail…' : 'Sending through Gmail. Keep this open until it finishes.'}</p>` : '';
158
+ const lost = form.uncertain ? '<p class="pm-note pr-alert" role="alert">FloLess didn’t get an answer, so it can’t tell whether Gmail sent this. Try again won’t send it twice. Or check the list first.</p>' : '';
159
+ const err = form.error ? `<p class="pm-note pr-alert" role="alert">${esc(form.error)}</p>` : '';
160
+ const held = form.busy ? ' aria-disabled="true" data-blocked-reason="Sending through Gmail. Wait for it to finish."' : '';
161
+ return `<div class="pr-form" role="group" aria-label="${esc(`Send ${rfi.id} with Gmail`)}"${form.busy ? ' aria-busy="true"' : ''}>${why}
162
+ <label class="pr-field">Send to<input type="email" class="pr-input" data-pr-input="to" value="${esc(draft.to || '')}" autocomplete="email"
163
+ data-command-id="shell.project-rfi-gmail-to#${esc(rfi.id)}" data-command-instance-label="${id}"${frozen}></label>
164
+ <p class="pg-row-meta">Gmail sends this RFI’s email text from your connected Google account, with a reference line FloLess uses to find it later in Sent.</p>
165
+ ${lineBusy}${err}${lost}
166
+ <div class="pm-strip-acts pr-form-acts">
167
+ ${form.uncertain
168
+ ? `<button type="button" class="ghost" data-pr-gmail-check="1" data-command-id="shell.project-rfi-gmail-check-list#${esc(rfi.id)}" data-command-instance-label="${id}">Check the list</button>`
169
+ : `<button type="button" class="ghost" data-pr-form-cancel="1" data-command-id="shell.project-rfi-form-cancel#${esc(rfi.id)}" data-command-instance-label="${id}"${held}${form.busy ? ' data-tip="A send in progress can’t be cancelled"' : ''}>Cancel</button>`}
170
+ <button type="button" class="primary" data-pr-form-submit="1" data-command-id="shell.project-rfi-gmail-submit#${esc(rfi.id)}" data-command-instance-label="${id}"
171
+ aria-label="${esc(`Send ${rfi.id} with Gmail`)}"${held}>${form.uncertain ? 'Try again' : form.busy ? 'Sending…' : 'Send email'}</button>
172
+ </div></div>`;
173
+ }
117
174
  case 'reopen':
118
175
  fields = `<label class="pr-field">Why is this open again?<textarea class="pr-input pr-text" data-pr-input="why" rows="2" maxlength="1000"
119
176
  data-command-id="shell.project-rfi-reopen-why#${esc(rfi.id)}" data-command-instance-label="${id}"${busy}${ro}>${esc(draft.why || '')}</textarea></label>`;
@@ -133,7 +190,7 @@
133
190
  const id = esc(rfi.id);
134
191
  const label = `data-command-instance-label="${id}"`;
135
192
  const meta = [];
136
- if (rfi.sent) meta.push(`<span data-tip="${esc(exact(rfi.sent.at))}">Marked sent to ${esc(rfi.sent.to)} · ${esc(ago(rfi.sent.at, now))}</span>`);
193
+ if (rfi.sent) meta.push(`<span data-tip="${esc(exact(rfi.sent.at))}">${rfi.sent.via === 'gmail' ? 'Sent with Gmail to' : 'Marked sent to'} ${esc(rfi.sent.to)} · ${esc(ago(rfi.sent.at, now))}</span>`);
137
194
  else meta.push(`<span data-tip="${esc(exact(rfi.raisedAt))}">Filed ${esc(ago(rfi.raisedAt, now))}${rfi.raisedBy === 'ai' ? ' by AI Chat' : ''}</span>`);
138
195
  if (rfi.reopens) meta.push(`Reopened ${rfi.reopens === 1 ? 'once' : `${rfi.reopens} times`}`);
139
196
  const answer = rfi.answer ? `<blockquote class="pr-answer"><span class="pr-answer-label">Answer</span> ${esc(rfi.answer.text)}</blockquote>` : '';
@@ -143,29 +200,56 @@
143
200
  const drifted = rfi.citations.some((c) => c.state !== 'current');
144
201
  const driftNote = drifted ? '<p class="pg-row-meta">One cited item no longer matches. You can send the RFI as it was, or File again from this… with the current items.</p>' : '';
145
202
  const form = state.form && state.form.rfiId === rfi.id ? formHtml(rfi, state.form) : '';
203
+ const d = rfi.delivery;
204
+ const pending = unresolved(d);
205
+ const recovering = state.recovering?.rfiId === rfi.id ? state.recovering.action : null;
206
+ // While a send is in flight on another row, its sends and records wait (one open form at a time).
207
+ const elsewhere = state.form?.busy && state.form.rfiId !== rfi.id ? ' aria-disabled="true" data-blocked-reason="A send is in progress"' : '';
208
+ let deliveryNote = '';
209
+ if (d && (d.status === 'recorded' || d.status === 'confirmed-sent' || d.status === 'failed' || pending)) {
210
+ const note = d.status === 'recorded' ? 'Gmail accepted it. That doesn’t prove it reached the inbox.'
211
+ : d.status === 'confirmed-sent' ? `You confirmed it in Sent on ${esc(exact(d.settledAt || ''))}.`
212
+ : d.status === 'failed' ? (rfi.status === 'open' ? 'Gmail didn’t receive this RFI, so nothing was sent. Send it again, or copy the email text and send it yourself.' : '')
213
+ : d.status === 'prepared' ? `FloLess began sending this with Gmail but didn’t finish recording it, so it can’t tell whether it went. Don’t send it again. Choose Finish sending. ${HELD}`
214
+ : `FloLess can’t tell whether Gmail accepted this RFI. Don’t send it again. Open the connected account’s Sent folder and search for <span class="pr-marker">${esc(d.reconciliationMarker || '')}</span>. If you find it, choose I found it in Sent. ${HELD}`;
215
+ const alert = state.alertFor === rfi.id ? ' role="alert"' : '';
216
+ if (note) deliveryNote = `<p class="pm-note${pending ? ' pr-delivery-held' : ''}" tabindex="-1" data-pr-delivery-note="${id}"${alert}>${note}</p>`;
217
+ }
218
+ const sendButton = rfi.status === 'open' && !pending && rfi.verbs.includes('mark-sent')
219
+ ? `<button type="button" class="${state.readiness?.status === 'ready' ? 'primary' : 'ghost'}" data-pr-gmail="${id}" data-command-id="shell.project-rfis-gmail-send#${esc(rfi.id)}" ${label}
220
+ aria-label="${esc(`Send ${rfi.id} with Gmail`)}" data-tip="${esc(elsewhere ? 'A send is in progress' : 'Sends this RFI from your connected Google account')}"${elsewhere}>Send with Gmail…</button>` : '';
221
+ const recoverButtons = !pending ? '' : d.status === 'prepared'
222
+ ? `<button type="button" class="primary" data-pr-gmail-continue="${id}" data-pr-attempt="${esc(d.attemptId)}" data-command-id="shell.project-rfis-gmail-continue#${esc(rfi.id)}" ${label}
223
+ aria-label="${esc(`Finish sending ${rfi.id} with Gmail`)}" data-tip="Finishes this one send. It never starts a second one."${recovering ? ' aria-busy="true" aria-disabled="true" data-blocked-reason="Finishing this send now."' : ''}>${recovering ? 'Finishing…' : 'Finish sending'}</button>`
224
+ : `<button type="button" class="primary" data-pr-gmail-confirm="${id}" data-pr-attempt="${esc(d.attemptId)}" data-command-id="shell.project-rfis-gmail-confirm#${esc(rfi.id)}" ${label}
225
+ aria-label="${esc(`I found ${rfi.id} in Sent`)}" data-tip="Use only after you found this exact send in the connected account’s Sent folder"${recovering ? ' aria-busy="true" aria-disabled="true" data-blocked-reason="Recording this now."' : ''}>${recovering ? 'Recording…' : 'I found it in Sent'}</button>
226
+ <button type="button" class="ghost" data-pr-gmail-marker="${id}" data-command-id="shell.project-rfis-gmail-marker#${esc(rfi.id)}" ${label}
227
+ aria-label="${esc(`Copy the search text for ${rfi.id}`)}" data-tip="Copies the reference line to search for in Sent">Copy search text</button>`;
146
228
  const verbButtons = form ? '' : [
229
+ sendButton, recoverButtons,
147
230
  rfi.status !== 'closed' ? `<button type="button" class="ghost" data-pr-copy="${id}" data-command-id="shell.project-rfi-copy#${esc(rfi.id)}" ${label} aria-label="Copy the email text of ${id}"
148
231
  data-tip="Copies the subject and the question, with what it cites, to paste into your email">Copy email text</button>` : '',
149
232
  ...rfi.verbs.map((verb) => {
150
233
  const text = { 'mark-sent': 'Mark sent…', answer: 'Answer…', close: 'Close…', reopen: 'Reopen…' }[verb];
151
- const tip = { 'mark-sent': 'Records who you sent it to. FloLess doesn’t send the email.', answer: 'Records the answer that came back',
234
+ const tip = { 'mark-sent': 'Records who you sent it to yourself. It sends nothing.', answer: 'Records the answer that came back',
152
235
  close: 'Closes the RFI, with why', reopen: 'Opens the RFI again, with why' }[verb];
153
236
  // Each command id is written whole; only the instance after "#" varies.
154
237
  const carrier = verb === 'mark-sent' ? `data-command-id="shell.project-rfi-mark-sent#${esc(rfi.id)}"`
155
238
  : verb === 'answer' ? `data-command-id="shell.project-rfi-answer#${esc(rfi.id)}"`
156
239
  : verb === 'close' ? `data-command-id="shell.project-rfi-close#${esc(rfi.id)}"`
157
240
  : `data-command-id="shell.project-rfi-reopen#${esc(rfi.id)}"`;
241
+ const wait = (verb === 'mark-sent' || verb === 'answer') && elsewhere;
158
242
  return `<button type="button" class="ghost" data-pr-verb="${esc(verb)}" data-pr-rfi="${id}" ${carrier} ${label}
159
- aria-label="${esc(`${text.replace('…', '')} ${rfi.id}`)}" data-tip="${esc(tip)}">${esc(text)}</button>`;
243
+ aria-label="${esc(`${text.replace('…', '')} ${rfi.id}`)}" data-tip="${esc(wait ? 'A send is in progress' : tip)}"${wait ? elsewhere : ''}>${esc(text)}</button>`;
160
244
  }),
161
245
  drifted ? `<button type="button" class="ghost" data-pr-again="${id}" data-command-id="shell.project-rfi-file-again#${esc(rfi.id)}" ${label}
162
246
  data-tip="Opens New RFI with this title and question and the items that still match">File again from this…</button>` : '',
163
247
  ].join('');
164
- return `<div class="pg-row pr-row" role="listitem">
248
+ return `<div class="pg-row pr-row" role="listitem"${(state.form?.busy && state.form.rfiId === rfi.id) || recovering ? ' aria-busy="true"' : ''}>
165
249
  <div class="pg-row-line"><span class="pg-row-title" tabindex="-1" data-pr-title="${id}">${id} · ${esc(rfi.title)}</span>
166
- <span class="pw-chip${rfi.status === 'closed' ? ' is-muted' : ''}">${esc(STATUS[rfi.status] || rfi.status)}</span></div>
250
+ <span class="pw-chip${rfi.status === 'closed' ? ' is-muted' : ''}">${esc(STATUS[rfi.status] || rfi.status)}</span>${pending ? `<span class="pw-chip is-muted">${d.status === 'prepared' ? 'Unfinished' : 'Not confirmed'}</span>` : ''}</div>
167
251
  <span class="pg-row-meta">${meta.join(' · ')}</span>
168
- <p class="pr-question">${esc(rfi.question)}</p>${answer}${closed}${provenance}${cites}${driftNote}
252
+ <p class="pr-question">${esc(rfi.question)}</p>${answer}${closed}${provenance}${cites}${driftNote}${deliveryNote}
169
253
  ${form || `<div class="pm-strip-acts pr-acts">${verbButtons}</div>`}
170
254
  ${state.copied?.rfiId === rfi.id ? `<textarea class="pr-input pr-text pr-copied" data-pr-copied="1" readonly rows="6" data-command-id="shell.project-rfi-copied-text#${esc(rfi.id)}" data-command-instance-label="${id}" aria-label="${esc(`Email text of ${rfi.id}`)}">${esc(state.copied.text)}</textarea>` : ''}</div>`;
171
255
  }
@@ -178,7 +262,7 @@
178
262
  const rfis = data?.rfis || [];
179
263
  const ready = view.status === 'ready' && data?.store === 'ok';
180
264
  const head = `<div class="step-head"><span tabindex="-1" data-pr-heading="1">RFIs</span>${ready && rfis.length ? newButton('pr-new') : ''}</div>
181
- <p class="pg-sub">Questions for the engineer, client or architect. FloLess gives you the email text to send and keeps the answer. It doesn’t send anything itself.</p>`;
265
+ <p class="pg-sub">Questions for the engineer, client or architect. FloLess can send an RFI with Gmail once Google is connected, or give you the email text to send yourself, and keeps the answer.</p>`;
182
266
  if (view.status === 'loading') return `${head}<p class="pg-loading-line">Loading this project’s RFIs…</p>`;
183
267
  if (view.status === 'gone') return `${head}<div class="pg-empty pr-failed"><p class="pg-empty-title">FloLess couldn’t find this project any more.</p><p>It may have been archived or removed. Go back to your projects to open it again.</p></div>`;
184
268
  if (view.status === 'failed') {
@@ -199,7 +283,7 @@
199
283
  }
200
284
  if (!rfis.length) {
201
285
  return `${head}<div class="pg-empty pr-empty"><p class="pg-empty-title">No RFIs in this project yet</p>
202
- <p>File a question for the engineer, client or architect. FloLess keeps it, gives you the email text, and records the answer.</p><p>${newButton('pr-new-empty')}</p></div>`;
286
+ <p>File a question for the engineer, client or architect. FloLess keeps it, sends it with Gmail or gives you the email text, and records the answer.</p><p>${newButton('pr-new-empty')}</p></div>`;
203
287
  }
204
288
  const counts = { open: visible(rfis, 'open').length, closed: visible(rfis, 'closed').length, all: rfis.length };
205
289
  const filters = `<div class="pr-filters" role="group" aria-label="Show RFIs">${['open', 'closed', 'all'].map((f) => `<button type="button" class="ghost pr-filter"
@@ -264,9 +348,35 @@
264
348
  if (!pane || !project) return;
265
349
  const same = state && state.pane === pane && state.project.id === project.id;
266
350
  state = { pane, project, generation: (state?.generation || 0) + 1, view: { status: 'loading', data: null },
267
- filter: same ? state.filter : 'open', form: null, inflight: false, again: false, focusAfter: null };
351
+ filter: same ? state.filter : 'open', form: null, inflight: false, again: false, focusAfter: null,
352
+ readiness: { status: 'loading' }, recovering: null, alertFor: null };
268
353
  paint();
269
354
  void load();
355
+ void checkReadiness();
356
+ }
357
+
358
+ /** Whether the connected Google account can send now (read when the step shows and on Check again). */
359
+ async function checkReadiness() {
360
+ const mine = state;
361
+ if (!mine) return;
362
+ const wasReady = mine.readiness?.status === 'ready';
363
+ mine.readiness = { status: 'loading' };
364
+ // Any open form keeps what was typed across the repaint (Codex review: an Answer draft was lost when readiness landed).
365
+ if (mine.form) { readDraft(); paint(); }
366
+ let readiness;
367
+ try {
368
+ const res = await api(`/api/projects/${encodeURIComponent(mine.project.id)}/correspondence-rfis/gmail-readiness`);
369
+ readiness = res.readiness && typeof res.readiness === 'object' ? res.readiness : { status: 'unavailable' };
370
+ } catch (error) {
371
+ readiness = { status: 'unavailable', message: said(error, '') || undefined };
372
+ }
373
+ if (state !== mine) return;
374
+ mine.readiness = readiness;
375
+ if (mine.form) readDraft();
376
+ if (mine.form?.verb === 'gmail' && !mine.form.busy) {
377
+ if (readiness.status === 'ready' && !wasReady) { mine.focusAfter = '.pr-form [data-pr-input="to"]'; paint(); announce('Gmail is ready.'); return; }
378
+ }
379
+ paint();
270
380
  }
271
381
  const shown = (pane) => !pane.hidden && (typeof pane.checkVisibility === 'function' ? pane.checkVisibility() : pane.offsetParent !== null);
272
382
  /** Something changed elsewhere: re-read while shown — but never under an open form (its text would be lost). */
@@ -275,14 +385,18 @@
275
385
  // ── verbs ──────────────────────────────────────────────────────────────────────────────────────────────────────
276
386
 
277
387
  function openForm(rfiId, verb) {
278
- state.form = { rfiId, verb, key: newKey(), draft: {}, error: null, busy: false, uncertain: false, stale: false };
279
- state.focusAfter = verb === 'close' ? '.pr-form [data-pr-disposition]' : '.pr-form [data-pr-input]';
388
+ const rfi = state.view.data?.rfis.find((r) => r.id === rfiId);
389
+ // A Gmail send starts from the last address this RFI went to, or was last tried with.
390
+ const draft = verb === 'gmail' ? { to: rfi?.delivery?.to || rfi?.sent?.to || '' } : {};
391
+ state.form = { rfiId, verb, key: newKey(), draft, error: null, busy: false, uncertain: false, stale: false };
392
+ state.focusAfter = verb === 'close' ? '.pr-form [data-pr-disposition]'
393
+ : verb === 'gmail' ? '.pr-form [data-pr-input="to"], .pr-form [data-pr-gmail-integrations], .pr-form [data-pr-gmail-recheck]' : '.pr-form [data-pr-input]';
280
394
  paint();
281
395
  }
282
396
  function closeForm() {
283
397
  const f = state.form;
284
398
  state.form = null;
285
- state.focusAfter = f ? `[data-pr-verb="${f.verb}"][data-pr-rfi="${CSS.escape(f.rfiId)}"]` : null;
399
+ state.focusAfter = !f ? null : f.verb === 'gmail' ? `[data-pr-gmail="${CSS.escape(f.rfiId)}"]` : `[data-pr-verb="${f.verb}"][data-pr-rfi="${CSS.escape(f.rfiId)}"]`;
286
400
  paint();
287
401
  }
288
402
  function readDraft() {
@@ -295,6 +409,7 @@
295
409
  const mine = state;
296
410
  const f = mine.form;
297
411
  if (!f || f.busy) return;
412
+ if (f.verb === 'gmail') { void submitGmail(mine, f); return; }
298
413
  if (f.uncertain) { void sendForm(mine, f, f.sent); return; }
299
414
  readDraft();
300
415
  const rfi = mine.view.data.rfis.find((r) => r.id === f.rfiId);
@@ -351,6 +466,114 @@
351
466
  }
352
467
  }
353
468
 
469
+ // ── Gmail send and its recovery (#2470 R6.6b) ──────────────────────────────────────────────────────────────────
470
+
471
+ async function submitGmail(mine, f) {
472
+ if (!f.uncertain) {
473
+ readDraft();
474
+ const to = String(f.draft.to || '').trim();
475
+ if (!isAddress(to)) { f.error = 'Give one email address, like name@company.com.'; mine.focusAfter = '.pr-form [data-pr-input="to"]'; paint(); announce(f.error); return; }
476
+ const rfi = mine.view.data.rfis.find((r) => r.id === f.rfiId);
477
+ f.sent = { ...identity(), operationKey: f.key, recordRevision: rfi.recordRevision, to };
478
+ }
479
+ f.busy = true; f.error = null; f.slow = false; mine.focusAfter = '.pr-form [data-pr-form-submit]'; paint();
480
+ const slow = setTimeout(() => { if (state === mine && mine.form === f && f.busy) { f.slow = true; mine.focusAfter = '.pr-form [data-pr-form-submit]'; paint(); } }, 10000);
481
+ try {
482
+ const res = await api(`/api/projects/${encodeURIComponent(target().projectId)}/correspondence-rfis/${encodeURIComponent(f.rfiId)}/deliver`,
483
+ { method: 'POST', body: JSON.stringify(f.sent) });
484
+ if (state !== mine) return;
485
+ await settleGmail(mine, f.rfiId, res, f.sent.to);
486
+ } catch (error) {
487
+ if (state !== mine) return;
488
+ f.busy = false;
489
+ if (error?.body?.attempt) {
490
+ // The server answered about the attempt — not sent, can't tell, or (whatever the status) it could not record
491
+ // what Gmail did. Never a plain refusal: the row is re-read and shows what is durably true, Finish sending included.
492
+ await settleGmail(mine, f.rfiId, error.body, f.sent.to);
493
+ } else if (error?.body?.code === 'rfi-gmail-not-ready') {
494
+ // Nothing was prepared or sent: Gmail isn't ready. The form shows why and the other ways, from this answer.
495
+ if (error.body.readiness) mine.readiness = error.body.readiness;
496
+ f.error = null; f.uncertain = false; f.sent = null; f.key = newKey();
497
+ mine.focusAfter = '.pr-form [data-pr-gmail-integrations], .pr-form [data-pr-gmail-recheck], .pr-form [data-pr-form-submit]';
498
+ paint(); announce(readinessText(mine.readiness));
499
+ } else if (refused(error)) {
500
+ f.error = said(error, 'FloLess couldn’t send it just now. Try again.');
501
+ f.uncertain = false; f.sent = null; f.key = newKey(); // a refusal: the next send is a new intent
502
+ mine.focusAfter = /recipient|address/.test(error.body.code || '') ? '.pr-form [data-pr-input="to"]' : '.pr-form [data-pr-form-submit]';
503
+ paint(); announce(f.error);
504
+ } else {
505
+ f.uncertain = true; // no answer: same key and payload on Try again, and no Edit (a changed address could send twice)
506
+ mine.focusAfter = '.pr-form [data-pr-form-submit]';
507
+ paint(); announce('FloLess didn’t get an answer, so it can’t tell whether Gmail sent this.');
508
+ }
509
+ } finally { clearTimeout(slow); }
510
+ }
511
+
512
+ /** After a send or recovery answered: re-read, then say what is durably true — success only from a recorded result. */
513
+ async function settleGmail(mine, rfiId, res, to) {
514
+ const status = res?.attempt?.status;
515
+ mine.form = null;
516
+ mine.recovering = null;
517
+ mine.quietLoad = true;
518
+ if (status === 'recorded' || status === 'confirmed-sent') {
519
+ await load();
520
+ if (state !== mine) return;
521
+ toast(status === 'recorded' ? `${rfiId} sent with Gmail to ${to || res.attempt.to}.` : `Recorded that you found ${rfiId} in Sent.`, 'ok');
522
+ mine.pane.querySelector(`[data-pr-title="${CSS.escape(rfiId)}"]`)?.focus({ preventScroll: true });
523
+ announce(status === 'recorded' ? `${rfiId} sent with Gmail to ${to || res.attempt.to}.` : `${rfiId} is recorded as sent.`);
524
+ return;
525
+ }
526
+ // Not sent, or not known: the note says which, and focus goes to it so it is read before anything else.
527
+ mine.alertFor = status === 'failed' ? null : rfiId;
528
+ mine.focusAfter = `[data-pr-delivery-note="${CSS.escape(rfiId)}"], [data-pr-title="${CSS.escape(rfiId)}"]`;
529
+ await load();
530
+ if (state !== mine) return;
531
+ mine.alertFor = null;
532
+ if (status === 'failed') announce(`Gmail didn’t receive ${rfiId}, so nothing was sent.`);
533
+ }
534
+
535
+ async function recoverGmail(rfiId, attemptId, action) {
536
+ const mine = state;
537
+ if (mine.recovering) return;
538
+ mine.recovering = { rfiId, action };
539
+ paint();
540
+ try {
541
+ // The server binds its own key for this attempt and action, so any retry — here, in another window or from chat —
542
+ // reaches the same one recovery and never sends twice (plan §4.4).
543
+ const res = await api(`/api/projects/${encodeURIComponent(target().projectId)}/correspondence-rfis/${encodeURIComponent(rfiId)}/delivery-attempts/${encodeURIComponent(attemptId)}/${action}`,
544
+ { method: 'POST', body: JSON.stringify({ ...identity(), operationKey: newKey() }) });
545
+ if (state !== mine) return;
546
+ await settleGmail(mine, rfiId, res);
547
+ } catch (error) {
548
+ if (state !== mine) return;
549
+ if (error?.body?.attempt) {
550
+ // Say what the durable state is, in this step's words (the server's reason may be a code).
551
+ const status = error.body.attempt.status;
552
+ await settleGmail(mine, rfiId, error.body);
553
+ toast(status === 'failed' ? `Gmail didn’t receive ${rfiId}, so nothing was sent.`
554
+ : status === 'outcome-unknown' ? `FloLess still can’t tell whether Gmail accepted ${rfiId}. Don’t send it again; check Sent.`
555
+ : `FloLess couldn’t finish recording ${rfiId}’s send. Don’t send it again; choose Finish sending.`, 'warn');
556
+ return;
557
+ }
558
+ mine.recovering = null;
559
+ const answered = refused(error);
560
+ // No answer: a Finish sending may already have reached Gmail, so nothing is claimed — the list is read again.
561
+ toast(answered ? said(error, 'FloLess couldn’t do that just now. Try again.')
562
+ : action === 'continue' ? 'FloLess didn’t get an answer, so it can’t tell whether Gmail sent this. Finishing again never sends twice.'
563
+ : 'FloLess didn’t get an answer, so it can’t tell whether that was recorded. Recording it again never records it twice.', 'warn');
564
+ mine.quietLoad = true;
565
+ await load();
566
+ }
567
+ }
568
+
569
+ async function copyMarker(rfiId) {
570
+ const rfi = state.view.data?.rfis.find((r) => r.id === rfiId);
571
+ const marker = rfi?.delivery?.reconciliationMarker;
572
+ if (!marker) return;
573
+ try { await navigator.clipboard.writeText(marker); toast('Search text copied. Paste it into the Sent folder’s search.', 'ok'); }
574
+ catch { toast('Select the reference line in the note and copy it.', 'info'); }
575
+ }
576
+
354
577
  async function copyText(rfiId) {
355
578
  try {
356
579
  const text = await api(`/api/projects/${encodeURIComponent(target().projectId)}/correspondence-rfis/${encodeURIComponent(rfiId)}/text`);
@@ -434,7 +657,7 @@
434
657
  if (!sheet || !t) return;
435
658
  if (sheet.mode === 'pick') { paintPicker(); return; }
436
659
  $title.textContent = 'New RFI';
437
- $sub.textContent = `A question from “${t.name}”. FloLess keeps it and gives you the email text. It doesn’t send anything itself.`;
660
+ $sub.textContent = `A question from “${t.name}”. FloLess keeps it; after filing you can send it with Gmail or copy its email text.`;
438
661
  const ro = sheet.uncertain || sheet.busy ? ' readonly' : '';
439
662
  const chips = sheet.cites.map((c, i) => `<span class="pw-chip pr-cite${c.changed ? ' is-muted' : ''}" role="listitem">${esc(citeLabel(c))}${c.changed ? ' · changed' : ''}
440
663
  <button type="button" class="pr-chip-x" data-pr-uncite="${i}" aria-label="${esc(`Remove ${citeLabel(c)}`)}" data-command-id="shell.project-rfi-cite-remove#${esc(citeKey(c))}"
@@ -458,7 +681,7 @@
458
681
  <button type="button" class="primary" data-pr-sheet-retry="1" data-command-id="shell.project-rfi-retry">Try again</button>`
459
682
  : `<button type="button" class="ghost" data-pr-sheet-cancel="1" data-command-id="shell.project-rfi-cancel">Cancel</button>
460
683
  <button type="button" class="ghost" data-pr-sheet-file="sent" data-command-id="shell.project-rfi-file-and-mark-sent"
461
- data-tip="Files the RFI and records that you’ve sent it to this person. FloLess doesn’t send the email."${sheet.busy ? ' disabled' : ''}>File and mark sent</button>
684
+ data-tip="Files the RFI and records that you’ve already sent it to this person yourself. It sends nothing."${sheet.busy ? ' disabled' : ''}>File and mark sent</button>
462
685
  <button type="button" class="primary" data-pr-sheet-file="file" data-command-id="shell.project-rfi-file"${sheet.busy ? ' disabled' : ''}>${sheet.busy ? 'Filing…' : 'File'}</button>`;
463
686
  }
464
687
 
@@ -559,7 +782,7 @@
559
782
  if (sheet !== mine) return;
560
783
  const id = res.rfi.id;
561
784
  closeSheet({ restoreFocus: false });
562
- toast(mine.payload.markSentTo ? `${id} filed and marked as sent to ${mine.payload.markSentTo}. FloLess hasn’t sent anything.` : `${id} filed. Copy its email text to send it.`, 'ok');
785
+ toast(mine.payload.markSentTo ? `${id} filed and marked as sent to ${mine.payload.markSentTo}. FloLess hasn’t sent anything itself.` : `${id} filed. Send it with Gmail or copy its email text.`, 'ok');
563
786
  if (state) {
564
787
  if (state.filter === 'closed') state.filter = 'open';
565
788
  state.quietLoad = true;
@@ -626,9 +849,22 @@
626
849
  announce(`Showing ${n} ${state.filter === 'all' ? '' : `${state.filter} `}RFI${n === 1 ? '' : 's'}`);
627
850
  return;
628
851
  }
852
+ const held = t.closest('[data-blocked-reason][aria-disabled="true"]');
853
+ if (held) { toast(held.getAttribute('data-blocked-reason'), 'info'); return; }
854
+ const gmail = t.closest('[data-pr-gmail]');
855
+ if (gmail) { openForm(gmail.getAttribute('data-pr-gmail'), 'gmail'); return; }
856
+ if (t.closest('[data-pr-gmail-integrations]')) { readDraft(); if (typeof window.openIntegrations === 'function') window.openIntegrations('google-workspace'); return; }
857
+ if (t.closest('[data-pr-gmail-recheck]')) { void checkReadiness(); return; }
858
+ if (t.closest('[data-pr-gmail-check]')) { state.form = null; state.quietLoad = true; void load(); return; }
859
+ const cont = t.closest('[data-pr-gmail-continue]');
860
+ if (cont) { if (cont.getAttribute('aria-disabled') !== 'true') void recoverGmail(cont.getAttribute('data-pr-gmail-continue'), cont.getAttribute('data-pr-attempt'), 'continue'); return; }
861
+ const confirm = t.closest('[data-pr-gmail-confirm]');
862
+ if (confirm) { if (confirm.getAttribute('aria-disabled') !== 'true') void recoverGmail(confirm.getAttribute('data-pr-gmail-confirm'), confirm.getAttribute('data-pr-attempt'), 'confirm-sent'); return; }
863
+ const marker = t.closest('[data-pr-gmail-marker]');
864
+ if (marker) { void copyMarker(marker.getAttribute('data-pr-gmail-marker')); return; }
629
865
  const verb = t.closest('[data-pr-verb]');
630
866
  if (verb) { openForm(verb.getAttribute('data-pr-rfi'), verb.getAttribute('data-pr-verb')); return; }
631
- if (t.closest('[data-pr-form-cancel]')) { closeForm(); return; }
867
+ if (t.closest('[data-pr-form-cancel]')) { if (state.form?.busy) return; closeForm(); return; }
632
868
  if (t.closest('[data-pr-form-submit]')) { void submitForm(); return; }
633
869
  if (t.closest('[data-pr-form-edit]')) { const f = state.form; f.uncertain = false; f.sent = null; f.key = newKey(); f.error = null;
634
870
  state.focusAfter = f.verb === 'close' ? '.pr-form [data-pr-disposition]' : '.pr-form [data-pr-input]'; paint(); return; }
@@ -681,7 +917,8 @@
681
917
  return;
682
918
  }
683
919
  if (!state || !state.pane.contains(event.target)) return;
684
- if (event.key === 'Escape' && state.form && event.target.closest('.pr-form')) { event.preventDefault(); closeForm(); return; }
920
+ if (event.key === 'Escape' && state.form && event.target.closest('.pr-form')) { event.preventDefault(); if (!state.form.busy) closeForm(); return; }
921
+ if (event.key === 'Enter' && state.form?.verb === 'gmail' && event.target.matches?.('[data-pr-input="to"]')) { event.preventDefault(); void submitForm(); return; }
685
922
  // The disposition choice is a radio group: arrows move and choose.
686
923
  const radio = event.target.closest?.('[data-pr-disposition]');
687
924
  if (radio && ['ArrowDown', 'ArrowRight', 'ArrowUp', 'ArrowLeft'].includes(event.key)) {
@@ -711,5 +948,7 @@
711
948
  }
712
949
 
713
950
  window.addEventListener('floless:projects-changed', refresh);
951
+ // Back from Integrations (or any window): a send that waited on Google may be possible now.
952
+ window.addEventListener('focus', () => { if (state && shown(state.pane) && state.readiness?.status !== 'ready' && !state.form?.busy) void checkReadiness(); });
714
953
  window.flolessProjectRfis = { render, refresh, html, transferNote };
715
954
  })();
@@ -9,7 +9,12 @@
9
9
  const clearTimer = options.clearTimeout || globalThis.clearTimeout.bind(globalThis);
10
10
  const probeTimeoutMs = options.probeTimeoutMs ?? 45000;
11
11
  const pollDelayMs = options.pollDelayMs ?? 1000;
12
- let generation = 0, suspended = false, disposed = false, probe = null, delay = null;
12
+ let generation = 0, suspended = false, disposed = false, probe = null, subscriptionProbe = null, delay = null;
13
+ // Background projections that used to poll private routes behind the sign-in screen.
14
+ // Exact read paths only: never park or replay a person's mutation after they sign in.
15
+ const subscriptionReads = new Set(['/api/workspace-root', '/api/agent-steps/status',
16
+ '/api/project-reconciliation', '/api/tool-updates', '/api/chat/session',
17
+ '/api/actions/proposals', '/api/terminal-runtimes']);
13
18
  const wakeups = new Set();
14
19
  const reset = () => Object.assign(new Error('Startup observation was superseded.'), { code: 'startup-observation-superseded' });
15
20
  const cancelled = () => new DOMException('The read was cancelled.', 'AbortError');
@@ -30,6 +35,8 @@
30
35
  generation++;
31
36
  const oldProbe = probe; probe = null;
32
37
  if (oldProbe) { clearTimer(oldProbe.timer); oldProbe.controller.abort(); oldProbe.reject(reset()); }
38
+ const oldSubscription = subscriptionProbe; subscriptionProbe = null;
39
+ if (oldSubscription) { clearTimer(oldSubscription.timer); oldSubscription.controller.abort(); oldSubscription.reject(reset()); }
33
40
  const oldDelay = delay; delay = null;
34
41
  if (oldDelay) { clearTimer(oldDelay.timer); oldDelay.reject(reset()); }
35
42
  wake();
@@ -93,6 +100,36 @@
93
100
  }
94
101
  }
95
102
 
103
+ function subscriptionObservation() {
104
+ if (subscriptionProbe) return subscriptionProbe.promise;
105
+ const owner = { generation, controller: new AbortController(), timer: null, promise: null, reject: null };
106
+ const superseded = new Promise((_, reject) => { owner.reject = reject; });
107
+ owner.timer = setTimer(() => owner.controller.abort(), probeTimeoutMs);
108
+ subscriptionProbe = owner;
109
+ // This endpoint is public. Calling an admitted API helper here would wait on itself.
110
+ owner.promise = Promise.race([Promise.resolve().then(async () => {
111
+ if (owner.generation !== generation) throw reset();
112
+ let response, body;
113
+ try {
114
+ response = await fetchHealth('/api/license/status', { cache: 'no-store', signal: owner.controller.signal });
115
+ body = await response.json();
116
+ } catch (cause) {
117
+ if (owner.generation !== generation) throw reset();
118
+ throw Object.assign(new Error('FloLess could not check your sign-in. Try again in a moment.'), { cause });
119
+ }
120
+ if (owner.generation !== generation) throw reset();
121
+ if (!response.ok || !body || typeof body.state !== 'string') {
122
+ throw Object.assign(new Error('FloLess could not check your sign-in. Try again in a moment.'), { status: response.status, body });
123
+ }
124
+ // An optional module's account chooser does not suspend core FloLess reads.
125
+ return body.state === 'valid' || body.state === 'offline-grace';
126
+ }), superseded]).finally(() => {
127
+ clearTimer(owner.timer);
128
+ if (subscriptionProbe === owner) subscriptionProbe = null;
129
+ });
130
+ return owner.promise;
131
+ }
132
+
96
133
  function pause() {
97
134
  if (!delay) {
98
135
  const owner = { timer: null, promise: null, reject: null };
@@ -109,13 +146,22 @@
109
146
  const url = new URL(path, origin);
110
147
  if (url.origin !== origin || !['GET', 'HEAD'].includes(method.toUpperCase()) || !url.pathname.startsWith('/api/')) return;
111
148
  const pathname = decodeURIComponent(url.pathname);
112
- if (pathname === '/api/health') return;
149
+ if (pathname === '/api/health' || pathname.startsWith('/api/license/')) return;
113
150
  for (;;) {
114
- const body = await health({ signal });
115
- const admission = body.startupAdmission;
116
- if (admission.ready || admission.independentReadPaths.includes(pathname)
117
- || admission.independentReadPrefixes.some(prefix => pathname === prefix || pathname.startsWith(`${prefix}/`))) return;
118
- try { await wait(pause(), signal); }
151
+ await active(signal);
152
+ const observedGeneration = generation;
153
+ try {
154
+ if (subscriptionReads.has(pathname) && !await wait(subscriptionObservation(), signal)) {
155
+ await wait(pause(), signal);
156
+ continue;
157
+ }
158
+ const body = await health({ signal });
159
+ if (subscriptionReads.has(pathname) && observedGeneration !== generation) continue;
160
+ const admission = body.startupAdmission;
161
+ if (admission.ready || admission.independentReadPaths.includes(pathname)
162
+ || admission.independentReadPrefixes.some(prefix => pathname === prefix || pathname.startsWith(`${prefix}/`))) return;
163
+ await wait(pause(), signal);
164
+ }
119
165
  catch (error) { if (error?.code !== 'startup-observation-superseded') throw error; }
120
166
  }
121
167
  }