@migma/mcp 1.11.12 → 1.11.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,10 +1,14 @@
1
1
  import { mcpAppMeta, registerMcpApp } from "./mcp-apps.js";
2
2
  /**
3
3
  * MCP Apps card for the email tools (generate, generation status, edit, get): progress while
4
- * Migma designs or changes an email, then each email as its picture at real width, a series
5
- * as tabs, "Edit in Migma" through ui/open-link, a few asks sent to the chat through
6
- * ui/message, and full screen where the host has it. It only reads: migma_get_generation_status,
7
- * migma_get_email_edit_status and migma_get_email. Hosts without MCP Apps read the text result.
4
+ * Migma designs or changes an email, then each email's first screen, a series as tabs, and the
5
+ * path from ready to sent (Test, Audience, Send). Each step runs on a click through tools/call: a
6
+ * test to the account's own inbox (migma_send_test_email), the audience from the brand's segments
7
+ * and lists, and a send that only prepares an approval (migma_send_email), which the user approves
8
+ * on migma.ai while the card reads it (migma_get_send_approval). "Make it shorter" changes the email
9
+ * in place (migma_edit_email). A host that refuses a call gets the step as a chat message
10
+ * (ui/message); what the card did reaches the model through ui/update-model-context. "Edit in
11
+ * Migma" goes through ui/open-link. Hosts without MCP Apps read the text result.
8
12
  */
9
13
  export const EMAIL_CARD_URI = "ui://migma/email";
10
14
  /** Tool `_meta` that links an email tool to the card, when the server shows it. */
@@ -156,8 +160,71 @@ export const EMAIL_CARD_HTML = `<!doctype html>
156
160
  /* Narrow full screen (Claude's side panel): tabs replace the rail and the arrows over the email. */
157
161
  @container (max-width: 720px) { .rail, .step-btn { display: none; } .fs .tabs { display: flex; } }
158
162
 
163
+ /* Ready: one line of status and fact, the email's first screen, the path from ready to sent. */
164
+ :root { --pink: light-dark(#e31c5b, #f0587f); }
165
+ .ready { display: flex; gap: 8px; align-items: center; min-height: 32px; margin: -6px 0 2px; color: var(--text-2); font-size: 13px; font-weight: var(--font-weight-medium, 500); }
166
+ .ready .fact { display: inline-flex; gap: 4px; align-items: center; padding-left: 10px; margin-left: 2px; border-left: 0.5px solid var(--line-2); color: var(--text-3); font-weight: 400; }
167
+ .ready .fact .i { width: 14px; height: 14px; color: var(--success); }
168
+ .ready .brand { margin-left: auto; display: inline-flex; gap: 6px; align-items: center; color: var(--text-3); font-weight: 400; }
169
+ .ready .brand i { width: 12px; height: 12px; border-radius: 3px; background: var(--pink); }
170
+ .ready .icon-btn { margin-right: -8px; }
171
+ @container (max-width: 420px) { .ready .fact { display: none; } }
172
+ .stage.first { height: var(--first-h, 320px); overflow: hidden; }
173
+ .stage.open { height: auto; overflow: visible; }
174
+ .whole { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); min-height: 32px; padding: 0 14px; border: 0.5px solid var(--line-2); border-radius: 999px; background: var(--surface); color: var(--text); font-size: 13px; font-weight: var(--font-weight-medium, 500); white-space: nowrap; box-shadow: 0 2px 8px rgb(0 0 0 / 8%); }
175
+ .whole:hover { background: var(--muted); }
176
+ .path { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin-top: 12px; list-style: none; padding: 0; }
177
+ .path.faded { opacity: .55; }
178
+ .step { display: flex; flex-direction: column; gap: 4px; min-height: 72px; padding: 10px 12px; border-radius: var(--radius); background: var(--muted); min-width: 0; }
179
+ .step .k { display: flex; gap: 6px; align-items: center; font-size: 13px; font-weight: var(--font-weight-semibold, 600); color: var(--text); }
180
+ .step .k .i { width: 14px; height: 14px; }
181
+ .step .v { font-size: 12.5px; color: var(--text-3); overflow-wrap: anywhere; }
182
+ .step .s { margin-left: auto; display: grid; place-items: center; width: 18px; height: 18px; flex: none; border-radius: 50%; }
183
+ .step .s.todo { width: 14px; height: 14px; border: 1.5px solid var(--line-2); }
184
+ .step .s.asked { width: 14px; height: 14px; border: 2px solid var(--info); }
185
+ .step .s.done { background: var(--success); color: #fff; }
186
+ .step .s.done .i { width: 12px; height: 12px; stroke-width: 2.5; }
187
+ .step .s.run { width: 14px; height: 14px; border: 2px solid var(--line-2); border-top-color: var(--pink); }
188
+ .step .s.warn { width: 10px; height: 10px; background: var(--warning-text); }
189
+ .step.warn .v { color: var(--warning-text); }
190
+ .step.next { background: var(--surface); box-shadow: 0 0 0 1.5px var(--pink); }
191
+ .step.done .v, .step.asked .v { color: var(--text-2); }
192
+ @container (max-width: 420px) { .path { grid-template-columns: minmax(0, 1fr); } .step { min-height: 0; } }
193
+ .pick { margin-top: 12px; padding: 12px; border-radius: var(--radius); background: var(--muted); display: flex; flex-direction: column; gap: 10px; }
194
+ .pick-h { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px; font-size: 13px; font-weight: var(--font-weight-semibold, 600); }
195
+ .pick-h span { color: var(--text-3); font-weight: 400; }
196
+ .opts { display: flex; gap: 6px; flex-wrap: wrap; }
197
+ .opt { display: inline-flex; gap: 8px; align-items: center; min-height: 36px; padding: 0 12px; border: 0.5px solid var(--line-2); border-radius: 999px; background: var(--surface); color: var(--text); font-size: 13px; font-weight: var(--font-weight-medium, 500); }
198
+ .opt small { color: var(--text-3); font-size: 12px; font-weight: 400; font-variant-numeric: tabular-nums; }
199
+ .opt[aria-pressed="true"] { box-shadow: 0 0 0 1.5px var(--text); border-color: transparent; }
200
+ .ghost.left { margin-left: 0; }
201
+ .facts { margin: 12px 0 0; display: grid; grid-template-columns: 72px 1fr; gap: 6px 12px; padding: 12px; border-radius: var(--radius); background: var(--muted); font-size: 13px; }
202
+ .facts dt { color: var(--text-3); }
203
+ .facts dd { margin: 0; color: var(--text); overflow-wrap: anywhere; }
204
+ .panel .facts { margin: 0; }
205
+ .note a.plans { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
206
+
207
+ /* Full screen: the whole email, the path in a panel beside it. */
208
+ .desk { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: minmax(0, 1fr); min-width: 0; min-height: 0; }
209
+ .desk .fs-wrap { min-height: 0; }
210
+ .panel { border-left: 0.5px solid var(--line); padding: 20px; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; }
211
+ .panel h2 { margin: 0; font-size: 14px; font-weight: var(--font-weight-semibold, 600); }
212
+ .panel .path { grid-template-columns: minmax(0, 1fr); margin-top: 0; }
213
+ .panel .step { min-height: 0; }
214
+ .panel .pick { margin-top: 0; }
215
+ .panel .asks { margin-top: auto; padding-top: 12px; }
216
+ @container (max-width: 720px) {
217
+ .desk { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; }
218
+ .panel { border-left: 0; border-top: 0.5px solid var(--line); padding: 12px 20px; overflow: visible; }
219
+ .panel h2 { display: none; }
220
+ .panel .path { grid-template-columns: repeat(3, minmax(0, 1fr)); }
221
+ .panel .asks { padding-top: 0; }
222
+ }
223
+
159
224
  @media (prefers-reduced-motion: no-preference) {
160
225
  .sk, .now .ring { animation: pulse 1.4s ease-in-out infinite; }
226
+ .step .s.run { animation: spin 0.9s linear infinite; }
227
+ @keyframes spin { to { transform: rotate(360deg); } }
161
228
  @keyframes pulse { 50% { opacity: .55; } }
162
229
  }
163
230
  </style>
@@ -178,7 +245,11 @@ export const EMAIL_CARD_HTML = `<!doctype html>
178
245
  next: '<path d="M9 18l6-6-6-6"/>',
