@mindstone/mcp-server-google-workspace 0.1.4 → 0.2.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.
Files changed (47) hide show
  1. package/README.md +19 -6
  2. package/dist/modules/accounts/manager.js +20 -2
  3. package/dist/modules/accounts/token.d.ts +13 -0
  4. package/dist/modules/accounts/token.js +73 -58
  5. package/dist/modules/accounts/types.d.ts +1 -0
  6. package/dist/modules/calendar/service.js +9 -0
  7. package/dist/modules/comments/service.js +6 -5
  8. package/dist/modules/docs/index.js +2 -1
  9. package/dist/modules/docs/service.js +8 -7
  10. package/dist/modules/drive/service.d.ts +2 -1
  11. package/dist/modules/drive/service.js +29 -0
  12. package/dist/modules/drive/types.d.ts +8 -0
  13. package/dist/modules/forms/service.js +4 -3
  14. package/dist/modules/gmail/services/attachment.js +2 -1
  15. package/dist/modules/gmail/services/base.js +2 -1
  16. package/dist/modules/gmail/services/draft.js +13 -7
  17. package/dist/modules/gmail/services/email.js +4 -3
  18. package/dist/modules/gmail/services/label.js +10 -9
  19. package/dist/modules/gmail/services/settings.js +2 -1
  20. package/dist/modules/slides/service.js +7 -6
  21. package/dist/modules/tasks/service.js +7 -6
  22. package/dist/resources/compose-email-template.d.ts +1 -1
  23. package/dist/resources/compose-email-template.js +448 -22
  24. package/dist/services/base/BaseGoogleService.js +7 -0
  25. package/dist/tools/calendar-handlers.js +28 -23
  26. package/dist/tools/contacts-handlers.js +8 -23
  27. package/dist/tools/definitions/account.js +8 -1
  28. package/dist/tools/definitions/destructive-overrides.json +1 -0
  29. package/dist/tools/definitions/drive.js +84 -6
  30. package/dist/tools/definitions/open-world-overrides.json +1 -0
  31. package/dist/tools/drive-handlers.d.ts +10 -0
  32. package/dist/tools/drive-handlers.js +44 -1
  33. package/dist/tools/forms-handlers.js +5 -12
  34. package/dist/tools/gmail-handlers.d.ts +7 -1
  35. package/dist/tools/gmail-handlers.js +38 -24
  36. package/dist/tools/server.js +15 -3
  37. package/dist/tools/tasks-handlers.js +7 -18
  38. package/dist/tools/type-guards.d.ts +3 -1
  39. package/dist/tools/type-guards.js +22 -2
  40. package/dist/tools/types.d.ts +13 -0
  41. package/dist/utils/apiError.d.ts +49 -0
  42. package/dist/utils/apiError.js +93 -0
  43. package/package.json +5 -1
  44. package/dist/services/calendar/index.d.ts +0 -27
  45. package/dist/services/calendar/index.js +0 -146
  46. package/dist/services/gmail/index.d.ts +0 -39
  47. package/dist/services/gmail/index.js +0 -337
@@ -1,4 +1,6 @@
1
- // NOTE: Keep this template in sync with compose-email.html.
1
+ // GENERATED by scripts/gen-compose-html.mjs — do not edit by hand.
2
+ // Regenerate with "npm run compose:template"; "npm test" runs the --check drift gate.
3
+ // The generator also writes compose-email.html, keeping the two in sync.
2
4
  export const COMPOSE_EMAIL_HTML = `
3
5
  <!DOCTYPE html>
4
6
  <html lang="en">
@@ -129,6 +131,19 @@ export const COMPOSE_EMAIL_HTML = `
129
131
  letter-spacing: 0.04em;
130
132
  }
131
133
 
134
+ .from-value {
135
+ color: var(--text);
136
+ font-size: 14px;
137
+ padding: 2px 0;
138
+ word-break: break-word;
139
+ }
140
+
141
+ .from-helper {
142
+ font-size: 12px;
143
+ color: var(--muted);
144
+ margin-top: 2px;
145
+ }
146
+
132
147
  .input,
