@migma/mcp 1.11.16 → 1.11.18
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 +3 -2
- package/build/tools/__tests__/catalog.test.js +1 -1
- package/build/tools/__tests__/email-card.test.js +16 -4
- package/build/tools/__tests__/email-card.test.js.map +1 -1
- package/build/tools/__tests__/export-markdown.test.d.ts +2 -0
- package/build/tools/__tests__/export-markdown.test.d.ts.map +1 -0
- package/build/tools/__tests__/export-markdown.test.js +38 -0
- package/build/tools/__tests__/export-markdown.test.js.map +1 -0
- package/build/tools/__tests__/review-annotations.test.js +2 -1
- package/build/tools/__tests__/review-annotations.test.js.map +1 -1
- package/build/tools/capabilities.d.ts.map +1 -1
- package/build/tools/capabilities.js +8 -7
- package/build/tools/capabilities.js.map +1 -1
- package/build/tools/email-card.d.ts +12 -9
- package/build/tools/email-card.d.ts.map +1 -1
- package/build/tools/email-card.js +898 -688
- package/build/tools/email-card.js.map +1 -1
- package/build/tools/export.d.ts.map +1 -1
- package/build/tools/export.js +22 -6
- package/build/tools/export.js.map +1 -1
- package/build/tools/projects.js +1 -1
- package/build/tools/projects.js.map +1 -1
- package/package.json +1 -1
|
@@ -1,18 +1,21 @@
|
|
|
1
1
|
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.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
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* (
|
|
11
|
-
*
|
|
4
|
+
* Migma designs or changes an email, then every email of the request as a poster, side by side.
|
|
5
|
+
* Nothing has an order. One row says who gets the picked email: Just me (a test to the account's
|
|
6
|
+
* own inbox, migma_send_test_email), the brand's lists and segments, read again each time the user
|
|
7
|
+
* comes back to the card, and, behind More, other tools (a Klaviyo template through
|
|
8
|
+
* migma_push_to_klaviyo; the rest are asked in the chat). A send to a list only prepares an approval
|
|
9
|
+
* (migma_send_email), which the user approves on migma.ai while the card reads it
|
|
10
|
+
* (migma_get_send_approval); what came back shows after it (migma_get_email_metrics). The brand line
|
|
11
|
+
* reads migma_get_project. Each action runs on a click through tools/call; a host that refuses a
|
|
12
|
+
* call gets it as a chat message (ui/message); what the card did reaches the model through
|
|
13
|
+
* ui/update-model-context. "Edit in Migma" goes through ui/open-link. Hosts without MCP Apps read
|
|
14
|
+
* the text result.
|
|
12
15
|
*/
|
|
13
16
|
export declare const EMAIL_CARD_URI = "ui://migma/email";
|
|
14
17
|
/** Tool `_meta` that links an email tool to the card, when the server shows it. */
|
|
15
18
|
export declare function emailCardMeta(card: boolean): Record<string, unknown> | undefined;
|
|
16
19
|
export declare function registerEmailCard(server: McpServer, card: boolean): void;
|
|
17
|
-
export declare const EMAIL_CARD_HTML = "<!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<meta name=\"color-scheme\" content=\"light dark\">\n<title>Email</title>\n<style>\n :root {\n color-scheme: light dark;\n --surface: var(--color-background-primary, light-dark(#ffffff, #30302e));\n --muted: var(--color-background-secondary, light-dark(#f5f4ed, #262624));\n --muted-2: var(--color-background-tertiary, light-dark(#ebe9df, #3a3a37));\n --text: var(--color-text-primary, light-dark(#141413, #faf9f5));\n --text-2: var(--color-text-secondary, light-dark(#3d3d3a, #c2c0b6));\n --text-3: var(--color-text-tertiary, light-dark(#73726c, #9c9a92));\n --line: var(--color-border-tertiary, light-dark(rgb(31 30 29 / 15%), rgb(222 220 209 / 15%)));\n --line-2: var(--color-border-secondary, light-dark(rgb(31 30 29 / 30%), rgb(222 220 209 / 30%)));\n --inverse: var(--color-background-inverse, light-dark(#141413, #faf9f5));\n --on-inverse: var(--color-text-inverse, light-dark(#ffffff, #141413));\n --info: var(--color-border-info, light-dark(#4682d5, #6c9be0));\n --success: var(--color-border-success, light-dark(#437426, #7fb05b));\n --danger: var(--color-border-danger, light-dark(#a73d39, #d1615c));\n --danger-text: var(--color-text-danger, light-dark(#7f2c28, #ee8884));\n --warning-text: var(--color-text-warning, light-dark(#5a4815, #d1a041));\n --radius: var(--border-radius-lg, 10px);\n --radius-md: var(--border-radius-md, 8px);\n }\n * { box-sizing: border-box; }\n html, body { margin: 0; background: transparent; }\n body {\n font-family: var(--font-sans, system-ui, -apple-system, sans-serif);\n font-size: var(--font-text-sm-size, 14px);\n line-height: var(--font-text-sm-line-height, 1.4);\n color: var(--text);\n -webkit-font-smoothing: antialiased;\n }\n p, h1, ul { margin: 0; }\n button { font: inherit; cursor: pointer; }\n button:focus-visible, .stage:focus-visible { outline: 2px solid var(--color-ring-primary, var(--info)); outline-offset: 2px; }\n button[disabled] { cursor: default; opacity: .5; }\n main {\n container-type: inline-size;\n padding: calc(16px + var(--inset-top, 0px)) calc(16px + var(--inset-right, 0px)) calc(16px + var(--inset-bottom, 0px)) calc(16px + var(--inset-left, 0px));\n }\n .i { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; }\n .i.big { width: 24px; height: 24px; }\n\n .head { display: flex; gap: 12px; align-items: flex-start; justify-content: space-between; }\n .title { min-width: 0; }\n h1 { font-size: var(--font-heading-md-size, 16px); line-height: var(--font-heading-md-line-height, 1.4); font-weight: var(--font-weight-semibold, 600); overflow-wrap: anywhere; }\n .pre { color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }\n .icon-btn { display: inline-grid; place-items: center; width: 32px; height: 32px; flex: none; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-2); }\n .icon-btn:hover { background: var(--muted); }\n\n .stage { position: relative; margin-top: 12px; height: var(--stage-h, 520px); border-radius: var(--radius); background: var(--muted); overflow: auto; overscroll-behavior: contain; display: flex; justify-content: center; align-items: flex-start; padding: 16px; scrollbar-width: thin; }\n .stage.short { height: 240px; overflow: hidden; }\n .shot { width: min(600px, 100%); flex: none; border-radius: 4px; overflow: hidden; box-shadow: 0 0 0 0.5px var(--line); background: var(--surface); }\n .shot img { display: block; width: 100%; height: auto; }\n .shot.dim { opacity: .45; }\n .skel { width: min(600px, 100%); height: 100%; min-height: 200px; flex: none; border-radius: 4px; background: var(--surface); box-shadow: 0 0 0 0.5px var(--line); padding: 28px; display: flex; flex-direction: column; gap: 14px; overflow: hidden; }\n .sk { background: var(--muted-2); border-radius: 6px; flex: none; }\n .stage-note { position: absolute; inset: 0; margin: auto; height: fit-content; display: flex; flex-direction: column; align-items: center; gap: 8px; padding: 16px; color: var(--text-2); text-align: center; max-width: 340px; }\n .pill { display: inline-flex; gap: 8px; align-items: center; padding: 6px 12px; border-radius: 999px; background: var(--surface); box-shadow: 0 0 0 0.5px var(--line); color: var(--text-2); }\n\n .tabs { display: flex; gap: 4px; margin-top: 12px; overflow-x: auto; scrollbar-width: none; }\n .tab { display: inline-flex; gap: 8px; align-items: center; height: 36px; max-width: 220px; flex: none; padding: 0 12px 0 8px; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-2); font-size: 13px; }\n .tab .n { display: grid; place-items: center; width: 20px; height: 20px; flex: none; border-radius: 50%; background: var(--muted); font-size: 12px; font-weight: 600; }\n .tab .t { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .tab .d { color: var(--text-3); flex: none; }\n .tab[aria-selected=\"true\"] { background: var(--muted); color: var(--text); }\n .tab[aria-selected=\"true\"] .n { background: var(--inverse); color: var(--on-inverse); }\n\n .foot { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 12px; flex-wrap: wrap; }\n .asks { display: flex; gap: 6px; flex-wrap: wrap; }\n .chip { display: inline-flex; gap: 6px; align-items: center; min-height: 32px; padding: 0 12px; border: 0.5px solid var(--line-2); border-radius: 999px; background: transparent; color: var(--text); font-size: 13px; font-weight: var(--font-weight-medium, 500); }\n .chip:hover { background: var(--muted); }\n .primary, .ghost { display: inline-flex; gap: 6px; align-items: center; justify-content: center; min-height: 36px; padding: 0 14px; border-radius: var(--radius-md); white-space: nowrap; font-weight: var(--font-weight-semibold, 600); }\n .primary { border: 0; background: var(--inverse); color: var(--on-inverse); margin-left: auto; }\n .ghost { border: 0.5px solid var(--line-2); background: transparent; color: var(--text); font-weight: var(--font-weight-medium, 500); margin-left: auto; }\n .ghost:hover { background: var(--muted); }\n @container (max-width: 420px) { .foot .primary, .foot .ghost { width: 100%; } }\n\n .status { display: flex; gap: 8px; align-items: center; margin-bottom: 6px; color: var(--text-2); font-weight: var(--font-weight-medium, 500); }\n .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--text-3); }\n .dot.info { background: var(--info); } .dot.ok { background: var(--success); } .dot.bad { background: var(--danger); }\n .time { margin-left: auto; color: var(--text-3); font-variant-numeric: tabular-nums; font-weight: 400; }\n .steps { list-style: none; padding: 0; margin-top: 12px; display: grid; gap: 6px; }\n .steps li { display: flex; gap: 8px; align-items: center; color: var(--text-3); min-width: 0; }\n .steps li span:nth-child(2) { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .steps li.now { color: var(--text); }\n .mark { display: grid; place-items: center; width: 16px; height: 16px; flex: none; }\n .ring { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid var(--line-2); }\n .now .ring { border-color: var(--info); background: var(--info); }\n .note { margin-top: 12px; color: var(--text-2); overflow-wrap: anywhere; }\n .note.bad { color: var(--danger-text); }\n .note.warn { margin-top: 4px; color: var(--warning-text); }\n .note.small { color: var(--text-3); font-size: 13px; }\n\n .slots { display: flex; gap: 12px; margin-top: 12px; overflow-x: auto; }\n .slot { flex: 1 0 72px; min-width: 0; max-width: 200px; display: flex; flex-direction: column; gap: 8px; }\n .slot .frame { aspect-ratio: 3 / 4; border-radius: var(--radius-md); background: var(--muted); display: grid; place-items: center; color: var(--text-3); }\n .slot.done .frame { color: var(--success); }\n .slot .lab { display: flex; flex-wrap: wrap; column-gap: 6px; color: var(--text-2); font-size: 13px; }\n .slot .lab span:last-child { color: var(--text-3); margin-left: auto; }\n\n .line { display: flex; gap: 8px; align-items: center; min-height: 28px; color: var(--text-2); min-width: 0; }\n .line .t { color: var(--text); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; min-width: 0; }\n .line .s { color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; min-width: 0; }\n .line .thumb { width: 40px; height: 40px; flex: none; border-radius: 6px; overflow: hidden; box-shadow: 0 0 0 0.5px var(--line); background: var(--muted); }\n .line .thumb img { display: block; width: 100%; }\n .line .ghost, .line .primary { min-height: 30px; padding: 0 10px; font-size: 13px; margin-left: 0; }\n .line .ghost:first-of-type { margin-left: auto; }\n @container (max-width: 420px) { .line { flex-wrap: wrap; } .line .ghost:first-of-type { margin-left: 48px; } }\n\n :root:has(.fs), :root:has(.fs) body { height: 100%; }\n main:has(.fs) { height: 100%; padding: 0; }\n .fs { height: 100%; display: flex; flex-direction: column; }\n .fs > .head { padding: calc(14px + var(--inset-top, 0px)) calc(20px + var(--inset-right, 0px)) 14px calc(20px + var(--inset-left, 0px)); border-bottom: 0.5px solid var(--line); }\n .fs-body { flex: 1; display: flex; min-height: 0; }\n .rail { width: 200px; flex: none; padding: 16px; display: flex; flex-direction: column; gap: 12px; border-right: 0.5px solid var(--line); overflow-y: auto; }\n .rail-item { display: flex; flex-direction: column; gap: 6px; padding: 6px; border-radius: var(--radius); border: 0; background: transparent; text-align: left; color: var(--text-2); font-size: 13px; }\n .rail-item .thumb { height: 140px; border-radius: 6px; overflow: hidden; box-shadow: 0 0 0 0.5px var(--line); background: var(--muted); display: grid; place-items: center; color: var(--text-3); }\n .rail-item .thumb img { display: block; width: 100%; align-self: start; }\n .rail-item[aria-current=\"true\"] { background: var(--muted); color: var(--text); }\n .fs .stage { flex: 1; height: auto; margin: 0; border-radius: 0; padding: 24px; }\n .fs .foot { margin: 0; padding: 12px calc(20px + var(--inset-right, 0px)) calc(12px + var(--inset-bottom, 0px)) calc(20px + var(--inset-left, 0px)); border-top: 0.5px solid var(--line); }\n .fs .note { margin: 0; padding: 0 20px 12px; }\n .step-btn { position: absolute; top: 50%; margin-top: -18px; display: grid; place-items: center; width: 36px; height: 36px; border-radius: 50%; border: 0.5px solid var(--line); background: var(--surface); color: var(--text); }\n .step-btn.prev { left: 16px; } .step-btn.next { right: 16px; }\n .fs-wrap { flex: 1; position: relative; display: flex; min-width: 0; }\n .fs .tabs { display: none; margin: 0; padding: 8px calc(20px + var(--inset-right, 0px)) 8px calc(20px + var(--inset-left, 0px)); border-bottom: 0.5px solid var(--line); }\n /* Narrow full screen (Claude's side panel): tabs replace the rail and the arrows over the email. */\n @container (max-width: 720px) { .rail, .step-btn { display: none; } .fs .tabs { display: flex; } }\n\n /* Ready: one line of status and fact, the email's first screen, the path from ready to sent. */\n :root { --pink: light-dark(#e31c5b, #f0587f); }\n .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); }\n .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; }\n .ready .fact .i { width: 14px; height: 14px; color: var(--success); }\n .ready .brand { margin-left: auto; display: inline-flex; gap: 6px; align-items: center; color: var(--text-3); font-weight: 400; }\n .ready .brand i { width: 12px; height: 12px; border-radius: 3px; background: var(--pink); }\n .ready .icon-btn { margin-right: -8px; }\n @container (max-width: 420px) { .ready .fact { display: none; } }\n .stage.first { height: var(--first-h, 320px); overflow: hidden; }\n .stage.open { height: auto; overflow: visible; }\n .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%); }\n .whole:hover { background: var(--muted); }\n .path { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin-top: 12px; list-style: none; padding: 0; }\n .path.faded { opacity: .55; }\n .step { display: flex; flex-direction: column; gap: 4px; min-height: 72px; padding: 10px 12px; border-radius: var(--radius); background: var(--muted); min-width: 0; }\n .step .k { display: flex; gap: 6px; align-items: center; font-size: 13px; font-weight: var(--font-weight-semibold, 600); color: var(--text); }\n .step .k .i { width: 14px; height: 14px; }\n .step .v { font-size: 12.5px; color: var(--text-3); overflow-wrap: anywhere; }\n .step .s { margin-left: auto; display: grid; place-items: center; width: 18px; height: 18px; flex: none; border-radius: 50%; }\n .step .s.todo { width: 14px; height: 14px; border: 1.5px solid var(--line-2); }\n .step .s.asked { width: 14px; height: 14px; border: 2px solid var(--info); }\n .step .s.done { background: var(--success); color: #fff; }\n .step .s.done .i { width: 12px; height: 12px; stroke-width: 2.5; }\n .step .s.run { width: 14px; height: 14px; border: 2px solid var(--line-2); border-top-color: var(--pink); }\n .step .s.warn { width: 10px; height: 10px; background: var(--warning-text); }\n .step.warn .v { color: var(--warning-text); }\n .step.next { background: var(--surface); box-shadow: 0 0 0 1.5px var(--pink); }\n .step.done .v, .step.asked .v { color: var(--text-2); }\n @container (max-width: 420px) { .path { grid-template-columns: minmax(0, 1fr); } .step { min-height: 0; } }\n .pick { margin-top: 12px; padding: 12px; border-radius: var(--radius); background: var(--muted); display: flex; flex-direction: column; gap: 10px; }\n .pick-h { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px; font-size: 13px; font-weight: var(--font-weight-semibold, 600); }\n .pick-h span { color: var(--text-3); font-weight: 400; }\n .opts { display: flex; gap: 6px; flex-wrap: wrap; }\n .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); }\n .opt small { color: var(--text-3); font-size: 12px; font-weight: 400; font-variant-numeric: tabular-nums; }\n .opt[aria-pressed=\"true\"] { box-shadow: 0 0 0 1.5px var(--text); border-color: transparent; }\n .ghost.left { margin-left: 0; }\n .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; }\n .facts dt { color: var(--text-3); }\n .facts dd { margin: 0; color: var(--text); overflow-wrap: anywhere; }\n .panel .facts { margin: 0; }\n .note a.plans { color: inherit; text-decoration: underline; text-underline-offset: 3px; }\n\n /* Full screen: the whole email, the path in a panel beside it. */\n .desk { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: minmax(0, 1fr); min-width: 0; min-height: 0; }\n .desk .fs-wrap { min-height: 0; }\n .panel { border-left: 0.5px solid var(--line); padding: 20px; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; }\n .panel h2 { margin: 0; font-size: 14px; font-weight: var(--font-weight-semibold, 600); }\n .panel .path { grid-template-columns: minmax(0, 1fr); margin-top: 0; }\n .panel .step { min-height: 0; }\n .panel .pick { margin-top: 0; }\n .panel .asks { margin-top: auto; padding-top: 12px; }\n @container (max-width: 720px) {\n .desk { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; }\n .panel { border-left: 0; border-top: 0.5px solid var(--line); padding: 12px 20px; overflow: visible; }\n .panel h2 { display: none; }\n .panel .path { grid-template-columns: repeat(3, minmax(0, 1fr)); }\n .panel .asks { padding-top: 0; }\n }\n\n @media (prefers-reduced-motion: no-preference) {\n .sk, .now .ring { animation: pulse 1.4s ease-in-out infinite; }\n .step .s.run { animation: spin 0.9s linear infinite; }\n @keyframes spin { to { transform: rotate(360deg); } }\n @keyframes pulse { 50% { opacity: .55; } }\n }\n</style>\n</head>\n<body>\n<main id=\"card\" aria-busy=\"true\">\n <div class=\"sk\" style=\"height:16px;width:40%\"></div>\n <div class=\"sk\" style=\"height:12px;width:70%;margin-top:8px\"></div>\n <div class=\"stage short\"></div>\n</main>\n<script type=\"module\">\n const ICON = {\n expand: '<path d=\"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7\"/>',\n collapse: '<path d=\"M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7\"/>',\n out: '<path d=\"M7 17L17 7M8 7h9v9\"/>',\n check: '<path d=\"M5 12l5 5L20 7\"/>',\n prev: '<path d=\"M15 18l-6-6 6-6\"/>',\n next: '<path d=\"M9 18l6-6-6-6\"/>',\n 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\"/>',\n alert: '<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 8v4M12 16h.01\"/>',\n mail: '<path d=\"M4 6h16v12H4zM4 7l8 6 8-6\"/>',\n 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\"/>',\n send: '<path d=\"M21 3L10 14M21 3l-7 18-4-7-7-4z\"/>',\n };\n const CONTACTS_URL = \"https://migma.ai/contacts/imports\";\n const EDIT_STEPS = [[\"Checking the email\", [\"queued\", \"checking\"]], [\"Changing it\", [\"editing\"]], [\"Saving\", [\"saved\"]]];\n const PICTURE_TRIES = 4;\n const $ = (id) => document.getElementById(id);\n const el = (tag, text, attrs = {}) => Object.assign(document.createElement(tag), { textContent: text ?? \"\" }, attrs);\n function icon(name, big) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"class\", big ? \"i big\" : \"i\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n svg.innerHTML = ICON[name];\n return svg;\n }\n function button(className, label, onclick, attrs = {}) {\n const b = el(\"button\", label, { type: \"button\", className, ...attrs });\n b.addEventListener(\"click\", onclick);\n return b;\n }\n const https = (url) => (typeof url === \"string\" && url.startsWith(\"https://\") ? url : \"\");\n\n let host = {}, caps = {}, input = {}, s = null, sel = 0, nextId = 1, timer = 0, ticker = 0, delay = 3000, tries = 0, busy = false;\n // The path from ready to sent: each email's steps (a series sends each email on its own), the\n // audience being picked, and whether the inline email is open to its full length.\n let brand = \"\", flow = {}, pick = null, whole = false, history = [];\n const pending = new Map();\n\n function send(msg) { window.parent.postMessage({ jsonrpc: \"2.0\", ...msg }, \"*\"); }\n function request(method, params, ms) {\n const id = nextId++;\n send({ id, method, params });\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject });\n // A host that never answers must not stall the card's reads.\n if (ms) setTimeout(() => pending.delete(id) && reject(new Error(\"timeout\")), ms);\n });\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== window.parent) return;\n const msg = event.data;\n if (!msg || msg.jsonrpc !== \"2.0\") return;\n if (msg.id !== undefined && !msg.method) {\n const waiter = pending.get(msg.id);\n pending.delete(msg.id);\n if (waiter) msg.error ? waiter.reject(msg.error) : waiter.resolve(msg.result);\n return;\n }\n if (msg.id !== undefined) {\n // Host requests (ping, teardown) need an answer; this card holds no state to save.\n send({ id: msg.id, result: {} });\n return;\n }\n if (msg.method === \"ui/notifications/tool-input\") input = msg.params?.arguments ?? {};\n if (msg.method === \"ui/notifications/tool-result\") onResult(msg.params);\n if (msg.method === \"ui/notifications/host-context-changed\") { applyHost(msg.params); if (s) render(); }\n });\n\n function applyHost(ctx = {}) {\n host = { ...host, ...ctx };\n const root = document.documentElement;\n if (ctx.theme) { root.dataset.theme = ctx.theme; root.style.colorScheme = ctx.theme; }\n for (const [key, value] of Object.entries(ctx.styles?.variables ?? {})) if (value) root.style.setProperty(key, value);\n if (ctx.styles?.css?.fonts && !$(\"host-fonts\")) document.head.append(el(\"style\", ctx.styles.css.fonts, { id: \"host-fonts\" }));\n const inset = ctx.safeAreaInsets;\n if (inset) for (const side of [\"top\", \"right\", \"bottom\", \"left\"]) root.style.setProperty(\"--inset-\" + side, (inset[side] || 0) + \"px\");\n root.dataset.mode = host.displayMode || \"inline\";\n // Inline, the email shows its first screen (no scrolling inside the card); keep the card within\n // the height the host allows. While designing or changing, the stage keeps --stage-h.\n const max = host.containerDimensions?.maxHeight;\n root.style.setProperty(\"--stage-h\", (max ? Math.max(240, Math.min(520, max - 200)) : innerWidth < 480 ? 420 : 520) + \"px\");\n root.style.setProperty(\"--first-h\", (max ? Math.max(200, Math.min(340, max - 280)) : 320) + \"px\");\n }\n\n // Each tool puts its JSON in one text item among others (a lead sentence, guidance, the Previews list).\n const texts = (result) => (result?.content ?? []).filter((c) => c.type === \"text\").map((c) => c.text);\n function json(result) {\n for (const text of texts(result)) {\n try { const value = JSON.parse(text); if (value && typeof value === \"object\" && !Array.isArray(value)) return value; } catch {}\n }\n return null;\n }\n // Lists come back as an array, or as an object holding one.\n function rows(result) {\n for (const text of texts(result)) {\n try {\n const value = JSON.parse(text);\n if (Array.isArray(value)) return value;\n for (const key of [\"data\", \"segments\", \"tags\", \"items\"]) if (Array.isArray(value?.[key])) return value[key];\n } catch {}\n }\n return null;\n }\n function toEmail(e = {}, link = \"\") {\n return {\n emailId: e.emailId || e.id || \"\",\n subject: e.subject || \"\",\n preheader: e.preheader || e.previewText || \"\",\n picture: https(e.screenshotFullUrl) || https(e.screenshotUrl) || https(e.thumbnailUrl),\n appUrl: https(e.appUrl) || link,\n failed: e.status === \"failed\",\n day: typeof e.sendOffsetDays === \"number\" ? e.sendOffsetDays : null,\n };\n }\n\n function onResult(result) {\n clearTimeout(timer);\n sel = 0; tries = 0;\n const data = json(result);\n // The brand, for reading its audiences: the tool input names it on hosted servers.\n brand = (typeof input.projectId === \"string\" && input.projectId) || (typeof data?.projectId === \"string\" && data.projectId) || \"\";\n flow = {}; pick = null; whole = false; history = [];\n if (result?.isError || !data || (data.error && !data.conversationId && !data.editId)) {\n const mode = input.emailId && input.prompt ? \"edit\" : input.prompt ? \"create\" : \"email\";\n // Refused before anything started (no credits, a locked email): trying again would only repeat it.\n s = { mode, phase: \"failed\", refused: true, emailId: input.emailId, count: input.count, error: (typeof data?.error === \"string\" && data.error) || (!data && texts(result)[0]) || \"Migma could not do this.\" };\n render();\n if (mode === \"edit\") readBefore();\n return;\n }\n if (data.editId) {\n s = { mode: \"edit\", phase: \"working\", emailId: data.emailId, editId: data.editId, appUrl: https(data.appUrl), createdAt: data.createdAt, stage: data.stage };\n delay = data.pollAfterMs || 2000;\n render();\n readBefore();\n poll();\n } else if (data.emailId && \"subject\" in data) {\n s = { mode: \"email\", phase: \"ready\", emails: [toEmail(data)] };\n render();\n if (missingPicture()) retryPicture();\n } else if (data.conversationId) {\n // A status check draws one line that turns into a Ready row, which opens in place. It keeps\n // itself current: ChatGPT shows only the last card of a reply, so the generate call's card may\n // never be seen.\n s = { mode: \"create\", phase: \"working\", compact: !!data.createdAt && !input.prompt, conversationId: data.conversationId, appUrl: https(data.appUrl), count: data.count || input.count };\n applyStatus(data);\n // Slower than the full card: several status lines can poll at once, and hosted MCP allows 100 calls a minute.\n delay = s.compact ? 6000 : 3000;\n render();\n poll();\n }\n }\n\n function applyStatus(d) {\n if (d.createdAt) s.createdAt = d.createdAt;\n if (d.status === \"failed\") { s.phase = \"failed\"; s.error = d.error || \"Migma could not create this email.\"; return; }\n if (d.status === \"completed\") {\n const r = d.result || {};\n const rows = Array.isArray(r.emails) && r.emails.length ? r.emails : [r];\n s.emails = rows.map((e) => toEmail(e, s.appUrl));\n s.phase = \"ready\";\n return;\n }\n const p = d.progress || {};\n const events = Array.isArray(p.events) ? p.events.filter((e) => e?.label) : [];\n const done = [...new Set(events.filter((e) => e.status === \"complete\").map((e) => e.label))];\n const live = p.now?.label && (p.now.status === \"start\" || p.now.status === \"progress\") ? p.now.label : \"\";\n s.now = live || events.filter((e) => e.status === \"processing\").pop()?.label || s.now || \"\";\n s.steps = done.filter((label) => label !== s.now).slice(-3);\n if (Array.isArray(p.slots) && p.slots.length) s.slots = p.slots;\n }\n\n function applyEdit(d) {\n if (d.createdAt) s.createdAt = d.createdAt;\n s.stage = d.stage || s.stage;\n if (d.status === \"completed\") {\n s.mode = \"email\"; s.phase = \"ready\";\n s.emails = [unchanged(toEmail(d.result || { emailId: s.emailId, subject: s.before?.subject }, s.before?.appUrl || s.appUrl), s.before?.picture)];\n } else if (d.status === \"failed\") {\n s.phase = \"failed\"; s.error = d.error || \"Migma could not change this email.\"; s.mayHaveSaved = !!d.changesMayHaveBeenSaved;\n }\n }\n\n // Right after a change the email can still carry its old picture until Migma captures the new\n // one: wait for a different picture, and show the old one only once the retries run out.\n function unchanged(e, old) {\n if (e.picture && e.picture === old) { e.stale = e.picture; e.picture = \"\"; }\n return e;\n }\n\n // Tried even when the host does not list serverTools or openLinks: a refusal falls back.\n async function read(name, args) {\n try {\n const result = await request(\"tools/call\", { name, arguments: args }, 30000);\n return result?.isError ? null : json(result);\n } catch { return null; }\n }\n\n async function readBefore() {\n if (!s?.emailId) return;\n const d = await read(\"migma_get_email\", { emailId: s.emailId });\n if (d?.emailId && s.mode !== \"email\") { s.before = toEmail(d); render(); }\n }\n\n async function poll() {\n clearTimeout(timer);\n if (!s || s.phase !== \"working\" || busy || document.visibilityState !== \"visible\") return;\n busy = true;\n if (s.mode === \"create\") {\n const d = await read(\"migma_get_generation_status\", { conversationId: s.conversationId });\n if (d?.conversationId) applyStatus(d);\n } else {\n const d = await read(\"migma_get_email_edit_status\", { emailId: s.emailId, editId: s.editId });\n if (d?.status) applyEdit(d);\n }\n busy = false;\n render();\n if (s.phase === \"working\") {\n // ponytail: backoff to one read every 15 s; a push from Migma would replace polling if hosts add it.\n timer = setTimeout(poll, delay);\n delay = Math.min(delay * 1.4, 15000);\n } else if (missingPicture()) retryPicture();\n }\n\n const missingPicture = () => s?.phase === \"ready\" && s.emails.some((e) => !e.failed && !e.picture);\n // The picture is captured after the email is saved. Each read returns every picture of the\n // run, so try a few times, further apart, then say it is ready in Migma.\n function retryPicture() {\n clearTimeout(timer);\n if (tries >= PICTURE_TRIES) {\n for (const e of s.emails) if (!e.picture && e.stale) e.picture = e.stale;\n s.noPicture = true;\n return render();\n }\n timer = setTimeout(async () => {\n tries++;\n if (s.mode === \"create\") {\n const d = await read(\"migma_get_generation_status\", { conversationId: s.conversationId });\n if (d?.status === \"completed\") applyStatus(d);\n } else {\n const d = await read(\"migma_get_email\", { emailId: s.emails[0].emailId });\n if (d?.emailId) s.emails = [unchanged(toEmail(d, s.emails[0].appUrl), s.emails[0].stale)];\n }\n render();\n if (missingPicture()) retryPicture();\n }, 4000 * 2 ** tries);\n }\n\n function refreshSoon() { if (s?.phase === \"working\") { delay = 3000; poll(); } }\n document.addEventListener(\"visibilitychange\", () => document.visibilityState === \"visible\" && refreshSoon());\n window.addEventListener(\"focus\", refreshSoon);\n\n function elapsed() {\n const start = Date.parse(s.createdAt);\n if (!start) return \"\";\n const secs = Math.max(0, Math.round((Date.now() - start) / 1000));\n return Math.floor(secs / 60) + \":\" + String(secs % 60).padStart(2, \"0\");\n }\n function tick() {\n clearInterval(ticker);\n if (s.phase !== \"working\" || !s.createdAt) return;\n ticker = setInterval(() => document.querySelectorAll(\".time\").forEach((t) => { t.textContent = elapsed(); }), 1000);\n }\n\n // ---- actions ----\n async function openLink(url) {\n if (!url) return;\n try { const r = await request(\"ui/open-link\", { url }); if (!r?.isError) return; } catch {}\n s.note = \"Could not open the link. Copy it: \" + url;\n render();\n }\n async function ask(text) {\n try {\n const r = await request(\"ui/message\", { role: \"user\", content: [{ type: \"text\", text }] });\n if (r?.isError) throw new Error();\n return true;\n } catch {\n s.note = \"Could not send that to the chat. Type it there instead.\";\n render();\n return false;\n }\n }\n async function displayMode(mode) {\n try { const r = await request(\"ui/request-display-mode\", { mode }); applyHost({ displayMode: r?.mode || host.displayMode }); } catch {}\n render();\n }\n const canFullScreen = () => (host.availableDisplayModes || []).includes(\"fullscreen\");\n const fullScreen = () => host.displayMode === \"fullscreen\" && s.phase === \"ready\" && !s.compact;\n function select(i) {\n sel = Math.max(0, Math.min(s.emails.length - 1, i));\n render();\n document.querySelector('[aria-selected=\"true\"], [aria-current=\"true\"]')?.focus();\n }\n document.addEventListener(\"keydown\", (event) => {\n if (!s || !fullScreen() || s.emails.length < 2 || event.target.closest?.('[role=\"tab\"]')) return;\n if (event.key === \"ArrowLeft\") select(sel - 1);\n if (event.key === \"ArrowRight\") select(sel + 1);\n });\n\n // ---- pieces ----\n const series = () => s.emails.length > 1;\n const quoted = (e) => (e.subject ? \"\u201C\" + e.subject + \"\u201D\" : \"this email\");\n const named = (e, i) => (series() ? \"email \" + (i + 1) + \" of the series, \" + quoted(e) + \",\" : quoted(e));\n // An ask is run by the card (a function) or sent to the chat (text, where the host takes messages).\n const chip = (label, act) => button(\"chip\", label, () => (typeof act === \"function\" ? act() : ask(act)));\n function asks(list) {\n const box = el(\"div\", \"\", { className: \"asks\" });\n box.append(...list.filter(([, act]) => typeof act === \"function\" || caps.message).map(([label, act]) => chip(label, act)));\n return box;\n }\n function linkButton(url, primary) {\n if (!url) return el(\"span\", \"\");\n const b = button(primary ? \"primary\" : \"ghost\", primary ? \"Edit in Migma\" : \"Open in Migma\", () => openLink(url));\n b.append(icon(\"out\"));\n return b;\n }\n function foot(list, url, primary) {\n const f = el(\"div\", \"\", { className: \"foot\" });\n f.append(asks(list), linkButton(url, primary));\n return f;\n }\n function head(title, pre, tools = []) {\n const h = el(\"div\", \"\", { className: \"head\" });\n const t = el(\"div\", \"\", { className: \"title\" });\n t.append(el(\"h1\", title));\n if (pre) t.append(el(\"p\", pre, { className: \"pre\", title: pre }));\n h.append(t);\n if (tools.length) { const box = el(\"div\", \"\", { className: \"tools\" }); box.append(...tools); h.append(box); }\n return h;\n }\n function statusLine(label, tone) {\n const p = el(\"p\", \"\", { className: \"status\" });\n p.append(el(\"span\", \"\", { className: \"dot \" + tone }), el(\"span\", label));\n return p;\n }\n function steps(items) {\n const ul = el(\"ul\", \"\", { className: \"steps\" });\n ul.setAttribute(\"aria-live\", \"polite\");\n for (const [label, state] of items) {\n const li = el(\"li\", \"\", { className: state });\n const mark = el(\"span\", \"\", { className: \"mark\" });\n mark.append(state === \"done\" ? icon(\"check\") : el(\"span\", \"\", { className: \"ring\" }));\n li.append(mark, el(\"span\", label));\n if (state === \"now\") li.append(el(\"span\", elapsed(), { className: \"time\" }));\n ul.append(li);\n }\n return ul;\n }\n function skeleton() {\n const box = el(\"div\", \"\", { className: \"skel\" });\n for (const [h, w, m] of [[14, 30, 0], [56, 85, 16], [56, 60, 0], [200, 100, 8]]) {\n box.append(el(\"div\", \"\", { className: \"sk\", style: \"height:\" + h + \"px;width:\" + w + \"%;margin-top:\" + m + \"px\" }));\n }\n return box;\n }\n function picture(e, dim) {\n const shot = el(\"div\", \"\", { className: dim ? \"shot dim\" : \"shot\" });\n const img = el(\"img\", \"\", { alt: (e.subject || \"Email\") + (dim ? \", before the change\" : \"\") });\n img.addEventListener(\"error\", () => { e.picture = \"\"; render(); if (missingPicture()) retryPicture(); }, { once: true });\n img.src = e.picture;\n shot.append(img);\n return shot;\n }\n function stageNote(iconName, text) {\n const note = el(\"div\", \"\", { className: \"stage-note\" });\n note.append(icon(iconName, true), el(\"p\", text));\n return note;\n }\n function stage(e, opts = {}) {\n const box = el(\"div\", \"\", { className: opts.short ? \"stage short\" : opts.first ? (whole ? \"stage open\" : \"stage first\") : \"stage\" });\n if (e?.failed) {\n const ready = s.emails.filter((x) => !x.failed).length;\n box.append(stageNote(\"alert\", \"Migma could not create this email.\" + (ready ? \" The other \" + (ready === 1 ? \"one is\" : ready + \" are\") + \" ready.\" : \"\")));\n } else if (e?.picture && opts.first) {\n // Inline, the first screen: no scrolling inside an inline card (host guidance). The whole email\n // opens full screen, or in place where the host has no full screen.\n box.append(picture(e, opts.dim));\n if (!whole) box.append(button(\"whole\", \"See the whole email\", () => (canFullScreen() ? displayMode(\"fullscreen\") : ((whole = true), render()))));\n } else if (e?.picture) {\n box.append(picture(e, opts.dim));\n box.tabIndex = 0;\n box.setAttribute(\"aria-label\", (e.subject || \"Email\") + \", scroll to read\");\n } else if (opts.short || !s.noPicture || !e) {\n box.append(skeleton());\n if (e && !opts.short) {\n const note = el(\"p\", \"\", { className: \"stage-note\", role: \"status\" });\n const pill = el(\"span\", \"\", { className: \"pill\" });\n pill.append(el(\"span\", \"\", { className: \"dot info\" }), el(\"span\", \"Preparing the picture\"));\n note.append(pill);\n box.append(note);\n }\n } else {\n box.append(stageNote(\"image\", \"No picture of this email yet. It is ready in Migma.\"));\n }\n return box;\n }\n function tabs() {\n const list = el(\"div\", \"\", { className: \"tabs\", role: \"tablist\" });\n list.setAttribute(\"aria-label\", \"Emails in this series\");\n s.emails.forEach((e, i) => {\n const tab = button(\"tab\", \"\", () => select(i), { role: \"tab\" });\n tab.setAttribute(\"aria-selected\", String(i === sel));\n tab.tabIndex = i === sel ? 0 : -1;\n tab.append(el(\"span\", String(i + 1), { className: \"n\" }), el(\"span\", e.failed ? \"Not created\" : e.subject || \"Email \" + (i + 1), { className: \"t\" }));\n if (e.failed) tab.append(el(\"span\", \"\", { className: \"dot bad\" }));\n else if (e.day !== null) tab.append(el(\"span\", \"Day \" + e.day, { className: \"d\" }));\n tab.addEventListener(\"keydown\", (event) => {\n if (event.key === \"ArrowLeft\") select(i - 1);\n if (event.key === \"ArrowRight\") select(i + 1);\n });\n list.append(tab);\n });\n return list;\n }\n function readyAsks(e, i) {\n if (e.failed) return [[\"Try this email again\", \"Try creating email \" + (i + 1) + \" of the series again.\"]];\n return [\n [\"Make it shorter\", () => shorten(e, i)],\n [\"Try another version\", \"Make another version of \" + named(e, i).replace(/,$/, \"\") + \".\"],\n ];\n }\n\n // ---- the path from ready to sent ----\n // The card runs each step itself on a click (tools/call): a test to the account's own inbox, the\n // audience from the brand's segments and lists, and a send that only prepares an approval, which\n // the user approves on migma.ai. A host that refuses the call gets the step as a chat message.\n // What the card did is told to the model (ui/update-model-context), so the chat keeps track.\n const SETUP_URL = \"https://migma.ai/sending-domains\";\n const PLANS_URL = \"https://migma.ai/pricing\";\n const keyOf = (e) => e.emailId || \"email-\" + sel;\n const blank = () => ({ test: \"\", sentTo: \"\", audience: null, send: \"\", approval: null, change: \"\", note: \"\", plans: false });\n const flowOf = (e) => (flow[keyOf(e)] ||= blank());\n const people = (n) => n.toLocaleString(\"en-US\") + (n === 1 ? \" person\" : \" people\");\n const short = (text) => (text.length > 24 ? text.slice(0, 23) + \"\u2026\" : text);\n const subjectOf = (e, i) => named(e, i).replace(/,$/, \"\");\n const target = (e) => (e.emailId ? { emailId: e.emailId } : { conversationId: s.conversationId });\n const stamp = () => Date.now().toString(36);\n // A refusal that names the plan gets the plans page; nothing else in the card mentions plans.\n const planRefusal = (text) => /\\bplan\\b|upgrade|pricing/i.test(text || \"\");\n const waitMs = (ms) => new Promise((done) => setTimeout(done, ms));\n\n // The tool's answer, the error it returned, or null when the host refused the call itself.\n async function run(name, args) {\n try {\n const result = await request(\"tools/call\", { name, arguments: args }, 60000);\n if (result?.isError) {\n const refusal = json(result);\n return { error: refusal?.error || texts(result)[0] || \"Migma could not do this.\", code: typeof refusal?.code === \"string\" ? refusal.code : \"\" };\n }\n return { data: json(result) ?? {}, list: rows(result) };\n } catch { return null; }\n }\n function remember(text) {\n history.push(text);\n const context = \"In the Migma email card, the user \" + history.join(\"; \") + \".\";\n request(\"ui/update-model-context\", { content: [{ type: \"text\", text: context }] }, 10000).catch(() => {});\n }\n function failed(f, error) {\n f.note = error;\n f.plans = planRefusal(error);\n }\n\n async function testIt(e, i) {\n const f = flowOf(e);\n f.test = \"running\"; f.note = \"\"; render();\n const r = await run(\"migma_send_test_email\", target(e));\n if (!r) f.test = (await ask(\"Send me a test of \" + subjectOf(e, i) + \".\")) ? \"asked\" : \"\";\n else if (r.error) { f.test = \"warn\"; failed(f, r.error); }\n else {\n f.test = \"done\";\n f.sentTo = String(r.data.sentTo || \"\");\n remember(\"sent a test of \" + subjectOf(e, i) + (f.sentTo ? \" to \" + f.sentTo : \" to their own inbox\"));\n }\n render();\n }\n\n async function chooseAudience(e, i) {\n if (!brand) return askSend(e, i);\n const key = keyOf(e);\n flowOf(e).note = \"\";\n pick = { key, kind: \"audience\", loading: true, options: [], chosen: 0 };\n render();\n const [segments, lists] = await Promise.all([\n run(\"migma_list_segments\", { projectId: brand }),\n run(\"migma_list_tags\", { projectId: brand }),\n ]);\n if (pick?.key !== key) return;\n // Without either list the chat picks the audience with the user.\n if (!segments?.list && !lists?.list) { pick = null; return askSend(e, i); }\n const count = (r) => (typeof r.count === \"number\" ? r.count : typeof r.subscriberCount === \"number\" ? r.subscriberCount : null);\n const option = (type) => (r) => ({ type, id: String(r?.id ?? r?._id ?? \"\"), name: String(r?.name ?? \"\"), count: count(r ?? {}) });\n pick.options = [...(segments?.list ?? []).map(option(\"segment\")), ...(lists?.list ?? []).map(option(\"list\"))]\n .filter((o) => o.id && o.name)\n .sort((a, b) => (b.count ?? -1) - (a.count ?? -1))\n .slice(0, 6);\n pick.loading = false;\n render();\n }\n function useAudience(e) {\n const f = flowOf(e);\n f.audience = pick.options[pick.chosen];\n f.send = \"\"; f.note = \"\"; f.plans = false;\n pick = null;\n render();\n }\n\n // Sending domains belong to the account, not a brand: one sender is used as it is; several are\n // offered as choices; none sends the user to set one up.\n let senders = null;\n async function loadSenders() {\n if (senders) return senders;\n const r = await run(\"migma_list_domains\", {});\n if (!r || r.error) return null;\n senders = (r.list ?? [])\n .filter((d) => d?.isVerified === true || d?.status === \"verified\")\n .flatMap((d) => (Array.isArray(d.senders) ? d.senders : []).map((x) => ({ email: String(x?.email ?? \"\"), name: String(x?.fromName ?? \"\"), first: x?.isDefault === true })))\n .filter((x) => x.email && x.name)\n .sort((a, b) => Number(b.first) - Number(a.first))\n .slice(0, 6);\n return senders;\n }\n async function sendIt(e, i, sender) {\n const f = flowOf(e);\n const a = f.audience;\n if (!a || a.chat) return askSend(e, i);\n f.note = \"\"; f.plans = false;\n if (!sender) {\n f.send = \"running\"; render();\n const list = await loadSenders();\n if (!list) { f.send = \"\"; return askSend(e, i); }\n if (!list.length) { f.send = \"nosender\"; return render(); }\n if (list.length > 1) {\n f.send = \"\";\n pick = { key: keyOf(e), kind: \"sender\", loading: false, options: list, chosen: 0 };\n return render();\n }\n sender = list[0];\n }\n pick = null;\n f.send = \"running\"; render();\n const key = \"card-\" + keyOf(e) + \"-\" + a.id + \"-\" + stamp();\n let r = await run(\"migma_send_email\", {\n recipientType: a.type === \"list\" ? \"tag\" : \"segment\",\n recipientId: a.id,\n from: sender.email,\n fromName: sender.name,\n subject: e.subject,\n ...target(e),\n idempotency_key: key,\n });\n if (r?.code === MANAGED_SINGLE_SEND_REFUSED) r = await viaCampaign(e, a, sender, key);\n if (!r) { f.send = \"\"; return askSend(e, i); }\n if (r.error) { f.send = \"warn\"; failed(f, r.error); return render(); }\n const approval = r.data.approval ?? {};\n const summary = r.data.summary ?? {};\n f.approval = {\n id: String(approval.id ?? \"\"),\n url: https(approval.approvalUrl),\n count: typeof summary.recipients === \"number\" ? summary.recipients : a.count,\n from: (summary.fromName || sender.name) + \" <\" + (summary.from || sender.email) + \">\",\n subject: summary.subject || e.subject,\n warning: Array.isArray(summary.warnings) ? String(summary.warnings[0] ?? \"\") : \"\",\n };\n f.send = \"waiting\";\n remember(\"prepared a send of \" + subjectOf(e, i) + \" to \" + a.name + \"; it waits for their approval on migma.ai (\" + f.approval.url + \")\");\n render();\n watchApproval(e, i, f);\n }\n // A workspace connected through managed sign-in may send only campaigns (their approval re-checks\n // the member's role), so the same send goes as a campaign draft and its approval, which the user\n // approves on migma.ai the same way. Null (the host refused, or no brand to save it in) asks the chat.\n const MANAGED_SINGLE_SEND_REFUSED = \"WORKSPACE_KEY_SINGLE_SEND_REFUSED\";\n async function viaCampaign(e, a, sender, key) {\n if (!brand) return null;\n const draft = await run(\"migma_create_campaign\", {\n projectId: brand,\n name: e.subject || \"Email from Migma\",\n ...target(e),\n subject: e.subject,\n from: sender.email,\n fromName: sender.name,\n recipientType: a.type === \"list\" ? \"tag\" : \"audience\",\n recipientId: a.id,\n idempotency_key: key + \"-draft\",\n });\n if (!draft || draft.error) return draft;\n if (!draft.data.id) return { error: \"Migma could not save the campaign.\" };\n return run(\"migma_send_campaign\", { campaignId: String(draft.data.id), idempotency_key: key + \"-send\" });\n }\n // The approval happens on migma.ai; the card reads it until it is decided.\n async function watchApproval(e, i, f) {\n let wait = 5000;\n while (f.send === \"waiting\" && f.approval?.id) {\n await waitMs(wait);\n wait = Math.min(wait * 1.3, 20000);\n if (document.visibilityState !== \"visible\") continue;\n const r = await run(\"migma_get_send_approval\", { approvalId: f.approval.id });\n const status = r?.data?.status;\n if (status === \"sent\" || status === \"scheduled\") {\n f.send = \"sent\";\n remember(\"approved the send of \" + subjectOf(e, i) + \" on migma.ai; Migma sent it\");\n } else if (status === \"declined\" || status === \"expired\" || status === \"failed\") {\n f.send = \"warn\";\n 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.\");\n } else continue;\n return render();\n }\n }\n async function askSend(e, i) {\n const f = flowOf(e);\n const a = f.audience;\n const to = a && !a.chat ? \" to the \" + a.name + (a.type === \"list\" ? \" list\" : \" segment\") : \" to my audience\";\n if (!(await ask(\"Send \" + subjectOf(e, i) + to + \".\"))) return;\n f.send = \"asked\";\n if (!f.audience) f.audience = { chat: true };\n render();\n }\n\n // \"Make it shorter\" changes the email in place; the steps start again for the changed email.\n async function shorten(e, i) {\n if (!e.emailId) return ask(\"Make \" + named(e, i) + \" shorter.\");\n const f = flowOf(e);\n f.change = \"running\"; f.note = \"\"; pick = null; render();\n const r = await run(\"migma_edit_email\", { emailId: e.emailId, prompt: \"Make it shorter.\", idempotency_key: \"card-shorter-\" + e.emailId + \"-\" + stamp() });\n if (!r) { f.change = \"\"; render(); return ask(\"Make \" + named(e, i) + \" shorter.\"); }\n if (r.error || !r.data.editId) { f.change = \"\"; failed(f, r.error || \"Migma could not change this email.\"); return render(); }\n let wait = r.data.pollAfterMs || 2000;\n for (;;) {\n await waitMs(wait);\n wait = Math.min(wait * 1.4, 15000);\n const d = await run(\"migma_get_email_edit_status\", { emailId: e.emailId, editId: r.data.editId });\n if (d?.data?.status === \"failed\") { f.change = \"\"; failed(f, d.data.error || \"Migma could not change this email.\"); return render(); }\n if (d?.data?.status === \"completed\") break;\n }\n const at = s.emails.indexOf(e);\n const now = await run(\"migma_get_email\", { emailId: e.emailId });\n if (at >= 0 && now?.data?.emailId) s.emails[at] = unchanged(toEmail(now.data, e.appUrl), e.picture);\n flow[keyOf(e)] = blank();\n remember(\"made \" + subjectOf(e, i) + \" shorter\");\n tries = 0;\n render();\n if (missingPicture()) retryPicture();\n }\n\n function pathView(e, opts = {}) {\n const f = e ? flowOf(e) : blank();\n const a = f.audience;\n const picking = e && pick?.key === keyOf(e) && pick.kind === \"audience\";\n const test = {\n \"\": [\"\", \"To your own inbox\"], running: [\"run\", \"Sending\"], done: [\"done\", f.sentTo ? \"Sent to \" + f.sentTo : \"In your inbox\"],\n warn: [\"warn\", \"Not sent\"], asked: [\"asked\", \"Asked in the chat\"],\n }[f.test];\n const audience = a\n ? (a.chat ? [\"asked\", \"In the chat\"] : [\"done\", a.name + (a.count !== null ? \", \" + people(a.count) : \"\")])\n : [\"\", picking && !pick.loading && !pick.options.length ? \"No contacts yet\" : picking ? \"Pick who gets it\" : \"Your list, or bring one\"];\n const send = {\n \"\": [\"\", \"You approve on migma.ai\"], running: [\"run\", \"Preparing\"], waiting: [\"asked\", \"Waiting for your approval\"],\n sent: [\"done\", typeof f.approval?.count === \"number\" ? \"Sent to \" + people(f.approval.count) : \"Sent\"],\n warn: [\"warn\", \"Not sent\"], nosender: [\"warn\", \"Needs a sending address\"], asked: [\"asked\", \"Asked in the chat\"],\n }[f.send];\n const next = opts.faded || f.change ? \"\" : !test[0] || f.test === \"running\" ? \"test\" : !a ? \"audience\" : f.send !== \"sent\" && f.send !== \"asked\" ? \"send\" : \"\";\n const list = el(\"ol\", \"\", { className: opts.faded ? \"path faded\" : \"path\" });\n list.setAttribute(\"aria-label\", \"From ready to sent\");\n for (const [key, label, iconName, [state, value]] of [[\"test\", \"Test\", \"mail\", test], [\"audience\", \"Audience\", \"people\", audience], [\"send\", \"Send\", \"send\", send]]) {\n const li = el(\"li\", \"\", { className: \"step\" + (key === next ? \" next\" : \"\") + (state ? \" \" + state : \"\") });\n if (key === next) li.setAttribute(\"aria-current\", \"step\");\n const mark = el(\"span\", \"\", { className: \"s \" + (state || \"todo\") });\n if (state === \"done\") mark.append(icon(\"check\"));\n const k = el(\"span\", \"\", { className: \"k\" });\n k.append(icon(iconName), el(\"span\", label), mark);\n li.append(k, el(\"span\", value, { className: \"v\" }));\n list.append(li);\n }\n return list;\n }\n // What the last step left: the approval as it will go out, or why a step stopped.\n function stepNote(e) {\n const f = flowOf(e);\n const parts = [];\n if (f.approval && (f.send === \"waiting\" || f.send === \"sent\")) {\n const facts = el(\"dl\", \"\", { className: \"facts\" });\n const a = f.audience;\n 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]]) {\n facts.append(el(\"dt\", k), el(\"dd\", v));\n }\n parts.push(facts);\n if (f.approval.warning) parts.push(el(\"p\", f.approval.warning, { className: \"note warn\" }));\n }\n if (f.send === \"nosender\") parts.push(el(\"p\", \"Emails go out from your own address. Set it up once in Migma.\", { className: \"note small\" }));\n if (f.note) {\n const p = el(\"p\", f.note, { className: \"note warn\" });\n if (f.plans) {\n const plans = el(\"a\", \"See plans\", { href: PLANS_URL, className: \"plans\" });\n plans.addEventListener(\"click\", (event) => { event.preventDefault(); openLink(PLANS_URL); });\n p.append(\" \", plans);\n }\n parts.push(p);\n }\n if (f.change === \"running\") parts.push(el(\"p\", \"Making it shorter\", { className: \"note small\", role: \"status\" }));\n return parts;\n }\n function pickView(e) {\n if (!pick || pick.key !== keyOf(e)) return null;\n const box = el(\"div\", \"\", { className: \"pick\", role: \"group\" });\n box.setAttribute(\"aria-label\", pick.kind === \"sender\" ? \"Sender\" : \"Audience\");\n if (pick.loading) {\n box.append(el(\"p\", \"Who gets it\", { className: \"pick-h\" }), el(\"div\", \"\", { className: \"sk\", style: \"height:36px;width:60%\" }));\n return box;\n }\n if (!pick.options.length) {\n box.append(\n el(\"p\", \"No contacts yet\", { className: \"pick-h\" }),\n 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\" }),\n );\n return box;\n }\n const h = el(\"p\", pick.kind === \"sender\" ? \"Who it is from\" : \"Who gets it\", { className: \"pick-h\" });\n h.append(el(\"span\", pick.kind === \"sender\" ? \"Your sending addresses in Migma\" : \"From your contacts in Migma\"));\n const opts = el(\"div\", \"\", { className: \"opts\" });\n pick.options.forEach((o, n) => {\n const b = button(\"opt\", o.name, () => { pick.chosen = n; render(); });\n b.setAttribute(\"aria-pressed\", String(n === pick.chosen));\n if (pick.kind === \"sender\") b.append(el(\"small\", o.email));\n else if (o.count !== null) b.append(el(\"small\", o.count.toLocaleString(\"en-US\")));\n opts.append(b);\n });\n box.append(h, opts);\n return box;\n }\n function linkPrimary(label, url) {\n const b = button(\"primary\", label, () => openLink(url));\n b.append(icon(\"out\"));\n return b;\n }\n function nextButton(e, i) {\n const f = flowOf(e);\n if (f.change) return null;\n const p = pick?.key === keyOf(e) ? pick : null;\n if (p?.kind === \"sender\") return button(\"primary\", \"Send from \" + short(p.options[p.chosen].name), () => sendIt(e, i, p.options[p.chosen]));\n if (!f.test || f.test === \"running\") return button(\"primary\", \"Send me a test\", () => testIt(e, i), { disabled: f.test === \"running\" });\n if (!f.audience) {\n if (!p) return button(\"primary\", \"Choose audience\", () => chooseAudience(e, i));\n if (p.loading) return button(\"primary\", \"Choose audience\", () => {}, { disabled: true });\n if (!p.options.length) return linkPrimary(\"Add contacts in Migma\", CONTACTS_URL);\n return button(\"primary\", \"Use \" + short(p.options[p.chosen].name), () => useAudience(e));\n }\n if (f.send === \"nosender\") return linkPrimary(\"Set up sending in Migma\", SETUP_URL);\n if (f.send === \"waiting\") return linkPrimary(\"Approve on migma.ai\", f.approval.url);\n if (f.send === \"sent\") return f.approval.url ? linkPrimary(\"See results\", f.approval.url) : null;\n if (f.send === \"warn\" && f.plans) return button(\"primary\", \"Choose another list\", () => { f.audience = null; f.send = \"\"; chooseAudience(e, i); });\n if (f.send === \"warn\") return button(\"primary\", \"Try the send again\", () => sendIt(e, i));\n if (f.send === \"\" || f.send === \"running\") return button(\"primary\", \"Send\", () => sendIt(e, i), { disabled: f.send === \"running\" });\n return null;\n }\n function pathFoot(e, i) {\n const f = el(\"div\", \"\", { className: \"foot\" });\n const url = e.appUrl || s.appUrl;\n if (url) {\n const edit = button(\"ghost left\", \"Edit in Migma\", () => openLink(url));\n edit.append(icon(\"out\"));\n f.append(edit);\n }\n const next = nextButton(e, i);\n if (next) f.append(next);\n return f;\n }\n function readyLine(tools) {\n const line = el(\"div\", \"\", { className: \"ready\" });\n const fact = el(\"span\", \"\", { className: \"fact\" });\n fact.append(icon(\"check\"), el(\"span\", \"Works in every inbox\"));\n const mark = el(\"span\", \"\", { className: \"brand\" });\n mark.append(el(\"i\", \"\"), el(\"span\", \"Migma\"));\n line.append(el(\"span\", \"\", { className: \"dot ok\" }), el(\"span\", series() ? \"Email designs ready\" : \"Email design ready\"), fact, mark, ...tools);\n return line;\n }\n // A host that can neither run tools nor take messages shows the email and its link.\n const hasPath = (e) => !e.failed && !!(caps.message || caps.serverTools);\n\n // ---- views ----\n function compactView() {\n const line = el(\"div\", \"\", { className: \"line\", role: \"status\" });\n const many = (s.count || s.slots?.length || s.emails?.length || 1) > 1;\n if (s.phase === \"working\") {\n line.append(el(\"span\", \"\", { className: \"dot info\" }), el(\"span\", many ? \"Designing \" + (s.count || s.slots.length) + \" emails\" : \"Designing your email\", { className: \"t\" }));\n if (s.now) line.append(el(\"span\", s.now, { className: \"s\" }));\n line.append(el(\"span\", elapsed(), { className: \"time\" }));\n } else if (s.phase === \"failed\") {\n line.append(el(\"span\", \"\", { className: \"dot bad\" }), el(\"span\", \"Not created\", { className: \"t\" }), el(\"span\", s.error, { className: \"s\" }));\n } else {\n const first = s.emails.find((e) => e.picture);\n const thumb = el(\"span\", \"\", { className: \"thumb\" });\n if (first) thumb.append(el(\"img\", \"\", { src: first.picture, alt: \"\" }));\n line.append(thumb, el(\"span\", many ? s.emails.length + \" emails\" : s.emails[0].subject || \"Your email\", { className: \"t\" }), el(\"span\", \"Ready\", { className: \"s\" }));\n const show = button(\"ghost\", \"Show\", () => { s.compact = false; render(); if (missingPicture()) retryPicture(); });\n show.setAttribute(\"aria-expanded\", \"false\");\n line.append(show, linkButton(s.emails[0].appUrl || s.appUrl, true));\n }\n return [line];\n }\n\n function workingView() {\n if (s.mode === \"edit\") {\n const at = Math.max(0, EDIT_STEPS.findIndex(([, stages]) => stages.includes(s.stage)));\n return [\n head(s.before?.subject || \"Changing your email\", input.prompt),\n steps(EDIT_STEPS.map(([label], i) => [label, i < at ? \"done\" : i === at ? \"now\" : \"todo\"])),\n s.before?.picture ? stage(s.before, { dim: true }) : stage(null, { short: true }),\n foot([], s.before?.appUrl || s.appUrl, false),\n ];\n }\n const count = s.count || s.slots?.length || 1;\n const parts = [\n head(count > 1 ? \"Designing \" + count + \" emails\" : \"Designing your email\", input.prompt),\n steps([...(s.steps || []).map((label) => [label, \"done\"]), [s.now || \"Starting\", \"now\"]]),\n ];\n if (count > 1) {\n const slots = el(\"div\", \"\", { className: \"slots\" });\n for (let i = 0; i < count; i++) {\n const done = s.slots?.[i] && !s.slots[i].pending;\n const slot = el(\"div\", \"\", { className: done ? \"slot done\" : \"slot\" });\n const frame = el(\"div\", \"\", { className: \"frame\" });\n frame.append(done ? icon(\"check\", true) : el(\"span\", \"\", { className: \"dot info\" }));\n const lab = el(\"div\", \"\", { className: \"lab\" });\n lab.append(el(\"span\", \"Email \" + (i + 1)), el(\"span\", done ? \"Done\" : \"Designing\"));\n slot.append(frame, lab);\n slots.append(slot);\n }\n parts.push(slots);\n } else {\n parts.push(stage(null, { short: true }));\n }\n // What comes next, faded, while people wait.\n if (caps.message) parts.push(el(\"p\", \"Next, without leaving the chat\", { className: \"note small\" }), pathView(null, { faded: true }));\n parts.push(foot([], s.appUrl, false));\n return parts;\n }\n\n function failedView() {\n if (s.mode === \"edit\") {\n const e = s.before;\n const parts = [statusLine(\"Not changed\", \"bad\"), head(e?.subject || \"Your email\", input.prompt), el(\"p\", s.error, { className: \"note bad\" })];\n if (s.mayHaveSaved) parts.push(el(\"p\", \"Some changes may have been saved. Check the email in Migma before you try again.\", { className: \"note warn\" }));\n if (e?.picture) parts.push(stage(e));\n parts.push(foot(input.prompt && !s.refused ? [[\"Try again\", \"Try that change to \" + (e ? quoted(e) : \"the email\") + \" again.\"]] : [], e?.appUrl || s.appUrl, true));\n return parts;\n }\n if (s.mode === \"email\") return [statusLine(\"Could not show this email\", \"bad\"), el(\"p\", s.error, { className: \"note bad\" })];\n const many = (s.count || 1) > 1;\n return [\n statusLine(\"Not created\", \"bad\"),\n head(many ? \"Your emails\" : \"Your email\", input.prompt),\n el(\"p\", s.error, { className: \"note bad\" }),\n foot(input.prompt && !s.refused ? [[\"Try again\", many ? \"Try creating those emails again.\" : \"Try creating that email again.\"]] : [], s.appUrl, false),\n ];\n }\n\n function readyView() {\n const e = s.emails[sel];\n const full = canFullScreen() ? [button(\"icon-btn\", \"\", () => displayMode(\"fullscreen\"), { ariaLabel: \"Full screen\" })] : [];\n full[0]?.append(icon(\"expand\"));\n const title = e.failed ? \"Email \" + (sel + 1) + \" was not created\" : e.subject || \"Your email\";\n const parts = e.failed ? [head(title, \"\", full)] : [readyLine(full), head(title, e.preheader)];\n if (series()) parts.push(tabs());\n parts.push(stage(e, { first: true, dim: !e.failed && flowOf(e).change === \"running\" }));\n if (!hasPath(e)) {\n parts.push(foot(e.failed ? readyAsks(e, sel) : [], e.appUrl || s.appUrl, true));\n return parts;\n }\n parts.push(pathView(e), ...stepNote(e));\n const picking = pickView(e);\n if (picking) parts.push(picking);\n parts.push(pathFoot(e, sel));\n return parts;\n }\n\n function fullScreenView() {\n const e = s.emails[sel];\n const back = button(\"icon-btn\", \"\", () => displayMode(\"inline\"), { ariaLabel: \"Back to the chat\" });\n back.append(icon(\"collapse\"));\n const box = el(\"section\", \"\", { className: \"fs\" });\n const body = el(\"div\", \"\", { className: \"fs-body\" });\n if (series()) {\n const rail = el(\"nav\", \"\", { className: \"rail\" });\n rail.setAttribute(\"aria-label\", \"Emails in this series\");\n s.emails.forEach((x, i) => {\n const item = button(\"rail-item\", \"\", () => select(i));\n if (i === sel) item.setAttribute(\"aria-current\", \"true\");\n const thumb = el(\"div\", \"\", { className: \"thumb\" });\n thumb.append(x.picture ? el(\"img\", \"\", { src: x.picture, alt: \"\" }) : icon(x.failed ? \"alert\" : \"image\", true));\n item.append(thumb, el(\"span\", (i + 1) + (x.failed ? \" \u00B7 Not created\" : x.day !== null ? \" \u00B7 Day \" + x.day : \"\")));\n rail.append(item);\n });\n body.append(rail);\n }\n const wrap = el(\"div\", \"\", { className: \"fs-wrap\" });\n wrap.append(stage(e));\n if (series()) {\n const prev = button(\"step-btn prev\", \"\", () => select(sel - 1), { ariaLabel: \"Previous email\", disabled: sel === 0 });\n const next = button(\"step-btn next\", \"\", () => select(sel + 1), { ariaLabel: \"Next email\", disabled: sel === s.emails.length - 1 });\n prev.append(icon(\"prev\")); next.append(icon(\"next\"));\n wrap.append(prev, next);\n }\n const desk = el(\"div\", \"\", { className: \"desk\" });\n desk.append(wrap);\n if (hasPath(e)) {\n // The path beside the whole email; changes to the email live here, where there is room.\n const panel = el(\"aside\", \"\", { className: \"panel\" });\n panel.setAttribute(\"aria-label\", \"From ready to sent\");\n panel.append(el(\"h2\", \"From ready to sent\"), pathView(e), ...stepNote(e));\n const picking = pickView(e);\n if (picking) panel.append(picking);\n panel.append(asks(readyAsks(e, sel)));\n desk.append(panel);\n }\n body.append(desk);\n box.append(head(e.failed ? \"Email \" + (sel + 1) + \" was not created\" : e.subject || \"Your email\", e.failed ? \"\" : e.preheader, [back]));\n if (series()) box.append(tabs());\n box.append(body, hasPath(e) ? pathFoot(e, sel) : foot(readyAsks(e, sel), e.appUrl || s.appUrl, true));\n if (s.note) box.append(el(\"p\", s.note, { className: \"note small\" }));\n return [box];\n }\n\n function render() {\n const main = $(\"card\");\n main.setAttribute(\"aria-busy\", String(s.phase === \"working\" && !s.compact));\n let parts;\n if (s.compact) parts = compactView();\n else if (fullScreen()) parts = fullScreenView();\n else parts = s.phase === \"working\" ? workingView() : s.phase === \"failed\" ? failedView() : readyView();\n if (s.note && !fullScreen()) parts.push(el(\"p\", s.note, { className: \"note small\" }));\n main.replaceChildren(...parts);\n // ChatGPT's own \"Open in\" button in full screen opens this card's page unless told otherwise.\n const link = s.emails?.[sel]?.appUrl || s.before?.appUrl || s.appUrl;\n if (link) window.openai?.setOpenInAppUrl?.({ href: link });\n tick();\n }\n\n new ResizeObserver(() => send({ method: \"ui/notifications/size-changed\", params: { height: Math.ceil(document.documentElement.getBoundingClientRect().height) } }))\n .observe(document.documentElement);\n\n const init = await request(\"ui/initialize\", {\n appInfo: { name: \"Migma email\", version: \"1.0.0\" },\n appCapabilities: { availableDisplayModes: [\"inline\", \"fullscreen\"] },\n protocolVersion: \"2026-01-26\",\n });\n caps = init?.hostCapabilities ?? {};\n applyHost(init?.hostContext);\n send({ method: \"ui/notifications/initialized\", params: {} });\n</script>\n</body>\n</html>\n";
|
|
20
|
+
export declare const EMAIL_CARD_HTML = "<!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<meta name=\"color-scheme\" content=\"light dark\">\n<title>Email</title>\n<style>\n :root {\n color-scheme: light dark;\n --surface: var(--color-background-primary, light-dark(#ffffff, #30302e));\n --muted: var(--color-background-secondary, light-dark(#f5f4ed, #262624));\n --text: var(--color-text-primary, light-dark(#141413, #faf9f5));\n --text-2: var(--color-text-secondary, light-dark(#3d3d3a, #c2c0b6));\n --text-3: var(--color-text-tertiary, light-dark(#73726c, #9c9a92));\n --line: var(--color-border-tertiary, light-dark(rgb(31 30 29 / 15%), rgb(222 220 209 / 15%)));\n --line-2: var(--color-border-secondary, light-dark(rgb(31 30 29 / 30%), rgb(222 220 209 / 30%)));\n --inverse: var(--color-background-inverse, light-dark(#141413, #faf9f5));\n --on-inverse: var(--color-text-inverse, light-dark(#ffffff, #141413));\n --info: var(--color-border-info, light-dark(#4682d5, #6c9be0));\n --success: var(--color-border-success, light-dark(#437426, #7fb05b));\n --success-text: var(--color-text-success, light-dark(#265b19, #7ab948));\n --danger: var(--color-border-danger, light-dark(#a73d39, #d1615c));\n --warning: var(--color-border-warning, light-dark(#8a6a12, #d1a041));\n --bone: color-mix(in srgb, var(--text) 9%, transparent);\n --radius: var(--border-radius-lg, 10px);\n --radius-md: var(--border-radius-md, 8px);\n }\n * { box-sizing: border-box; }\n html, body { margin: 0; background: transparent; }\n body {\n font-family: var(--font-sans, system-ui, -apple-system, sans-serif);\n font-size: var(--font-text-sm-size, 14px);\n line-height: var(--font-text-sm-line-height, 1.4);\n color: var(--text);\n -webkit-font-smoothing: antialiased;\n }\n p, h1, ul { margin: 0; }\n button { font: inherit; cursor: pointer; }\n button:focus-visible { outline: 2px solid var(--color-ring-primary, var(--info)); outline-offset: 2px; }\n button[disabled] { cursor: default; opacity: .45; }\n main {\n container-type: inline-size;\n display: flex; flex-direction: column; gap: 14px;\n padding: calc(16px + var(--inset-top, 0px)) calc(16px + var(--inset-right, 0px)) calc(16px + var(--inset-bottom, 0px)) calc(16px + var(--inset-left, 0px));\n }\n .i { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; }\n .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--text-3); }\n .dot.info { background: var(--info); } .dot.ok { background: var(--success); } .dot.bad { background: var(--danger); } .dot.warn { background: var(--warning); }\n .time { margin-left: auto; color: var(--text-3); font-variant-numeric: tabular-nums; flex: none; }\n .note { color: var(--text-3); font-size: 13px; overflow-wrap: anywhere; }\n .h { font-size: 20px; line-height: 1.25; font-weight: var(--font-weight-semibold, 600); letter-spacing: -.01em; overflow-wrap: anywhere; text-wrap: balance; }\n .pre { margin-top: 6px; color: var(--text-3); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }\n .why { color: var(--text-2); overflow-wrap: anywhere; }\n\n /* The brand the emails were made from. */\n .brand { display: flex; align-items: center; gap: 10px; min-height: 22px; min-width: 0; font-size: 13px; color: var(--text-2); }\n .brand .logo { width: 22px; height: 22px; flex: none; border-radius: 6px; object-fit: contain; background: var(--muted); }\n .brand .mono { width: 22px; height: 22px; flex: none; border-radius: 6px; display: grid; place-items: center; font-size: 12px; font-weight: 600; }\n .brand b { color: var(--text); font-weight: var(--font-weight-semibold, 600); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .brand .dots { display: flex; gap: 4px; flex: none; }\n .brand .dots i { width: 12px; height: 12px; border-radius: 50%; box-shadow: 0 0 0 0.5px var(--line-2); }\n .brand .type { color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .brand .fact { margin-left: auto; flex: none; display: inline-flex; gap: 6px; align-items: center; color: var(--text-3); white-space: nowrap; }\n .brand .fact .i { width: 14px; height: 14px; color: var(--success); stroke-width: 2.25; }\n\n /* Every email as a poster: the top of the email, side by side. */\n .rowwrap { position: relative; }\n .row { display: flex; gap: 16px; min-width: 0; }\n .poster { flex: 1 1 0; min-width: 0; max-width: 240px; display: flex; flex-direction: column; gap: 9px; color: var(--text-3); }\n .row.two .poster { max-width: none; }\n .row.two .pic { aspect-ratio: 1 / 1; }\n .row.many { overflow-x: auto; scroll-snap-type: x proximity; scrollbar-width: none; margin: -6px calc(-16px - var(--inset-right, 0px)) -6px -6px; padding: 6px 16px 6px 6px; }\n .row.many .poster { flex: none; width: 184px; scroll-snap-align: start; }\n .pic { position: relative; display: block; width: 100%; aspect-ratio: 3 / 4; max-height: var(--pic-max, none); padding: 0; border: 0; border-radius: var(--radius); overflow: hidden; background: var(--muted); box-shadow: 0 0 0 0.5px var(--line-2); color: inherit; text-align: left; }\n .pic img { display: block; width: 100%; height: auto; }\n .pic.dim img { opacity: .4; }\n .poster.on .pic { outline: 2px solid var(--text); outline-offset: 3px; }\n .cap { display: flex; gap: 8px; align-items: baseline; min-width: 0; padding: 0 1px; font-size: 13px; }\n .cap b { flex: 1; min-width: 0; font-weight: var(--font-weight-medium, 500); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .poster.on .cap b { color: var(--text); font-weight: var(--font-weight-semibold, 600); }\n .cap span { flex: none; }\n .cap .ok { color: var(--success-text); font-weight: var(--font-weight-medium, 500); }\n .open { position: absolute; right: 8px; bottom: 8px; width: 32px; height: 32px; border-radius: 50%; display: grid; place-items: center; background: #ffffff; color: #141413; box-shadow: 0 1px 4px rgb(0 0 0 / 18%), 0 0 0 0.5px rgb(0 0 0 / 10%); }\n .sk { display: block; margin: 14px 14px 0; border-radius: 5px; background: var(--bone); }\n .mid { position: absolute; inset: 0; display: grid; place-items: center; align-content: center; gap: 8px; padding: 12px; color: var(--text-3); font-size: 13px; text-align: center; }\n .mid .i { width: 22px; height: 22px; }\n .pill { display: inline-flex; gap: 8px; align-items: center; padding: 6px 12px; border-radius: 999px; background: var(--surface); box-shadow: 0 0 0 0.5px var(--line-2); color: var(--text-2); }\n .done { position: absolute; right: 8px; top: 8px; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; background: var(--success); color: #ffffff; }\n .done .i { width: 13px; height: 13px; stroke-width: 2.5; }\n .next { position: absolute; right: 0; top: 104px; width: 36px; height: 36px; border: 0; border-radius: 50%; display: grid; place-items: center; background: #ffffff; color: #141413; box-shadow: 0 1px 4px rgb(0 0 0 / 18%), 0 0 0 0.5px rgb(0 0 0 / 10%); }\n\n /* The whole email in place, where the host has no full screen. */\n .whole { align-self: center; width: min(600px, 100%); border-radius: var(--radius-md); overflow: hidden; background: var(--surface); box-shadow: 0 0 0 0.5px var(--line-2); }\n .whole img { display: block; width: 100%; height: auto; }\n\n /* One email: its poster beside its subject and the controls. */\n .one { display: flex; gap: 24px; min-width: 0; }\n .one .poster { flex: none; width: 232px; max-width: none; }\n .side { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 14px; }\n .grow { flex: 1; }\n\n /* Who gets it, in any order. */\n .to { position: relative; display: flex; gap: 10px; align-items: flex-start; }\n .to .k { flex: none; width: 38px; color: var(--text-3); font-size: 13px; line-height: 32px; }\n .chips { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }\n .chip { display: inline-flex; gap: 7px; align-items: center; min-height: 32px; max-width: 100%; padding: 0 13px; border: 0.5px solid var(--line-2); border-radius: 999px; background: transparent; color: var(--text); font-size: 13.5px; font-weight: var(--font-weight-medium, 500); white-space: nowrap; }\n .chip .n { overflow: hidden; text-overflow: ellipsis; }\n .chip small { font-size: 12.5px; font-weight: 400; color: var(--text-3); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; }\n .chip[aria-pressed=\"true\"] { background: var(--inverse); border-color: var(--inverse); color: var(--on-inverse); }\n .chip[aria-pressed=\"true\"] small, .chip[aria-pressed=\"true\"] .i { color: inherit; opacity: .72; }\n .chip:not([aria-pressed=\"true\"]):hover, .btn.ghost:hover, .ref:hover, .x:hover { background: var(--muted); }\n .chip.more { border-style: dashed; color: var(--text-2); }\n .chip .i { width: 13px; height: 13px; color: var(--text-3); }\n .chip .dot { width: 7px; height: 7px; }\n .ref { width: 32px; height: 32px; flex: none; display: grid; place-items: center; border: 0; border-radius: 50%; background: transparent; color: var(--text-3); }\n\n /* The two actions, and what happened. */\n .foot { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }\n .btn { display: inline-flex; gap: 7px; align-items: center; justify-content: center; min-height: 38px; padding: 0 16px; border-radius: var(--radius); white-space: nowrap; font-weight: var(--font-weight-semibold, 600); }\n .btn.primary { border: 0; background: var(--inverse); color: var(--on-inverse); }\n .btn.ghost { border: 0.5px solid var(--line-2); background: transparent; color: var(--text); font-weight: var(--font-weight-medium, 500); }\n .st { margin-left: auto; min-width: 0; display: inline-flex; gap: 8px; align-items: center; color: var(--text-2); font-size: 13.5px; overflow-wrap: anywhere; }\n .said { margin-left: auto; min-width: 0; display: flex; flex-direction: column; align-items: flex-end; gap: 3px; }\n .said .st { margin-left: 0; }\n .st a { color: inherit; text-decoration: underline; text-underline-offset: 3px; }\n .nums { display: inline-flex; gap: 14px; color: var(--text-3); }\n .nums b { margin-right: 5px; color: var(--text); font-weight: var(--font-weight-semibold, 600); font-variant-numeric: tabular-nums; }\n .steps { list-style: none; padding: 0; display: grid; gap: 6px; color: var(--text-3); font-size: 13.5px; }\n .steps li { display: flex; gap: 8px; align-items: center; min-width: 0; }\n .steps .l { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .steps .i { width: 14px; height: 14px; color: var(--success); stroke-width: 2.25; }\n .steps .now { color: var(--text); }\n .steps .now .dot { margin: 0 3px; }\n\n /* A status check: one line that opens in place. */\n .line { display: flex; gap: 10px; align-items: center; min-height: 36px; min-width: 0; color: var(--text-2); }\n .line .t { min-width: 0; color: var(--text); font-weight: var(--font-weight-semibold, 600); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .line .s { min-width: 0; color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .line .mini { width: 36px; height: 48px; flex: none; border-radius: 6px; overflow: hidden; background: var(--muted); box-shadow: 0 0 0 0.5px var(--line-2); }\n .line .mini img { display: block; width: 100%; }\n .line .btn { min-height: 32px; padding: 0 12px; font-size: 13.5px; flex: none; }\n .line .btn:first-of-type { margin-left: auto; }\n\n /* The big view (full screen, or the side panel): every email whole, side by side. */\n :root:has(.big), :root:has(.big) body { height: 100%; }\n main:has(.big) { height: 100%; padding: 0; gap: 0; }\n .big { height: 100%; min-height: 0; display: flex; flex-direction: column; }\n .top { display: flex; align-items: center; gap: 12px; min-height: 52px; padding: var(--inset-top, 0px) calc(20px + var(--inset-right, 0px)) 0 calc(20px + var(--inset-left, 0px)); border-bottom: 0.5px solid var(--line); }\n .top .h { flex: 1; min-width: 0; font-size: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }\n .x { width: 32px; height: 32px; flex: none; display: grid; place-items: center; border: 0; border-radius: var(--radius-md); background: transparent; color: var(--text-2); }\n .strip { display: none; gap: 10px; padding: 12px calc(20px + var(--inset-right, 0px)) 12px calc(20px + var(--inset-left, 0px)); border-bottom: 0.5px solid var(--line); overflow-x: auto; scrollbar-width: none; }\n .strip button { width: 54px; height: 72px; flex: none; padding: 0; border: 0; border-radius: 6px; overflow: hidden; background: var(--muted); box-shadow: 0 0 0 0.5px var(--line-2); display: grid; place-items: center; color: var(--text-3); }\n .strip img { display: block; width: 100%; align-self: start; }\n .strip button[aria-current=\"true\"] { outline: 2px solid var(--text); outline-offset: 2px; }\n .wall { flex: 1; min-height: 0; display: flex; justify-content: safe center; align-items: flex-start; gap: 28px; padding: 28px; background: var(--muted); overflow: auto; overscroll-behavior: contain; }\n .col { width: 340px; flex: none; display: flex; flex-direction: column; gap: 10px; color: var(--text-3); font-size: 13px; }\n .col.only { width: min(600px, 100%); }\n .col .pic { aspect-ratio: auto; max-height: none; min-height: 200px; border-radius: var(--radius-md); background: var(--surface); }\n .col.on .pic { outline: 2px solid var(--text); outline-offset: 3px; }\n .col.only .pic { outline: 0; }\n .col.on .cap b { color: var(--text); font-weight: var(--font-weight-semibold, 600); }\n .bar { display: flex; flex-direction: column; gap: 12px; padding: 14px calc(20px + var(--inset-right, 0px)) calc(16px + var(--inset-bottom, 0px)) calc(20px + var(--inset-left, 0px)); border-top: 0.5px solid var(--line); background: var(--surface); }\n\n @container (max-width: 720px) {\n .strip { display: flex; }\n .wall { padding: 20px; }\n .col { display: none; width: 100%; }\n .col.on { display: flex; }\n .col.on .pic { outline: 0; }\n .col .cap { display: none; }\n }\n @container (max-width: 520px) {\n .brand .type { display: none; }\n .row { overflow-x: auto; scroll-snap-type: x proximity; scrollbar-width: none; margin: -6px calc(-16px - var(--inset-right, 0px)) -6px -6px; padding: 6px 16px 6px 6px; gap: 12px; }\n .row .poster, .row.two .poster, .row.many .poster { flex: none; width: 150px; scroll-snap-align: start; }\n .row.two .pic { aspect-ratio: 3 / 4; }\n .next { display: none; }\n .one { flex-direction: column; gap: 14px; }\n .one .poster { width: 100%; }\n .one .pic { aspect-ratio: 5 / 4; }\n .to { flex-direction: column; gap: 4px; }\n .to .k { width: auto; line-height: 1.4; }\n .to .ref { position: absolute; right: -8px; top: -14px; width: 44px; height: 44px; }\n .chip { min-height: 44px; padding: 0 16px; }\n .btn { min-height: 46px; flex: 1; }\n .line .btn { min-height: 44px; flex: none; }\n .st, .said { order: -1; width: 100%; margin-left: 0; }\n .said { align-items: flex-start; }\n .nums { flex-wrap: wrap; gap: 4px 12px; }\n }\n @container (max-width: 380px) { .brand .dots { display: none; } }\n\n @media (prefers-reduced-motion: no-preference) {\n .pulse { animation: pulse 1.4s ease-in-out infinite; }\n .spin .i { animation: spin 0.9s linear infinite; }\n @keyframes spin { to { transform: rotate(360deg); } }\n @keyframes pulse { 50% { opacity: .45; } }\n }\n</style>\n</head>\n<body>\n<main id=\"card\" aria-busy=\"true\">\n <div class=\"sk\" style=\"height:16px;width:40%;margin:0\"></div>\n <div class=\"sk\" style=\"height:12px;width:70%;margin:0\"></div>\n <div class=\"sk\" style=\"height:180px;margin:0\"></div>\n</main>\n<script type=\"module\">\n const ICON = {\n expand: '<path d=\"M15 3h6v6M9 21H3v-6M21 3l-7 7M3 21l7-7\"/>',\n collapse: '<path d=\"M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7\"/>',\n out: '<path d=\"M7 17L17 7M8 7h9v9\"/>',\n check: '<path d=\"M5 12l5 5L20 7\"/>',\n next: '<path d=\"M9 18l6-6-6-6\"/>',\n 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\"/>',\n alert: '<circle cx=\"12\" cy=\"12\" r=\"9\"/><path d=\"M12 8v4M12 16h.01\"/>',\n refresh: '<path d=\"M20 11a8 8 0 1 0-2.3 6.3M20 4v7h-7\"/>',\n };\n const CONTACTS_URL = \"https://migma.ai/contacts/imports\";\n const SETUP_URL = \"https://migma.ai/sending-domains\";\n const PLANS_URL = \"https://migma.ai/pricing\";\n const EDIT_STEPS = [[\"Checking the email\", [\"queued\", \"checking\"]], [\"Changing it\", [\"editing\"]], [\"Saving\", [\"saved\"]]];\n const PICTURE_TRIES = 4;\n // Lists and emails are read again when the user comes back to the card, at most this often.\n const REREAD_MS = 30000;\n const TOP_LISTS = 3;\n // Other places an email can go. Out of sight until More is opened.\n const TOOLS = [[\"tool:klaviyo\", \"Klaviyo\"], [\"tool:mailchimp\", \"Mailchimp\"], [\"tool:hubspot\", \"HubSpot\"], [\"tool:html\", \"HTML\"]];\n const $ = (id) => document.getElementById(id);\n const el = (tag, text, attrs = {}) => Object.assign(document.createElement(tag), { textContent: text ?? \"\" }, attrs);\n function icon(name) {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"class\", \"i\");\n svg.setAttribute(\"viewBox\", \"0 0 24 24\");\n svg.setAttribute(\"aria-hidden\", \"true\");\n svg.innerHTML = ICON[name];\n return svg;\n }\n // Every control carries a key, so the one in use keeps the keyboard focus when the card redraws.\n function button(className, label, onclick, key, attrs = {}) {\n const b = el(\"button\", label, { type: \"button\", className, ...attrs });\n if (key) b.dataset.k = key;\n b.addEventListener(\"click\", onclick);\n return b;\n }\n const https = (url) => (typeof url === \"string\" && url.startsWith(\"https://\") ? url : \"\");\n const num = (value) => (typeof value === \"number\" && value > 0 ? value : 0);\n\n let host = {}, caps = {}, input = {}, s = null, sel = 0, nextId = 1, timer = 0, ticker = 0, delay = 3000, tries = 0, busy = false;\n // Raised by each tool result. A read that started before it belongs to what the card showed\n // then, and its answer is dropped.\n let turn = 0;\n // Nothing here has an order. Each email keeps who it goes to and what happened for each audience;\n // the brand, its lists and its sending addresses are read from Migma, never kept from an earlier look.\n let brand = \"\", brandInfo = null, brandAsked = false, lists = null, listsOff = false, listsBusy = false, asking = false, known = null, more = false, whole = false, rereadAt = 0, senders = null, from = 0, flow = {}, history = [];\n const pending = new Map();\n\n function send(msg) { window.parent.postMessage({ jsonrpc: \"2.0\", ...msg }, \"*\"); }\n function request(method, params, ms) {\n const id = nextId++;\n send({ id, method, params });\n return new Promise((resolve, reject) => {\n pending.set(id, { resolve, reject });\n // A host that never answers must not stall the card's reads.\n if (ms) setTimeout(() => pending.delete(id) && reject(new Error(\"timeout\")), ms);\n });\n }\n\n window.addEventListener(\"message\", (event) => {\n if (event.source !== window.parent) return;\n const msg = event.data;\n if (!msg || msg.jsonrpc !== \"2.0\") return;\n if (msg.id !== undefined && !msg.method) {\n const waiter = pending.get(msg.id);\n pending.delete(msg.id);\n if (waiter) msg.error ? waiter.reject(msg.error) : waiter.resolve(msg.result);\n return;\n }\n if (msg.id !== undefined) {\n // Host requests (ping, teardown) need an answer; this card holds no state to save.\n send({ id: msg.id, result: {} });\n return;\n }\n if (msg.method === \"ui/notifications/tool-input\") input = msg.params?.arguments ?? {};\n if (msg.method === \"ui/notifications/tool-result\") onResult(msg.params);\n if (msg.method === \"ui/notifications/host-context-changed\") { applyHost(msg.params); if (s) render(); }\n });\n\n function applyHost(ctx = {}) {\n host = { ...host, ...ctx };\n const root = document.documentElement;\n if (ctx.theme) { root.dataset.theme = ctx.theme; root.style.colorScheme = ctx.theme; }\n for (const [key, value] of Object.entries(ctx.styles?.variables ?? {})) if (value) root.style.setProperty(key, value);\n if (ctx.styles?.css?.fonts && !$(\"host-fonts\")) document.head.append(el(\"style\", ctx.styles.css.fonts, { id: \"host-fonts\" }));\n const inset = ctx.safeAreaInsets;\n if (inset) for (const side of [\"top\", \"right\", \"bottom\", \"left\"]) root.style.setProperty(\"--inset-\" + side, (inset[side] || 0) + \"px\");\n root.dataset.mode = host.displayMode || \"inline\";\n // Inline there is no scrolling inside the card: a poster gives up height before the card\n // passes what the host allows.\n const max = host.containerDimensions?.maxHeight;\n root.style.setProperty(\"--pic-max\", max ? Math.max(150, max - 270) + \"px\" : \"none\");\n }\n\n // Each tool puts its JSON in one text item among others (a lead sentence, guidance, the Previews list).\n const texts = (result) => (result?.content ?? []).filter((c) => c.type === \"text\").map((c) => c.text);\n function json(result) {\n for (const text of texts(result)) {\n try { const value = JSON.parse(text); if (value && typeof value === \"object\" && !Array.isArray(value)) return value; } catch {}\n }\n return null;\n }\n // Lists come back as an array, or as an object holding one.\n function rows(result) {\n for (const text of texts(result)) {\n try {\n const value = JSON.parse(text);\n if (Array.isArray(value)) return value;\n for (const key of [\"data\", \"segments\", \"tags\", \"items\"]) if (Array.isArray(value?.[key])) return value[key];\n } catch {}\n }\n return null;\n }\n function toEmail(e = {}, link = \"\") {\n const picture = https(e.screenshotFullUrl) || https(e.screenshotUrl) || https(e.thumbnailUrl);\n return {\n emailId: e.emailId || e.id || \"\",\n conversationId: typeof e.conversationId === \"string\" ? e.conversationId : \"\",\n subject: e.subject || \"\",\n preheader: e.preheader || e.previewText || \"\",\n picture,\n // Which version of the email this is: when Migma last saved it, or what it shows.\n version: typeof e.updatedAt === \"string\" && e.updatedAt ? e.updatedAt : (e.subject || \"\") + \"|\" + picture,\n appUrl: https(e.appUrl) || link,\n failed: e.status === \"failed\",\n day: typeof e.sendOffsetDays === \"number\" ? e.sendOffsetDays : null,\n };\n }\n\n function onResult(result) {\n clearTimeout(timer);\n turn++;\n sel = 0; tries = 0; busy = false;\n const data = json(result);\n // The brand, for its look, lists and senders: the tool input names it on hosted servers.\n brand = (typeof input.projectId === \"string\" && input.projectId) || (typeof data?.projectId === \"string\" && data.projectId) || \"\";\n brandInfo = null; brandAsked = false; lists = null; listsOff = false; listsBusy = false; asking = false; known = null; more = false; whole = false; flow = {}; history = [];\n if (result?.isError || !data || (data.error && !data.conversationId && !data.editId)) {\n const mode = input.emailId && input.prompt ? \"edit\" : input.prompt ? \"create\" : \"email\";\n // Refused before anything started (a limit, a locked email): trying again would only repeat it.\n s = { mode, phase: \"failed\", refused: true, emailId: input.emailId, count: input.count, error: (typeof data?.error === \"string\" && data.error) || (!data && texts(result)[0]) || \"Migma could not do this.\" };\n render();\n if (mode === \"edit\") readBefore();\n return;\n }\n if (data.editId) {\n s = { mode: \"edit\", phase: \"working\", emailId: data.emailId, editId: data.editId, appUrl: https(data.appUrl), createdAt: data.createdAt, stage: data.stage };\n delay = data.pollAfterMs || 2000;\n render();\n readBefore();\n poll();\n } else if (data.emailId && \"subject\" in data) {\n s = { mode: \"email\", phase: \"ready\", emails: [toEmail(data)] };\n render();\n if (missingPicture()) retryPicture();\n } else if (data.conversationId) {\n // A status check draws one line that turns into a Ready row, which opens in place. It keeps\n // itself current: ChatGPT shows only the last card of a reply, so the generate call's card may\n // never be seen.\n s = { mode: \"create\", phase: \"working\", compact: !!data.createdAt && !input.prompt, conversationId: data.conversationId, appUrl: https(data.appUrl), count: data.count || input.count };\n applyStatus(data);\n // Slower than the full card: several status lines can poll at once, and hosted MCP allows 100 calls a minute.\n delay = s.compact ? 6000 : 3000;\n render();\n poll();\n }\n }\n\n function applyStatus(d) {\n if (d.createdAt) s.createdAt = d.createdAt;\n if (!brand && typeof d.projectId === \"string\") brand = d.projectId;\n if (d.status === \"failed\") { s.phase = \"failed\"; s.error = d.error || \"Migma could not create this email.\"; return; }\n if (d.status === \"completed\") {\n const r = d.result || {};\n const list = Array.isArray(r.emails) && r.emails.length ? r.emails : [r];\n s.emails = list.map((e) => toEmail(e, s.appUrl));\n s.phase = \"ready\";\n return;\n }\n const p = d.progress || {};\n const events = Array.isArray(p.events) ? p.events.filter((e) => e?.label) : [];\n const done = [...new Set(events.filter((e) => e.status === \"complete\").map((e) => e.label))];\n const live = p.now?.label && (p.now.status === \"start\" || p.now.status === \"progress\") ? p.now.label : \"\";\n s.now = live || events.filter((e) => e.status === \"processing\").pop()?.label || s.now || \"\";\n s.steps = done.filter((label) => label !== s.now).slice(-2);\n if (Array.isArray(p.slots) && p.slots.length) s.slots = p.slots;\n }\n\n function applyEdit(d) {\n if (d.createdAt) s.createdAt = d.createdAt;\n s.stage = d.stage || s.stage;\n if (d.status === \"completed\") {\n s.mode = \"email\"; s.phase = \"ready\";\n s.emails = [unchanged(toEmail(d.result || { emailId: s.emailId, subject: s.before?.subject }, s.before?.appUrl || s.appUrl), s.before?.picture)];\n } else if (d.status === \"failed\") {\n s.phase = \"failed\"; s.error = d.error || \"Migma could not change this email.\"; s.mayHaveSaved = !!d.changesMayHaveBeenSaved;\n }\n }\n\n // Right after a change the email can still carry its old picture until Migma captures the new\n // one: wait for a different picture, and show the old one only once the retries run out.\n function unchanged(e, old) {\n if (e.picture && e.picture === old) { e.stale = e.picture; e.picture = \"\"; }\n return e;\n }\n\n // Tried even when the host does not list serverTools or openLinks: a refusal falls back.\n async function read(name, args) {\n try {\n const result = await request(\"tools/call\", { name, arguments: args }, 30000);\n return result?.isError ? null : json(result);\n } catch { return null; }\n }\n\n async function readBefore() {\n if (!s?.emailId) return;\n const mine = turn;\n const d = await read(\"migma_get_email\", { emailId: s.emailId });\n if (mine !== turn || !d?.emailId || s.mode === \"email\") return;\n s.before = toEmail(d);\n if (!brand && typeof d.projectId === \"string\") brand = d.projectId;\n render();\n }\n\n async function poll() {\n clearTimeout(timer);\n if (!s || s.phase !== \"working\" || busy || document.visibilityState !== \"visible\") return;\n busy = true;\n const mine = turn;\n const d = s.mode === \"create\"\n ? await read(\"migma_get_generation_status\", { conversationId: s.conversationId })\n : await read(\"migma_get_email_edit_status\", { emailId: s.emailId, editId: s.editId });\n if (mine !== turn) return;\n if (s.mode === \"create\") { if (d?.conversationId) applyStatus(d); } else if (d?.status) applyEdit(d);\n busy = false;\n render();\n if (s.phase === \"working\") {\n // ponytail: backoff to one read every 15 s; a push from Migma would replace polling if hosts add it.\n timer = setTimeout(poll, delay);\n delay = Math.min(delay * 1.4, 15000);\n } else if (missingPicture()) retryPicture();\n }\n\n const missingPicture = () => s?.phase === \"ready\" && s.emails.some((e) => !e.failed && !e.picture);\n // The picture is captured after the email is saved. Each read returns every picture of the\n // run, so try a few times, further apart, then say it is ready in Migma.\n function retryPicture() {\n clearTimeout(timer);\n if (tries >= PICTURE_TRIES) {\n for (const e of s.emails) if (!e.picture && e.stale) e.picture = e.stale;\n s.noPicture = true;\n return render();\n }\n const mine = turn;\n timer = setTimeout(async () => {\n tries++;\n await readEmails();\n if (mine !== turn) return;\n render();\n if (missingPicture()) retryPicture();\n }, 4000 * 2 ** tries);\n }\n // The emails as Migma has them now: a change made in the chat, or a picture captured since.\n async function readEmails() {\n const mine = turn;\n if (s.mode === \"create\") {\n const d = await read(\"migma_get_generation_status\", { conversationId: s.conversationId });\n if (mine === turn && d?.status === \"completed\") applyStatus(d);\n } else if (s.emails?.[0]?.emailId) {\n const was = s.emails[0];\n const d = await read(\"migma_get_email\", { emailId: was.emailId });\n if (mine === turn && d?.emailId) s.emails = [unchanged(toEmail(d, was.appUrl), was.stale)];\n }\n if (mine !== turn || !s.emails) return;\n sel = Math.min(sel, s.emails.length - 1);\n // A template made from an earlier version of an email is not this email in Klaviyo.\n for (const e of s.emails) {\n const made = flow[keyOf(e)]?.tools[\"tool:klaviyo\"];\n if (made?.state === \"done\" && made.of !== e.version) { made.state = \"\"; made.url = \"\"; }\n }\n }\n\n function refreshSoon() { if (s?.phase === \"working\") { delay = 3000; poll(); } }\n document.addEventListener(\"visibilitychange\", () => document.visibilityState === \"visible\" && refreshSoon());\n window.addEventListener(\"focus\", refreshSoon);\n\n function elapsed() {\n const start = Date.parse(s.createdAt);\n if (!start) return \"\";\n const secs = Math.max(0, Math.round((Date.now() - start) / 1000));\n return Math.floor(secs / 60) + \":\" + String(secs % 60).padStart(2, \"0\");\n }\n function tick() {\n clearInterval(ticker);\n if (s.phase !== \"working\" || !s.createdAt) return;\n ticker = setInterval(() => document.querySelectorAll(\".time\").forEach((t) => { t.textContent = elapsed(); }), 1000);\n }\n\n // ---- what the card reads from Migma ----\n // The tool's answer, the error it returned, or null when the host refused the call itself. A call\n // that outlasts the card's patience may still finish: it is an error to try again, never a refusal.\n const SLOW = \"CARD_TIMEOUT\";\n async function run(name, args) {\n try {\n const result = await request(\"tools/call\", { name, arguments: args }, 60000);\n if (result?.isError) {\n const refusal = json(result);\n return { error: refusal?.error || texts(result)[0] || \"Migma could not do this.\", code: typeof refusal?.code === \"string\" ? refusal.code : \"\" };\n }\n return { data: json(result) ?? {}, list: rows(result) };\n } catch (err) {\n return err?.message === \"timeout\" ? { error: \"This is taking longer than usual. Try again in a moment.\", code: SLOW } : null;\n }\n }\n\n // The brand the emails were made from. A member who may not read it sees the card without this line.\n async function loadBrand() {\n brandAsked = true;\n const mine = turn;\n const d = await read(\"migma_get_project\", { projectId: brand });\n if (mine !== turn || typeof d?.name !== \"string\" || !d.name) return;\n const hex = (value) => (typeof value === \"string\" && /^#[0-9a-f]{3,8}$/i.test(value.trim()) ? value.trim().toLowerCase() : \"\");\n const c = d.colors || {};\n const colors = [...new Set([hex(c.accent), hex(c.text), hex(c.background?.page), hex(c.background?.container)].filter(Boolean))].slice(0, 4);\n const fonts = [...new Set((Array.isArray(d.fonts) ? d.fonts : []).map((f) => String(f?.family || f?.name || \"\").split(\",\")[0].replaceAll('\"', \"\").trim()).filter(Boolean))].slice(0, 2);\n // The small square mark first, then the full logo; the card may load neither from every host.\n brandInfo = { name: d.name, logos: [https(d.logoUrls?.favicon), https(d.logoUrls?.primary)].filter(Boolean), colors, fonts };\n if (s) render();\n }\n\n // Every list and segment of the brand, biggest first. Read again on each look, so one added in\n // Migma or in the chat is there; those that appeared after the first read are marked.\n async function loadLists() {\n if (!brand || listsBusy) return;\n listsBusy = true;\n const mine = turn;\n const [segments, tags] = await Promise.all([\n run(\"migma_list_segments\", { projectId: brand }),\n run(\"migma_list_tags\", { projectId: brand }),\n ]);\n if (mine !== turn) return;\n listsBusy = false;\n if (!segments?.list && !tags?.list) {\n // Neither could be read: the chat picks the audience with the user.\n if (!lists) listsOff = true;\n return;\n }\n const count = (r) => (typeof r.count === \"number\" ? r.count : typeof r.subscriberCount === \"number\" ? r.subscriberCount : null);\n const option = (type) => (r) => ({ type, raw: String(r?.id ?? r?._id ?? \"\"), name: String(r?.name ?? \"\"), count: count(r ?? {}) });\n const all = [...(segments?.list ?? []).map(option(\"segment\")), ...(tags?.list ?? []).map(option(\"list\"))]\n .filter((o) => o.raw && o.name)\n .sort((a, b) => (b.count ?? -1) - (a.count ?? -1));\n for (const o of all) { o.id = o.type + \":\" + o.raw; o.fresh = !!known && !known.has(o.id); }\n known ||= new Set(all.map((o) => o.id));\n lists = all;\n listsOff = false;\n }\n\n // Sending domains belong to the account, not a brand: one sender is used as it is; several are\n // offered as choices; none sends the user to set one up.\n async function loadSenders() {\n if (senders?.length) return senders;\n const r = await run(\"migma_list_domains\", {});\n if (!r || r.error) return null;\n senders = (r.list ?? [])\n .filter((d) => d?.isVerified === true || d?.status === \"verified\")\n .flatMap((d) => (Array.isArray(d.senders) ? d.senders : []).map((x) => ({ email: String(x?.email ?? \"\"), name: String(x?.fromName ?? \"\"), first: x?.isDefault === true })))\n .filter((x) => x.email && x.name)\n .sort((a, b) => Number(b.first) - Number(a.first))\n .slice(0, 6);\n return senders;\n }\n\n // What came back for an email, across every send of it Migma tracked (a test counts, and so does\n // every list): never one list's result. Where sends went out as campaigns, their numbers together.\n async function loadMetrics(e) {\n const f = flowOf(e);\n const campaigns = Object.values(f.sends).filter((x) => x.campaignId && x.state === \"sent\");\n if (campaigns.length) {\n const all = await Promise.all(campaigns.map((x) => read(\"migma_get_campaign_stats\", { campaignId: x.campaignId })));\n const got = all.filter(Boolean);\n if (got.length) f.metrics = { delivered: got.reduce((n, d) => n + num(d.totalDelivered), 0), opened: got.reduce((n, d) => n + num(d.uniqueOpens), 0), clicked: got.reduce((n, d) => n + num(d.uniqueClicks), 0) };\n } else if (e.emailId) {\n const d = await read(\"migma_get_email_metrics\", { emailId: e.emailId });\n if (d?.summary) f.metrics = { delivered: num(d.summary.delivered), opened: num(d.summary.opened), clicked: num(d.summary.clicked) };\n }\n }\n\n // Each tool call opens its own card, so an older card learns of a change made in the chat (a\n // new list, a changed email) only by reading again: when the user comes back to it, or asks.\n const allSends = () => Object.values(flow).flatMap((f) => Object.values(f.sends));\n const signature = () => JSON.stringify([lists?.map((o) => [o.id, o.name, o.count]), s.emails?.map((e) => [e.emailId, e.subject, e.picture, e.failed]), allSends().map((x) => x.state)]);\n async function reread(asked) {\n if (!s || s.phase !== \"ready\" || s.compact || listsBusy || asking) return;\n if (!asked && Date.now() - rereadAt < REREAD_MS) return;\n rereadAt = Date.now();\n const was = s, before = signature();\n if (asked) { asking = true; render(); }\n const jobs = [loadLists(), readEmails()];\n const e = s.emails[sel];\n if (asked && e && !e.failed) jobs.push(loadMetrics(e));\n // A sending address set up since the card last looked lets a held send go ahead.\n const held = allSends().filter((x) => x.state === \"nosender\");\n if (held.length) jobs.push(loadSenders().then((list) => { if (list?.length) for (const x of held) x.state = \"\"; }));\n await Promise.all(jobs);\n asking = false;\n if (s !== was) return;\n tries = 0;\n // Nothing new: the card stays as it is under the pointer.\n if (asked || signature() !== before) render();\n if (missingPicture()) retryPicture();\n }\n document.documentElement.addEventListener(\"pointerenter\", () => reread(false));\n document.addEventListener(\"focusin\", () => reread(false));\n\n // ---- what the user can do ----\n async function openLink(url) {\n if (!url) return;\n try { const r = await request(\"ui/open-link\", { url }); if (!r?.isError) return; } catch {}\n s.note = \"Could not open the link. Copy it: \" + url;\n render();\n }\n async function ask(text) {\n try {\n const r = await request(\"ui/message\", { role: \"user\", content: [{ type: \"text\", text }] });\n if (r?.isError) throw new Error();\n return true;\n } catch {\n s.note = \"Could not send that to the chat. Type it there instead.\";\n render();\n return false;\n }\n }\n async function displayMode(mode) {\n try { const r = await request(\"ui/request-display-mode\", { mode }); applyHost({ displayMode: r?.mode || host.displayMode }); } catch {}\n render();\n }\n const canFullScreen = () => (host.availableDisplayModes || []).includes(\"fullscreen\");\n const fullScreen = () => host.displayMode === \"fullscreen\" && s.phase === \"ready\" && !s.compact;\n // A host that can neither run tools nor take messages shows the emails and their link.\n const canAct = () => !!(caps.message || caps.serverTools);\n function select(i) {\n sel = Math.max(0, Math.min(s.emails.length - 1, i));\n render();\n }\n document.addEventListener(\"keydown\", (event) => {\n if (!s || !fullScreen() || s.emails.length < 2) return;\n if (event.key === \"ArrowLeft\") select(sel - 1);\n if (event.key === \"ArrowRight\") select(sel + 1);\n });\n\n const series = () => s.emails.length > 1;\n const quoted = (e) => (e.subject ? \"\u201C\" + e.subject + \"\u201D\" : \"this email\");\n const subjectOf = (e, i) => (series() ? \"email \" + (i + 1) + \" of the series, \" + quoted(e) : quoted(e));\n const keyOf = (e) => e.emailId || \"email-\" + s.emails.indexOf(e);\n const flowOf = (e) => (flow[keyOf(e)] ||= { to: \"me\", test: \"\", sentTo: \"\", note: \"\", plans: false, chat: \"\", sends: {}, tools: {}, metrics: null });\n const sendOf = (f, id) => (f.sends[id] ||= { state: \"\", approval: null, note: \"\", plans: false, n: 0, campaignId: \"\" });\n const toolOf = (f, id) => (f.tools[id] ||= { state: \"\", url: \"\", note: \"\", n: 0 });\n const listOf = (f) => lists?.find((o) => o.id === f.to);\n const people = (n) => n.toLocaleString(\"en-US\") + (n === 1 ? \" person\" : \" people\");\n const target = (e) => (e.emailId ? { emailId: e.emailId } : { conversationId: s.conversationId });\n const hash = (text) => { let h = 5381; for (const ch of text) h = ((h * 33) ^ ch.charCodeAt(0)) >>> 0; return h.toString(36); };\n // A refusal that names the plan gets the plans page; nothing else in the card mentions plans.\n const planRefusal = (text) => /\\bplan\\b|upgrade|pricing/i.test(text || \"\");\n const waitMs = (ms) => new Promise((done) => setTimeout(done, ms));\n // What the card did is told to the model, so the chat keeps track.\n function remember(text) {\n history.push(text);\n const context = \"In the Migma email card, the user \" + history.join(\"; \") + \".\";\n request(\"ui/update-model-context\", { content: [{ type: \"text\", text: context }] }, 10000).catch(() => {});\n }\n\n function pickTo(e, id) {\n const f = flowOf(e);\n f.to = id;\n render();\n // Who it is from matters once a list is picked: several sending addresses are offered then.\n if (listOf(f) && !senders) loadSenders().then(() => render());\n }\n\n // Just me: a test to the account owner's own inbox. Nothing to approve.\n async function testIt(e, i) {\n const f = flowOf(e);\n f.test = \"running\"; f.note = \"\"; f.plans = false; render();\n const r = await run(\"migma_send_test_email\", target(e));\n if (!r) f.test = (await ask(\"Send me a test of \" + subjectOf(e, i) + \".\")) ? \"asked\" : \"\";\n else if (r.error) { f.test = \"warn\"; f.note = r.error; f.plans = planRefusal(r.error); }\n else {\n f.test = \"done\";\n f.sentTo = String(r.data.sentTo || \"\");\n remember(\"sent a test of \" + subjectOf(e, i) + (f.sentTo ? \" to \" + f.sentTo : \" to their own inbox\"));\n }\n render();\n }\n\n // A list: the card only prepares the send, and the user approves it on migma.ai. One approval per\n // email, list and sender: a second click shows the one that is waiting, and a new one is asked for\n // only after the last ended (sent, declined, expired or refused).\n const MANAGED_SINGLE_SEND_REFUSED = \"WORKSPACE_KEY_SINGLE_SEND_REFUSED\";\n const NO_ELIGIBLE_RECIPIENTS = \"NO_ELIGIBLE_RECIPIENTS\";\n const IDEMPOTENCY_CONFLICT = \"IDEMPOTENCY_CONFLICT\";\n const IDEMPOTENCY_IN_PROGRESS = \"IDEMPOTENCY_IN_PROGRESS\";\n const ENDED = [\"sent\", \"scheduled\", \"declined\", \"expired\", \"failed\"];\n const OPEN = [\"running\", \"waiting\", \"sending\"];\n // An approved send reads \"sent\" with result \"queued\" until it goes out, and can still fail then.\n const queued = (a) => a?.status === \"sent\" && a.result?.status === \"queued\" && !a.result.batchId;\n async function sendIt(e, i) {\n const f = flowOf(e);\n const a = listOf(f);\n if (!a) return askSend(e, i);\n const sd = sendOf(f, a.id);\n if (OPEN.includes(sd.state)) return;\n sd.note = \"\"; sd.plans = false; sd.state = \"running\"; render();\n const list = await loadSenders();\n if (!list) { sd.state = \"\"; return askSend(e, i, a); }\n if (!list.length) { sd.state = \"nosender\"; return render(); }\n const sender = list[Math.min(from, list.length - 1)];\n // The same key within a day returns the approval it made before, also to a later card. One\n // still waiting is this send. One that ended is not, nor is a key used for another subject:\n // those ask again under the next key.\n let r = null, going = false;\n for (let attempt = 0; attempt < 8; attempt++) {\n const key = \"card-\" + keyOf(e) + \"-\" + a.raw + \"-\" + hash(sender.email) + \"-\" + sd.n;\n r = await run(\"migma_send_email\", {\n recipientType: a.type === \"list\" ? \"tag\" : \"segment\",\n recipientId: a.raw,\n from: sender.email,\n fromName: sender.name,\n subject: e.subject,\n ...target(e),\n idempotency_key: key,\n });\n if (r?.code === MANAGED_SINGLE_SEND_REFUSED) r = await viaCampaign(e, a, sender, key, sd);\n if (!r || (r.error && r.code !== IDEMPOTENCY_CONFLICT)) break;\n if (!r.error) {\n const id = String(r.data.approval?.id ?? \"\");\n const seen = id ? await run(\"migma_get_send_approval\", { approvalId: id }) : null;\n // Approved earlier and still going out: asking again would send it twice.\n going = queued(seen?.data);\n if (going || !ENDED.includes(seen?.data?.status)) break;\n }\n sd.n++;\n r = { error: \"Migma could not prepare this send. Try again.\", code: \"\" };\n }\n if (!r) { sd.state = \"\"; return askSend(e, i, a); }\n if (r.error) {\n sd.state = \"warn\";\n sd.note = r.code === NO_ELIGIBLE_RECIPIENTS ? \"No one on \" + a.name + \" can get email. Pick another list.\"\n : r.code === IDEMPOTENCY_IN_PROGRESS ? \"Migma is still preparing this send. Try again in a moment.\" : r.error;\n sd.plans = planRefusal(r.error);\n // Migma replays a refusal for a day under its key, so the next try needs the next key, or\n // what the user fixed would never be seen. A request still running, or one the card stopped\n // waiting for, may yet prepare its approval: the same key finds it.\n if (r.code !== IDEMPOTENCY_IN_PROGRESS && r.code !== SLOW) sd.n++;\n return render();\n }\n const approval = r.data.approval ?? {};\n const summary = r.data.summary ?? {};\n sd.approval = {\n id: String(approval.id ?? \"\"),\n url: https(approval.approvalUrl),\n count: typeof summary.recipients === \"number\" ? summary.recipients : a.count,\n warning: Array.isArray(summary.warnings) ? String(summary.warnings[0] ?? \"\") : \"\",\n };\n sd.state = going ? \"sending\" : \"waiting\";\n if (!going) remember(\"prepared a send of \" + subjectOf(e, i) + \" to \" + a.name + \"; it waits for their approval on migma.ai (\" + sd.approval.url + \")\");\n render();\n watchApproval(e, i, sd, a);\n }\n // A workspace connected through managed sign-in may send only campaigns (their approval re-checks\n // the member's role), so the same send goes as a campaign draft and its approval, which the user\n // approves on migma.ai the same way. Null (the host refused, or no brand to save it in) asks the chat.\n async function viaCampaign(e, a, sender, key, sd) {\n const conversationId = e.conversationId || s.conversationId;\n if (!brand || !conversationId) return null;\n const draft = await run(\"migma_create_campaign\", {\n projectId: brand,\n name: e.subject || \"Email from Migma\",\n conversationId,\n ...(e.emailId ? { emailId: e.emailId } : {}),\n subject: e.subject,\n from: sender.email,\n fromName: sender.name,\n recipientType: a.type === \"list\" ? \"tag\" : \"audience\",\n recipientId: a.raw,\n idempotency_key: key + \"-draft\",\n });\n if (!draft || draft.error) return draft;\n if (!draft.data.id) return { error: \"Migma could not save the campaign.\", code: \"\" };\n sd.campaignId = String(draft.data.id);\n return run(\"migma_send_campaign\", { campaignId: sd.campaignId, idempotency_key: key + \"-send\" });\n }\n // The approval happens on migma.ai; the card reads it until it is decided, whichever list is in view.\n async function watchApproval(e, i, sd, a) {\n const mine = turn;\n const what = \"the send of \" + subjectOf(e, i) + \" to \" + a.name;\n let wait = 5000;\n while ((sd.state === \"waiting\" || sd.state === \"sending\") && sd.approval?.id) {\n await waitMs(wait);\n if (mine !== turn) return;\n wait = Math.min(wait * 1.3, 20000);\n if (document.visibilityState !== \"visible\") continue;\n const r = await run(\"migma_get_send_approval\", { approvalId: sd.approval.id });\n if (mine !== turn) return;\n const status = r?.data?.status;\n if (queued(r?.data)) {\n // Approved, and on its way out: not sent until Migma says so.\n if (sd.state === \"sending\") continue;\n sd.state = \"sending\";\n } else if (status === \"sent\" || status === \"scheduled\") {\n sd.state = \"sent\"; sd.later = status === \"scheduled\"; sd.n++;\n remember(\"approved \" + what + \" on migma.ai; Migma \" + (sd.later ? \"scheduled it\" : \"sent it\"));\n render();\n await loadMetrics(e);\n } else if (status === \"declined\" || status === \"expired\" || status === \"failed\") {\n sd.state = \"warn\"; sd.n++;\n sd.note = 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.\";\n sd.plans = planRefusal(sd.note);\n remember(status === \"declined\" ? \"declined \" + what + \" on migma.ai; nothing was sent\" : status === \"expired\" ? \"let the approval for \" + what + \" expire; nothing was sent\" : \"approved \" + what + \", but it did not go out: \" + sd.note);\n } else continue;\n if (mine === turn) render();\n if (sd.state !== \"sending\") return;\n }\n }\n async function askSend(e, i, a) {\n const f = flowOf(e);\n const to = a ? \" to the \" + a.name + (a.type === \"list\" ? \" list\" : \" segment\") : \" to my audience\";\n if (!(await ask(\"Send \" + subjectOf(e, i) + to + \".\"))) return;\n if (a) sendOf(f, a.id).state = \"asked\"; else f.chat = \"asked\";\n render();\n }\n\n // Other tools. Klaviyo gets the email as a template in the user's own account; the others are a\n // file, which the chat hands over.\n const TOOL_ASK = {\n \"tool:klaviyo\": (text) => \"Put \" + text + \" in my Klaviyo as a template.\",\n \"tool:mailchimp\": (text) => \"Export \" + text + \" for Mailchimp.\",\n \"tool:hubspot\": (text) => \"Export \" + text + \" for HubSpot.\",\n \"tool:html\": (text) => \"Export \" + text + \" as HTML.\",\n };\n async function askTool(e, i, id) {\n const t = toolOf(flowOf(e), id);\n if (await ask(TOOL_ASK[id](subjectOf(e, i)))) t.state = \"asked\";\n render();\n }\n async function toKlaviyo(e, i) {\n const t = toolOf(flowOf(e), \"tool:klaviyo\");\n const conversationId = e.conversationId || s.conversationId;\n if (!conversationId) return askTool(e, i, \"tool:klaviyo\");\n t.state = \"running\"; t.note = \"\"; render();\n // The same key until it works: a retry after a refusal the user fixed returns the one template.\n const r = await run(\"migma_push_to_klaviyo\", { conversationId, ...(e.emailId ? { emailId: e.emailId } : {}), idempotency_key: \"card-klaviyo-\" + keyOf(e) + \"-\" + t.n });\n if (!r) { t.state = \"\"; return askTool(e, i, \"tool:klaviyo\"); }\n // Still running when the card stopped waiting: the same key returns that one template.\n if (r.code === SLOW) { t.state = \"\"; t.note = r.error; return render(); }\n // Why Klaviyo refused (not connected, several accounts, the plan) is written for the chat, which\n // can act on it with the user: the request goes there.\n if (r.error) {\n t.state = \"\";\n if (caps.message) return askTool(e, i, \"tool:klaviyo\");\n t.note = \"Klaviyo did not take it. Ask for it in the chat to see why.\";\n return render();\n }\n t.state = \"done\"; t.url = https(r.data.editorUrl); t.of = e.version; t.n++;\n remember(\"put \" + subjectOf(e, i) + \" in their Klaviyo as a template\");\n render();\n }\n\n // ---- pieces ----\n function linkButton(className, label, url, key) {\n const b = button(\"btn \" + className, label, () => openLink(url), key);\n b.append(icon(\"out\"));\n return b;\n }\n function skeleton() {\n return [[10, 34], [34, 78], [34, 56], [104, 88]].map(([h, w]) => el(\"span\", \"\", { className: \"sk pulse\", style: \"height:\" + h + \"px;width:\" + w + \"%\" }));\n }\n function middle(...parts) {\n const box = el(\"span\", \"\", { className: \"mid\" });\n box.append(...parts);\n return box;\n }\n function image(e, alt) {\n const img = el(\"img\", \"\", { alt });\n img.addEventListener(\"error\", () => { e.picture = \"\"; render(); if (missingPicture()) retryPicture(); }, { once: true });\n img.src = e.picture;\n return img;\n }\n // What a poster or a column shows: the email, why there is none, or that its picture is on its way.\n function fill(pic, e, dim) {\n if (!e) pic.append(...skeleton());\n else if (e.failed) pic.append(middle(icon(\"alert\"), el(\"span\", \"Not created\")));\n else if (e.picture) { pic.append(image(e, (e.subject || \"Email\") + (dim ? \", before the change\" : \"\"))); if (dim) pic.classList.add(\"dim\"); }\n else if (s.noPicture) pic.append(middle(icon(\"image\"), el(\"span\", \"No picture yet. It is ready in Migma.\")));\n else {\n const pill = el(\"span\", \"\", { className: \"pill\", role: \"status\" });\n pill.append(el(\"span\", \"\", { className: \"dot info pulse\" }), el(\"span\", \"Preparing the picture\"));\n pic.append(...skeleton(), middle(pill));\n }\n }\n const sentOf = (e) => Object.values(flowOf(e).sends).filter((x) => x.state === \"sent\");\n function caption(e, i) {\n const cap = el(\"div\", \"\", { className: \"cap\" });\n cap.append(el(\"b\", e.failed ? \"Email \" + (i + 1) : e.subject || \"Email \" + (i + 1)));\n const sent = e.failed ? [] : sentOf(e);\n if (sent.length) cap.append(el(\"span\", sent.some((x) => !x.later) ? \"Sent\" : \"Scheduled\", { className: \"ok\" }));\n else if (e.day !== null) cap.append(el(\"span\", \"Day \" + e.day));\n return cap;\n }\n // One email of the row. A click picks it; a click on the picked one opens the whole email: full\n // screen where the host has it, in place under the row where it has not.\n function poster(e, i) {\n const many = series();\n const on = many && i === sel;\n const box = el(\"div\", \"\", { className: on ? \"poster on\" : \"poster\" });\n const shows = !e.failed && !!e.picture && (on || !many);\n const opens = shows && canFullScreen();\n let pic;\n if (many || shows) {\n pic = button(\"pic\", \"\", () => (opens ? displayMode(\"fullscreen\") : shows ? ((whole = !whole), render()) : select(i)), \"email-\" + i);\n const name = e.subject || \"email \" + (i + 1);\n pic.setAttribute(\"aria-label\", !shows ? \"Email \" + (i + 1) + (e.subject ? \": \" + e.subject : \"\") : whole && !opens ? \"Show less of \" + name : \"See the whole email: \" + name);\n if (many) pic.setAttribute(\"aria-pressed\", String(on));\n if (shows && !opens) pic.setAttribute(\"aria-expanded\", String(whole));\n } else pic = el(\"div\", \"\", { className: \"pic\" });\n fill(pic, e);\n if (shows) { const mark = el(\"span\", \"\", { className: \"open\" }); mark.append(icon(whole && !opens ? \"collapse\" : \"expand\")); pic.append(mark); }\n box.append(pic);\n if (many) box.append(caption(e, i));\n return box;\n }\n function wholeEmail(e) {\n if (!whole || canFullScreen() || e.failed || !e.picture) return [];\n const box = el(\"div\", \"\", { className: \"whole\" });\n box.append(image(e, e.subject || \"Email\"));\n return [box];\n }\n function posters() {\n const n = s.emails.length;\n const row = el(\"div\", \"\", { className: n === 2 ? \"row two\" : n > 3 ? \"row many\" : \"row\" });\n s.emails.forEach((e, i) => row.append(poster(e, i)));\n if (n <= 3) return row;\n const wrap = el(\"div\", \"\", { className: \"rowwrap\" });\n const next = button(\"next\", \"\", () => {\n const end = row.scrollLeft + row.clientWidth >= row.scrollWidth - 8;\n row.scrollTo({ left: end ? 0 : row.scrollLeft + 400, behavior: \"smooth\" });\n }, \"next\", { ariaLabel: \"More emails\" });\n next.append(icon(\"next\"));\n wrap.append(row, next);\n return wrap;\n }\n\n function brandLine() {\n const line = el(\"div\", \"\", { className: \"brand\" });\n const b = brandInfo;\n if (b) {\n if (b.logos.length) {\n const img = el(\"img\", \"\", { className: \"logo\", alt: \"\" });\n img.addEventListener(\"error\", () => { b.logos.shift(); render(); }, { once: true });\n img.src = b.logos[0];\n line.append(img);\n } else {\n // No logo the card may load: the brand's initial on its own colour.\n const tone = b.colors[0] || \"\";\n const light = tone.length === 7 && (parseInt(tone.slice(1, 3), 16) * 299 + parseInt(tone.slice(3, 5), 16) * 587 + parseInt(tone.slice(5, 7), 16) * 114) / 1000 > 150;\n line.append(el(\"span\", b.name.trim().charAt(0).toUpperCase(), { className: \"mono\", ariaHidden: \"true\", style: tone ? \"background:\" + tone + \";color:\" + (light ? \"#141413\" : \"#ffffff\") : \"background:var(--inverse);color:var(--on-inverse)\" }));\n }\n line.append(el(\"b\", b.name));\n if (b.colors.length) {\n const dots = el(\"span\", \"\", { className: \"dots\", ariaHidden: \"true\" });\n dots.append(...b.colors.map((c) => el(\"i\", \"\", { style: \"background:\" + c })));\n line.append(dots);\n }\n if (b.fonts.length) line.append(el(\"span\", b.fonts.join(\", \"), { className: \"type\" }));\n }\n const fact = el(\"span\", \"\", { className: \"fact\" });\n fact.append(icon(\"check\"), el(\"span\", \"Works in every inbox\"));\n line.append(fact);\n return line;\n }\n\n // Who gets it. Just me first, then the biggest lists; More opens the rest and the other tools.\n function chip(e, id, label, extra) {\n const f = flowOf(e);\n const b = button(\"chip\", \"\", () => pickTo(e, id), \"to-\" + id);\n b.setAttribute(\"aria-pressed\", String(f.to === id));\n b.append(el(\"span\", label, { className: \"n\" }));\n if (extra) b.append(...extra);\n return b;\n }\n function toRows(e) {\n const f = flowOf(e);\n const all = lists || [];\n // A list that is gone from Migma cannot stay picked.\n if (lists && f.to !== \"me\" && f.to !== \"chat\" && !f.to.startsWith(\"tool:\") && !listOf(f)) f.to = \"me\";\n const to = el(\"div\", \"\", { className: \"to\" });\n to.append(el(\"span\", \"To\", { className: \"k\" }));\n const chips = el(\"div\", \"\", { className: \"chips\", role: \"group\" });\n chips.setAttribute(\"aria-label\", \"Who gets it\");\n chips.append(chip(e, \"me\", \"Just me\"));\n // The biggest lists, plus any that is new since the card opened, waits for an approval or is picked.\n const picked = listOf(f);\n const open = (o) => OPEN.includes(f.sends[o.id]?.state);\n const shown = more ? all : all.filter((o, n) => n < TOP_LISTS || o.fresh || o === picked || open(o));\n for (const o of shown) {\n const extra = [];\n if (open(o)) extra.push(el(\"span\", \"\", { className: \"dot info\" }));\n else if (o.fresh) extra.push(el(\"span\", \"\", { className: \"dot ok\" }));\n if (o.count !== null) extra.push(el(\"small\", o.count.toLocaleString(\"en-US\")));\n chips.append(chip(e, o.id, o.name, extra));\n }\n if (lists && !all.length) {\n const add = button(\"chip more\", \"\", () => openLink(CONTACTS_URL), \"add\");\n add.append(el(\"span\", \"Add contacts\", { className: \"n\" }), icon(\"out\"));\n chips.append(add);\n }\n // No lists to read (no brand named, or the host refused): the chat picks the audience.\n if (!lists && (listsOff || !brand) && caps.message) chips.append(chip(e, \"chat\", \"My audience\"));\n chips.append(button(\"chip more\", more ? \"Fewer\" : \"More\", () => { more = !more; render(); }, \"more\", { ariaExpanded: String(more) }));\n to.append(chips);\n if (brand) {\n const again = button(asking ? \"ref spin\" : \"ref\", \"\", () => reread(true), \"refresh\", { ariaLabel: \"Read the lists and emails again\" });\n again.append(icon(\"refresh\"));\n to.append(again);\n }\n const out = [to];\n // Who it is from, while it can still change: before this list's send is prepared.\n if (picked && senders && senders.length > 1 && [\"\", \"warn\"].includes(sendOf(f, picked.id).state)) {\n const row = el(\"div\", \"\", { className: \"to\" });\n const group = el(\"div\", \"\", { className: \"chips\", role: \"group\" });\n group.setAttribute(\"aria-label\", \"Who it is from\");\n senders.forEach((x, n) => {\n const b = button(\"chip\", \"\", () => { from = n; render(); }, \"from-\" + n);\n b.setAttribute(\"aria-pressed\", String(n === Math.min(from, senders.length - 1)));\n b.append(el(\"span\", x.name, { className: \"n\" }), el(\"small\", x.email));\n group.append(b);\n });\n row.append(el(\"span\", \"From\", { className: \"k\" }), group);\n out.push(row);\n }\n // A file export is of the whole request, so one email of a series can only go to Klaviyo; and\n // a file is handed over by the chat, so a host that takes no messages offers none.\n const tools = TOOLS.filter(([id]) => id === \"tool:klaviyo\" || (caps.message && !series()));\n if (more || f.to.startsWith(\"tool:\")) {\n const row = el(\"div\", \"\", { className: \"to\" });\n const group = el(\"div\", \"\", { className: \"chips\", role: \"group\" });\n group.setAttribute(\"aria-label\", \"Other tools\");\n for (const [id, label] of tools) group.append(chip(e, id, label, [icon(\"out\")]));\n row.append(el(\"span\", \"Or in\", { className: \"k\" }), group);\n out.push(row);\n }\n return out;\n }\n\n // The one thing to do next for what is picked. Never a step: picking something else changes it.\n function primary(e, i) {\n const f = flowOf(e);\n const label = series() ? \"Send email \" + (i + 1) : \"Send\";\n if (f.to === \"me\") return button(\"btn primary\", label, () => testIt(e, i), \"primary\", { disabled: f.test === \"running\" });\n if (f.to === \"tool:klaviyo\") {\n const t = toolOf(f, f.to);\n if (t.state === \"done\" && t.url) return linkButton(\"primary\", \"Open in Klaviyo\", t.url, \"primary\");\n if (t.state === \"asked\" || t.state === \"done\") return null;\n return button(\"btn primary\", \"Create in Klaviyo\", () => toKlaviyo(e, i), \"primary\", { disabled: t.state === \"running\" });\n }\n if (f.to.startsWith(\"tool:\")) return toolOf(f, f.to).state === \"asked\" ? null : button(\"btn primary\", \"Get the file\", () => askTool(e, i, f.to), \"primary\");\n const a = listOf(f);\n if (!a) return f.chat === \"asked\" ? null : button(\"btn primary\", label, () => askSend(e, i), \"primary\");\n const sd = sendOf(f, a.id);\n if (sd.state === \"nosender\") return linkButton(\"primary\", \"Set up sending\", SETUP_URL, \"primary\");\n if (sd.state === \"waiting\" && sd.approval?.url) return linkButton(\"primary\", \"Approve on migma.ai\", sd.approval.url, \"primary\");\n if (sd.state === \"sent\") return sd.approval?.url ? linkButton(\"ghost\", \"See results\", sd.approval.url, \"primary\") : null;\n if (sd.state === \"asked\" || sd.state === \"sending\") return null;\n return button(\"btn primary\", label, () => sendIt(e, i), \"primary\", { disabled: OPEN.includes(sd.state) });\n }\n // What happened for what is picked, in one line beside the actions; under it, what came back\n // for the email as a whole, said as that.\n function status(e, i) {\n const f = flowOf(e);\n const line = (tone, text, plans) => {\n const p = el(\"span\", \"\", { className: \"st\", role: \"status\" });\n if (tone) p.append(el(\"span\", \"\", { className: \"dot \" + tone }));\n p.append(el(\"span\", text));\n if (plans) {\n const link = el(\"a\", \"See plans\", { href: PLANS_URL });\n link.addEventListener(\"click\", (event) => { event.preventDefault(); openLink(PLANS_URL); });\n p.lastChild.append(\" \", link);\n }\n return p;\n };\n if (f.to === \"me\") {\n if (f.test === \"running\") return line(\"info pulse\", \"Sending\");\n if (f.test === \"done\") return line(\"ok\", f.sentTo ? \"Sent to \" + f.sentTo : \"Sent to your inbox\");\n if (f.test === \"warn\") return line(\"bad\", f.note, f.plans);\n if (f.test === \"asked\") return line(\"\", \"Asked in the chat\");\n return null;\n }\n if (f.to.startsWith(\"tool:\")) {\n const t = toolOf(f, f.to);\n if (t.state === \"running\") return line(\"info pulse\", \"Creating the template\");\n if (t.state === \"done\") return line(\"ok\", (series() ? \"Email \" + (i + 1) + \" is\" : \"It is\") + \" in your Klaviyo\");\n if (t.state === \"asked\") return line(\"\", \"Asked in the chat\");\n return t.note ? line(\"warn\", t.note) : null;\n }\n const a = listOf(f);\n if (!a) return f.chat === \"asked\" ? line(\"\", \"Asked in the chat\") : null;\n const sd = sendOf(f, a.id);\n if (sd.state === \"running\") return line(\"info pulse\", \"Preparing\");\n if (sd.state === \"waiting\") return line(\"info pulse\", sd.approval.warning || \"Waiting for your approval\");\n if (sd.state === \"sending\") return line(\"info pulse\", \"Sending\");\n if (sd.state === \"sent\" && sd.later) return line(\"ok\", \"Scheduled on migma.ai\");\n if (sd.state === \"sent\") return line(\"ok\", typeof sd.approval?.count === \"number\" ? \"Sent to \" + people(sd.approval.count) : \"Sent\");\n if (sd.state === \"warn\") return line(\"bad\", sd.note, sd.plans);\n if (sd.state === \"nosender\") return line(\"warn\", \"Needs a sending address\");\n if (sd.state === \"asked\") return line(\"\", \"Asked in the chat\");\n return null;\n }\n function numbers(e, i) {\n const m = flowOf(e).metrics;\n if (!m || !m.delivered) return null;\n const p = el(\"span\", \"\", { className: \"st\" });\n const nums = el(\"span\", \"\", { className: \"nums\" });\n nums.append(el(\"span\", series() ? \"Email \" + (i + 1) + \" so far\" : \"So far\"));\n for (const [value, label] of [[m.delivered, \"delivered\"], [m.opened, \"opened\"], [m.clicked, \"clicked\"]]) {\n const part = el(\"span\", \"\");\n part.append(el(\"b\", value.toLocaleString(\"en-US\")), label);\n nums.append(part);\n }\n p.append(nums);\n return p;\n }\n function foot(e, i) {\n const f = el(\"div\", \"\", { className: \"foot\" });\n const url = e.appUrl || s.appUrl;\n if (e.failed) {\n // Nothing to send: the chat can try this one again.\n if (caps.message) f.append(button(\"btn primary\", series() ? \"Try email \" + (i + 1) + \" again\" : \"Try again\", () => ask(series() ? \"Try creating email \" + (i + 1) + \" of the series again.\" : \"Try creating that email again.\"), \"primary\"));\n if (url) f.append(linkButton(\"ghost\", \"Open in Migma\", url, \"edit\"));\n const p = el(\"span\", \"\", { className: \"st\" });\n p.append(el(\"span\", \"\", { className: \"dot bad\" }), el(\"span\", series() ? \"Email \" + (i + 1) + \" was not created\" : \"Not created\"));\n f.append(p);\n return f;\n }\n const next = canAct() ? primary(e, i) : null;\n if (next) f.append(next);\n if (url) f.append(linkButton(canAct() ? \"ghost\" : \"primary\", \"Edit in Migma\", url, \"edit\"));\n const said = canAct() ? [status(e, i), numbers(e, i)].filter(Boolean) : [];\n if (said.length) {\n const box = el(\"div\", \"\", { className: \"said\" });\n box.append(...said);\n f.append(box);\n }\n return f;\n }\n const controls = (e, i) => (canAct() && !e.failed ? [...toRows(e), foot(e, i)] : [foot(e, i)]);\n\n function steps(items) {\n const ul = el(\"ul\", \"\", { className: \"steps\" });\n ul.setAttribute(\"aria-live\", \"polite\");\n for (const [label, state] of items) {\n const li = el(\"li\", \"\", { className: state === \"now\" ? \"now\" : \"\" });\n li.append(state === \"done\" ? icon(\"check\") : el(\"span\", \"\", { className: state === \"now\" ? \"dot info pulse\" : \"dot\" }), el(\"span\", label, { className: \"l\" }));\n if (state === \"now\") li.append(el(\"span\", elapsed(), { className: \"time\" }));\n ul.append(li);\n }\n return ul;\n }\n function openFoot(url, label = \"Open in Migma\") {\n const f = el(\"div\", \"\", { className: \"foot\" });\n if (url) f.append(linkButton(\"ghost\", label, url, \"edit\"));\n return f;\n }\n // One email: its poster beside what there is to say about it.\n function one(pic, ...side) {\n const box = el(\"div\", \"\", { className: \"one\" });\n const col = el(\"div\", \"\", { className: \"side\" });\n col.append(...side);\n box.append(pic, col);\n return box;\n }\n function titled(title, pre) {\n const head = el(\"div\", \"\");\n head.append(el(\"h1\", title, { className: \"h\" }));\n if (pre) head.append(el(\"p\", pre, { className: \"pre\", title: pre }));\n return head;\n }\n function plainPoster(e, dim) {\n const box = el(\"div\", \"\", { className: \"poster\" });\n const pic = el(\"div\", \"\", { className: \"pic\" });\n fill(pic, e, dim);\n box.append(pic);\n return box;\n }\n\n // ---- views ----\n function compactView() {\n const line = el(\"div\", \"\", { className: \"line\", role: \"status\" });\n const many = (s.count || s.slots?.length || s.emails?.length || 1) > 1;\n if (s.phase === \"working\") {\n line.append(el(\"span\", \"\", { className: \"dot info pulse\" }), el(\"span\", many ? \"Designing \" + (s.count || s.slots.length) + \" emails\" : \"Designing your email\", { className: \"t\" }));\n if (s.now) line.append(el(\"span\", s.now, { className: \"s\" }));\n line.append(el(\"span\", elapsed(), { className: \"time\" }));\n } else if (s.phase === \"failed\") {\n line.append(el(\"span\", \"\", { className: \"dot bad\" }), el(\"span\", \"Not created\", { className: \"t\" }), el(\"span\", s.error, { className: \"s\" }));\n } else {\n const first = s.emails.find((e) => e.picture);\n const mini = el(\"span\", \"\", { className: \"mini\" });\n if (first) mini.append(el(\"img\", \"\", { src: first.picture, alt: \"\" }));\n line.append(mini, el(\"span\", many ? s.emails.length + \" emails ready\" : s.emails[0].subject || \"Your email\", { className: \"t\" }));\n if (!many) line.append(el(\"span\", \"Ready\", { className: \"s\" }));\n line.append(button(\"btn ghost\", \"Show\", () => { s.compact = false; render(); if (missingPicture()) retryPicture(); }, \"show\", { ariaExpanded: \"false\" }));\n const url = s.emails[0].appUrl || s.appUrl;\n if (url) line.append(linkButton(\"primary\", \"Edit in Migma\", url, \"edit\"));\n }\n return [line];\n }\n\n function workingView() {\n if (s.mode === \"edit\") {\n const at = Math.max(0, EDIT_STEPS.findIndex(([, stages]) => stages.includes(s.stage)));\n return [brandLine(), one(\n plainPoster(s.before?.picture ? s.before : null, true),\n titled(s.before?.subject || \"Changing your email\", input.prompt),\n el(\"div\", \"\", { className: \"grow\" }),\n steps(EDIT_STEPS.map(([label], i) => [label, i < at ? \"done\" : i === at ? \"now\" : \"todo\"])),\n openFoot(s.before?.appUrl || s.appUrl),\n )];\n }\n const count = s.count || s.slots?.length || 1;\n const live = steps([...(s.steps || []).map((label) => [label, \"done\"]), [s.now || \"Starting\", \"now\"]]);\n if (count === 1) return [brandLine(), one(plainPoster(null), titled(\"Designing your email\", input.prompt), el(\"div\", \"\", { className: \"grow\" }), live, openFoot(s.appUrl))];\n const row = el(\"div\", \"\", { className: count === 2 ? \"row two\" : count > 3 ? \"row many\" : \"row\" });\n for (let i = 0; i < count; i++) {\n const done = s.slots?.[i] && !s.slots[i].pending;\n const box = el(\"div\", \"\", { className: \"poster\" });\n const pic = el(\"div\", \"\", { className: \"pic\" });\n pic.append(...skeleton());\n if (done) { const mark = el(\"span\", \"\", { className: \"done\" }); mark.append(icon(\"check\")); pic.append(mark); }\n const cap = el(\"div\", \"\", { className: \"cap\" });\n cap.append(el(\"b\", \"Email \" + (i + 1)), el(\"span\", done ? \"Done\" : \"Designing\"));\n box.append(pic, cap);\n row.append(box);\n }\n return [brandLine(), row, live, openFoot(s.appUrl)];\n }\n\n function failedView() {\n const retry = (text) => (input.prompt && !s.refused && caps.message ? button(\"btn primary\", \"Try again\", () => ask(text), \"primary\") : null);\n const end = (again, url, label) => {\n const f = openFoot(url, label);\n if (again) f.prepend(again);\n return f;\n };\n if (s.mode === \"edit\") {\n const e = s.before;\n const said = [titled(\"Not changed\", e?.subject), el(\"p\", s.error, { className: \"why\" })];\n if (s.mayHaveSaved) said.push(el(\"p\", \"Some changes may have been saved. Check the email in Migma before you try again.\", { className: \"why\" }));\n const last = end(retry(\"Try that change to \" + (e ? quoted(e) : \"the email\") + \" again.\"), e?.appUrl || s.appUrl, \"Edit in Migma\");\n return e?.picture ? [one(plainPoster(e), ...said, el(\"div\", \"\", { className: \"grow\" }), last)] : [...said, last];\n }\n if (s.mode === \"email\") return [titled(\"Could not show this email\"), el(\"p\", s.error, { className: \"why\" })];\n const many = (s.count || 1) > 1;\n return [titled(\"Not created\", input.prompt), el(\"p\", s.error, { className: \"why\" }), end(retry(many ? \"Try creating those emails again.\" : \"Try creating that email again.\"), s.appUrl)];\n }\n\n function readyView() {\n const e = s.emails[sel];\n if (series()) return [brandLine(), posters(), ...wholeEmail(e), ...controls(e, sel)];\n return [brandLine(), one(poster(e, 0), titled(e.failed ? \"Not created\" : e.subject || \"Your email\", e.failed ? \"\" : e.preheader), el(\"div\", \"\", { className: \"grow\" }), ...controls(e, 0)), ...wholeEmail(e)];\n }\n\n // The big view: every email whole, side by side; the same row and actions under them.\n function bigView() {\n const e = s.emails[sel];\n const box = el(\"section\", \"\", { className: \"big\" });\n const top = el(\"div\", \"\", { className: \"top\" });\n const back = button(\"x\", \"\", () => displayMode(\"inline\"), \"back\", { ariaLabel: \"Back to the chat\" });\n back.append(icon(\"collapse\"));\n const count = s.emails.length + \" emails\";\n top.append(el(\"h1\", series() ? (brandInfo ? brandInfo.name + \", \" + count : count) : e.subject || \"Your email\", { className: \"h\" }), back);\n box.append(top);\n if (series()) {\n const strip = el(\"div\", \"\", { className: \"strip\" });\n s.emails.forEach((x, i) => {\n const b = button(\"\", \"\", () => select(i), \"strip-\" + i, { ariaLabel: \"Email \" + (i + 1) + (x.subject ? \": \" + x.subject : \"\") });\n if (i === sel) b.setAttribute(\"aria-current\", \"true\");\n b.append(x.picture ? el(\"img\", \"\", { src: x.picture, alt: \"\" }) : icon(x.failed ? \"alert\" : \"image\"));\n strip.append(b);\n });\n box.append(strip);\n }\n const wall = el(\"div\", \"\", { className: \"wall\" });\n s.emails.forEach((x, i) => {\n const col = el(\"div\", \"\", { className: series() ? (i === sel ? \"col on\" : \"col\") : \"col only on\" });\n if (series()) col.append(caption(x, i));\n let pic;\n if (series() && i !== sel) {\n pic = button(\"pic\", \"\", () => select(i), \"email-\" + i);\n pic.setAttribute(\"aria-label\", \"Email \" + (i + 1) + (x.subject ? \": \" + x.subject : \"\"));\n } else pic = el(\"div\", \"\", { className: \"pic\" });\n fill(pic, x);\n col.append(pic);\n wall.append(col);\n });\n const bar = el(\"div\", \"\", { className: \"bar\" });\n bar.append(...controls(e, sel));\n if (s.note) bar.append(el(\"p\", s.note, { className: \"note\" }));\n box.append(wall, bar);\n return [box];\n }\n\n // A redraw replaces the controls, so one that lands between a press and its release would\n // swallow the click: it waits for the release.\n let pressed = 0, redraw = false;\n function release() {\n clearTimeout(pressed);\n pressed = 0;\n if (redraw) { redraw = false; draw(); }\n }\n document.addEventListener(\"pointerdown\", () => { clearTimeout(pressed); pressed = setTimeout(release, 1500); }, true);\n for (const type of [\"pointerup\", \"pointercancel\"]) document.addEventListener(type, () => setTimeout(release, 0), true);\n function render() { if (pressed) redraw = true; else draw(); }\n function draw() {\n const main = $(\"card\");\n main.setAttribute(\"aria-busy\", String(s.phase === \"working\" && !s.compact));\n let parts;\n if (s.compact) parts = compactView();\n else if (fullScreen()) parts = bigView();\n else parts = s.phase === \"working\" ? workingView() : s.phase === \"failed\" ? failedView() : readyView();\n if (s.note && !fullScreen()) parts.push(el(\"p\", s.note, { className: \"note\" }));\n // A redraw keeps where the user was: the control in use, and how far the row was scrolled.\n const key = document.activeElement?.dataset?.k;\n const left = main.querySelector(\".row\")?.scrollLeft || 0;\n const wall = main.querySelector(\".wall\");\n const down = wall?.scrollTop || 0, across = wall?.scrollLeft || 0;\n main.replaceChildren(...parts);\n if (left) main.querySelector(\".row\")?.scrollTo({ left });\n if (down || across) main.querySelector(\".wall\")?.scrollTo({ top: down, left: across });\n if (key) main.querySelector('[data-k=\"' + CSS.escape(key) + '\"]')?.focus({ preventScroll: true });\n // ChatGPT's own \"Open in\" button in full screen opens this card's page unless told otherwise.\n const link = s.emails?.[sel]?.appUrl || s.before?.appUrl || s.appUrl;\n if (link) window.openai?.setOpenInAppUrl?.({ href: link });\n tick();\n // The brand as soon as it is named; its lists once there is an email to send.\n if (brand && !brandAsked && !s.compact && s.phase !== \"failed\") loadBrand();\n if (s.phase === \"ready\" && !s.compact && canAct() && brand && !lists && !listsOff && !listsBusy) { rereadAt = Date.now(); loadLists().then(render); }\n }\n\n new ResizeObserver(() => send({ method: \"ui/notifications/size-changed\", params: { height: Math.ceil(document.documentElement.getBoundingClientRect().height) } }))\n .observe(document.documentElement);\n\n const init = await request(\"ui/initialize\", {\n appInfo: { name: \"Migma email\", version: \"1.0.0\" },\n appCapabilities: { availableDisplayModes: [\"inline\", \"fullscreen\"] },\n protocolVersion: \"2026-01-26\",\n });\n caps = init?.hostCapabilities ?? {};\n applyHost(init?.hostContext);\n send({ method: \"ui/notifications/initialized\", params: {} });\n</script>\n</body>\n</html>\n";
|
|
18
21
|
//# sourceMappingURL=email-card.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"email-card.d.ts","sourceRoot":"","sources":["../../src/tools/email-card.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE
|
|
1
|
+
{"version":3,"file":"email-card.d.ts","sourceRoot":"","sources":["../../src/tools/email-card.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,yCAAyC,CAAC;AAGzE;;;;;;;;;;;;;GAaG;AAEH,eAAO,MAAM,cAAc,qBAAqB,CAAC;AAEjD,mFAAmF;AACnF,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,CAEhF;AAED,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,SAAS,EAAE,IAAI,EAAE,OAAO,QAQjE;AAED,eAAO,MAAM,eAAe,yg8EA21C3B,CAAC"}
|