179
246
  image: '<rect x="3" y="3" width="18" height="18" rx="2"/><circle cx="9" cy="9" r="2"/><path d="M21 15l-5-5L5 21"/>',
180
247
  alert: '<circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/>',
248
+ mail: '<path d="M4 6h16v12H4zM4 7l8 6 8-6"/>',
249
+ people: '<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0113 0M16 4.5a3.5 3.5 0 010 7M18 14a6 6 0 013.5 6"/>',
250
+ send: '<path d="M21 3L10 14M21 3l-7 18-4-7-7-4z"/>',
181
251
  };
252
+ const CONTACTS_URL = "https://migma.ai/contacts/imports";
182
253
  const EDIT_STEPS = [["Checking the email", ["queued", "checking"]], ["Changing it", ["editing"]], ["Saving", ["saved"]]];
183
254
  const PICTURE_TRIES = 4;
184
255
  const $ = (id) => document.getElementById(id);
@@ -199,6 +270,9 @@ export const EMAIL_CARD_HTML = `<!doctype html>
199
270
  const https = (url) => (typeof url === "string" && url.startsWith("https://") ? url : "");
200
271
 
201
272
  let host = {}, caps = {}, input = {}, s = null, sel = 0, nextId = 1, timer = 0, ticker = 0, delay = 3000, tries = 0, busy = false;
273
+ // The path from ready to sent: each email's steps (a series sends each email on its own), the
274
+ // audience being picked, and whether the inline email is open to its full length.
275
+ let brand = "", flow = {}, pick = null, whole = false, history = [];
202
276
  const pending = new Map();
203
277
 
204
278
  function send(msg) { window.parent.postMessage({ jsonrpc: "2.0", ...msg }, "*"); }
@@ -241,9 +315,11 @@ export const EMAIL_CARD_HTML = `<!doctype html>
241
315
  const inset = ctx.safeAreaInsets;
242
316
  if (inset) for (const side of ["top", "right", "bottom", "left"]) root.style.setProperty("--inset-" + side, (inset[side] || 0) + "px");
243
317
  root.dataset.mode = host.displayMode || "inline";
244
- // Inline, the email scrolls inside the card; keep the card within the height the host allows.
318
+ // Inline, the email shows its first screen (no scrolling inside the card); keep the card within
319
+ // the height the host allows. While designing or changing, the stage keeps --stage-h.
245
320
  const max = host.containerDimensions?.maxHeight;