133
148
  .textarea {
134
149
  width: 100%;
@@ -271,6 +286,10 @@ export const COMPOSE_EMAIL_HTML = `
271
286
  opacity: 0.85;
272
287
  }
273
288
 
289
+ .blocked-actions {
290
+ margin-top: 8px;
291
+ }
292
+
274
293
  .collapsed {
275
294
  border: 1px solid var(--border);
276
295
  border-radius: 10px;
@@ -286,6 +305,49 @@ export const COMPOSE_EMAIL_HTML = `
286
305
  .hidden {
287
306
  display: none !important;
288
307
  }
308
+
309
+ .sent-header {
310
+ display: flex;
311
+ align-items: center;
312
+ gap: 8px;
313
+ flex-wrap: wrap;
314
+ }
315
+
316
+ .sent-badge {
317
+ display: inline-flex;
318
+ align-items: center;
319
+ background: var(--success-bg);
320
+ color: var(--success-text);
321
+ border: 1px solid var(--success-border);
322
+ border-radius: 999px;
323
+ padding: 2px 10px;
324
+ font-size: 12px;
325
+ font-weight: 600;
326
+ }
327
+
328
+ .sent-timestamp {
329
+ color: var(--muted);
330
+ font-size: 12px;
331
+ }
332
+
333
+ .sent-value {
334
+ color: var(--text);
335
+ font-size: 14px;
336
+ word-break: break-word;
337
+ }
338
+
339
+ .sent-body {
340
+ color: var(--text);
341
+ font-size: 14px;
342
+ white-space: pre-wrap;
343
+ word-break: break-word;
344
+ max-height: 260px;
345
+ overflow: auto;
346
+ border: 1px solid var(--border);
347
+ border-radius: 8px;
348
+ padding: 10px 12px;
349
+ background: var(--input-bg);
350
+ }
289
351
  </style>
290
352
  </head>
291
353
  <body>
@@ -295,15 +357,21 @@ export const COMPOSE_EMAIL_HTML = `
295
357
  <button id="reopenButton" type="button" class="button button-secondary">Reopen</button>
296
358
  </div>
297
359
 
298
- <form id="composeForm" class="card" novalidate>
360
+ <form id="composeForm" class="card" novalidate aria-label="Compose email">
361
+ <div class="field from-field">
362
+ <label>From</label>
363
+ <span id="fromValue" class="from-value"></span>
364
+ <span id="fromHelper" class="from-helper hidden"></span>
365
+ </div>
366
+
299
367
  <div class="field">
300
368
  <label for="toInput">To</label>
301
369
  <input id="toInput" class="input" type="text" autocomplete="off" placeholder="name@example.com, team@example.com">
302
370
  </div>
303
371
 
304
372
  <div class="toggles">
305
- <button id="toggleCcButton" type="button" class="link-button">Add CC</button>
306
- <button id="toggleBccButton" type="button" class="link-button">Add BCC</button>
373
+ <button id="toggleCcButton" type="button" class="link-button" aria-expanded="false" aria-controls="ccRow">Add CC</button>
374
+ <button id="toggleBccButton" type="button" class="link-button" aria-expanded="false" aria-controls="bccRow">Add BCC</button>
307
375
  </div>
308
376
 
309
377
  <div id="ccRow" class="field hidden">
@@ -326,12 +394,19 @@ export const COMPOSE_EMAIL_HTML = `
326
394
  <textarea id="bodyInput" class="textarea" placeholder="Write your email"></textarea>
327
395
  </div>
328
396
 
329
- <div id="errorBox" class="status error hidden">
397
+ <div id="errorBox" class="status error hidden" role="alert">
330
398
  <span id="errorText"></span>
331
399
  <button id="retryButton" type="button" class="link-button">Retry</button>
332
400
  </div>
333
401
 
334
- <div id="successBox" class="status success hidden"></div>
402
+ <div id="blockedBox" class="status warning hidden" role="status" aria-live="polite">
403
+ <span id="blockedText"></span>
404
+ <div class="blocked-actions">
405
+ <button id="openComposeButton" type="button" class="button button-secondary">Open in Gmail</button>
406
+ </div>
407
+ </div>
408
+
409
+ <div id="successBox" class="status success hidden" role="status" aria-live="polite"></div>
335
410
 
336
411
  <div id="unknownBox" class="status warning hidden" role="status" aria-live="polite">
337
412
  <strong id="unknownTitle"></strong>
@@ -340,12 +415,54 @@ export const COMPOSE_EMAIL_HTML = `
340
415
 
341
416
  <div class="actions">
342
417
  <button id="cancelButton" type="button" class="button button-secondary">Cancel</button>
343
- <button id="sendButton" type="submit" class="button button-primary">
418
+ <button id="sendButton" type="button" class="button button-primary">
344
419
  <span id="sendSpinner" class="spinner hidden" aria-hidden="true"></span>
345
420
  <span id="sendLabel">Send email</span>
346
421
  </button>
347
422
  </div>
348
423
  </form>
424
+
425
+ <div id="sentView" class="card hidden" role="status" aria-live="polite">
426
+ <div class="sent-header">
427
+ <span class="sent-badge">Sent</span>
428
+ <span id="sentTimestamp" class="sent-timestamp"></span>
429
+ </div>
430
+
431
+ <div class="field">
432
+ <label>From</label>
433
+ <span id="sentFrom" class="sent-value"></span>
434
+ </div>
435
+
436
+ <div class="field">
437
+ <label>To</label>
438
+ <span id="sentTo" class="sent-value"></span>
439
+ </div>
440
+
441
+ <div id="sentCcField" class="field hidden">
442
+ <label>CC</label>
443
+ <span id="sentCc" class="sent-value"></span>
444
+ </div>
445
+
446
+ <div id="sentBccField" class="field hidden">
447
+ <label>BCC</label>
448
+ <span id="sentBcc" class="sent-value"></span>
449
+ </div>
450
+
451
+ <div class="field">
452
+ <label>Subject</label>
453
+ <span id="sentSubject" class="sent-value"></span>
454
+ </div>
455
+
456
+ <div class="field">
457
+ <label>Message</label>
458
+ <div id="sentBody" class="sent-body"></div>
459
+ </div>
460
+
461
+ <div class="actions">
462
+ <button id="openGmailButton" type="button" class="button button-secondary hidden">Open in Gmail</button>
463
+ <button id="sentCollapseButton" type="button" class="button button-secondary">Collapse</button>
464
+ </div>
465
+ </div>
349
466
  </div>
350
467
 
351
468
  <script>
@@ -354,15 +471,23 @@ export const COMPOSE_EMAIL_HTML = `
354
471
 
355
472
  var RESOURCE_URI = 'ui://google-workspace/compose-email';
356
473
  var currentEmail = '';
474
+ // The host prefills the draft exactly once via ui/notifications/tool-result
475
+ // on ready. We apply only the FIRST prefill and ignore any later ones, so a
476
+ // stray or hostile re-post can't silently rewrite a draft the user has
477
+ // already reviewed before clicking Send.
478
+ var draftApplied = false;
357
479
  var pendingRequestId = null;
358
480
  var pendingPayload = null;
359
481
  var sending = false;
360
482
  var collapsed = false;
361
483
  var outcomeUnknown = false;
484
+ var sent = false;
485
+ var sendBlocked = false;
486
+ var gmailUrl = null;
362
487
  var sendTimeoutId = null;
363
488
  // Just beyond the host-side tool-call timeout (60s) so a legitimately slow
364
489
  // send resolves to its real result first; this only fires when the reply
365
- // is genuinely lost (REBEL-677), so the button can never stay stuck-silent.
490
+ // is genuinely lost, so the button can never stay stuck-silent.
366
491
  var SEND_TIMEOUT_MS = 75000;
367
492
 
368
493
  var composeForm = document.getElementById('composeForm');
@@ -370,11 +495,26 @@ export const COMPOSE_EMAIL_HTML = `
370
495
  var collapsedMessage = document.getElementById('collapsedMessage');
371
496
  var reopenButton = document.getElementById('reopenButton');
372
497
 
498
+ var sentView = document.getElementById('sentView');
499
+ var sentTimestamp = document.getElementById('sentTimestamp');
500
+ var sentFrom = document.getElementById('sentFrom');
501
+ var sentTo = document.getElementById('sentTo');
502
+ var sentCcField = document.getElementById('sentCcField');
503
+ var sentCc = document.getElementById('sentCc');
504
+ var sentBccField = document.getElementById('sentBccField');
505
+ var sentBcc = document.getElementById('sentBcc');
506
+ var sentSubject = document.getElementById('sentSubject');
507
+ var sentBody = document.getElementById('sentBody');
508
+ var openGmailButton = document.getElementById('openGmailButton');
509
+ var sentCollapseButton = document.getElementById('sentCollapseButton');
510
+
373
511
  var toInput = document.getElementById('toInput');
374
512
  var ccInput = document.getElementById('ccInput');
375
513
  var bccInput = document.getElementById('bccInput');
376
514
  var subjectInput = document.getElementById('subjectInput');
377
515
  var bodyInput = document.getElementById('bodyInput');
516
+ var fromValue = document.getElementById('fromValue');
517
+ var fromHelper = document.getElementById('fromHelper');
378
518
  var ccRow = document.getElementById('ccRow');
379
519
  var bccRow = document.getElementById('bccRow');
380
520
  var toggleCcButton = document.getElementById('toggleCcButton');
@@ -392,6 +532,9 @@ export const COMPOSE_EMAIL_HTML = `
392
532
  var unknownBox = document.getElementById('unknownBox');
393
533
  var unknownTitle = document.getElementById('unknownTitle');
394
534
  var unknownText = document.getElementById('unknownText');
535
+ var blockedBox = document.getElementById('blockedBox');
536
+ var blockedText = document.getElementById('blockedText');
537
+ var openComposeButton = document.getElementById('openComposeButton');
395
538
 
396
539
  function applyThemeFromHostContext() {
397
540
  try {
@@ -409,6 +552,21 @@ export const COMPOSE_EMAIL_HTML = `
409
552
  return String(value || '').trim();
410
553
  }
411
554
 
555
+ function applyFromValue(email) {
556
+ var trimmed = trimString(email);
557
+ if (trimmed) {
558
+ fromValue.textContent = trimmed;
559
+ fromValue.style.color = '';
560
+ fromHelper.textContent = '';
561
+ fromHelper.classList.add('hidden');
562
+ } else {
563
+ fromValue.textContent = 'Account not shown';
564
+ fromValue.style.color = 'var(--muted)';
565
+ fromHelper.textContent = 'Rebel could not confirm the sending account. Cancel and ask Rebel to recreate the draft before sending.';
566
+ fromHelper.classList.remove('hidden');
567
+ }
568
+ }
569
+
412
570
  function formatAddressItem(item) {
413
571
  if (item && typeof item === 'object') {
414
572
  var email = trimString(item.email || item.address || item.value);
@@ -465,21 +623,31 @@ export const COMPOSE_EMAIL_HTML = `
465
623
  );
466
624
  }
467
625
 
626
+ // Exactly one of the three panels is visible at a time: the editable form,
627
+ // the read-only sent view, or the collapsed summary bar.
628
+ function showView(view) {
629
+ composeForm.classList.toggle('hidden', view !== 'form');
630
+ sentView.classList.toggle('hidden', view !== 'sent');
631
+ collapsedState.classList.toggle('hidden', view !== 'collapsed');
632
+ postResize();
633
+ }
634
+
468
635
  function setCollapsed(nextCollapsed, message) {
469
636
  collapsed = nextCollapsed;
470
- composeForm.classList.toggle('hidden', collapsed);
471
- collapsedState.classList.toggle('hidden', !collapsed);
472
- if (message) {
473
- collapsedMessage.textContent = message;
637
+ if (nextCollapsed) {
638
+ collapsedMessage.textContent = message || 'Draft collapsed.';
639
+ showView('collapsed');
474
640
  } else {
475
- collapsedMessage.textContent = collapsed ? 'Draft collapsed.' : '';
641
+ // Expanding after a send restores the read-only sent view (never the
642
+ // editable form) so the user can re-read what went out without any risk
643
+ // of a duplicate send; before sending, it restores the editable form.
644
+ showView(sent ? 'sent' : 'form');
476
645
  }
477
- postResize();
478
646
  }
479
647
 
480
648
  function setSending(nextSending) {
481
649
  sending = nextSending;
482
- sendButton.disabled = nextSending;
650
+ sendButton.disabled = nextSending || sendBlocked;
483
651
  cancelButton.disabled = nextSending;
484
652
  toInput.disabled = nextSending;
485
653
  ccInput.disabled = nextSending;
@@ -488,6 +656,7 @@ export const COMPOSE_EMAIL_HTML = `
488
656
  bodyInput.disabled = nextSending;
489
657
  sendSpinner.classList.toggle('hidden', !nextSending);
490
658
  sendLabel.textContent = nextSending ? 'Sending…' : 'Send email';
659
+ sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');
491
660
  postResize();
492
661
  }
493
662
 
@@ -531,7 +700,7 @@ export const COMPOSE_EMAIL_HTML = `
531
700
  // before reaching this iframe). We genuinely don't know whether the email
532
701
  // went out, so we must NOT claim success or failure: re-enable the form and
533
702
  // tell the user to verify before resending (the send is not idempotent, so
534
- // a blind retry could send a duplicate). REBEL-677 / FOX-3484.
703
+ // a blind retry could send a duplicate).
535
704
  function showSendUnknown() {
536
705
  outcomeUnknown = true;
537
706
  clearError();
@@ -555,11 +724,13 @@ export const COMPOSE_EMAIL_HTML = `
555
724
  function setCcVisible(visible) {
556
725
  ccRow.classList.toggle('hidden', !visible);
557
726
  toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';
727
+ toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');
558
728
  }
559
729
 
560
730
  function setBccVisible(visible) {
561
731
  bccRow.classList.toggle('hidden', !visible);
562
732
  toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';
733
+ toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');
563
734
  }
564
735
 
565
736
  function readFormPayload() {
@@ -621,6 +792,7 @@ export const COMPOSE_EMAIL_HTML = `
621
792
  subjectInput.value = typeof draft.subject === 'string' ? draft.subject : '';
622
793
  bodyInput.value = typeof draft.body === 'string' ? draft.body : '';
623
794
  currentEmail = typeof draft.email === 'string' ? draft.email : '';
795
+ applyFromValue(currentEmail);
624
796
  setCcVisible(normalizeAddressList(draft.cc).length > 0);
625
797
  setBccVisible(normalizeAddressList(draft.bcc).length > 0);
626
798
  clearError();
@@ -674,9 +846,190 @@ export const COMPOSE_EMAIL_HTML = `
674
846
  return null;
675
847
  }
676
848
 
677
- composeForm.addEventListener('submit', function (event) {
678
- event.preventDefault();
849
+ function findTextBlock(blocks) {
850
+ if (!Array.isArray(blocks)) return null;
851
+ var block = blocks.find(function (c) {
852
+ return c && c.type === 'text' && typeof c.text === 'string';
853
+ });
854
+ return block ? block.text : null;
855
+ }
856
+
857
+ // Extract the send result identifiers ({ messageId, threadId, labelIds })
858
+ // from the tool-call reply. The connector attaches structuredContent, which
859
+ // super-mcp hoists onto the outer block, so the fast path is a single read.
860
+ // The envelope-unwrapping fallback keeps this robust for hosts (or replayed
861
+ // sessions) that forward only the serialized super-mcp text envelope.
862
+ function getSendMetaFromResult(result) {
863
+ if (!result || typeof result !== 'object') return null;
864
+ if (result.structuredContent && typeof result.structuredContent === 'object') {
865
+ return result.structuredContent;
866
+ }
867
+ try {
868
+ var outerText = findTextBlock(result.content);
869
+ if (typeof outerText !== 'string' && typeof result.text === 'string') {
870
+ outerText = result.text;
871
+ }
872
+ if (typeof outerText !== 'string') return null;
873
+ var envelope = JSON.parse(outerText);
874
+ if (!envelope || typeof envelope !== 'object') return null;
875
+ // outerText was the connector payload directly (no super-mcp envelope).
876
+ if (envelope.messageId || envelope.threadId) return envelope;
877
+ var inner = envelope.result;
878
+ if (!inner || typeof inner !== 'object') return null;
879
+ if (inner.structuredContent && typeof inner.structuredContent === 'object') {
880
+ return inner.structuredContent;
881
+ }
882
+ var innerText = findTextBlock(inner.content);
883
+ if (typeof innerText !== 'string') return null;
884
+ var payload = JSON.parse(innerText);
885
+ return (payload && typeof payload === 'object') ? payload : null;
886
+ } catch (_) {
887
+ return null;
888
+ }
889
+ }
890
+
891
+ // ---- Blocked-send Gmail escape hatch ----
892
+ // Shown ONLY when the user's own send preference blocks the tool
893
+ // (super-mcp TOOL_BLOCKED / -33008 + "disabled by user preference"). We
894
+ // never call the disabled tool; instead we open a prefilled Gmail compose
895
+ // window so the user finishes the send in Gmail (no copy-paste). This is
896
+ // deliberately narrow: admin-disabled ("disabled by your organization…")
897
+ // and generic security-policy blocks fall through to the normal retryable
898
+ // error, because offering a Gmail bypass there would route around a control
899
+ // the user did not set.
900
+ //
901
+ // Gmail compose URLs that get too long can silently fail to open, so we cap
902
+ // the length and degrade visibly (recipients + subject only, paste the body)
903
+ // rather than truncating without telling the user.
904
+ var GMAIL_COMPOSE_MAX_URL = 8000;
905
+ var BLOCKED_SEND_MESSAGE =
906
+ 'Sending from here is turned off in your settings. You can finish and send this email in Gmail, or turn sending back on in Settings.';
907
+
908
+ function isUserDisabledSendError(message) {
909
+ var m = String(message || '').toLowerCase();
910
+ // Anchor the code so it can't match inside a longer number (-330080),
911
+ // and require the user-preference phrase so admin-disabled / generic
912
+ // security blocks fall through to the ordinary retryable error.
913
+ return /-33008\\b/.test(m) && m.indexOf('disabled by user preference') !== -1;
914
+ }
915
+
916
+ // Base URL + path are constant (code-reviewed here, never config-provided);
917
+ // only the field VALUES vary and go through URLSearchParams, so query
918
+ // delimiters, newlines, and reserved characters become encoded data — no
919
+ // query injection or header splitting. The host ui/open-external-link
920
+ // bridge re-validates the mail.google.com host before opening.
921
+ function buildGmailComposeUrl(payload, includeBody) {
922
+ var url = new URL('https://mail.google.com/mail/');
923
+ var params = new URLSearchParams();
924
+ params.set('view', 'cm');
925
+ params.set('fs', '1');
926
+ var to = normalizeAddressList(payload.to).join(',');
927
+ if (to) params.set('to', to);
928
+ var cc = normalizeAddressList(payload.cc).join(',');
929
+ if (cc) params.set('cc', cc);
930
+ var bcc = normalizeAddressList(payload.bcc).join(',');
931
+ if (bcc) params.set('bcc', bcc);
932
+ var subject = trimString(payload.subject);
933
+ if (subject) params.set('su', subject);
934
+ if (includeBody) {
935
+ var body = String(payload.body || '');
936
+ if (body) params.set('body', body);
937
+ }
938
+ url.search = params.toString();
939
+ return url.toString();
940
+ }
941
+
942
+ function showBlockedSend() {
943
+ sendBlocked = true;
944
+ clearError();
945
+ clearSuccess();
946
+ clearUnknown();
947
+ sendButton.disabled = true;
948
+ sendButton.title =
949
+ 'Sending from here is turned off in your settings. Turn it back on in Settings, or open this draft in Gmail to send.';
950
+ blockedText.textContent = BLOCKED_SEND_MESSAGE;
951
+ blockedBox.classList.remove('hidden');
952
+ postResize();
953
+ }
954
+
955
+ openComposeButton.addEventListener('click', function () {
956
+ // Reset any prior "too long" note, then rebuild from the live form so
957
+ // edits made after the block are reflected.
958
+ blockedText.textContent = BLOCKED_SEND_MESSAGE;
959
+ var payload = readFormPayload();
960
+ var composeUrl = buildGmailComposeUrl(payload, true);
961
+ if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {
962
+ composeUrl = buildGmailComposeUrl(payload, false);
963
+ if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {
964
+ // Even without the body the link is too long (many recipients, or a
965
+ // very long subject). Gmail would silently refuse to open it, so
966
+ // don't pretend — tell the user and post nothing.
967
+ blockedText.textContent =
968
+ 'This draft is too large to open in Gmail. Shorten the recipients or subject, or turn sending back on in Settings.';
969
+ postResize();
970
+ return;
971
+ }
972
+ blockedText.textContent =
973
+ 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';
974
+ postResize();
975
+ }
976
+ window.parent.postMessage(
977
+ { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },
978
+ '*'
979
+ );
980
+ });
981
+
982
+ function looksLikeEmail(value) {
983
+ var at = value.indexOf('@');
984
+ return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;
985
+ }
986
+
987
+ // Build a Gmail deep link to the just-sent message. The /u/<account> segment
988
+ // targets the right inbox when the user is signed into several Google
989
+ // accounts; #all/<id> opens the thread (falling back to the message id).
990
+ function buildGmailUrl(meta, email) {
991
+ if (!meta || typeof meta !== 'object') return null;
992
+ var id = trimString(meta.threadId) || trimString(meta.messageId);
993
+ if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;
994
+ var account = trimString(email);
995
+ var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';
996
+ return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);
997
+ }
998
+
999
+ function formatSentTime() {
1000
+ try {
1001
+ return new Date().toLocaleString(undefined, {
1002
+ month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'
1003
+ });
1004
+ } catch (_) {
1005
+ return '';
1006
+ }
1007
+ }
1008
+
1009
+ function renderSentView(payload, meta, stamp) {
1010
+ payload = payload && typeof payload === 'object' ? payload : {};
1011
+ sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';
1012
+ sentFrom.textContent = trimString(payload.email) || 'Account not shown';
1013
+ sentTo.textContent = normalizeAddressList(payload.to).join(', ');
1014
+ var ccList = normalizeAddressList(payload.cc);
1015
+ sentCc.textContent = ccList.join(', ');
1016
+ sentCcField.classList.toggle('hidden', ccList.length === 0);
1017
+ var bccList = normalizeAddressList(payload.bcc);
1018
+ sentBcc.textContent = bccList.join(', ');
1019
+ sentBccField.classList.toggle('hidden', bccList.length === 0);
1020
+ sentSubject.textContent = String(payload.subject || '');
1021
+ sentBody.textContent = String(payload.body || '');
1022
+ gmailUrl = buildGmailUrl(meta, payload.email);
1023
+ openGmailButton.classList.toggle('hidden', !gmailUrl);
1024
+ }
1025
+
1026
+ function handleSendRequest() {
679
1027
  if (sending) return;
1028
+ // Once the user's own send preference has blocked this tool, never
1029
+ // re-invoke it — the escape hatch is the only path out. The Send button
1030
+ // is already disabled, but this also fends off a future host that grants
1031
+ // allow-forms (a submit could otherwise re-fire the disabled tool).
1032
+ if (sendBlocked) return;
680
1033
 
681
1034
  var payload = readFormPayload();
682
1035
  var validationError = validatePayload(payload);
@@ -686,6 +1039,27 @@ export const COMPOSE_EMAIL_HTML = `
686
1039
  }
687
1040
 
688
1041
  sendPayload(payload);
1042
+ }
1043
+
1044
+ // The Send button is type="button" with an explicit click handler rather
1045
+ // than a form submit button. The Rebel host renders this iframe with a
1046
+ // sandbox of "allow-scripts" only — no "allow-forms" — so native form
1047
+ // submission is blocked by the browser BEFORE the submit event fires
1048
+ // ("Blocked form submission ... the form's frame is sandboxed and the
1049
+ // allow-forms permission is not set"). A submit-driven Send therefore
1050
+ // silently did nothing: no postMessage, no spinner, no telemetry.
1051
+ // A click handler needs no sandbox permission and is the same path
1052
+ // Cancel/Retry already use. The submit listener below stays only as a
1053
+ // defensive fallback for hosts that DO grant allow-forms; in this sandbox
1054
+ // it never fires (neither the button click nor Enter routes through it).
1055
+ // The sending guard keeps any double-fire (in an allow-forms host) a no-op.
1056
+ sendButton.addEventListener('click', function () {
1057
+ handleSendRequest();
1058
+ });
1059
+
1060
+ composeForm.addEventListener('submit', function (event) {
1061
+ event.preventDefault();
1062
+ handleSendRequest();
689
1063
  });
690
1064
 
691
1065
  retryButton.addEventListener('click', function () {
@@ -716,6 +1090,22 @@ export const COMPOSE_EMAIL_HTML = `
716
1090
  setCollapsed(false);
717
1091
  });
718
1092
 
1093
+ sentCollapseButton.addEventListener('click', function () {
1094
+ setCollapsed(true, collapsedMessage.textContent || 'Email sent.');
1095
+ });
1096
+
1097
+ // The iframe sandbox is "allow-scripts" only (no allow-popups / allow-forms),
1098
+ // so it cannot open a URL itself. Ask the host to open the Gmail link in the
1099
+ // user's browser via the ui/open-external-link bridge, which re-validates the
1100
+ // URL against its own allowlist before handing it to the OS.
1101
+ openGmailButton.addEventListener('click', function () {
1102
+ if (!gmailUrl) return;
1103
+ window.parent.postMessage(
1104
+ { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },
1105
+ '*'
1106
+ );
1107
+ });
1108
+
719
1109
  toggleCcButton.addEventListener('click', function () {
720
1110
  setCcVisible(ccRow.classList.contains('hidden'));
721
1111
  postResize();
@@ -736,14 +1126,32 @@ export const COMPOSE_EMAIL_HTML = `
736
1126
  });
737
1127
 
738
1128
  window.addEventListener('message', function (event) {
1129
+ // Honest scope (origin-independent): the iframe sandbox origin is 'null',
1130
+ // so validating event.origin is unreliable across dev/prod/custom-scheme
1131
+ // hosts. Instead reject any *identified* sender that isn't our host frame
1132
+ // (window.parent). A real cross-frame postMessage always stamps
1133
+ // event.source with the sending window, so a hostile sibling frame is
1134
+ // rejected here; a null source only occurs for same-context synthetic
1135
+ // dispatch (our own code) and cannot be forged from outside, so we
1136
+ // tolerate it. This does not authenticate the host's identity — the host
1137
+ // separately authenticates this iframe by origin+source.
1138
+ if (event.source && event.source !== window.parent) {
1139
+ return;
1140
+ }
1141
+
739
1142
  var data = event.data;
740
1143
  if (!data || typeof data !== 'object') {
741
1144
  return;
742
1145
  }
743
1146
 
744
1147
  if (data.method === 'ui/notifications/tool-result') {
1148
+ // Always parse (so the migration-shim's malformed-envelope warning
1149
+ // still fires), but apply only the first successful prefill: a stray
1150
+ // or hostile re-post can't silently rewrite a draft the user has
1151
+ // already reviewed.
745
1152
  var draft = getDraftFromToolResult(data.params);
746
- if (draft) {
1153
+ if (draft && !draftApplied) {
1154
+ draftApplied = true;
747
1155
  applyDraftData(draft);
748
1156
  }
749
1157
  return;
@@ -762,14 +1170,32 @@ export const COMPOSE_EMAIL_HTML = `
762
1170
  var errorMessage = data.error && typeof data.error.message === 'string'
763
1171
  ? data.error.message
764
1172
  : 'Failed to send email.';
1173
+ // Prefer the host-vetted structured reason (a closed enum the host
1174
+ // derives from the tool-block error data) and fall back to
1175
+ // text-matching the flattened message for hosts that don't forward it
1176
+ // yet. Only 'user-disabled' opens the Gmail escape hatch —
1177
+ // admin-disabled and security-policy blocks stay ordinary errors (see
1178
+ // the detector comment above for why).
1179
+ var blockedReason = data.error.data && data.error.data.reason;
1180
+ if (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage)) {
1181
+ showBlockedSend();
1182
+ return;
1183
+ }
765
1184
  showError(errorMessage);
766
1185
  return;
767
1186
  }
768
1187
 
769
1188
  clearError();
770
- showSuccess('Email sent successfully.');
771
- setCollapsed(true, 'Email sent.');
772
- reopenButton.classList.add('hidden');
1189
+ clearSuccess();
1190
+ // Preserve what was sent (and how to reach it) instead of discarding the
1191
+ // draft. pendingPayload is the exact payload we posted; the reply carries
1192
+ // the Gmail message/thread ids. We default to the collapsed summary, but
1193
+ // Reopen now restores a read-only view of the sent message.
1194
+ var sentPayload = pendingPayload || readFormPayload();
1195
+ var stamp = formatSentTime();
1196
+ renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);
1197
+ sent = true;
1198
+ setCollapsed(true, stamp ? 'Email sent · ' + stamp : 'Email sent.');
773
1199
  });
774
1200
 
775
1201
  if (typeof ResizeObserver === 'function' && document.body) {
@@ -54,6 +54,13 @@ export class BaseGoogleService {
54
54
  if (tokenStatus.status === 'AUTH_REQUIRED') {
55
55
  throw new AccountError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', 'Connect Google Workspace to continue');
56
56
  }
57
+ // Transient refresh blip (a temporary network error, not a dead grant): surface a
58
+ // retryable error rather than an AUTH_REQUIRED that would push the user to reconnect a
59
+ // grant that's actually fine. formatErrorResponse maps this to a generic retry, not the
60
+ // reconnect CTA. Mirrors the canRetry handling in withTokenRenewal / listAccounts.
61
+ if (!tokenStatus.valid && tokenStatus.canRetry) {
62
+ throw new AccountError(`${this.serviceName} token refresh failed temporarily`, 'TEMPORARY_AUTH_ERROR', 'Please try again in a moment');
63
+ }
57
64
  if (!tokenStatus.valid || !tokenStatus.token) {
58
65
  throw new GoogleServiceError(`${this.serviceName} authentication required`, 'AUTH_REQUIRED', 'Please authenticate the account');
59
66
  }