@mindstone/mcp-server-google-workspace 0.4.0 → 0.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,7 +8,7 @@ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Co
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.4.0](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.4.2](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
13
  - **Tools:** [116](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Tasks, Forms, Comments, Account)
14
14
  - **Surface:** cloud-api
@@ -127,6 +127,28 @@ export class DraftService {
127
127
  async updateDraft(email, draftId, data) {
128
128
  try {
129
129
  const client = this.ensureClient();
130
+ // Preserve the existing draft's thread on body-only updates. Gmail's
131
+ // drafts.update REPLACES the draft message, and an omitted threadId
132
+ // detaches the draft from its conversation — so a body-only update
133
+ // (caller passed no thread_id and no reply_to_message_id) would
134
+ // silently unthread the draft. Fetch the existing draft first and keep
135
+ // its threadId; an explicit threadId (reply threading resolved at the
136
+ // handler layer) still wins.
137
+ let threadId = data.threadId;
138
+ if (threadId === undefined) {
139
+ try {
140
+ const existing = await this.getDraft(email, draftId);
141
+ threadId = existing.message.threadId;
142
+ }
143
+ catch (error) {
144
+ // Observable degradation, not a new failure mode: the update still
145
+ // proceeds as before (unthreaded) rather than failing an operation
146
+ // that used to succeed — but the degradation is logged, not silent.
147
+ const cause = error instanceof Error ? error.message : error;
148
+ const detail = error instanceof GmailError && error.details ? `${cause} (${error.details})` : cause;
149
+ logger.warn(`Failed to fetch draft ${draftId} for thread preservation; updating without a threadId:`, detail);
150
+ }
151
+ }
130
152
  // Validate and prepare attachments
131
153
  const processedAttachments = data.attachments?.map(attachment => {
132
154
  this.attachmentService.validateAttachment(attachment);
@@ -153,7 +175,7 @@ export class DraftService {
153
175
  requestBody: {
154
176
  message: {
155
177
  raw: encodedMessage,
156
- threadId: data.threadId // Include threadId for replies
178
+ threadId // Preserved from the existing draft unless explicitly overridden
157
179
  }
158
180
  }
159
181
  });
@@ -1,2 +1,2 @@
1
- export declare const COMPOSE_EMAIL_HTML = "\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Compose Email</title>\n <style>\n :root {\n --bg: #ffffff;\n --panel: #ffffff;\n --border: #d9dde5;\n --text: #1f2937;\n --muted: #6b7280;\n --input-bg: #ffffff;\n --button-bg: #1f6feb;\n --button-text: #ffffff;\n --button-bg-hover: #1b63d3;\n --secondary-bg: #f3f4f6;\n --secondary-text: #1f2937;\n --secondary-border: #d1d5db;\n --error-bg: #fef2f2;\n --error-border: #fecaca;\n --error-text: #991b1b;\n --success-bg: #ecfdf5;\n --success-border: #bbf7d0;\n --success-text: #166534;\n --warning-bg: #fffbeb;\n --warning-border: #fde68a;\n --warning-text: #92400e;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n }\n\n html[data-theme=\"light\"] {\n color-scheme: light;\n }\n\n html[data-theme=\"dark\"] {\n color-scheme: dark;\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n\n * {\n box-sizing: border-box;\n }\n\n body {\n margin: 0;\n padding: 16px;\n background: var(--bg);\n color: var(--text);\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n line-height: 1.4;\n }\n\n .wrapper {\n width: 100%;\n max-width: 720px;\n margin: 0 auto;\n }\n\n .card {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .field label {\n font-size: 12px;\n font-weight: 600;\n color: var(--muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n }\n\n .from-value {\n color: var(--text);\n font-size: 14px;\n padding: 2px 0;\n word-break: break-word;\n }\n\n .from-helper {\n font-size: 12px;\n color: var(--muted);\n margin-top: 2px;\n }\n\n .input,\n .textarea {\n width: 100%;\n background: var(--input-bg);\n color: var(--text);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n font-size: 14px;\n font-family: inherit;\n }\n\n .input:focus,\n .textarea:focus {\n outline: 2px solid rgba(59, 130, 246, 0.35);\n outline-offset: 1px;\n }\n\n .textarea {\n min-height: 180px;\n resize: vertical;\n white-space: pre-wrap;\n }\n\n .toggles {\n display: flex;\n gap: 12px;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .link-button {\n border: none;\n padding: 0;\n background: none;\n color: var(--muted);\n text-decoration: underline;\n font-size: 12px;\n cursor: pointer;\n }\n\n .link-button:hover {\n color: var(--text);\n }\n\n .actions {\n display: flex;\n justify-content: flex-end;\n gap: 10px;\n margin-top: 2px;\n }\n\n .button {\n border-radius: 8px;\n border: 1px solid transparent;\n min-height: 36px;\n padding: 0 14px;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n transition: background 120ms ease, opacity 120ms ease, border-color 120ms ease;\n }\n\n .button:disabled {\n cursor: not-allowed;\n opacity: 0.75;\n }\n\n .button-primary {\n background: var(--button-bg);\n color: var(--button-text);\n }\n\n .button-primary:hover:enabled {\n background: var(--button-bg-hover);\n }\n\n .button-secondary {\n background: var(--secondary-bg);\n color: var(--secondary-text);\n border-color: var(--secondary-border);\n }\n\n .spinner {\n width: 14px;\n height: 14px;\n border: 2px solid currentColor;\n border-right-color: transparent;\n border-radius: 50%;\n display: inline-block;\n animation: spin 700ms linear infinite;\n }\n\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n\n .status {\n border-radius: 8px;\n border: 1px solid transparent;\n padding: 8px 10px;\n font-size: 13px;\n }\n\n .error {\n background: var(--error-bg);\n border-color: var(--error-border);\n color: var(--error-text);\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .success {\n background: var(--success-bg);\n border-color: var(--success-border);\n color: var(--success-text);\n }\n\n .warning {\n background: var(--warning-bg);\n border-color: var(--warning-border);\n color: var(--warning-text);\n display: block;\n }\n\n .warning strong {\n display: block;\n margin-bottom: 2px;\n }\n\n .warning .warning-detail {\n opacity: 0.85;\n }\n\n .blocked-actions {\n margin-top: 8px;\n }\n\n .collapsed {\n border: 1px solid var(--border);\n border-radius: 10px;\n background: var(--panel);\n padding: 10px 12px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n }\n\n .hidden {\n display: none !important;\n }\n\n .sent-header {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .sent-badge {\n display: inline-flex;\n align-items: center;\n background: var(--success-bg);\n color: var(--success-text);\n border: 1px solid var(--success-border);\n border-radius: 999px;\n padding: 2px 10px;\n font-size: 12px;\n font-weight: 600;\n }\n\n .sent-timestamp {\n color: var(--muted);\n font-size: 12px;\n }\n\n .sent-value {\n color: var(--text);\n font-size: 14px;\n word-break: break-word;\n }\n\n .sent-body {\n color: var(--text);\n font-size: 14px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 260px;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n background: var(--input-bg);\n }\n </style>\n</head>\n<body>\n <div class=\"wrapper\">\n <div id=\"collapsedState\" class=\"collapsed hidden\">\n <span id=\"collapsedMessage\">Draft collapsed.</span>\n <button id=\"reopenButton\" type=\"button\" class=\"button button-secondary\">Reopen</button>\n </div>\n\n <form id=\"composeForm\" class=\"card\" novalidate aria-label=\"Compose email\">\n <div class=\"field from-field\">\n <label>From</label>\n <span id=\"fromValue\" class=\"from-value\"></span>\n <span id=\"fromHelper\" class=\"from-helper hidden\"></span>\n </div>\n\n <div class=\"field\">\n <label for=\"toInput\">To</label>\n <input id=\"toInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"name@example.com, team@example.com\">\n </div>\n\n <div class=\"toggles\">\n <button id=\"toggleCcButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"ccRow\">Add CC</button>\n <button id=\"toggleBccButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"bccRow\">Add BCC</button>\n </div>\n\n <div id=\"ccRow\" class=\"field hidden\">\n <label for=\"ccInput\">CC</label>\n <input id=\"ccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"cc@example.com\">\n </div>\n\n <div id=\"bccRow\" class=\"field hidden\">\n <label for=\"bccInput\">BCC</label>\n <input id=\"bccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"bcc@example.com\">\n </div>\n\n <div class=\"field\">\n <label for=\"subjectInput\">Subject</label>\n <input id=\"subjectInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"Email subject\">\n </div>\n\n <div class=\"field\">\n <label for=\"bodyInput\">Body</label>\n <textarea id=\"bodyInput\" class=\"textarea\" placeholder=\"Write your email\"></textarea>\n </div>\n\n <div id=\"errorBox\" class=\"status error hidden\" role=\"alert\">\n <span id=\"errorText\"></span>\n <button id=\"retryButton\" type=\"button\" class=\"link-button\">Retry</button>\n </div>\n\n <div id=\"blockedBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <span id=\"blockedText\"></span>\n <div class=\"blocked-actions\">\n <button id=\"openComposeButton\" type=\"button\" class=\"button button-secondary\">Open in Gmail</button>\n </div>\n </div>\n\n <div id=\"successBox\" class=\"status success hidden\" role=\"status\" aria-live=\"polite\"></div>\n\n <div id=\"unknownBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <strong id=\"unknownTitle\"></strong>\n <span id=\"unknownText\" class=\"warning-detail\"></span>\n </div>\n\n <div class=\"actions\">\n <button id=\"cancelButton\" type=\"button\" class=\"button button-secondary\">Cancel</button>\n <button id=\"sendButton\" type=\"button\" class=\"button button-primary\">\n <span id=\"sendSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"sendLabel\">Send email</span>\n </button>\n </div>\n </form>\n\n <div id=\"sentView\" class=\"card hidden\" role=\"status\" aria-live=\"polite\">\n <div class=\"sent-header\">\n <span class=\"sent-badge\">Sent</span>\n <span id=\"sentTimestamp\" class=\"sent-timestamp\"></span>\n </div>\n\n <div class=\"field\">\n <label>From</label>\n <span id=\"sentFrom\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>To</label>\n <span id=\"sentTo\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentCcField\" class=\"field hidden\">\n <label>CC</label>\n <span id=\"sentCc\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentBccField\" class=\"field hidden\">\n <label>BCC</label>\n <span id=\"sentBcc\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Subject</label>\n <span id=\"sentSubject\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Message</label>\n <div id=\"sentBody\" class=\"sent-body\"></div>\n </div>\n\n <div class=\"actions\">\n <button id=\"openGmailButton\" type=\"button\" class=\"button button-secondary hidden\">Open in Gmail</button>\n <button id=\"sentCollapseButton\" type=\"button\" class=\"button button-secondary\">Collapse</button>\n </div>\n </div>\n </div>\n\n <script>\n (function () {\n 'use strict';\n\n var RESOURCE_URI = 'ui://google-workspace/compose-email';\n var currentEmail = '';\n // The host prefills the draft exactly once via ui/notifications/tool-result\n // on ready. We apply only the FIRST prefill and ignore any later ones, so a\n // stray or hostile re-post can't silently rewrite a draft the user has\n // already reviewed before clicking Send.\n var draftApplied = false;\n var pendingRequestId = null;\n var pendingPayload = null;\n var sending = false;\n var collapsed = false;\n var outcomeUnknown = false;\n var sent = false;\n var sendBlocked = false;\n var gmailUrl = null;\n var sendTimeoutId = null;\n // Just beyond the host-side tool-call timeout (60s) so a legitimately slow\n // send resolves to its real result first; this only fires when the reply\n // is genuinely lost, so the button can never stay stuck-silent.\n var SEND_TIMEOUT_MS = 75000;\n\n var composeForm = document.getElementById('composeForm');\n var collapsedState = document.getElementById('collapsedState');\n var collapsedMessage = document.getElementById('collapsedMessage');\n var reopenButton = document.getElementById('reopenButton');\n\n var sentView = document.getElementById('sentView');\n var sentTimestamp = document.getElementById('sentTimestamp');\n var sentFrom = document.getElementById('sentFrom');\n var sentTo = document.getElementById('sentTo');\n var sentCcField = document.getElementById('sentCcField');\n var sentCc = document.getElementById('sentCc');\n var sentBccField = document.getElementById('sentBccField');\n var sentBcc = document.getElementById('sentBcc');\n var sentSubject = document.getElementById('sentSubject');\n var sentBody = document.getElementById('sentBody');\n var openGmailButton = document.getElementById('openGmailButton');\n var sentCollapseButton = document.getElementById('sentCollapseButton');\n\n var toInput = document.getElementById('toInput');\n var ccInput = document.getElementById('ccInput');\n var bccInput = document.getElementById('bccInput');\n var subjectInput = document.getElementById('subjectInput');\n var bodyInput = document.getElementById('bodyInput');\n var fromValue = document.getElementById('fromValue');\n var fromHelper = document.getElementById('fromHelper');\n var ccRow = document.getElementById('ccRow');\n var bccRow = document.getElementById('bccRow');\n var toggleCcButton = document.getElementById('toggleCcButton');\n var toggleBccButton = document.getElementById('toggleBccButton');\n\n var sendButton = document.getElementById('sendButton');\n var sendLabel = document.getElementById('sendLabel');\n var sendSpinner = document.getElementById('sendSpinner');\n var cancelButton = document.getElementById('cancelButton');\n var retryButton = document.getElementById('retryButton');\n\n var errorBox = document.getElementById('errorBox');\n var errorText = document.getElementById('errorText');\n var successBox = document.getElementById('successBox');\n var unknownBox = document.getElementById('unknownBox');\n var unknownTitle = document.getElementById('unknownTitle');\n var unknownText = document.getElementById('unknownText');\n var blockedBox = document.getElementById('blockedBox');\n var blockedText = document.getElementById('blockedText');\n var openComposeButton = document.getElementById('openComposeButton');\n\n function applyThemeFromHostContext() {\n try {\n var context = window.__MCP_HOST_CONTEXT__;\n if (!context || (context.theme !== 'light' && context.theme !== 'dark')) {\n return;\n }\n document.documentElement.setAttribute('data-theme', context.theme);\n } catch (_) {\n // Ignore theme extraction errors\n }\n }\n\n function trimString(value) {\n return String(value || '').trim();\n }\n\n function applyFromValue(email) {\n var trimmed = trimString(email);\n if (trimmed) {\n fromValue.textContent = trimmed;\n fromValue.style.color = '';\n fromHelper.textContent = '';\n fromHelper.classList.add('hidden');\n } else {\n fromValue.textContent = 'Account not shown';\n fromValue.style.color = 'var(--muted)';\n fromHelper.textContent = 'Rebel could not confirm the sending account. Cancel and ask Rebel to recreate the draft before sending.';\n fromHelper.classList.remove('hidden');\n }\n }\n\n function formatAddressItem(item) {\n if (item && typeof item === 'object') {\n var email = trimString(item.email || item.address || item.value);\n var name = trimString(item.name || item.displayName);\n if (email && name) {\n return name + ' <' + email + '>';\n }\n return email;\n }\n return trimString(item);\n }\n\n function normalizeAddressList(value) {\n if (Array.isArray(value)) {\n return value.map(formatAddressItem).filter(Boolean);\n }\n if (typeof value === 'string') {\n return value\n .split(',')\n .map(function (item) { return trimString(item); })\n .filter(Boolean);\n }\n return [];\n }\n\n function listToInputValue(list) {\n return normalizeAddressList(list).join(', ');\n }\n\n var resizeQueued = false;\n function postResize() {\n if (resizeQueued) return;\n resizeQueued = true;\n requestAnimationFrame(function () {\n resizeQueued = false;\n var height = Math.max(\n document.documentElement.scrollHeight,\n document.body ? document.body.scrollHeight : 0\n );\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/resize', params: { height: height } },\n '*'\n );\n });\n }\n\n function postReady() {\n window.parent.postMessage(\n {\n method: 'mcp-app:ready',\n params: { resourceUri: RESOURCE_URI }\n },\n '*'\n );\n }\n\n // Exactly one of the three panels is visible at a time: the editable form,\n // the read-only sent view, or the collapsed summary bar.\n function showView(view) {\n composeForm.classList.toggle('hidden', view !== 'form');\n sentView.classList.toggle('hidden', view !== 'sent');\n collapsedState.classList.toggle('hidden', view !== 'collapsed');\n postResize();\n }\n\n function setCollapsed(nextCollapsed, message) {\n collapsed = nextCollapsed;\n if (nextCollapsed) {\n collapsedMessage.textContent = message || 'Draft collapsed.';\n showView('collapsed');\n } else {\n // Expanding after a send restores the read-only sent view (never the\n // editable form) so the user can re-read what went out without any risk\n // of a duplicate send; before sending, it restores the editable form.\n showView(sent ? 'sent' : 'form');\n }\n }\n\n function setSending(nextSending) {\n sending = nextSending;\n sendButton.disabled = nextSending || sendBlocked;\n cancelButton.disabled = nextSending;\n toInput.disabled = nextSending;\n ccInput.disabled = nextSending;\n bccInput.disabled = nextSending;\n subjectInput.disabled = nextSending;\n bodyInput.disabled = nextSending;\n sendSpinner.classList.toggle('hidden', !nextSending);\n sendLabel.textContent = nextSending ? 'Sending\u2026' : 'Send email';\n sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');\n postResize();\n }\n\n function clearError() {\n errorText.textContent = '';\n errorBox.classList.add('hidden');\n }\n\n function showError(message) {\n errorText.textContent = message || 'Failed to send email.';\n errorBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSuccess() {\n successBox.textContent = '';\n successBox.classList.add('hidden');\n }\n\n function showSuccess(message) {\n successBox.textContent = message;\n successBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSendTimeout() {\n if (sendTimeoutId !== null) {\n clearTimeout(sendTimeoutId);\n sendTimeoutId = null;\n }\n }\n\n function clearUnknown() {\n outcomeUnknown = false;\n unknownTitle.textContent = '';\n unknownText.textContent = '';\n unknownBox.classList.add('hidden');\n }\n\n // No reply ever came back for the send (e.g. the host's response was lost\n // before reaching this iframe). We genuinely don't know whether the email\n // went out, so we must NOT claim success or failure: re-enable the form and\n // tell the user to verify before resending (the send is not idempotent, so\n // a blind retry could send a duplicate).\n function showSendUnknown() {\n outcomeUnknown = true;\n clearError();\n clearSuccess();\n unknownTitle.textContent = 'Not sure if this sent.';\n unknownText.textContent = \"Rebel didn't hear back in time. Check your Sent folder before sending again, so it doesn't go out twice.\";\n unknownBox.classList.remove('hidden');\n postResize();\n }\n\n function handleSendTimeout() {\n sendTimeoutId = null;\n if (!pendingRequestId) {\n return;\n }\n pendingRequestId = null;\n setSending(false);\n showSendUnknown();\n }\n\n function setCcVisible(visible) {\n ccRow.classList.toggle('hidden', !visible);\n toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';\n toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function setBccVisible(visible) {\n bccRow.classList.toggle('hidden', !visible);\n toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';\n toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function readFormPayload() {\n var payload = {\n to: normalizeAddressList(toInput.value),\n cc: normalizeAddressList(ccInput.value),\n bcc: normalizeAddressList(bccInput.value),\n subject: String(subjectInput.value || ''),\n body: String(bodyInput.value || '')\n };\n if (currentEmail) {\n payload.email = currentEmail;\n }\n return payload;\n }\n\n function validatePayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before sending.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before sending.';\n }\n return null;\n }\n\n function sendPayload(payload) {\n pendingPayload = payload;\n pendingRequestId = 'send-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n setSending(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'send_workspace_email',\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function applyDraftData(rawDraft) {\n var draft = rawDraft && typeof rawDraft === 'object' ? rawDraft : {};\n toInput.value = listToInputValue(draft.to);\n ccInput.value = listToInputValue(draft.cc);\n bccInput.value = listToInputValue(draft.bcc);\n subjectInput.value = typeof draft.subject === 'string' ? draft.subject : '';\n bodyInput.value = typeof draft.body === 'string' ? draft.body : '';\n currentEmail = typeof draft.email === 'string' ? draft.email : '';\n applyFromValue(currentEmail);\n setCcVisible(normalizeAddressList(draft.cc).length > 0);\n setBccVisible(normalizeAddressList(draft.bcc).length > 0);\n clearError();\n clearSuccess();\n postResize();\n }\n\n function getDraftFromToolResult(payload) {\n if (!payload || typeof payload !== 'object') {\n return null;\n }\n // CANONICAL: post-A0 super-mcp hoists structuredContent onto the\n // outer block; the host posts it through `params.structuredContent`.\n if (payload.structuredContent && typeof payload.structuredContent === 'object') {\n return payload.structuredContent;\n }\n // MIGRATION SHIM: pre-A0 stored sessions replayed through the\n // current iframe lack `params.structuredContent` because the outer\n // block had no hoist at capture time. Read inner envelope text \u2192\n // JSON.parse \u2192 result.structuredContent. NOT regex-based.\n //\n // Lifetime: PERMANENT defensive read-side helper. Pre-A0 sessions\n // are persisted on disk and may be replayed indefinitely; there is\n // no time-based sunset. Removing this fallback would silently break\n // pre-A0 conversation replay.\n var text = typeof payload.text === 'string' ? payload.text :\n (Array.isArray(payload.content)\n ? (payload.content.find(function (c) { return c && c.type === 'text' && typeof c.text === 'string'; }) || {}).text\n : null);\n if (typeof text !== 'string') return null;\n try {\n var parsed = JSON.parse(text);\n if (parsed && typeof parsed === 'object' && parsed.result && typeof parsed.result === 'object') {\n var inner = parsed.result;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n }\n } catch (_) {\n // Likely-envelope heuristic: text starts with `{` and contains\n // `\"package_id\"` in the first 64 chars. If JSON.parse failed on a\n // likely-envelope, surface a warning so the developer chasing\n // \"compose form is empty on replay\" sees a signal. For non-envelope\n // text (the dominant case), no log fires.\n var prefix = text.length > 64 ? text.slice(0, 64) : text;\n var likelyEnvelope = prefix.charAt(0) === '{' && prefix.indexOf('\"package_id\"') !== -1;\n if (likelyEnvelope && typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn('[compose-email] Migration shim: JSON.parse failed on likely super-mcp envelope; pre-fill skipped');\n }\n }\n return null;\n }\n\n function findTextBlock(blocks) {\n if (!Array.isArray(blocks)) return null;\n var block = blocks.find(function (c) {\n return c && c.type === 'text' && typeof c.text === 'string';\n });\n return block ? block.text : null;\n }\n\n // Extract the send result identifiers ({ messageId, threadId, labelIds })\n // from the tool-call reply. The connector attaches structuredContent, which\n // super-mcp hoists onto the outer block, so the fast path is a single read.\n // The envelope-unwrapping fallback keeps this robust for hosts (or replayed\n // sessions) that forward only the serialized super-mcp text envelope.\n function getSendMetaFromResult(result) {\n if (!result || typeof result !== 'object') return null;\n if (result.structuredContent && typeof result.structuredContent === 'object') {\n return result.structuredContent;\n }\n try {\n var outerText = findTextBlock(result.content);\n if (typeof outerText !== 'string' && typeof result.text === 'string') {\n outerText = result.text;\n }\n if (typeof outerText !== 'string') return null;\n var envelope = JSON.parse(outerText);\n if (!envelope || typeof envelope !== 'object') return null;\n // outerText was the connector payload directly (no super-mcp envelope).\n if (envelope.messageId || envelope.threadId) return envelope;\n var inner = envelope.result;\n if (!inner || typeof inner !== 'object') return null;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n var innerText = findTextBlock(inner.content);\n if (typeof innerText !== 'string') return null;\n var payload = JSON.parse(innerText);\n return (payload && typeof payload === 'object') ? payload : null;\n } catch (_) {\n return null;\n }\n }\n\n // ---- Blocked-send Gmail escape hatch ----\n // Shown ONLY when the user's own send preference blocks the tool\n // (super-mcp TOOL_BLOCKED / -33008 + \"disabled by user preference\"). We\n // never call the disabled tool; instead we open a prefilled Gmail compose\n // window so the user finishes the send in Gmail (no copy-paste). This is\n // deliberately narrow: admin-disabled (\"disabled by your organization\u2026\")\n // and generic security-policy blocks fall through to the normal retryable\n // error, because offering a Gmail bypass there would route around a control\n // the user did not set.\n //\n // Gmail compose URLs that get too long can silently fail to open, so we cap\n // the length and degrade visibly (recipients + subject only, paste the body)\n // rather than truncating without telling the user.\n var GMAIL_COMPOSE_MAX_URL = 8000;\n var BLOCKED_SEND_MESSAGE =\n '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.';\n\n function isUserDisabledSendError(message) {\n var m = String(message || '').toLowerCase();\n // Anchor the code so it can't match inside a longer number (-330080),\n // and require the user-preference phrase so admin-disabled / generic\n // security blocks fall through to the ordinary retryable error.\n return /-33008\\b/.test(m) && m.indexOf('disabled by user preference') !== -1;\n }\n\n // Base URL + path are constant (code-reviewed here, never config-provided);\n // only the field VALUES vary and go through URLSearchParams, so query\n // delimiters, newlines, and reserved characters become encoded data \u2014 no\n // query injection or header splitting. The host ui/open-external-link\n // bridge re-validates the mail.google.com host before opening.\n function buildGmailComposeUrl(payload, includeBody) {\n var url = new URL('https://mail.google.com/mail/');\n var params = new URLSearchParams();\n params.set('view', 'cm');\n params.set('fs', '1');\n var to = normalizeAddressList(payload.to).join(',');\n if (to) params.set('to', to);\n var cc = normalizeAddressList(payload.cc).join(',');\n if (cc) params.set('cc', cc);\n var bcc = normalizeAddressList(payload.bcc).join(',');\n if (bcc) params.set('bcc', bcc);\n var subject = trimString(payload.subject);\n if (subject) params.set('su', subject);\n if (includeBody) {\n var body = String(payload.body || '');\n if (body) params.set('body', body);\n }\n url.search = params.toString();\n return url.toString();\n }\n\n function showBlockedSend() {\n sendBlocked = true;\n clearError();\n clearSuccess();\n clearUnknown();\n sendButton.disabled = true;\n sendButton.title =\n 'Sending from here is turned off in your settings. Turn it back on in Settings, or open this draft in Gmail to send.';\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n blockedBox.classList.remove('hidden');\n postResize();\n }\n\n openComposeButton.addEventListener('click', function () {\n // Reset any prior \"too long\" note, then rebuild from the live form so\n // edits made after the block are reflected.\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n var payload = readFormPayload();\n var composeUrl = buildGmailComposeUrl(payload, true);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n composeUrl = buildGmailComposeUrl(payload, false);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n // Even without the body the link is too long (many recipients, or a\n // very long subject). Gmail would silently refuse to open it, so\n // don't pretend \u2014 tell the user and post nothing.\n blockedText.textContent =\n 'This draft is too large to open in Gmail. Shorten the recipients or subject, or turn sending back on in Settings.';\n postResize();\n return;\n }\n blockedText.textContent =\n 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';\n postResize();\n }\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },\n '*'\n );\n });\n\n function looksLikeEmail(value) {\n var at = value.indexOf('@');\n return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;\n }\n\n // Build a Gmail deep link to the just-sent message. The /u/<account> segment\n // targets the right inbox when the user is signed into several Google\n // accounts; #all/<id> opens the thread (falling back to the message id).\n function buildGmailUrl(meta, email) {\n if (!meta || typeof meta !== 'object') return null;\n var id = trimString(meta.threadId) || trimString(meta.messageId);\n if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;\n var account = trimString(email);\n var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';\n return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);\n }\n\n function formatSentTime() {\n try {\n return new Date().toLocaleString(undefined, {\n month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'\n });\n } catch (_) {\n return '';\n }\n }\n\n function renderSentView(payload, meta, stamp) {\n payload = payload && typeof payload === 'object' ? payload : {};\n sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';\n sentFrom.textContent = trimString(payload.email) || 'Account not shown';\n sentTo.textContent = normalizeAddressList(payload.to).join(', ');\n var ccList = normalizeAddressList(payload.cc);\n sentCc.textContent = ccList.join(', ');\n sentCcField.classList.toggle('hidden', ccList.length === 0);\n var bccList = normalizeAddressList(payload.bcc);\n sentBcc.textContent = bccList.join(', ');\n sentBccField.classList.toggle('hidden', bccList.length === 0);\n sentSubject.textContent = String(payload.subject || '');\n sentBody.textContent = String(payload.body || '');\n gmailUrl = buildGmailUrl(meta, payload.email);\n openGmailButton.classList.toggle('hidden', !gmailUrl);\n }\n\n function handleSendRequest() {\n if (sending) return;\n // Once the user's own send preference has blocked this tool, never\n // re-invoke it \u2014 the escape hatch is the only path out. The Send button\n // is already disabled, but this also fends off a future host that grants\n // allow-forms (a submit could otherwise re-fire the disabled tool).\n if (sendBlocked) return;\n\n var payload = readFormPayload();\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n\n sendPayload(payload);\n }\n\n // The Send button is type=\"button\" with an explicit click handler rather\n // than a form submit button. The Rebel host renders this iframe with a\n // sandbox of \"allow-scripts\" only \u2014 no \"allow-forms\" \u2014 so native form\n // submission is blocked by the browser BEFORE the submit event fires\n // (\"Blocked form submission ... the form's frame is sandboxed and the\n // allow-forms permission is not set\"). A submit-driven Send therefore\n // silently did nothing: no postMessage, no spinner, no telemetry.\n // A click handler needs no sandbox permission and is the same path\n // Cancel/Retry already use. The submit listener below stays only as a\n // defensive fallback for hosts that DO grant allow-forms; in this sandbox\n // it never fires (neither the button click nor Enter routes through it).\n // The sending guard keeps any double-fire (in an allow-forms host) a no-op.\n sendButton.addEventListener('click', function () {\n handleSendRequest();\n });\n\n composeForm.addEventListener('submit', function (event) {\n event.preventDefault();\n handleSendRequest();\n });\n\n retryButton.addEventListener('click', function () {\n if (sending) return;\n var payload = readFormPayload();\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n sendPayload(payload);\n });\n\n cancelButton.addEventListener('click', function () {\n if (sending) return;\n // After a lost-reply timeout we don't know if the email sent, so don't\n // claim \"Nothing sent.\" on collapse \u2014 point the user to verify instead.\n var collapseMessage = outcomeUnknown\n ? 'Collapsed. Check your Sent folder if you are not sure.'\n : 'Draft collapsed. Nothing sent.';\n clearError();\n clearSuccess();\n clearUnknown();\n setCollapsed(true, collapseMessage);\n });\n\n reopenButton.addEventListener('click', function () {\n setCollapsed(false);\n });\n\n sentCollapseButton.addEventListener('click', function () {\n setCollapsed(true, collapsedMessage.textContent || 'Email sent.');\n });\n\n // The iframe sandbox is \"allow-scripts\" only (no allow-popups / allow-forms),\n // so it cannot open a URL itself. Ask the host to open the Gmail link in the\n // user's browser via the ui/open-external-link bridge, which re-validates the\n // URL against its own allowlist before handing it to the OS.\n openGmailButton.addEventListener('click', function () {\n if (!gmailUrl) return;\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },\n '*'\n );\n });\n\n toggleCcButton.addEventListener('click', function () {\n setCcVisible(ccRow.classList.contains('hidden'));\n postResize();\n });\n\n toggleBccButton.addEventListener('click', function () {\n setBccVisible(bccRow.classList.contains('hidden'));\n postResize();\n });\n\n [toInput, ccInput, bccInput, subjectInput, bodyInput].forEach(function (element) {\n element.addEventListener('input', function () {\n clearError();\n clearSuccess();\n clearUnknown();\n postResize();\n });\n });\n\n window.addEventListener('message', function (event) {\n // Honest scope (origin-independent): the iframe sandbox origin is 'null',\n // so validating event.origin is unreliable across dev/prod/custom-scheme\n // hosts. Instead reject any *identified* sender that isn't our host frame\n // (window.parent). A real cross-frame postMessage always stamps\n // event.source with the sending window, so a hostile sibling frame is\n // rejected here; a null source only occurs for same-context synthetic\n // dispatch (our own code) and cannot be forged from outside, so we\n // tolerate it. This does not authenticate the host's identity \u2014 the host\n // separately authenticates this iframe by origin+source.\n if (event.source && event.source !== window.parent) {\n return;\n }\n\n var data = event.data;\n if (!data || typeof data !== 'object') {\n return;\n }\n\n if (data.method === 'ui/notifications/tool-result') {\n // Always parse (so the migration-shim's malformed-envelope warning\n // still fires), but apply only the first successful prefill: a stray\n // or hostile re-post can't silently rewrite a draft the user has\n // already reviewed.\n var draft = getDraftFromToolResult(data.params);\n if (draft && !draftApplied) {\n draftApplied = true;\n applyDraftData(draft);\n }\n return;\n }\n\n if (data.jsonrpc !== '2.0' || !pendingRequestId || data.id !== pendingRequestId) {\n return;\n }\n\n pendingRequestId = null;\n clearSendTimeout();\n clearUnknown();\n setSending(false);\n\n if (data.error) {\n var errorMessage = data.error && typeof data.error.message === 'string'\n ? data.error.message\n : 'Failed to send email.';\n // Prefer the host-vetted structured reason (a closed enum the host\n // derives from the tool-block error data) and fall back to\n // text-matching the flattened message for hosts that don't forward it\n // yet. Only 'user-disabled' opens the Gmail escape hatch \u2014\n // admin-disabled and security-policy blocks stay ordinary errors (see\n // the detector comment above for why).\n var blockedReason = data.error.data && data.error.data.reason;\n if (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage)) {\n showBlockedSend();\n return;\n }\n showError(errorMessage);\n return;\n }\n\n clearError();\n clearSuccess();\n // Preserve what was sent (and how to reach it) instead of discarding the\n // draft. pendingPayload is the exact payload we posted; the reply carries\n // the Gmail message/thread ids. We default to the collapsed summary, but\n // Reopen now restores a read-only view of the sent message.\n var sentPayload = pendingPayload || readFormPayload();\n var stamp = formatSentTime();\n renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);\n sent = true;\n setCollapsed(true, stamp ? 'Email sent \u00B7 ' + stamp : 'Email sent.');\n });\n\n if (typeof ResizeObserver === 'function' && document.body) {\n var observer = new ResizeObserver(postResize);\n observer.observe(document.body);\n }\n\n applyThemeFromHostContext();\n setCcVisible(false);\n setBccVisible(false);\n setCollapsed(false);\n postResize();\n postReady();\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'ui/initialize',\n params: { resourceUri: RESOURCE_URI },\n id: 'compose-email-init'\n },\n '*'\n );\n })();\n </script>\n</body>\n</html>\n";
1
+ export declare const COMPOSE_EMAIL_HTML = "\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <title>Compose Email</title>\n <style>\n :root {\n --bg: #ffffff;\n --panel: #ffffff;\n --border: #d9dde5;\n --text: #1f2937;\n --muted: #6b7280;\n --input-bg: #ffffff;\n --button-bg: #1f6feb;\n --button-text: #ffffff;\n --button-bg-hover: #1b63d3;\n --secondary-bg: #f3f4f6;\n --secondary-text: #1f2937;\n --secondary-border: #d1d5db;\n --error-bg: #fef2f2;\n --error-border: #fecaca;\n --error-text: #991b1b;\n --success-bg: #ecfdf5;\n --success-border: #bbf7d0;\n --success-text: #166534;\n --warning-bg: #fffbeb;\n --warning-border: #fde68a;\n --warning-text: #92400e;\n }\n\n @media (prefers-color-scheme: dark) {\n :root {\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n }\n\n html[data-theme=\"light\"] {\n color-scheme: light;\n }\n\n html[data-theme=\"dark\"] {\n color-scheme: dark;\n --bg: #0f172a;\n --panel: #111827;\n --border: #334155;\n --text: #e5e7eb;\n --muted: #9ca3af;\n --input-bg: #0b1220;\n --button-bg: #3b82f6;\n --button-text: #eff6ff;\n --button-bg-hover: #2563eb;\n --secondary-bg: #1f2937;\n --secondary-text: #e5e7eb;\n --secondary-border: #374151;\n --error-bg: #2b1011;\n --error-border: #7f1d1d;\n --error-text: #fca5a5;\n --success-bg: #052e1b;\n --success-border: #166534;\n --success-text: #86efac;\n --warning-bg: #2a2106;\n --warning-border: #854d0e;\n --warning-text: #fcd34d;\n }\n\n * {\n box-sizing: border-box;\n }\n\n body {\n margin: 0;\n padding: 16px;\n background: var(--bg);\n color: var(--text);\n font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", Roboto, sans-serif;\n line-height: 1.4;\n }\n\n .wrapper {\n width: 100%;\n max-width: 720px;\n margin: 0 auto;\n }\n\n .card {\n background: var(--panel);\n border: 1px solid var(--border);\n border-radius: 12px;\n padding: 14px;\n display: flex;\n flex-direction: column;\n gap: 12px;\n }\n\n .field {\n display: flex;\n flex-direction: column;\n gap: 6px;\n }\n\n .field label {\n font-size: 12px;\n font-weight: 600;\n color: var(--muted);\n text-transform: uppercase;\n letter-spacing: 0.04em;\n }\n\n .from-value {\n color: var(--text);\n font-size: 14px;\n padding: 2px 0;\n word-break: break-word;\n }\n\n .from-helper {\n font-size: 12px;\n color: var(--muted);\n margin-top: 2px;\n }\n\n .input,\n .textarea {\n width: 100%;\n background: var(--input-bg);\n color: var(--text);\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n font-size: 14px;\n font-family: inherit;\n }\n\n .input:focus,\n .textarea:focus {\n outline: 2px solid rgba(59, 130, 246, 0.35);\n outline-offset: 1px;\n }\n\n .textarea {\n min-height: 180px;\n resize: vertical;\n white-space: pre-wrap;\n }\n\n .toggles {\n display: flex;\n gap: 12px;\n align-items: center;\n flex-wrap: wrap;\n }\n\n .link-button {\n border: none;\n padding: 0;\n background: none;\n color: var(--muted);\n text-decoration: underline;\n font-size: 12px;\n cursor: pointer;\n }\n\n .link-button:hover {\n color: var(--text);\n }\n\n .actions {\n display: flex;\n justify-content: flex-end;\n gap: 10px;\n margin-top: 2px;\n flex-wrap: wrap;\n }\n\n .button {\n border-radius: 8px;\n border: 1px solid transparent;\n min-height: 36px;\n padding: 0 14px;\n font-size: 13px;\n font-weight: 600;\n font-family: inherit;\n cursor: pointer;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: 8px;\n transition: background 120ms ease, opacity 120ms ease, border-color 120ms ease;\n }\n\n .button:disabled {\n cursor: not-allowed;\n opacity: 0.75;\n }\n\n .button-primary {\n background: var(--button-bg);\n color: var(--button-text);\n }\n\n .button-primary:hover:enabled {\n background: var(--button-bg-hover);\n }\n\n .button-secondary {\n background: var(--secondary-bg);\n color: var(--secondary-text);\n border-color: var(--secondary-border);\n }\n\n .spinner {\n width: 14px;\n height: 14px;\n border: 2px solid currentColor;\n border-right-color: transparent;\n border-radius: 50%;\n display: inline-block;\n animation: spin 700ms linear infinite;\n }\n\n @keyframes spin {\n to { transform: rotate(360deg); }\n }\n\n .status {\n border-radius: 8px;\n border: 1px solid transparent;\n padding: 8px 10px;\n font-size: 13px;\n }\n\n .error {\n background: var(--error-bg);\n border-color: var(--error-border);\n color: var(--error-text);\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .success {\n background: var(--success-bg);\n border-color: var(--success-border);\n color: var(--success-text);\n }\n\n .warning {\n background: var(--warning-bg);\n border-color: var(--warning-border);\n color: var(--warning-text);\n display: block;\n }\n\n .warning strong {\n display: block;\n margin-bottom: 2px;\n }\n\n .warning .warning-detail {\n opacity: 0.85;\n }\n\n .blocked-actions {\n margin-top: 8px;\n }\n\n .collapsed {\n border: 1px solid var(--border);\n border-radius: 10px;\n background: var(--panel);\n padding: 10px 12px;\n display: flex;\n justify-content: space-between;\n align-items: center;\n gap: 8px;\n font-size: 13px;\n }\n\n .hidden {\n display: none !important;\n }\n\n .sent-header {\n display: flex;\n align-items: center;\n gap: 8px;\n flex-wrap: wrap;\n }\n\n .sent-badge {\n display: inline-flex;\n align-items: center;\n background: var(--success-bg);\n color: var(--success-text);\n border: 1px solid var(--success-border);\n border-radius: 999px;\n padding: 2px 10px;\n font-size: 12px;\n font-weight: 600;\n }\n\n .sent-timestamp {\n color: var(--muted);\n font-size: 12px;\n }\n\n .sent-value {\n color: var(--text);\n font-size: 14px;\n word-break: break-word;\n }\n\n .sent-body {\n color: var(--text);\n font-size: 14px;\n white-space: pre-wrap;\n word-break: break-word;\n max-height: 260px;\n overflow: auto;\n border: 1px solid var(--border);\n border-radius: 8px;\n padding: 10px 12px;\n background: var(--input-bg);\n }\n </style>\n</head>\n<body>\n <div class=\"wrapper\">\n <div id=\"collapsedState\" class=\"collapsed hidden\">\n <span id=\"collapsedMessage\">Draft collapsed.</span>\n <button id=\"reopenButton\" type=\"button\" class=\"button button-secondary\">Reopen</button>\n </div>\n\n <form id=\"composeForm\" class=\"card\" novalidate aria-label=\"Compose email\">\n <div class=\"field from-field\">\n <label>From</label>\n <span id=\"fromValue\" class=\"from-value\"></span>\n <span id=\"fromHelper\" class=\"from-helper hidden\"></span>\n </div>\n\n <div class=\"field\">\n <label for=\"toInput\">To</label>\n <input id=\"toInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"name@example.com, team@example.com\">\n </div>\n\n <div class=\"toggles\">\n <button id=\"toggleCcButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"ccRow\">Add CC</button>\n <button id=\"toggleBccButton\" type=\"button\" class=\"link-button\" aria-expanded=\"false\" aria-controls=\"bccRow\">Add BCC</button>\n </div>\n\n <div id=\"ccRow\" class=\"field hidden\">\n <label for=\"ccInput\">CC</label>\n <input id=\"ccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"cc@example.com\">\n </div>\n\n <div id=\"bccRow\" class=\"field hidden\">\n <label for=\"bccInput\">BCC</label>\n <input id=\"bccInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"bcc@example.com\">\n </div>\n\n <div class=\"field\">\n <label for=\"subjectInput\">Subject</label>\n <input id=\"subjectInput\" class=\"input\" type=\"text\" autocomplete=\"off\" placeholder=\"Email subject\">\n </div>\n\n <div class=\"field\">\n <label for=\"bodyInput\">Body</label>\n <textarea id=\"bodyInput\" class=\"textarea\" placeholder=\"Write your email\"></textarea>\n </div>\n\n <div id=\"errorBox\" class=\"status error hidden\" role=\"alert\">\n <span id=\"errorText\"></span>\n <button id=\"retryButton\" type=\"button\" class=\"link-button\">Retry</button>\n </div>\n\n <div id=\"blockedBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <span id=\"blockedText\"></span>\n <div class=\"blocked-actions\">\n <button id=\"openComposeButton\" type=\"button\" class=\"button button-secondary\">Open in Gmail</button>\n </div>\n </div>\n\n <div id=\"successBox\" class=\"status success hidden\" role=\"status\" aria-live=\"polite\"></div>\n\n <div id=\"unknownBox\" class=\"status warning hidden\" role=\"status\" aria-live=\"polite\">\n <strong id=\"unknownTitle\"></strong>\n <span id=\"unknownText\" class=\"warning-detail\"></span>\n </div>\n\n <div class=\"actions\">\n <button id=\"cancelButton\" type=\"button\" class=\"button button-secondary\">Cancel</button>\n <button id=\"draftButton\" type=\"button\" class=\"button button-secondary\">\n <span id=\"draftSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"draftLabel\">Save draft</span>\n </button>\n <button id=\"sendButton\" type=\"button\" class=\"button button-primary\">\n <span id=\"sendSpinner\" class=\"spinner hidden\" aria-hidden=\"true\"></span>\n <span id=\"sendLabel\">Send email</span>\n </button>\n </div>\n </form>\n\n <div id=\"sentView\" class=\"card hidden\" role=\"status\" aria-live=\"polite\">\n <div class=\"sent-header\">\n <span class=\"sent-badge\">Sent</span>\n <span id=\"sentTimestamp\" class=\"sent-timestamp\"></span>\n </div>\n\n <div class=\"field\">\n <label>From</label>\n <span id=\"sentFrom\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>To</label>\n <span id=\"sentTo\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentCcField\" class=\"field hidden\">\n <label>CC</label>\n <span id=\"sentCc\" class=\"sent-value\"></span>\n </div>\n\n <div id=\"sentBccField\" class=\"field hidden\">\n <label>BCC</label>\n <span id=\"sentBcc\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Subject</label>\n <span id=\"sentSubject\" class=\"sent-value\"></span>\n </div>\n\n <div class=\"field\">\n <label>Message</label>\n <div id=\"sentBody\" class=\"sent-body\"></div>\n </div>\n\n <div class=\"actions\">\n <button id=\"openGmailButton\" type=\"button\" class=\"button button-secondary hidden\">Open in Gmail</button>\n <button id=\"sentCollapseButton\" type=\"button\" class=\"button button-secondary\">Collapse</button>\n </div>\n </div>\n </div>\n\n <script>\n (function () {\n 'use strict';\n\n var RESOURCE_URI = 'ui://google-workspace/compose-email';\n var currentEmail = '';\n // The host prefills the draft exactly once via ui/notifications/tool-result\n // on ready. We apply only the FIRST prefill and ignore any later ones, so a\n // stray or hostile re-post can't silently rewrite a draft the user has\n // already reviewed before clicking Send.\n var draftApplied = false;\n var pendingRequestId = null;\n var pendingPayload = null;\n var sending = false;\n var collapsed = false;\n var outcomeUnknown = false;\n var sent = false;\n // Which action the in-flight request belongs to ('send' | 'draft').\n // Captured before clearing on reply/timeout so the response handler can\n // route error/success correctly. retryAction survives the reply so a\n // later Retry click still knows which tool to re-invoke.\n var pendingAction = null;\n var retryAction = null;\n var sendBlocked = false;\n var gmailUrl = null;\n var sendTimeoutId = null;\n // Just beyond the host-side tool-call timeout (60s) so a legitimately slow\n // send resolves to its real result first; this only fires when the reply\n // is genuinely lost, so the button can never stay stuck-silent.\n var SEND_TIMEOUT_MS = 75000;\n\n var composeForm = document.getElementById('composeForm');\n var collapsedState = document.getElementById('collapsedState');\n var collapsedMessage = document.getElementById('collapsedMessage');\n var reopenButton = document.getElementById('reopenButton');\n\n var sentView = document.getElementById('sentView');\n var sentTimestamp = document.getElementById('sentTimestamp');\n var sentFrom = document.getElementById('sentFrom');\n var sentTo = document.getElementById('sentTo');\n var sentCcField = document.getElementById('sentCcField');\n var sentCc = document.getElementById('sentCc');\n var sentBccField = document.getElementById('sentBccField');\n var sentBcc = document.getElementById('sentBcc');\n var sentSubject = document.getElementById('sentSubject');\n var sentBody = document.getElementById('sentBody');\n var openGmailButton = document.getElementById('openGmailButton');\n var sentCollapseButton = document.getElementById('sentCollapseButton');\n\n var toInput = document.getElementById('toInput');\n var ccInput = document.getElementById('ccInput');\n var bccInput = document.getElementById('bccInput');\n var subjectInput = document.getElementById('subjectInput');\n var bodyInput = document.getElementById('bodyInput');\n var fromValue = document.getElementById('fromValue');\n var fromHelper = document.getElementById('fromHelper');\n var ccRow = document.getElementById('ccRow');\n var bccRow = document.getElementById('bccRow');\n var toggleCcButton = document.getElementById('toggleCcButton');\n var toggleBccButton = document.getElementById('toggleBccButton');\n\n var sendButton = document.getElementById('sendButton');\n var sendLabel = document.getElementById('sendLabel');\n var sendSpinner = document.getElementById('sendSpinner');\n var draftButton = document.getElementById('draftButton');\n var draftLabel = document.getElementById('draftLabel');\n var draftSpinner = document.getElementById('draftSpinner');\n var cancelButton = document.getElementById('cancelButton');\n var retryButton = document.getElementById('retryButton');\n\n var errorBox = document.getElementById('errorBox');\n var errorText = document.getElementById('errorText');\n var successBox = document.getElementById('successBox');\n var unknownBox = document.getElementById('unknownBox');\n var unknownTitle = document.getElementById('unknownTitle');\n var unknownText = document.getElementById('unknownText');\n var blockedBox = document.getElementById('blockedBox');\n var blockedText = document.getElementById('blockedText');\n var openComposeButton = document.getElementById('openComposeButton');\n\n function applyThemeFromHostContext() {\n try {\n var context = window.__MCP_HOST_CONTEXT__;\n if (!context || (context.theme !== 'light' && context.theme !== 'dark')) {\n return;\n }\n document.documentElement.setAttribute('data-theme', context.theme);\n } catch (_) {\n // Ignore theme extraction errors\n }\n }\n\n function trimString(value) {\n return String(value || '').trim();\n }\n\n function applyFromValue(email) {\n var trimmed = trimString(email);\n if (trimmed) {\n fromValue.textContent = trimmed;\n fromValue.style.color = '';\n fromHelper.textContent = '';\n fromHelper.classList.add('hidden');\n } else {\n fromValue.textContent = 'Account not shown';\n fromValue.style.color = 'var(--muted)';\n fromHelper.textContent = 'Rebel could not confirm the sending account. Cancel and ask Rebel to recreate the draft before sending.';\n fromHelper.classList.remove('hidden');\n }\n }\n\n function formatAddressItem(item) {\n if (item && typeof item === 'object') {\n var email = trimString(item.email || item.address || item.value);\n var name = trimString(item.name || item.displayName);\n if (email && name) {\n return name + ' <' + email + '>';\n }\n return email;\n }\n return trimString(item);\n }\n\n function normalizeAddressList(value) {\n if (Array.isArray(value)) {\n return value.map(formatAddressItem).filter(Boolean);\n }\n if (typeof value === 'string') {\n return value\n .split(',')\n .map(function (item) { return trimString(item); })\n .filter(Boolean);\n }\n return [];\n }\n\n function listToInputValue(list) {\n return normalizeAddressList(list).join(', ');\n }\n\n var resizeQueued = false;\n function postResize() {\n if (resizeQueued) return;\n resizeQueued = true;\n requestAnimationFrame(function () {\n resizeQueued = false;\n var height = Math.max(\n document.documentElement.scrollHeight,\n document.body ? document.body.scrollHeight : 0\n );\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/resize', params: { height: height } },\n '*'\n );\n });\n }\n\n function postReady() {\n window.parent.postMessage(\n {\n method: 'mcp-app:ready',\n params: { resourceUri: RESOURCE_URI }\n },\n '*'\n );\n }\n\n // Exactly one of the three panels is visible at a time: the editable form,\n // the read-only sent view, or the collapsed summary bar.\n function showView(view) {\n composeForm.classList.toggle('hidden', view !== 'form');\n sentView.classList.toggle('hidden', view !== 'sent');\n collapsedState.classList.toggle('hidden', view !== 'collapsed');\n postResize();\n }\n\n function setCollapsed(nextCollapsed, message) {\n collapsed = nextCollapsed;\n if (nextCollapsed) {\n collapsedMessage.textContent = message || 'Draft collapsed.';\n showView('collapsed');\n } else {\n // Expanding after a send restores the read-only sent view (never the\n // editable form) so the user can re-read what went out without any risk\n // of a duplicate send; before sending, it restores the editable form.\n showView(sent ? 'sent' : 'form');\n }\n }\n\n function setSending(nextSending) {\n sending = nextSending;\n sendButton.disabled = nextSending || sendBlocked;\n draftButton.disabled = nextSending;\n cancelButton.disabled = nextSending;\n toInput.disabled = nextSending;\n ccInput.disabled = nextSending;\n bccInput.disabled = nextSending;\n subjectInput.disabled = nextSending;\n bodyInput.disabled = nextSending;\n sendSpinner.classList.toggle('hidden', !nextSending);\n sendLabel.textContent = nextSending ? 'Sending\u2026' : 'Send email';\n sendButton.setAttribute('aria-busy', nextSending ? 'true' : 'false');\n postResize();\n }\n\n // Mirror of setSending for the Save-draft action. One request is in\n // flight at a time (both paths share pendingRequestId and set the same\n // `sending` flag), so the two busy states can never overlap; every\n // control locks either way and only the active button shows a spinner\n // and aria-busy.\n function setSavingDraft(nextSaving) {\n sending = nextSaving;\n sendButton.disabled = nextSaving || sendBlocked;\n draftButton.disabled = nextSaving;\n cancelButton.disabled = nextSaving;\n toInput.disabled = nextSaving;\n ccInput.disabled = nextSaving;\n bccInput.disabled = nextSaving;\n subjectInput.disabled = nextSaving;\n bodyInput.disabled = nextSaving;\n sendSpinner.classList.add('hidden');\n sendLabel.textContent = 'Send email';\n sendButton.setAttribute('aria-busy', 'false');\n draftSpinner.classList.toggle('hidden', !nextSaving);\n draftLabel.textContent = nextSaving ? 'Saving\u2026' : 'Save draft';\n draftButton.setAttribute('aria-busy', nextSaving ? 'true' : 'false');\n postResize();\n }\n\n function clearError() {\n errorText.textContent = '';\n errorBox.classList.add('hidden');\n }\n\n function showError(message) {\n errorText.textContent = message || 'Failed to send email.';\n errorBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSuccess() {\n successBox.textContent = '';\n successBox.classList.add('hidden');\n }\n\n function showSuccess(message) {\n successBox.textContent = message;\n successBox.classList.remove('hidden');\n postResize();\n }\n\n function clearSendTimeout() {\n if (sendTimeoutId !== null) {\n clearTimeout(sendTimeoutId);\n sendTimeoutId = null;\n }\n }\n\n function clearUnknown() {\n outcomeUnknown = false;\n unknownTitle.textContent = '';\n unknownText.textContent = '';\n unknownBox.classList.add('hidden');\n }\n\n // No reply ever came back for the send (e.g. the host's response was lost\n // before reaching this iframe). We genuinely don't know whether the email\n // went out, so we must NOT claim success or failure: re-enable the form and\n // tell the user to verify before resending (the send is not idempotent, so\n // a blind retry could send a duplicate).\n function showSendUnknown() {\n outcomeUnknown = true;\n clearError();\n clearSuccess();\n unknownTitle.textContent = 'Not sure if this sent.';\n unknownText.textContent = \"Rebel didn't hear back in time. Check your Sent folder before sending again, so it doesn't go out twice.\";\n unknownBox.classList.remove('hidden');\n postResize();\n }\n\n function handleSendTimeout() {\n sendTimeoutId = null;\n if (!pendingRequestId) {\n return;\n }\n pendingRequestId = null;\n if (pendingAction === 'draft') {\n pendingAction = null;\n setSavingDraft(false);\n showDraftSaveUnknown();\n return;\n }\n pendingAction = null;\n setSending(false);\n showSendUnknown();\n }\n\n // Same lost-reply honesty as a send, lower stakes: a blind retry here\n // could create a duplicate draft, so we say we're not sure and point at\n // the Drafts folder instead of offering Retry.\n function showDraftSaveUnknown() {\n outcomeUnknown = true;\n clearError();\n clearSuccess();\n unknownTitle.textContent = 'Not sure if the draft was saved.';\n unknownText.textContent =\n \"Rebel didn't hear back in time. Check your Drafts folder before trying again, so you don't create a duplicate.\";\n unknownBox.classList.remove('hidden');\n postResize();\n }\n\n function setCcVisible(visible) {\n ccRow.classList.toggle('hidden', !visible);\n toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';\n toggleCcButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function setBccVisible(visible) {\n bccRow.classList.toggle('hidden', !visible);\n toggleBccButton.textContent = visible ? 'Hide BCC' : 'Add BCC';\n toggleBccButton.setAttribute('aria-expanded', visible ? 'true' : 'false');\n }\n\n function readFormPayload() {\n var payload = {\n to: normalizeAddressList(toInput.value),\n cc: normalizeAddressList(ccInput.value),\n bcc: normalizeAddressList(bccInput.value),\n subject: String(subjectInput.value || ''),\n body: String(bodyInput.value || '')\n };\n if (currentEmail) {\n payload.email = currentEmail;\n }\n return payload;\n }\n\n function validatePayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before sending.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before sending.';\n }\n return null;\n }\n\n // Same provider-compatible minimum as sending (the draft tools require\n // To, Subject, and Body too) with save-specific copy. Draft is\n // email-mode only, so this body is the email shape unconditionally.\n function validateDraftPayload(payload) {\n if (!payload.to || payload.to.length === 0) {\n return 'Add at least one recipient in To.';\n }\n if (!trimString(payload.subject)) {\n return 'Add a subject before saving.';\n }\n if (!trimString(payload.body)) {\n return 'Add an email body before saving.';\n }\n return null;\n }\n\n function sendPayload(payload) {\n pendingPayload = payload;\n pendingRequestId = 'send-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingAction = 'send';\n retryAction = null;\n setSending(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'send_workspace_email',\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function saveDraftPayload(payload) {\n pendingPayload = payload;\n pendingRequestId = 'draft-' + Date.now() + '-' + Math.random().toString(16).slice(2);\n pendingAction = 'draft';\n retryAction = null;\n setSavingDraft(true);\n clearError();\n clearSuccess();\n clearUnknown();\n clearSendTimeout();\n sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'tools/call',\n params: {\n name: 'create_workspace_draft',\n arguments: payload\n },\n id: pendingRequestId\n },\n '*'\n );\n }\n\n function applyDraftData(rawDraft) {\n var draft = rawDraft && typeof rawDraft === 'object' ? rawDraft : {};\n toInput.value = listToInputValue(draft.to);\n ccInput.value = listToInputValue(draft.cc);\n bccInput.value = listToInputValue(draft.bcc);\n subjectInput.value = typeof draft.subject === 'string' ? draft.subject : '';\n bodyInput.value = typeof draft.body === 'string' ? draft.body : '';\n currentEmail = typeof draft.email === 'string' ? draft.email : '';\n applyFromValue(currentEmail);\n setCcVisible(normalizeAddressList(draft.cc).length > 0);\n setBccVisible(normalizeAddressList(draft.bcc).length > 0);\n clearError();\n clearSuccess();\n postResize();\n }\n\n function getDraftFromToolResult(payload) {\n if (!payload || typeof payload !== 'object') {\n return null;\n }\n // CANONICAL: post-A0 super-mcp hoists structuredContent onto the\n // outer block; the host posts it through `params.structuredContent`.\n if (payload.structuredContent && typeof payload.structuredContent === 'object') {\n return payload.structuredContent;\n }\n // MIGRATION SHIM: pre-A0 stored sessions replayed through the\n // current iframe lack `params.structuredContent` because the outer\n // block had no hoist at capture time. Read inner envelope text \u2192\n // JSON.parse \u2192 result.structuredContent. NOT regex-based.\n //\n // Lifetime: PERMANENT defensive read-side helper. Pre-A0 sessions\n // are persisted on disk and may be replayed indefinitely; there is\n // no time-based sunset. Removing this fallback would silently break\n // pre-A0 conversation replay.\n var text = typeof payload.text === 'string' ? payload.text :\n (Array.isArray(payload.content)\n ? (payload.content.find(function (c) { return c && c.type === 'text' && typeof c.text === 'string'; }) || {}).text\n : null);\n if (typeof text !== 'string') return null;\n try {\n var parsed = JSON.parse(text);\n if (parsed && typeof parsed === 'object' && parsed.result && typeof parsed.result === 'object') {\n var inner = parsed.result;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n }\n } catch (_) {\n // Likely-envelope heuristic: text starts with `{` and contains\n // `\"package_id\"` in the first 64 chars. If JSON.parse failed on a\n // likely-envelope, surface a warning so the developer chasing\n // \"compose form is empty on replay\" sees a signal. For non-envelope\n // text (the dominant case), no log fires.\n var prefix = text.length > 64 ? text.slice(0, 64) : text;\n var likelyEnvelope = prefix.charAt(0) === '{' && prefix.indexOf('\"package_id\"') !== -1;\n if (likelyEnvelope && typeof console !== 'undefined' && typeof console.warn === 'function') {\n console.warn('[compose-email] Migration shim: JSON.parse failed on likely super-mcp envelope; pre-fill skipped');\n }\n }\n return null;\n }\n\n function findTextBlock(blocks) {\n if (!Array.isArray(blocks)) return null;\n var block = blocks.find(function (c) {\n return c && c.type === 'text' && typeof c.text === 'string';\n });\n return block ? block.text : null;\n }\n\n // Extract the send result identifiers ({ messageId, threadId, labelIds })\n // from the tool-call reply. The connector attaches structuredContent, which\n // super-mcp hoists onto the outer block, so the fast path is a single read.\n // The envelope-unwrapping fallback keeps this robust for hosts (or replayed\n // sessions) that forward only the serialized super-mcp text envelope.\n function getSendMetaFromResult(result) {\n if (!result || typeof result !== 'object') return null;\n if (result.structuredContent && typeof result.structuredContent === 'object') {\n return result.structuredContent;\n }\n try {\n var outerText = findTextBlock(result.content);\n if (typeof outerText !== 'string' && typeof result.text === 'string') {\n outerText = result.text;\n }\n if (typeof outerText !== 'string') return null;\n var envelope = JSON.parse(outerText);\n if (!envelope || typeof envelope !== 'object') return null;\n // outerText was the connector payload directly (no super-mcp envelope).\n if (envelope.messageId || envelope.threadId) return envelope;\n var inner = envelope.result;\n if (!inner || typeof inner !== 'object') return null;\n if (inner.structuredContent && typeof inner.structuredContent === 'object') {\n return inner.structuredContent;\n }\n var innerText = findTextBlock(inner.content);\n if (typeof innerText !== 'string') return null;\n var payload = JSON.parse(innerText);\n return (payload && typeof payload === 'object') ? payload : null;\n } catch (_) {\n return null;\n }\n }\n\n // ---- Blocked-send Gmail escape hatch ----\n // Shown ONLY when the user's own send preference blocks the tool\n // (super-mcp TOOL_BLOCKED / -33008 + \"disabled by user preference\"). We\n // never call the disabled tool; instead we open a prefilled Gmail compose\n // window so the user finishes the send in Gmail (no copy-paste). This is\n // deliberately narrow: admin-disabled (\"disabled by your organization\u2026\")\n // and generic security-policy blocks fall through to the normal retryable\n // error, because offering a Gmail bypass there would route around a control\n // the user did not set.\n //\n // Gmail compose URLs that get too long can silently fail to open, so we cap\n // the length and degrade visibly (recipients + subject only, paste the body)\n // rather than truncating without telling the user.\n var GMAIL_COMPOSE_MAX_URL = 8000;\n var BLOCKED_SEND_MESSAGE =\n '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.';\n\n function isUserDisabledSendError(message) {\n var m = String(message || '').toLowerCase();\n // Anchor the code so it can't match inside a longer number (-330080),\n // and require the user-preference phrase so admin-disabled / generic\n // security blocks fall through to the ordinary retryable error.\n return /-33008\\b/.test(m) && m.indexOf('disabled by user preference') !== -1;\n }\n\n // Base URL + path are constant (code-reviewed here, never config-provided);\n // only the field VALUES vary and go through URLSearchParams, so query\n // delimiters, newlines, and reserved characters become encoded data \u2014 no\n // query injection or header splitting. The host ui/open-external-link\n // bridge re-validates the mail.google.com host before opening.\n function buildGmailComposeUrl(payload, includeBody) {\n var url = new URL('https://mail.google.com/mail/');\n var params = new URLSearchParams();\n params.set('view', 'cm');\n params.set('fs', '1');\n var to = normalizeAddressList(payload.to).join(',');\n if (to) params.set('to', to);\n var cc = normalizeAddressList(payload.cc).join(',');\n if (cc) params.set('cc', cc);\n var bcc = normalizeAddressList(payload.bcc).join(',');\n if (bcc) params.set('bcc', bcc);\n var subject = trimString(payload.subject);\n if (subject) params.set('su', subject);\n if (includeBody) {\n var body = String(payload.body || '');\n if (body) params.set('body', body);\n }\n url.search = params.toString();\n return url.toString();\n }\n\n function showBlockedSend() {\n sendBlocked = true;\n clearError();\n clearSuccess();\n clearUnknown();\n sendButton.disabled = true;\n sendButton.title =\n 'Sending from here is turned off in your settings. Turn it back on in Settings, or open this draft in Gmail to send.';\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n blockedBox.classList.remove('hidden');\n postResize();\n }\n\n openComposeButton.addEventListener('click', function () {\n // Reset any prior \"too long\" note, then rebuild from the live form so\n // edits made after the block are reflected.\n blockedText.textContent = BLOCKED_SEND_MESSAGE;\n var payload = readFormPayload();\n var composeUrl = buildGmailComposeUrl(payload, true);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n composeUrl = buildGmailComposeUrl(payload, false);\n if (composeUrl.length > GMAIL_COMPOSE_MAX_URL) {\n // Even without the body the link is too long (many recipients, or a\n // very long subject). Gmail would silently refuse to open it, so\n // don't pretend \u2014 tell the user and post nothing.\n blockedText.textContent =\n 'This draft is too large to open in Gmail. Shorten the recipients or subject, or turn sending back on in Settings.';\n postResize();\n return;\n }\n blockedText.textContent =\n 'This email is long, so Gmail will open with just the recipients and subject. Copy the message text above into Gmail before sending.';\n postResize();\n }\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: composeUrl } },\n '*'\n );\n });\n\n function looksLikeEmail(value) {\n var at = value.indexOf('@');\n return at > 0 && at === value.lastIndexOf('@') && value.indexOf(' ') === -1;\n }\n\n // Build a Gmail deep link to the just-sent message. The /u/<account> segment\n // targets the right inbox when the user is signed into several Google\n // accounts; #all/<id> opens the thread (falling back to the message id).\n function buildGmailUrl(meta, email) {\n if (!meta || typeof meta !== 'object') return null;\n var id = trimString(meta.threadId) || trimString(meta.messageId);\n if (!id || !/^[A-Za-z0-9_-]+$/.test(id)) return null;\n var account = trimString(email);\n var userPart = looksLikeEmail(account) ? encodeURIComponent(account) : '0';\n return 'https://mail.google.com/mail/u/' + userPart + '/#all/' + encodeURIComponent(id);\n }\n\n function formatSentTime() {\n try {\n return new Date().toLocaleString(undefined, {\n month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit'\n });\n } catch (_) {\n return '';\n }\n }\n\n function renderSentView(payload, meta, stamp) {\n payload = payload && typeof payload === 'object' ? payload : {};\n sentTimestamp.textContent = stamp ? 'Sent ' + stamp : 'Sent';\n sentFrom.textContent = trimString(payload.email) || 'Account not shown';\n sentTo.textContent = normalizeAddressList(payload.to).join(', ');\n var ccList = normalizeAddressList(payload.cc);\n sentCc.textContent = ccList.join(', ');\n sentCcField.classList.toggle('hidden', ccList.length === 0);\n var bccList = normalizeAddressList(payload.bcc);\n sentBcc.textContent = bccList.join(', ');\n sentBccField.classList.toggle('hidden', bccList.length === 0);\n sentSubject.textContent = String(payload.subject || '');\n sentBody.textContent = String(payload.body || '');\n gmailUrl = buildGmailUrl(meta, payload.email);\n openGmailButton.classList.toggle('hidden', !gmailUrl);\n }\n\n function handleSendRequest() {\n if (sending) return;\n // Once the user's own send preference has blocked this tool, never\n // re-invoke it \u2014 the escape hatch is the only path out. The Send button\n // is already disabled, but this also fends off a future host that grants\n // allow-forms (a submit could otherwise re-fire the disabled tool).\n if (sendBlocked) return;\n\n var payload = readFormPayload();\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n\n sendPayload(payload);\n }\n\n // The Send button is type=\"button\" with an explicit click handler rather\n // than a form submit button. The Rebel host renders this iframe with a\n // sandbox of \"allow-scripts\" only \u2014 no \"allow-forms\" \u2014 so native form\n // submission is blocked by the browser BEFORE the submit event fires\n // (\"Blocked form submission ... the form's frame is sandboxed and the\n // allow-forms permission is not set\"). A submit-driven Send therefore\n // silently did nothing: no postMessage, no spinner, no telemetry.\n // A click handler needs no sandbox permission and is the same path\n // Cancel/Retry already use. The submit listener below stays only as a\n // defensive fallback for hosts that DO grant allow-forms; in this sandbox\n // it never fires (neither the button click nor Enter routes through it).\n // The sending guard keeps any double-fire (in an allow-forms host) a no-op.\n sendButton.addEventListener('click', function () {\n handleSendRequest();\n });\n\n draftButton.addEventListener('click', function () {\n if (sending) return;\n var payload = readFormPayload();\n var validationError = validateDraftPayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n saveDraftPayload(payload);\n });\n\n composeForm.addEventListener('submit', function (event) {\n event.preventDefault();\n handleSendRequest();\n });\n\n retryButton.addEventListener('click', function () {\n if (sending) return;\n var payload = readFormPayload();\n if (retryAction === 'draft') {\n var draftValidationError = validateDraftPayload(payload);\n if (draftValidationError) {\n showError(draftValidationError);\n return;\n }\n retryAction = null;\n saveDraftPayload(payload);\n return;\n }\n var validationError = validatePayload(payload);\n if (validationError) {\n showError(validationError);\n return;\n }\n sendPayload(payload);\n });\n\n cancelButton.addEventListener('click', function () {\n if (sending) return;\n // After a lost-reply timeout we don't know if the email sent, so don't\n // claim \"Nothing sent.\" on collapse \u2014 point the user to verify instead.\n var collapseMessage = outcomeUnknown\n ? 'Collapsed. Check your Sent folder if you are not sure.'\n : 'Draft collapsed. Nothing sent.';\n clearError();\n clearSuccess();\n clearUnknown();\n setCollapsed(true, collapseMessage);\n });\n\n reopenButton.addEventListener('click', function () {\n setCollapsed(false);\n });\n\n sentCollapseButton.addEventListener('click', function () {\n setCollapsed(true, collapsedMessage.textContent || 'Email sent.');\n });\n\n // The iframe sandbox is \"allow-scripts\" only (no allow-popups / allow-forms),\n // so it cannot open a URL itself. Ask the host to open the Gmail link in the\n // user's browser via the ui/open-external-link bridge, which re-validates the\n // URL against its own allowlist before handing it to the OS.\n openGmailButton.addEventListener('click', function () {\n if (!gmailUrl) return;\n window.parent.postMessage(\n { jsonrpc: '2.0', method: 'ui/open-external-link', params: { url: gmailUrl } },\n '*'\n );\n });\n\n toggleCcButton.addEventListener('click', function () {\n setCcVisible(ccRow.classList.contains('hidden'));\n postResize();\n });\n\n toggleBccButton.addEventListener('click', function () {\n setBccVisible(bccRow.classList.contains('hidden'));\n postResize();\n });\n\n [toInput, ccInput, bccInput, subjectInput, bodyInput].forEach(function (element) {\n element.addEventListener('input', function () {\n clearError();\n clearSuccess();\n clearUnknown();\n postResize();\n });\n });\n\n window.addEventListener('message', function (event) {\n // Honest scope (origin-independent): the iframe sandbox origin is 'null',\n // so validating event.origin is unreliable across dev/prod/custom-scheme\n // hosts. Instead reject any *identified* sender that isn't our host frame\n // (window.parent). A real cross-frame postMessage always stamps\n // event.source with the sending window, so a hostile sibling frame is\n // rejected here; a null source only occurs for same-context synthetic\n // dispatch (our own code) and cannot be forged from outside, so we\n // tolerate it. This does not authenticate the host's identity \u2014 the host\n // separately authenticates this iframe by origin+source.\n if (event.source && event.source !== window.parent) {\n return;\n }\n\n var data = event.data;\n if (!data || typeof data !== 'object') {\n return;\n }\n\n if (data.method === 'ui/notifications/tool-result') {\n // Always parse (so the migration-shim's malformed-envelope warning\n // still fires), but apply only the first successful prefill: a stray\n // or hostile re-post can't silently rewrite a draft the user has\n // already reviewed.\n var draft = getDraftFromToolResult(data.params);\n if (draft && !draftApplied) {\n draftApplied = true;\n applyDraftData(draft);\n }\n return;\n }\n\n if (data.jsonrpc !== '2.0' || !pendingRequestId || data.id !== pendingRequestId) {\n return;\n }\n\n pendingRequestId = null;\n clearSendTimeout();\n clearUnknown();\n var completedAction = pendingAction;\n pendingAction = null;\n if (completedAction === 'draft') {\n setSavingDraft(false);\n } else {\n setSending(false);\n }\n\n if (data.error) {\n var errorMessage = data.error && typeof data.error.message === 'string'\n ? data.error.message\n : (completedAction === 'draft' ? 'Failed to save draft.' : 'Failed to send email.');\n if (completedAction === 'draft') {\n // Retry re-invokes the draft tool, not the send tool \u2014 pendingAction\n // is already cleared, so this is what the Retry handler routes on.\n retryAction = 'draft';\n }\n // Prefer the host-vetted structured reason (a closed enum the host\n // derives from the tool-block error data) and fall back to\n // text-matching the flattened message for hosts that don't forward it\n // yet. Only 'user-disabled' opens the Gmail escape hatch \u2014\n // admin-disabled and security-policy blocks stay ordinary errors (see\n // the detector comment above for why).\n // Send-failure only: a blocked DRAFT tool must never surface the\n // \"sending is turned off\" copy or the Open-in-Gmail bypass.\n var blockedReason = data.error.data && data.error.data.reason;\n if (completedAction !== 'draft' && (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage))) {\n showBlockedSend();\n return;\n }\n showError(errorMessage);\n return;\n }\n\n clearError();\n clearSuccess();\n if (completedAction === 'draft') {\n // Terminal: the draft now lives in the mailbox's Drafts folder.\n // Collapse to a stamped confirmation and retire the form \u2014 Reopen\n // would resurrect an editable copy whose next Save/Send silently\n // diverges from (or duplicates) the saved draft.\n var draftStamp = formatSentTime();\n setCollapsed(true, draftStamp ? 'Draft saved \u00B7 ' + draftStamp : 'Draft saved.');\n reopenButton.classList.add('hidden');\n return;\n }\n // Preserve what was sent (and how to reach it) instead of discarding the\n // draft. pendingPayload is the exact payload we posted; the reply carries\n // the Gmail message/thread ids. We default to the collapsed summary, but\n // Reopen now restores a read-only view of the sent message.\n var sentPayload = pendingPayload || readFormPayload();\n var stamp = formatSentTime();\n renderSentView(sentPayload, getSendMetaFromResult(data.result), stamp);\n sent = true;\n setCollapsed(true, stamp ? 'Email sent \u00B7 ' + stamp : 'Email sent.');\n });\n\n if (typeof ResizeObserver === 'function' && document.body) {\n var observer = new ResizeObserver(postResize);\n observer.observe(document.body);\n }\n\n applyThemeFromHostContext();\n setCcVisible(false);\n setBccVisible(false);\n setCollapsed(false);\n postResize();\n postReady();\n\n window.parent.postMessage(\n {\n jsonrpc: '2.0',\n method: 'ui/initialize',\n params: { resourceUri: RESOURCE_URI },\n id: 'compose-email-init'\n },\n '*'\n );\n })();\n </script>\n</body>\n</html>\n";
2
2
  //# sourceMappingURL=compose-email-template.d.ts.map
@@ -194,6 +194,7 @@ export const COMPOSE_EMAIL_HTML = `
194
194
  justify-content: flex-end;
195
195
  gap: 10px;
196
196
  margin-top: 2px;
197
+ flex-wrap: wrap;
197
198
  }
198
199
 
199
200
  .button {
@@ -415,6 +416,10 @@ export const COMPOSE_EMAIL_HTML = `
415
416
 
416
417
  <div class="actions">
417
418
  <button id="cancelButton" type="button" class="button button-secondary">Cancel</button>
419
+ <button id="draftButton" type="button" class="button button-secondary">
420
+ <span id="draftSpinner" class="spinner hidden" aria-hidden="true"></span>
421
+ <span id="draftLabel">Save draft</span>
422
+ </button>
418
423
  <button id="sendButton" type="button" class="button button-primary">
419
424
  <span id="sendSpinner" class="spinner hidden" aria-hidden="true"></span>
420
425
  <span id="sendLabel">Send email</span>
@@ -482,6 +487,12 @@ export const COMPOSE_EMAIL_HTML = `
482
487
  var collapsed = false;
483
488
  var outcomeUnknown = false;
484
489
  var sent = false;
490
+ // Which action the in-flight request belongs to ('send' | 'draft').
491
+ // Captured before clearing on reply/timeout so the response handler can
492
+ // route error/success correctly. retryAction survives the reply so a
493
+ // later Retry click still knows which tool to re-invoke.
494
+ var pendingAction = null;
495
+ var retryAction = null;
485
496
  var sendBlocked = false;
486
497
  var gmailUrl = null;
487
498
  var sendTimeoutId = null;
@@ -523,6 +534,9 @@ export const COMPOSE_EMAIL_HTML = `
523
534
  var sendButton = document.getElementById('sendButton');
524
535
  var sendLabel = document.getElementById('sendLabel');
525
536
  var sendSpinner = document.getElementById('sendSpinner');
537
+ var draftButton = document.getElementById('draftButton');
538
+ var draftLabel = document.getElementById('draftLabel');
539
+ var draftSpinner = document.getElementById('draftSpinner');
526
540
  var cancelButton = document.getElementById('cancelButton');
527
541
  var retryButton = document.getElementById('retryButton');
528
542
 
@@ -648,6 +662,7 @@ export const COMPOSE_EMAIL_HTML = `
648
662
  function setSending(nextSending) {
649
663
  sending = nextSending;
650
664
  sendButton.disabled = nextSending || sendBlocked;
665
+ draftButton.disabled = nextSending;
651
666
  cancelButton.disabled = nextSending;
652
667
  toInput.disabled = nextSending;
653
668
  ccInput.disabled = nextSending;
@@ -660,6 +675,30 @@ export const COMPOSE_EMAIL_HTML = `
660
675
  postResize();
661
676
  }
662
677
 
678
+ // Mirror of setSending for the Save-draft action. One request is in
679
+ // flight at a time (both paths share pendingRequestId and set the same
680
+ // \`sending\` flag), so the two busy states can never overlap; every
681
+ // control locks either way and only the active button shows a spinner
682
+ // and aria-busy.
683
+ function setSavingDraft(nextSaving) {
684
+ sending = nextSaving;
685
+ sendButton.disabled = nextSaving || sendBlocked;
686
+ draftButton.disabled = nextSaving;
687
+ cancelButton.disabled = nextSaving;
688
+ toInput.disabled = nextSaving;
689
+ ccInput.disabled = nextSaving;
690
+ bccInput.disabled = nextSaving;
691
+ subjectInput.disabled = nextSaving;
692
+ bodyInput.disabled = nextSaving;
693
+ sendSpinner.classList.add('hidden');
694
+ sendLabel.textContent = 'Send email';
695
+ sendButton.setAttribute('aria-busy', 'false');
696
+ draftSpinner.classList.toggle('hidden', !nextSaving);
697
+ draftLabel.textContent = nextSaving ? 'Saving…' : 'Save draft';
698
+ draftButton.setAttribute('aria-busy', nextSaving ? 'true' : 'false');
699
+ postResize();
700
+ }
701
+
663
702
  function clearError() {
664
703
  errorText.textContent = '';
665
704
  errorBox.classList.add('hidden');
@@ -717,10 +756,31 @@ export const COMPOSE_EMAIL_HTML = `
717
756
  return;
718
757
  }
719
758
  pendingRequestId = null;
759
+ if (pendingAction === 'draft') {
760
+ pendingAction = null;
761
+ setSavingDraft(false);
762
+ showDraftSaveUnknown();
763
+ return;
764
+ }
765
+ pendingAction = null;
720
766
  setSending(false);
721
767
  showSendUnknown();
722
768
  }
723
769
 
770
+ // Same lost-reply honesty as a send, lower stakes: a blind retry here
771
+ // could create a duplicate draft, so we say we're not sure and point at
772
+ // the Drafts folder instead of offering Retry.
773
+ function showDraftSaveUnknown() {
774
+ outcomeUnknown = true;
775
+ clearError();
776
+ clearSuccess();
777
+ unknownTitle.textContent = 'Not sure if the draft was saved.';
778
+ unknownText.textContent =
779
+ "Rebel didn't hear back in time. Check your Drafts folder before trying again, so you don't create a duplicate.";
780
+ unknownBox.classList.remove('hidden');
781
+ postResize();
782
+ }
783
+
724
784
  function setCcVisible(visible) {
725
785
  ccRow.classList.toggle('hidden', !visible);
726
786
  toggleCcButton.textContent = visible ? 'Hide CC' : 'Add CC';
@@ -760,9 +820,27 @@ export const COMPOSE_EMAIL_HTML = `
760
820
  return null;
761
821
  }
762
822
 
823
+ // Same provider-compatible minimum as sending (the draft tools require
824
+ // To, Subject, and Body too) with save-specific copy. Draft is
825
+ // email-mode only, so this body is the email shape unconditionally.
826
+ function validateDraftPayload(payload) {
827
+ if (!payload.to || payload.to.length === 0) {
828
+ return 'Add at least one recipient in To.';
829
+ }
830
+ if (!trimString(payload.subject)) {
831
+ return 'Add a subject before saving.';
832
+ }
833
+ if (!trimString(payload.body)) {
834
+ return 'Add an email body before saving.';
835
+ }
836
+ return null;
837
+ }
838
+
763
839
  function sendPayload(payload) {
764
840
  pendingPayload = payload;
765
841
  pendingRequestId = 'send-' + Date.now() + '-' + Math.random().toString(16).slice(2);
842
+ pendingAction = 'send';
843
+ retryAction = null;
766
844
  setSending(true);
767
845
  clearError();
768
846
  clearSuccess();
@@ -784,6 +862,32 @@ export const COMPOSE_EMAIL_HTML = `
784
862
  );
785
863
  }
786
864
 
865
+ function saveDraftPayload(payload) {
866
+ pendingPayload = payload;
867
+ pendingRequestId = 'draft-' + Date.now() + '-' + Math.random().toString(16).slice(2);
868
+ pendingAction = 'draft';
869
+ retryAction = null;
870
+ setSavingDraft(true);
871
+ clearError();
872
+ clearSuccess();
873
+ clearUnknown();
874
+ clearSendTimeout();
875
+ sendTimeoutId = setTimeout(handleSendTimeout, SEND_TIMEOUT_MS);
876
+
877
+ window.parent.postMessage(
878
+ {
879
+ jsonrpc: '2.0',
880
+ method: 'tools/call',
881
+ params: {
882
+ name: 'create_workspace_draft',
883
+ arguments: payload
884
+ },
885
+ id: pendingRequestId
886
+ },
887
+ '*'
888
+ );
889
+ }
890
+
787
891
  function applyDraftData(rawDraft) {
788
892
  var draft = rawDraft && typeof rawDraft === 'object' ? rawDraft : {};
789
893
  toInput.value = listToInputValue(draft.to);
@@ -1057,6 +1161,17 @@ export const COMPOSE_EMAIL_HTML = `
1057
1161
  handleSendRequest();
1058
1162
  });
1059
1163
 
1164
+ draftButton.addEventListener('click', function () {
1165
+ if (sending) return;
1166
+ var payload = readFormPayload();
1167
+ var validationError = validateDraftPayload(payload);
1168
+ if (validationError) {
1169
+ showError(validationError);
1170
+ return;
1171
+ }
1172
+ saveDraftPayload(payload);
1173
+ });
1174
+
1060
1175
  composeForm.addEventListener('submit', function (event) {
1061
1176
  event.preventDefault();
1062
1177
  handleSendRequest();
@@ -1065,6 +1180,16 @@ export const COMPOSE_EMAIL_HTML = `
1065
1180
  retryButton.addEventListener('click', function () {
1066
1181
  if (sending) return;
1067
1182
  var payload = readFormPayload();
1183
+ if (retryAction === 'draft') {
1184
+ var draftValidationError = validateDraftPayload(payload);
1185
+ if (draftValidationError) {
1186
+ showError(draftValidationError);
1187
+ return;
1188
+ }
1189
+ retryAction = null;
1190
+ saveDraftPayload(payload);
1191
+ return;
1192
+ }
1068
1193
  var validationError = validatePayload(payload);
1069
1194
  if (validationError) {
1070
1195
  showError(validationError);
@@ -1164,20 +1289,33 @@ export const COMPOSE_EMAIL_HTML = `
1164
1289
  pendingRequestId = null;
1165
1290
  clearSendTimeout();
1166
1291
  clearUnknown();
1167
- setSending(false);
1292
+ var completedAction = pendingAction;
1293
+ pendingAction = null;
1294
+ if (completedAction === 'draft') {
1295
+ setSavingDraft(false);
1296
+ } else {
1297
+ setSending(false);
1298
+ }
1168
1299
 
1169
1300
  if (data.error) {
1170
1301
  var errorMessage = data.error && typeof data.error.message === 'string'
1171
1302
  ? data.error.message
1172
- : 'Failed to send email.';
1303
+ : (completedAction === 'draft' ? 'Failed to save draft.' : 'Failed to send email.');
1304
+ if (completedAction === 'draft') {
1305
+ // Retry re-invokes the draft tool, not the send tool — pendingAction
1306
+ // is already cleared, so this is what the Retry handler routes on.
1307
+ retryAction = 'draft';
1308
+ }
1173
1309
  // Prefer the host-vetted structured reason (a closed enum the host
1174
1310
  // derives from the tool-block error data) and fall back to
1175
1311
  // text-matching the flattened message for hosts that don't forward it
1176
1312
  // yet. Only 'user-disabled' opens the Gmail escape hatch —
1177
1313
  // admin-disabled and security-policy blocks stay ordinary errors (see
1178
1314
  // the detector comment above for why).
1315
+ // Send-failure only: a blocked DRAFT tool must never surface the
1316
+ // "sending is turned off" copy or the Open-in-Gmail bypass.
1179
1317
  var blockedReason = data.error.data && data.error.data.reason;
1180
- if (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage)) {
1318
+ if (completedAction !== 'draft' && (blockedReason === 'user-disabled' || isUserDisabledSendError(errorMessage))) {
1181
1319
  showBlockedSend();
1182
1320
  return;
1183
1321
  }
@@ -1187,6 +1325,16 @@ export const COMPOSE_EMAIL_HTML = `
1187
1325
 
1188
1326
  clearError();
1189
1327
  clearSuccess();
1328
+ if (completedAction === 'draft') {
1329
+ // Terminal: the draft now lives in the mailbox's Drafts folder.
1330
+ // Collapse to a stamped confirmation and retire the form — Reopen
1331
+ // would resurrect an editable copy whose next Save/Send silently
1332
+ // diverges from (or duplicates) the saved draft.
1333
+ var draftStamp = formatSentTime();
1334
+ setCollapsed(true, draftStamp ? 'Draft saved · ' + draftStamp : 'Draft saved.');
1335
+ reopenButton.classList.add('hidden');
1336
+ return;
1337
+ }
1190
1338
  // Preserve what was sent (and how to reach it) instead of discarding the
1191
1339
  // draft. pendingPayload is the exact payload we posted; the reply carries
1192
1340
  // the Gmail message/thread ids. We default to the collapsed summary, but
@@ -123,7 +123,7 @@ export const gmailTools = [
123
123
 
124
124
  Gmail query syntax: from:, to:, subject:, has:attachment, is:unread, after:YYYY-MM-DD, before:YYYY-MM-DD, label:
125
125
 
126
- Use get_workspace_email_thread with a thread_id from results to get full conversation.`,
126
+ Each result shows its id (message id) and thread_id. Use get_workspace_email_thread with that thread_id (or the message id) to get the full conversation.`,
127
127
  aliases: ['search_emails', 'find_emails', 'query_emails'],
128
128
  annotations: { readOnlyHint: true },
129
129
  inputSchema: {
@@ -143,6 +143,14 @@ Use get_workspace_email_thread with a thread_id from results to get full convers
143
143
  type: 'number',
144
144
  description: 'Maximum emails to return (default: 10, max: 100)'
145
145
  },
146
+ limit: {
147
+ type: 'number',
148
+ description: 'Alias of max_results.'
149
+ },
150
+ max_messages: {
151
+ type: 'number',
152
+ description: 'Alias of max_results.'
153
+ },
146
154
  // COMMON FILTERS: Flat for ease of use
147
155
  from: {
148
156
  oneOf: [
@@ -333,7 +341,23 @@ Use get_workspace_email_thread with a thread_id from results to get full convers
333
341
  },
334
342
  thread_id: {
335
343
  type: 'string',
336
- description: 'Thread ID (from search results or message)'
344
+ description: 'Thread ID (the thread_id shown in search results). Give this OR message_id.'
345
+ },
346
+ threadId: {
347
+ type: 'string',
348
+ description: 'Alias of thread_id.'
349
+ },
350
+ message_id: {
351
+ type: 'string',
352
+ description: 'ID of any message in the thread (the id shown in search results). The thread is looked up from it. Ignored when thread_id is given.'
353
+ },
354
+ messageId: {
355
+ type: 'string',
356
+ description: 'Alias of message_id.'
357
+ },
358
+ id: {
359
+ type: 'string',
360
+ description: 'Alias of message_id.'
337
361
  },
338
362
  max_messages: {
339
363
  type: 'number',
@@ -356,7 +380,10 @@ Use get_workspace_email_thread with a thread_id from results to get full convers
356
380
  description: 'Return structured JSON instead of formatted text (default: false)'
357
381
  }
358
382
  },
359
- required: ['thread_id']
383
+ // One of thread_id / message_id is required; the handler enforces it so
384
+ // the aliases stay valid alone (no oneOf, which would disable strict
385
+ // unknown-field rejection in the SuperMCP gate).
386
+ required: []
360
387
  }
361
388
  },
362
389
  {
@@ -149,6 +149,9 @@ interface GetThreadParams {
149
149
  email?: string;
150
150
  thread_id?: string;
151
151
  threadId?: string;
152
+ message_id?: string;
153
+ messageId?: string;
154
+ id?: string;
152
155
  max_messages?: number;
153
156
  maxMessages?: number;
154
157
  offset?: number;
@@ -7,6 +7,7 @@ import { ATTACHMENT_FOLDERS } from '../modules/attachments/types.js';
7
7
  import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, realpathSync, statSync } from 'fs';
8
8
  import path from 'path';
9
9
  import { wrapUntrustedContent, wrapUntrustedJsonStrings } from '../utils/untrusted-content.js';
10
+ import logger from '../utils/logger.js';
10
11
  // Singleton instances
11
12
  let gmailService;
12
13
  let accountManager;
@@ -26,12 +27,34 @@ async function initializeServices() {
26
27
  attachmentService = AttachmentService.getInstance();
27
28
  }
28
29
  }
30
+ const NO_REPLY_THREADING = { headers: {} };
31
+ const REPLY_THREADING_WARNING_CODE = 'reply_threading_degraded';
32
+ function unthreadedReplyReason(replyToMessageId) {
33
+ return (`Could not fetch the original message ${replyToMessageId}, so the reply is NOT ` +
34
+ 'threaded onto it — it will go out as a new, separate conversation.');
35
+ }
36
+ /**
37
+ * Attach the degraded-threading warning to a tool result (additive `warnings`
38
+ * array) so the agent — and through it the user — can see that a reply went
39
+ * out unthreaded. Connector-authored text only: no external content is
40
+ * embedded, so no untrusted-content envelope is needed.
41
+ */
42
+ function withReplyThreadingWarning(result, degradedReason) {
43
+ if (degradedReason === undefined)
44
+ return result;
45
+ if (result === null || typeof result !== 'object')
46
+ return result;
47
+ return {
48
+ ...result,
49
+ warnings: [{ code: REPLY_THREADING_WARNING_CODE, message: degradedReason }],
50
+ };
51
+ }
29
52
  async function resolveReplyThreading(email, replyToMessageId) {
30
53
  try {
31
54
  const originalMessage = await gmailService.getMessage(email, replyToMessageId);
32
55
  if (!originalMessage) {
33
- console.warn(`[gmail-handlers] Could not fetch message ${replyToMessageId} for threading — draft will be unthreaded`);
34
- return {};
56
+ logger.warn(`[gmail-handlers] Reply threading degraded: original message ${replyToMessageId} not found for account ${email}; sending unthreaded`);
57
+ return { headers: {}, degradedReason: unthreadedReplyReason(replyToMessageId) };
35
58
  }
36
59
  const result = { threadId: originalMessage.threadId };
37
60
  const messageIdHeader = originalMessage.headers?.find((h) => h.name.toLowerCase() === 'message-id');
@@ -51,11 +74,11 @@ async function resolveReplyThreading(email, replyToMessageId) {
51
74
  else if (existingRefs.length > 0) {
52
75
  result.references = existingRefs;
53
76
  }
54
- return result;
77
+ return { headers: result };
55
78
  }
56
79
  catch (error) {
57
- console.warn(`[gmail-handlers] Failed to resolve threading for ${replyToMessageId}:`, error instanceof Error ? error.message : error);
58
- return {};
80
+ logger.warn(`[gmail-handlers] Reply threading degraded: failed to fetch original message ${replyToMessageId} for account ${email}:`, error instanceof Error ? error.message : error);
81
+ return { headers: {}, degradedReason: unthreadedReplyReason(replyToMessageId) };
59
82
  }
60
83
  }
61
84
  const MIME_TYPES = {
@@ -220,11 +243,11 @@ export function formatEmailsAsText(result) {
220
243
  const attachmentList = email.attachments.map(a => a.name).join(', ');
221
244
  lines.push(` Attachments: ${attachmentList}`);
222
245
  }
223
- lines.push(` [id: ${email.id}, thread: ${email.threadId}${labels ? `, labels: ${labels}` : ''}]`);
246
+ lines.push(` [id: ${email.id}, thread_id: ${email.threadId}${labels ? `, labels: ${labels}` : ''}]`);
224
247
  lines.push('');
225
248
  });
226
249
  if (result.nextPageToken) {
227
- lines.push(`More results available. Use pageToken: "${result.nextPageToken}" to continue.`);
250
+ lines.push(`More results available. Use page_token: "${result.nextPageToken}" to continue.`);
228
251
  }
229
252
  return wrapUntrustedContent(lines.join('\n'), 'google-workspace:gmail:search');
230
253
  }
@@ -356,6 +379,9 @@ export async function handleSearchWorkspaceEmails(params) {
356
379
  if ('limit' in unknownParams && mergedOptions.maxResults === undefined) {
357
380
  mergedOptions.maxResults = unknownParams.limit;
358
381
  }
382
+ if (typeof unknownParams.max_messages === 'number' && mergedOptions.maxResults === undefined) {
383
+ mergedOptions.maxResults = unknownParams.max_messages;
384
+ }
359
385
  const search = mergedSearch;
360
386
  const options = mergedOptions;
361
387
  // Normalize search.from - if it's a partial name (no @), convert to content query
@@ -449,7 +475,7 @@ export function formatThreadAsText(result, offset = 0, includeFullBodies = false
449
475
  export async function handleGetWorkspaceEmailThread(params) {
450
476
  await initializeServices();
451
477
  const rawParams = params;
452
- const threadId = readAliasedString(rawParams, 'thread_id', 'threadId');
478
+ const requestedThreadId = readAliasedString(rawParams, 'thread_id', 'threadId');
453
479
  const maxMessages = readAliasedNumber(rawParams, 'max_messages', 'maxMessages') ?? 50;
454
480
  const offset = typeof params.offset === 'number' ? params.offset : 0;
455
481
  const includeBody = readAliasedBoolean(rawParams, 'include_body', 'includeBody') ?? true;
@@ -457,12 +483,23 @@ export async function handleGetWorkspaceEmailThread(params) {
457
483
  const returnJson = readAliasedBoolean(rawParams, 'return_json', 'returnJson') ?? false;
458
484
  // Resolve email - uses instance account if not provided, validates if provided
459
485
  const email = await resolveEmail(params);
460
- if (!threadId) {
461
- throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "thread_id" (from search results or a message). ' +
486
+ const messageId = readAliasedString(rawParams, 'message_id', 'messageId') ?? readAliasedString(rawParams, 'message_id', 'id');
487
+ if (!requestedThreadId && !messageId) {
488
+ throw new McpError(ErrorCode.InvalidParams, 'Missing required parameter: "thread_id" (the thread_id shown in search results) or "message_id" (any message id in the thread). ' +
462
489
  'Example: { "email": "user@example.com", "thread_id": "thread123" }');
463
490
  }
464
491
  return accountManager.withTokenRenewal(email, async () => {
465
492
  try {
493
+ let threadId = requestedThreadId;
494
+ if (!threadId) {
495
+ // A message id was given instead: one extra lookup finds its thread.
496
+ const message = await gmailService.getMessage(email, messageId);
497
+ if (!message) {
498
+ throw new McpError(ErrorCode.InvalidRequest, `Message not found: "${messageId}" does not exist in the ${email} mailbox. ` +
499
+ 'Use search_workspace_emails to find the email and pass its thread_id or id.');
500
+ }
501
+ threadId = message.threadId;
502
+ }
466
503
  const result = await gmailService.getThread(email, threadId, { maxMessages, offset, includeBody });
467
504
  if (returnJson) {
468
505
  // JSON path: when full bodies aren't requested, strip body content from
@@ -537,9 +574,9 @@ export async function handleSendWorkspaceEmail(params) {
537
574
  bcc.forEach(validateEmail);
538
575
  return accountManager.withTokenRenewal(email, async () => {
539
576
  try {
540
- const threading = replyToMessageId
577
+ const threadingResolution = replyToMessageId
541
578
  ? await resolveReplyThreading(email, replyToMessageId)
542
- : {};
579
+ : NO_REPLY_THREADING;
543
580
  const emailParams = {
544
581
  email,
545
582
  to,
@@ -548,19 +585,22 @@ export async function handleSendWorkspaceEmail(params) {
548
585
  cc,
549
586
  bcc,
550
587
  isHtml,
551
- threadId: threading.threadId,
552
- inReplyTo: threading.inReplyTo,
553
- references: threading.references,
588
+ threadId: threadingResolution.headers.threadId,
589
+ inReplyTo: threadingResolution.headers.inReplyTo,
590
+ references: threadingResolution.headers.references,
554
591
  attachments: processOutgoingAttachments(attachments)
555
592
  };
556
593
  const sendResult = await gmailService.sendEmail(emailParams);
594
+ // Degraded reply threading is observable in the result (additive
595
+ // `warnings`), not just in the logs — the send still succeeds.
596
+ const payload = withReplyThreadingWarning(sendResult, threadingResolution.degradedReason);
557
597
  // Return an McpToolResponse-shaped result so the identifiers survive as
558
598
  // structuredContent (hoisted by super-mcp) — the compose-email UI reads
559
599
  // { messageId, threadId } from it to build an "Open in Gmail" deep link.
560
600
  // The text block preserves the same JSON the model saw before this change.
561
601
  return {
562
- content: [{ type: 'text', text: JSON.stringify(sendResult) }],
563
- structuredContent: sendResult,
602
+ content: [{ type: 'text', text: JSON.stringify(payload) }],
603
+ structuredContent: payload,
564
604
  };
565
605
  }
566
606
  catch (error) {
@@ -675,93 +715,99 @@ export async function handleManageWorkspaceDraft(params) {
675
715
  return accountManager.withTokenRenewal(email, async () => {
676
716
  try {
677
717
  // Resolve reply threading headers if replyToMessageId is provided
678
- const threading = data?.replyToMessageId
718
+ const threadingResolution = data?.replyToMessageId
679
719
  ? await resolveReplyThreading(email, data.replyToMessageId)
680
- : {};
681
- switch (action) {
682
- case 'create':
683
- if (!data) {
684
- throw new McpError(ErrorCode.InvalidParams, 'Draft data is required for create action');
685
- }
686
- assertRecipientsArray(data.to, 'to');
687
- assertRecipientsArray(data.cc, 'cc');
688
- assertRecipientsArray(data.bcc, 'bcc');
689
- if (data.to)
690
- data.to.forEach(validateEmail);
691
- if (data.cc)
692
- data.cc.forEach(validateEmail);
693
- if (data.bcc)
694
- data.bcc.forEach(validateEmail);
695
- {
696
- // Destructure replyToMessageId out so it doesn't leak to the service
697
- const { replyToMessageId: _, ...draftData } = data;
720
+ : NO_REPLY_THREADING;
721
+ const threading = threadingResolution.headers;
722
+ const managed = await (async () => {
723
+ switch (action) {
724
+ case 'create':
725
+ if (!data) {
726
+ throw new McpError(ErrorCode.InvalidParams, 'Draft data is required for create action');
727
+ }
728
+ assertRecipientsArray(data.to, 'to');
729
+ assertRecipientsArray(data.cc, 'cc');
730
+ assertRecipientsArray(data.bcc, 'bcc');
731
+ if (data.to)
732
+ data.to.forEach(validateEmail);
733
+ if (data.cc)
734
+ data.cc.forEach(validateEmail);
735
+ if (data.bcc)
736
+ data.bcc.forEach(validateEmail);
737
+ {
738
+ // Destructure replyToMessageId out so it doesn't leak to the service
739
+ const { replyToMessageId: _, ...draftData } = data;
740
+ return await gmailService.manageDraft({
741
+ email,
742
+ action: 'create',
743
+ data: {
744
+ ...draftData,
745
+ threadId: data.threadId ?? threading.threadId,
746
+ inReplyTo: data.inReplyTo ?? threading.inReplyTo,
747
+ references: data.references ?? threading.references,
748
+ attachments: processOutgoingAttachments(data.attachments)
749
+ }
750
+ });
751
+ }
752
+ case 'read':
698
753
  return await gmailService.manageDraft({
699
754
  email,
700
- action: 'create',
701
- data: {
702
- ...draftData,
703
- threadId: data.threadId ?? threading.threadId,
704
- inReplyTo: data.inReplyTo ?? threading.inReplyTo,
705
- references: data.references ?? threading.references,
706
- attachments: processOutgoingAttachments(data.attachments)
707
- }
755
+ action: 'read',
756
+ draftId
708
757
  });
709
- }
710
- case 'read':
711
- return await gmailService.manageDraft({
712
- email,
713
- action: 'read',
714
- draftId
715
- });
716
- case 'update':
717
- if (!draftId || !data) {
718
- throw new McpError(ErrorCode.InvalidParams, 'Draft ID and data are required for update action');
719
- }
720
- assertRecipientsArray(data.to, 'to');
721
- assertRecipientsArray(data.cc, 'cc');
722
- assertRecipientsArray(data.bcc, 'bcc');
723
- if (data.to)
724
- data.to.forEach(validateEmail);
725
- if (data.cc)
726
- data.cc.forEach(validateEmail);
727
- if (data.bcc)
728
- data.bcc.forEach(validateEmail);
729
- {
730
- const { replyToMessageId: _, ...draftData } = data;
758
+ case 'update':
759
+ if (!draftId || !data) {
760
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID and data are required for update action');
761
+ }
762
+ assertRecipientsArray(data.to, 'to');
763
+ assertRecipientsArray(data.cc, 'cc');
764
+ assertRecipientsArray(data.bcc, 'bcc');
765
+ if (data.to)
766
+ data.to.forEach(validateEmail);
767
+ if (data.cc)
768
+ data.cc.forEach(validateEmail);
769
+ if (data.bcc)
770
+ data.bcc.forEach(validateEmail);
771
+ {
772
+ const { replyToMessageId: _, ...draftData } = data;
773
+ return await gmailService.manageDraft({
774
+ email,
775
+ action: 'update',
776
+ draftId,
777
+ data: {
778
+ ...draftData,
779
+ threadId: data.threadId ?? threading.threadId,
780
+ inReplyTo: data.inReplyTo ?? threading.inReplyTo,
781
+ references: data.references ?? threading.references,
782
+ attachments: processOutgoingAttachments(data.attachments)
783
+ }
784
+ });
785
+ }
786
+ case 'delete':
787
+ if (!draftId) {
788
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for delete action');
789
+ }
731
790
  return await gmailService.manageDraft({
732
791
  email,
733
- action: 'update',
734
- draftId,
735
- data: {
736
- ...draftData,
737
- threadId: data.threadId ?? threading.threadId,
738
- inReplyTo: data.inReplyTo ?? threading.inReplyTo,
739
- references: data.references ?? threading.references,
740
- attachments: processOutgoingAttachments(data.attachments)
741
- }
792
+ action: 'delete',
793
+ draftId
742
794
  });
743
- }
744
- case 'delete':
745
- if (!draftId) {
746
- throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for delete action');
747
- }
748
- return await gmailService.manageDraft({
749
- email,
750
- action: 'delete',
751
- draftId
752
- });
753
- case 'send':
754
- if (!draftId) {
755
- throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for send action');
756
- }
757
- return await gmailService.manageDraft({
758
- email,
759
- action: 'send',
760
- draftId
761
- });
762
- default:
763
- throw new McpError(ErrorCode.InvalidParams, 'Invalid action. Supported actions are: create, read, update, delete, send');
764
- }
795
+ case 'send':
796
+ if (!draftId) {
797
+ throw new McpError(ErrorCode.InvalidParams, 'Draft ID is required for send action');
798
+ }
799
+ return await gmailService.manageDraft({
800
+ email,
801
+ action: 'send',
802
+ draftId
803
+ });
804
+ default:
805
+ throw new McpError(ErrorCode.InvalidParams, 'Invalid action. Supported actions are: create, read, update, delete, send');
806
+ }
807
+ })();
808
+ // A degraded reply-threading lookup still creates/updates the draft
809
+ // (unthreaded) — make that visible in the result, not just the logs.
810
+ return withReplyThreadingWarning(managed, threadingResolution.degradedReason);
765
811
  }
766
812
  catch (error) {
767
813
  throw toMcpError(error, 'Failed to manage draft');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mindstone/mcp-server-google-workspace",
3
- "version": "0.4.0",
3
+ "version": "0.4.2",
4
4
  "mcpName": "io.github.mindstone/mcp-server-google-workspace",
5
5
  "description": "Google Workspace MCP server for Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Tasks, and Forms",
6
6
  "license": "FSL-1.1-MIT",