246
321
  root.style.setProperty("--stage-h", (max ? Math.max(240, Math.min(520, max - 200)) : innerWidth < 480 ? 420 : 520) + "px");
322
+ root.style.setProperty("--first-h", (max ? Math.max(200, Math.min(340, max - 280)) : 320) + "px");
247
323
  }
248
324
 
249
325
  // Each tool puts its JSON in one text item among others (a lead sentence, guidance, the Previews list).
@@ -254,6 +330,17 @@ export const EMAIL_CARD_HTML = `<!doctype html>
254
330
  }
255
331
  return null;
256
332
  }
333
+ // Lists come back as an array, or as an object holding one.
334
+ function rows(result) {
335
+ for (const text of texts(result)) {
336
+ try {
337
+ const value = JSON.parse(text);
338
+ if (Array.isArray(value)) return value;
339
+ for (const key of ["data", "segments", "tags", "items"]) if (Array.isArray(value?.[key])) return value[key];
340
+ } catch {}
341
+ }
342
+ return null;
343
+ }
257
344
  function toEmail(e = {}, link = "") {
258
345
  return {
259
346
  emailId: e.emailId || e.id || "",
@@ -270,6 +357,9 @@ export const EMAIL_CARD_HTML = `<!doctype html>
270
357
  clearTimeout(timer);
271
358
  sel = 0; tries = 0;
272
359
  const data = json(result);
360
+ // The brand, for reading its audiences: the tool input names it on hosted servers.
361
+ brand = (typeof input.projectId === "string" && input.projectId) || (typeof data?.projectId === "string" && data.projectId) || "";
362
+ flow = {}; pick = null; whole = false; history = [];
273
363
  if (result?.isError || !data || (data.error && !data.conversationId && !data.editId)) {
274
364
  const mode = input.emailId && input.prompt ? "edit" : input.prompt ? "create" : "email";
275
365
  // Refused before anything started (no credits, a locked email): trying again would only repeat it.
@@ -423,9 +513,11 @@ export const EMAIL_CARD_HTML = `<!doctype html>
423
513
  try {
424
514
  const r = await request("ui/message", { role: "user", content: [{ type: "text", text }] });
425
515
  if (r?.isError) throw new Error();
516
+ return true;
426
517
  } catch {
427
518
  s.note = "Could not send that to the chat. Type it there instead.";
428
519
  render();
520
+ return false;
429
521
  }
430
522
  }
431
523
  async function displayMode(mode) {
@@ -449,10 +541,11 @@ export const EMAIL_CARD_HTML = `<!doctype html>
449
541
  const series = () => s.emails.length > 1;
450
542
  const quoted = (e) => (e.subject ? "“" + e.subject + "”" : "this email");
451
543
  const named = (e, i) => (series() ? "email " + (i + 1) + " of the series, " + quoted(e) + "," : quoted(e));
452
- const chip = (label, text) => button("chip", label, () => ask(text));
544
+ // An ask is run by the card (a function) or sent to the chat (text, where the host takes messages).
545
+ const chip = (label, act) => button("chip", label, () => (typeof act === "function" ? act() : ask(act)));
453
546
  function asks(list) {
454
547
  const box = el("div", "", { className: "asks" });
455
- if (caps.message) box.append(...list.map(([label, text]) => chip(label, text)));
548
+ box.append(...list.filter(([, act]) => typeof act === "function" || caps.message).map(([label, act]) => chip(label, act)));
456
549
  return box;
457
550
  }
458
551
  function linkButton(url, primary) {
@@ -514,10 +607,15 @@ export const EMAIL_CARD_HTML = `<!doctype html>
514
607
  return note;
515
608
  }
516
609
  function stage(e, opts = {}) {
517
- const box = el("div", "", { className: opts.short ? "stage short" : "stage" });
610
+ const box = el("div", "", { className: opts.short ? "stage short" : opts.first ? (whole ? "stage open" : "stage first") : "stage" });
518
611
  if (e?.failed) {
519
612
  const ready = s.emails.filter((x) => !x.failed).length;
520
613
  box.append(stageNote("alert", "Migma could not create this email." + (ready ? " The other " + (ready === 1 ? "one is" : ready + " are") + " ready." : "")));
614
+ } else if (e?.picture && opts.first) {
615
+ // Inline, the first screen: no scrolling inside an inline card (host guidance). The whole email
616
+ // opens full screen, or in place where the host has no full screen.
617
+ box.append(picture(e, opts.dim));
618
+ if (!whole) box.append(button("whole", "See the whole email", () => (canFullScreen() ? displayMode("fullscreen") : ((whole = true), render()))));
521
619
  } else if (e?.picture) {
522
620
  box.append(picture(e, opts.dim));
523
621
  box.tabIndex = 0;
@@ -557,11 +655,367 @@ export const EMAIL_CARD_HTML = `<!doctype html>
557
655
  function readyAsks(e, i) {
558
656
  if (e.failed) return [["Try this email again", "Try creating email " + (i + 1) + " of the series again."]];
559
657
  return [
560
- ["Make it shorter", "Make " + named(e, i) + " shorter."],
658
+ ["Make it shorter", () => shorten(e, i)],
561
659
  ["Try another version", "Make another version of " + named(e, i).replace(/,$/, "") + "."],
562
660
  ];
563
661
  }
564
662
 
663
+ // ---- the path from ready to sent ----
664
+ // The card runs each step itself on a click (tools/call): a test to the account's own inbox, the
665
+ // audience from the brand's segments and lists, and a send that only prepares an approval, which
666
+ // the user approves on migma.ai. A host that refuses the call gets the step as a chat message.
667
+ // What the card did is told to the model (ui/update-model-context), so the chat keeps track.
668
+ const SETUP_URL = "https://migma.ai/sending-domains";
669
+ const PLANS_URL = "https://migma.ai/pricing";
670
+ const keyOf = (e) => e.emailId || "email-" + sel;
671
+ const blank = () => ({ test: "", sentTo: "", audience: null, send: "", approval: null, change: "", note: "", plans: false });
672
+ const flowOf = (e) => (flow[keyOf(e)] ||= blank());
673
+ const people = (n) => n.toLocaleString("en-US") + (n === 1 ? " person" : " people");
674
+ const short = (text) => (text.length > 24 ? text.slice(0, 23) + "…" : text);
675
+ const subjectOf = (e, i) => named(e, i).replace(/,$/, "");
676
+ const target = (e) => (e.emailId ? { emailId: e.emailId } : { conversationId: s.conversationId });
677
+ const stamp = () => Date.now().toString(36);
678
+ // A refusal that names the plan gets the plans page; nothing else in the card mentions plans.
679
+ const planRefusal = (text) => /\\bplan\\b|upgrade|pricing/i.test(text || "");
680
+ const waitMs = (ms) => new Promise((done) => setTimeout(done, ms));
681
+
682
+ // The tool's answer, the error it returned, or null when the host refused the call itself.
683
+ async function run(name, args) {
684
+ try {
685
+ const result = await request("tools/call", { name, arguments: args }, 60000);
686
+ if (result?.isError) {
687
+ const refusal = json(result);
688
+ return { error: refusal?.error || texts(result)[0] || "Migma could not do this.", code: typeof refusal?.code === "string" ? refusal.code : "" };
689
+ }
690
+ return { data: json(result) ?? {}, list: rows(result) };
691
+ } catch { return null; }
692
+ }
693
+ function remember(text) {
694
+ history.push(text);
695
+ const context = "In the Migma email card, the user " + history.join("; ") + ".";
696
+ request("ui/update-model-context", { content: [{ type: "text", text: context }] }, 10000).catch(() => {});
697
+ }
698
+ function failed(f, error) {
699
+ f.note = error;
700
+ f.plans = planRefusal(error);
701
+ }
702
+
703
+ async function testIt(e, i) {
704
+ const f = flowOf(e);
705
+ f.test = "running"; f.note = ""; render();
706
+ const r = await run("migma_send_test_email", target(e));
707
+ if (!r) f.test = (await ask("Send me a test of " + subjectOf(e, i) + ".")) ? "asked" : "";
708
+ else if (r.error) { f.test = "warn"; failed(f, r.error); }
709
+ else {
710
+ f.test = "done";
711
+ f.sentTo = String(r.data.sentTo || "");
712
+ remember("sent a test of " + subjectOf(e, i) + (f.sentTo ? " to " + f.sentTo : " to their own inbox"));
713
+ }
714
+ render();
715
+ }
716
+
717
+ async function chooseAudience(e, i) {
718
+ if (!brand) return askSend(e, i);
719
+ const key = keyOf(e);
720
+ flowOf(e).note = "";
721
+ pick = { key, kind: "audience", loading: true, options: [], chosen: 0 };
722
+ render();
723
+ const [segments, lists] = await Promise.all([
724
+ run("migma_list_segments", { projectId: brand }),
725
+ run("migma_list_tags", { projectId: brand }),
726
+ ]);
727
+ if (pick?.key !== key) return;
728
+ // Without either list the chat picks the audience with the user.
729
+ if (!segments?.list && !lists?.list) { pick = null; return askSend(e, i); }
730
+ const count = (r) => (typeof r.count === "number" ? r.count : typeof r.subscriberCount === "number" ? r.subscriberCount : null);
731
+ const option = (type) => (r) => ({ type, id: String(r?.id ?? r?._id ?? ""), name: String(r?.name ?? ""), count: count(r ?? {}) });
732
+ pick.options = [...(segments?.list ?? []).map(option("segment")), ...(lists?.list ?? []).map(option("list"))]
733
+ .filter((o) => o.id && o.name)
734
+ .sort((a, b) => (b.count ?? -1) - (a.count ?? -1))
735
+ .slice(0, 6);
736
+ pick.loading = false;
737
+ render();
738
+ }
739
+ function useAudience(e) {
740
+ const f = flowOf(e);
741
+ f.audience = pick.options[pick.chosen];
742
+ f.send = ""; f.note = ""; f.plans = false;
743
+ pick = null;
744
+ render();
745
+ }
746
+
747
+ // Sending domains belong to the account, not a brand: one sender is used as it is; several are
748
+ // offered as choices; none sends the user to set one up.
749
+ let senders = null;
750
+ async function loadSenders() {
751
+ if (senders) return senders;
752
+ const r = await run("migma_list_domains", {});
753
+ if (!r || r.error) return null;
754
+ senders = (r.list ?? [])
755
+ .filter((d) => d?.isVerified === true || d?.status === "verified")
756
+ .flatMap((d) => (Array.isArray(d.senders) ? d.senders : []).map((x) => ({ email: String(x?.email ?? ""), name: String(x?.fromName ?? ""), first: x?.isDefault === true })))
757
+ .filter((x) => x.email && x.name)
758
+ .sort((a, b) => Number(b.first) - Number(a.first))
759
+ .slice(0, 6);
760
+ return senders;
761
+ }
762
+ async function sendIt(e, i, sender) {
763
+ const f = flowOf(e);
764
+ const a = f.audience;
765
+ if (!a || a.chat) return askSend(e, i);
766
+ f.note = ""; f.plans = false;
767
+ if (!sender) {
768
+ f.send = "running"; render();
769
+ const list = await loadSenders();
770
+ if (!list) { f.send = ""; return askSend(e, i); }
771
+ if (!list.length) { f.send = "nosender"; return render(); }
772
+ if (list.length > 1) {
773
+ f.send = "";
774
+ pick = { key: keyOf(e), kind: "sender", loading: false, options: list, chosen: 0 };
775
+ return render();
776
+ }
777
+ sender = list[0];
778
+ }
779
+ pick = null;
780
+ f.send = "running"; render();
781
+ const key = "card-" + keyOf(e) + "-" + a.id + "-" + stamp();
782
+ let r = await run("migma_send_email", {
783
+ recipientType: a.type === "list" ? "tag" : "segment",
784
+ recipientId: a.id,
785
+ from: sender.email,
786
+ fromName: sender.name,
787
+ subject: e.subject,
788
+ ...target(e),
789
+ idempotency_key: key,
790
+ });
791
+ if (r?.code === MANAGED_SINGLE_SEND_REFUSED) r = await viaCampaign(e, a, sender, key);
792
+ if (!r) { f.send = ""; return askSend(e, i); }
793
+ if (r.error) { f.send = "warn"; failed(f, r.error); return render(); }
794
+ const approval = r.data.approval ?? {};
795
+ const summary = r.data.summary ?? {};
796
+ f.approval = {
797
+ id: String(approval.id ?? ""),
798
+ url: https(approval.approvalUrl),
799
+ count: typeof summary.recipients === "number" ? summary.recipients : a.count,
800
+ from: (summary.fromName || sender.name) + " <" + (summary.from || sender.email) + ">",
801
+ subject: summary.subject || e.subject,
802
+ warning: Array.isArray(summary.warnings) ? String(summary.warnings[0] ?? "") : "",
803
+ };
804
+ f.send = "waiting";
805
+ remember("prepared a send of " + subjectOf(e, i) + " to " + a.name + "; it waits for their approval on migma.ai (" + f.approval.url + ")");
806
+ render();
807
+ watchApproval(e, i, f);
808
+ }
809
+ // A workspace connected through managed sign-in may send only campaigns (their approval re-checks
810
+ // the member's role), so the same send goes as a campaign draft and its approval, which the user
811
+ // approves on migma.ai the same way. Null (the host refused, or no brand to save it in) asks the chat.
812
+ const MANAGED_SINGLE_SEND_REFUSED = "WORKSPACE_KEY_SINGLE_SEND_REFUSED";
813
+ async function viaCampaign(e, a, sender, key) {
814
+ if (!brand) return null;
815
+ const draft = await run("migma_create_campaign", {
816
+ projectId: brand,
817
+ name: e.subject || "Email from Migma",
818
+ ...target(e),
819
+ subject: e.subject,
820
+ from: sender.email,
821
+ fromName: sender.name,
822
+ recipientType: a.type === "list" ? "tag" : "audience",
823
+ recipientId: a.id,
824
+ idempotency_key: key + "-draft",
825
+ });
826
+ if (!draft || draft.error) return draft;
827
+ if (!draft.data.id) return { error: "Migma could not save the campaign." };
828
+ return run("migma_send_campaign", { campaignId: String(draft.data.id), idempotency_key: key + "-send" });
829
+ }
830
+ // The approval happens on migma.ai; the card reads it until it is decided.
831
+ async function watchApproval(e, i, f) {
832
+ let wait = 5000;
833
+ while (f.send === "waiting" && f.approval?.id) {
834
+ await waitMs(wait);
835
+ wait = Math.min(wait * 1.3, 20000);
836
+ if (document.visibilityState !== "visible") continue;
837
+ const r = await run("migma_get_send_approval", { approvalId: f.approval.id });
838
+ const status = r?.data?.status;
839
+ if (status === "sent" || status === "scheduled") {
840
+ f.send = "sent";
841
+ remember("approved the send of " + subjectOf(e, i) + " on migma.ai; Migma sent it");
842
+ } else if (status === "declined" || status === "expired" || status === "failed") {
843
+ f.send = "warn";
844
+ failed(f, status === "declined" ? "The send was declined on migma.ai." : status === "expired" ? "The approval expired before anyone approved it." : r.data.error || "The send did not go out.");
845
+ } else continue;
846
+ return render();
847
+ }
848
+ }
849
+ async function askSend(e, i) {
850
+ const f = flowOf(e);
851
+ const a = f.audience;
852
+ const to = a && !a.chat ? " to the " + a.name + (a.type === "list" ? " list" : " segment") : " to my audience";
853
+ if (!(await ask("Send " + subjectOf(e, i) + to + "."))) return;
854
+ f.send = "asked";
855
+ if (!f.audience) f.audience = { chat: true };
856
+ render();
857
+ }
858
+
859
+ // "Make it shorter" changes the email in place; the steps start again for the changed email.
860
+ async function shorten(e, i) {
861
+ if (!e.emailId) return ask("Make " + named(e, i) + " shorter.");
862
+ const f = flowOf(e);
863
+ f.change = "running"; f.note = ""; pick = null; render();
864
+ const r = await run("migma_edit_email", { emailId: e.emailId, prompt: "Make it shorter.", idempotency_key: "card-shorter-" + e.emailId + "-" + stamp() });
865
+ if (!r) { f.change = ""; render(); return ask("Make " + named(e, i) + " shorter."); }
866
+ if (r.error || !r.data.editId) { f.change = ""; failed(f, r.error || "Migma could not change this email."); return render(); }
867
+ let wait = r.data.pollAfterMs || 2000;
868
+ for (;;) {
869
+ await waitMs(wait);
870
+ wait = Math.min(wait * 1.4, 15000);
871
+ const d = await run("migma_get_email_edit_status", { emailId: e.emailId, editId: r.data.editId });
872
+ if (d?.data?.status === "failed") { f.change = ""; failed(f, d.data.error || "Migma could not change this email."); return render(); }
873
+ if (d?.data?.status === "completed") break;
874
+ }
875
+ const at = s.emails.indexOf(e);
876
+ const now = await run("migma_get_email", { emailId: e.emailId });
877
+ if (at >= 0 && now?.data?.emailId) s.emails[at] = unchanged(toEmail(now.data, e.appUrl), e.picture);
878
+ flow[keyOf(e)] = blank();
879
+ remember("made " + subjectOf(e, i) + " shorter");
880
+ tries = 0;
881
+ render();
882
+ if (missingPicture()) retryPicture();
883
+ }
884
+
885
+ function pathView(e, opts = {}) {
886
+ const f = e ? flowOf(e) : blank();
887
+ const a = f.audience;
888
+ const picking = e && pick?.key === keyOf(e) && pick.kind === "audience";
889
+ const test = {
890
+ "": ["", "To your own inbox"], running: ["run", "Sending"], done: ["done", f.sentTo ? "Sent to " + f.sentTo : "In your inbox"],
891
+ warn: ["warn", "Not sent"], asked: ["asked", "Asked in the chat"],
892
+ }[f.test];
893
+ const audience = a
894
+ ? (a.chat ? ["asked", "In the chat"] : ["done", a.name + (a.count !== null ? ", " + people(a.count) : "")])
895
+ : ["", picking && !pick.loading && !pick.options.length ? "No contacts yet" : picking ? "Pick who gets it" : "Your list, or bring one"];
896
+ const send = {
897
+ "": ["", "You approve on migma.ai"], running: ["run", "Preparing"], waiting: ["asked", "Waiting for your approval"],
898
+ sent: ["done", typeof f.approval?.count === "number" ? "Sent to " + people(f.approval.count) : "Sent"],
899
+ warn: ["warn", "Not sent"], nosender: ["warn", "Needs a sending address"], asked: ["asked", "Asked in the chat"],
900
+ }[f.send];
901
+ const next = opts.faded || f.change ? "" : !test[0] || f.test === "running" ? "test" : !a ? "audience" : f.send !== "sent" && f.send !== "asked" ? "send" : "";
902
+ const list = el("ol", "", { className: opts.faded ? "path faded" : "path" });
903
+ list.setAttribute("aria-label", "From ready to sent");
904
+ for (const [key, label, iconName, [state, value]] of [["test", "Test", "mail", test], ["audience", "Audience", "people", audience], ["send", "Send", "send", send]]) {
905
+ const li = el("li", "", { className: "step" + (key === next ? " next" : "") + (state ? " " + state : "") });
906
+ if (key === next) li.setAttribute("aria-current", "step");
907
+ const mark = el("span", "", { className: "s " + (state || "todo") });
908
+ if (state === "done") mark.append(icon("check"));
909
+ const k = el("span", "", { className: "k" });
910
+ k.append(icon(iconName), el("span", label), mark);
911
+ li.append(k, el("span", value, { className: "v" }));
912
+ list.append(li);
913
+ }
914
+ return list;
915
+ }
916
+ // What the last step left: the approval as it will go out, or why a step stopped.
917
+ function stepNote(e) {
918
+ const f = flowOf(e);
919
+ const parts = [];
920
+ if (f.approval && (f.send === "waiting" || f.send === "sent")) {
921
+ const facts = el("dl", "", { className: "facts" });
922
+ const a = f.audience;
923
+ for (const [k, v] of [["To", a.name + (typeof f.approval.count === "number" ? ", " + people(f.approval.count) : "")], ["From", f.approval.from], ["Subject", f.approval.subject]]) {
924
+ facts.append(el("dt", k), el("dd", v));
925
+ }
926
+ parts.push(facts);
927
+ if (f.approval.warning) parts.push(el("p", f.approval.warning, { className: "note warn" }));
928
+ }
929
+ if (f.send === "nosender") parts.push(el("p", "Emails go out from your own address. Set it up once in Migma.", { className: "note small" }));
930
+ if (f.note) {
931
+ const p = el("p", f.note, { className: "note warn" });
932
+ if (f.plans) {
933
+ const plans = el("a", "See plans", { href: PLANS_URL, className: "plans" });
934
+ plans.addEventListener("click", (event) => { event.preventDefault(); openLink(PLANS_URL); });
935
+ p.append(" ", plans);
936
+ }
937
+ parts.push(p);
938
+ }
939
+ if (f.change === "running") parts.push(el("p", "Making it shorter", { className: "note small", role: "status" }));
940
+ return parts;
941
+ }
942
+ function pickView(e) {
943
+ if (!pick || pick.key !== keyOf(e)) return null;
944
+ const box = el("div", "", { className: "pick", role: "group" });
945
+ box.setAttribute("aria-label", pick.kind === "sender" ? "Sender" : "Audience");
946
+ if (pick.loading) {
947
+ box.append(el("p", "Who gets it", { className: "pick-h" }), el("div", "", { className: "sk", style: "height:36px;width:60%" }));
948
+ return box;
949
+ }
950
+ if (!pick.options.length) {
951
+ box.append(
952
+ el("p", "No contacts yet", { className: "pick-h" }),
953
+ el("p", "Bring your list from Klaviyo, Shopify, Mailchimp or a CSV once, and every send can use it.", { className: "note small", style: "margin:0" }),
954
+ );
955
+ return box;
956
+ }
957
+ const h = el("p", pick.kind === "sender" ? "Who it is from" : "Who gets it", { className: "pick-h" });
958
+ h.append(el("span", pick.kind === "sender" ? "Your sending addresses in Migma" : "From your contacts in Migma"));
959
+ const opts = el("div", "", { className: "opts" });
960
+ pick.options.forEach((o, n) => {
961
+ const b = button("opt", o.name, () => { pick.chosen = n; render(); });
962
+ b.setAttribute("aria-pressed", String(n === pick.chosen));
963
+ if (pick.kind === "sender") b.append(el("small", o.email));
964
+ else if (o.count !== null) b.append(el("small", o.count.toLocaleString("en-US")));
965
+ opts.append(b);
966
+ });
967
+ box.append(h, opts);
968
+ return box;
969
+ }
970
+ function linkPrimary(label, url) {
971
+ const b = button("primary", label, () => openLink(url));
972
+ b.append(icon("out"));
973
+ return b;
974
+ }
975
+ function nextButton(e, i) {
976
+ const f = flowOf(e);
977
+ if (f.change) return null;
978
+ const p = pick?.key === keyOf(e) ? pick : null;
979
+ if (p?.kind === "sender") return button("primary", "Send from " + short(p.options[p.chosen].name), () => sendIt(e, i, p.options[p.chosen]));
980
+ if (!f.test || f.test === "running") return button("primary", "Send me a test", () => testIt(e, i), { disabled: f.test === "running" });
981
+ if (!f.audience) {
982
+ if (!p) return button("primary", "Choose audience", () => chooseAudience(e, i));
983
+ if (p.loading) return button("primary", "Choose audience", () => {}, { disabled: true });
984
+ if (!p.options.length) return linkPrimary("Add contacts in Migma", CONTACTS_URL);
985
+ return button("primary", "Use " + short(p.options[p.chosen].name), () => useAudience(e));
986
+ }
987
+ if (f.send === "nosender") return linkPrimary("Set up sending in Migma", SETUP_URL);
988
+ if (f.send === "waiting") return linkPrimary("Approve on migma.ai", f.approval.url);
989
+ if (f.send === "sent") return f.approval.url ? linkPrimary("See results", f.approval.url) : null;
990
+ if (f.send === "warn" && f.plans) return button("primary", "Choose another list", () => { f.audience = null; f.send = ""; chooseAudience(e, i); });
991
+ if (f.send === "warn") return button("primary", "Try the send again", () => sendIt(e, i));
992
+ if (f.send === "" || f.send === "running") return button("primary", "Send", () => sendIt(e, i), { disabled: f.send === "running" });
993
+ return null;
994
+ }
995
+ function pathFoot(e, i) {
996
+ const f = el("div", "", { className: "foot" });
997
+ const url = e.appUrl || s.appUrl;
998
+ if (url) {
999
+ const edit = button("ghost left", "Edit in Migma", () => openLink(url));
1000
+ edit.append(icon("out"));
1001
+ f.append(edit);
1002
+ }
1003
+ const next = nextButton(e, i);
1004
+ if (next) f.append(next);
1005
+ return f;
1006
+ }
1007
+ function readyLine(tools) {
1008
+ const line = el("div", "", { className: "ready" });
1009
+ const fact = el("span", "", { className: "fact" });
1010
+ fact.append(icon("check"), el("span", "Works in every inbox"));
1011
+ const mark = el("span", "", { className: "brand" });
1012
+ mark.append(el("i", ""), el("span", "Migma"));
1013
+ line.append(el("span", "", { className: "dot ok" }), el("span", series() ? "Email designs ready" : "Email design ready"), fact, mark, ...tools);
1014
+ return line;
1015
+ }
1016
+ // A host that can neither run tools nor take messages shows the email and its link.
1017
+ const hasPath = (e) => !e.failed && !!(caps.message || caps.serverTools);
1018
+
565
1019
  // ---- views ----
566
1020
  function compactView() {
567
1021
  const line = el("div", "", { className: "line", role: "status" });
@@ -615,6 +1069,8 @@ export const EMAIL_CARD_HTML = `<!doctype html>
615
1069
  } else {
616
1070
  parts.push(stage(null, { short: true }));
617
1071
  }
1072
+ // What comes next, faded, while people wait.
1073
+ if (caps.message) parts.push(el("p", "Next, without leaving the chat", { className: "note small" }), pathView(null, { faded: true }));
618
1074
  parts.push(foot([], s.appUrl, false));
619
1075
  return parts;
620
1076
  }
@@ -643,9 +1099,17 @@ export const EMAIL_CARD_HTML = `<!doctype html>
643
1099
  const full = canFullScreen() ? [button("icon-btn", "", () => displayMode("fullscreen"), { ariaLabel: "Full screen" })] : [];
644
1100
  full[0]?.append(icon("expand"));
645
1101
  const title = e.failed ? "Email " + (sel + 1) + " was not created" : e.subject || "Your email";
646
- const parts = [head(title, e.failed ? "" : e.preheader, full)];
1102
+ const parts = e.failed ? [head(title, "", full)] : [readyLine(full), head(title, e.preheader)];
647
1103
  if (series()) parts.push(tabs());
648
- parts.push(stage(e), foot(readyAsks(e, sel), e.appUrl || s.appUrl, true));
1104
+ parts.push(stage(e, { first: true, dim: !e.failed && flowOf(e).change === "running" }));
1105
+ if (!hasPath(e)) {
1106
+ parts.push(foot(e.failed ? readyAsks(e, sel) : [], e.appUrl || s.appUrl, true));
1107
+ return parts;
1108
+ }
1109
+ parts.push(pathView(e), ...stepNote(e));
1110
+ const picking = pickView(e);
1111
+ if (picking) parts.push(picking);
1112
+ parts.push(pathFoot(e, sel));
649
1113
  return parts;
650
1114
  }
651
1115
 
@@ -676,10 +1140,22 @@ export const EMAIL_CARD_HTML = `<!doctype html>
676
1140
  prev.append(icon("prev")); next.append(icon("next"));
677
1141
  wrap.append(prev, next);
678
1142
  }
679
- body.append(wrap);
1143
+ const desk = el("div", "", { className: "desk" });
1144
+ desk.append(wrap);
1145
+ if (hasPath(e)) {
1146
+ // The path beside the whole email; changes to the email live here, where there is room.
1147
+ const panel = el("aside", "", { className: "panel" });
1148
+ panel.setAttribute("aria-label", "From ready to sent");
1149
+ panel.append(el("h2", "From ready to sent"), pathView(e), ...stepNote(e));
1150
+ const picking = pickView(e);
1151
+ if (picking) panel.append(picking);
1152
+ panel.append(asks(readyAsks(e, sel)));
1153
+ desk.append(panel);
1154
+ }
1155
+ body.append(desk);
680
1156
  box.append(head(e.failed ? "Email " + (sel + 1) + " was not created" : e.subject || "Your email", e.failed ? "" : e.preheader, [back]));
681
1157
  if (series()) box.append(tabs());
682
- box.append(body, foot(readyAsks(e, sel), e.appUrl || s.appUrl, true));
1158
+ box.append(body, hasPath(e) ? pathFoot(e, sel) : foot(readyAsks(e, sel), e.appUrl || s.appUrl, true));
683
1159
  if (s.note) box.append(el("p", s.note, { className: "note small" }));
684
1160
  return [box];
685
1161
  }
@@ -1 +1 @@
1
- {"version":3,"file":"email-card.js","sourceRoot":"","sources":["../../src/tools/email-card.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAE3D;;;;;;GAMG;AAEH,MAAM,CAAC,MAAM,cAAc,GAAG,kBAAkB,CAAC;AAEjD,mFAAmF;AACnF,MAAM,UAAU,aAAa,CAAC,IAAa;IACzC,OAAO,UAAU,CAAC,cAAc,EAAE,IAAI,CAAC,CAAC;AAC1C,CAAC;AAED,MAAM,UAAU,iBAAiB,CAAC,MAAiB,EAAE,IAAa;IAChE,IAAI,CAAC,IAAI;QAAE,OAAO;IAClB,cAAc,CAAC,MAAM,EAAE;QACrB,IAAI,EAAE,OAAO;QACb,GAAG,EAAE,cAAc;QACnB,WAAW,EAAE,2DAA2D;QACxE,IAAI,EAAE,eAAe;KACtB,CAAC,CAAC;AACL,CAAC;AAED,MAAM,CAAC,MAAM,eAAe,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4oC9B,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/tools/generate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAGnC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAY3C,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,KAAK,EACb,MAAM,EAAE,MAAM,EACd,kBAAkB,CAAC,EAAE,MAAM,EAAE,EAC7B,IAAI,UAAO,EACX,SAAS,GAAE,MAAM,OAAqB,QAsXvC;AAED,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,kBAAkB,CAAC,EAAE,MAAM,EAAE,EAAE,SAAS,UAAQ,GAAG,MAAM,CAUtF"}
1
+ {"version":3,"file":"generate.d.ts","sourceRoot":"","sources":["../../src/tools/generate.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AACzE,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,OAAO,CAAC;AAGnC,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAY3C,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,SAAS,EACjB,MAAM,EAAE,KAAK,EACb,MAAM,EAAE,MAAM,EACd,kBAAkB,CAAC,EAAE,MAAM,EAAE,EAC7B,IAAI,UAAO,EACX,SAAS,GAAE,MAAM,OAAqB,QAuXvC;AAED,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,kBAAkB,CAAC,EAAE,MAAM,EAAE,EAAE,SAAS,UAAQ,GAAG,MAAM,CAUtF"}