@migma/mcp 1.11.15 → 1.11.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,17 @@
1
1
  import { mcpAppMeta, registerMcpApp } from "./mcp-apps.js";
2
2
  /**
3
3
  * MCP Apps card for the email tools (generate, generation status, edit, get): progress while
4
- * Migma designs or changes an email, then each email's first screen, a series as tabs, and the
5
- * path from ready to sent (Test, Audience, Send). Each step runs on a click through tools/call: a
6
- * test to the account's own inbox (migma_send_test_email), the audience from the brand's segments
7
- * and lists, and a send that only prepares an approval (migma_send_email), which the user approves
8
- * on migma.ai while the card reads it (migma_get_send_approval). "Make it shorter" changes the email
9
- * in place (migma_edit_email). A host that refuses a call gets the step as a chat message
10
- * (ui/message); what the card did reaches the model through ui/update-model-context. "Edit in
11
- * Migma" goes through ui/open-link. Hosts without MCP Apps read the text result.
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 const EMAIL_CARD_URI = "ui://migma/email";
14
17
  /** Tool `_meta` that links an email tool to the card, when the server shows it. */
@@ -37,7 +40,6 @@ export const EMAIL_CARD_HTML = `<!doctype html>
37
40
  color-scheme: light dark;
38
41
  --surface: var(--color-background-primary, light-dark(#ffffff, #30302e));
39
42
  --muted: var(--color-background-secondary, light-dark(#f5f4ed, #262624));
40
- --muted-2: var(--color-background-tertiary, light-dark(#ebe9df, #3a3a37));
41
43
  --text: var(--color-text-primary, light-dark(#141413, #faf9f5));
42
44
  --text-2: var(--color-text-secondary, light-dark(#3d3d3a, #c2c0b6));
43
45
  --text-3: var(--color-text-tertiary, light-dark(#73726c, #9c9a92));
@@ -47,9 +49,10 @@ export const EMAIL_CARD_HTML = `<!doctype html>
47
49
  --on-inverse: var(--color-text-inverse, light-dark(#ffffff, #141413));
48
50
  --info: var(--color-border-info, light-dark(#4682d5, #6c9be0));
49
51
  --success: var(--color-border-success, light-dark(#437426, #7fb05b));
52
+ --success-text: var(--color-text-success, light-dark(#265b19, #7ab948));
50
53
  --danger: var(--color-border-danger, light-dark(#a73d39, #d1615c));
51
- --danger-text: var(--color-text-danger, light-dark(#7f2c28, #ee8884));
52
- --warning-text: var(--color-text-warning, light-dark(#5a4815, #d1a041));
54
+ --warning: var(--color-border-warning, light-dark(#8a6a12, #d1a041));
55
+ --bone: color-mix(in srgb, var(--text) 9%, transparent);
53
56
  --radius: var(--border-radius-lg, 10px);
54
57
  --radius-md: var(--border-radius-md, 8px);
55
58
  }
@@ -64,176 +67,173 @@ export const EMAIL_CARD_HTML = `<!doctype html>
64
67
  }
65
68
  p, h1, ul { margin: 0; }
66
69
  button { font: inherit; cursor: pointer; }
67
- button:focus-visible, .stage:focus-visible { outline: 2px solid var(--color-ring-primary, var(--info)); outline-offset: 2px; }
68
- button[disabled] { cursor: default; opacity: .5; }
70
+ button:focus-visible { outline: 2px solid var(--color-ring-primary, var(--info)); outline-offset: 2px; }
71
+ button[disabled] { cursor: default; opacity: .45; }
69
72
  main {
70
73
  container-type: inline-size;
74
+ display: flex; flex-direction: column; gap: 14px;
71
75
  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));
72
76
  }
73
77
  .i { width: 16px; height: 16px; flex: none; fill: none; stroke: currentColor; stroke-width: 1.75; stroke-linecap: round; stroke-linejoin: round; }
74
- .i.big { width: 24px; height: 24px; }
75
-
76
- .head { display: flex; gap: 12px; align-items: flex-start; justify-content: space-between; }
77
- .title { min-width: 0; }
78
- 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; }
79
- .pre { color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
80
- .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); }
81
- .icon-btn:hover { background: var(--muted); }
78
+ .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--text-3); }
79
+ .dot.info { background: var(--info); } .dot.ok { background: var(--success); } .dot.bad { background: var(--danger); } .dot.warn { background: var(--warning); }
80
+ .time { margin-left: auto; color: var(--text-3); font-variant-numeric: tabular-nums; flex: none; }
81
+ .note { color: var(--text-3); font-size: 13px; overflow-wrap: anywhere; }
82
+ .h { font-size: 20px; line-height: 1.25; font-weight: var(--font-weight-semibold, 600); letter-spacing: -.01em; overflow-wrap: anywhere; text-wrap: balance; }
83
+ .pre { margin-top: 6px; color: var(--text-3); overflow-wrap: anywhere; display: -webkit-box; -webkit-line-clamp: 3; -webkit-box-orient: vertical; overflow: hidden; }
84
+ .why { color: var(--text-2); overflow-wrap: anywhere; }
82
85
 
83
- .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; }
84
- .stage.short { height: 240px; overflow: hidden; }
85
- .shot { width: min(600px, 100%); flex: none; border-radius: 4px; overflow: hidden; box-shadow: 0 0 0 0.5px var(--line); background: var(--surface); }
86
- .shot img { display: block; width: 100%; height: auto; }
87
- .shot.dim { opacity: .45; }
88
- .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; }
89
- .sk { background: var(--muted-2); border-radius: 6px; flex: none; }
90
- .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; }
91
- .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); }
86
+ /* The brand the emails were made from. */
87
+ .brand { display: flex; align-items: center; gap: 10px; min-height: 22px; min-width: 0; font-size: 13px; color: var(--text-2); }
88
+ .brand .logo { width: 22px; height: 22px; flex: none; border-radius: 6px; object-fit: contain; background: var(--muted); }
89
+ .brand .mono { width: 22px; height: 22px; flex: none; border-radius: 6px; display: grid; place-items: center; font-size: 12px; font-weight: 600; }
90
+ .brand b { color: var(--text); font-weight: var(--font-weight-semibold, 600); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
91
+ .brand .dots { display: flex; gap: 4px; flex: none; }
92
+ .brand .dots i { width: 12px; height: 12px; border-radius: 50%; box-shadow: 0 0 0 0.5px var(--line-2); }
93
+ .brand .type { color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
94
+ .brand .fact { margin-left: auto; flex: none; display: inline-flex; gap: 6px; align-items: center; color: var(--text-3); white-space: nowrap; }
95
+ .brand .fact .i { width: 14px; height: 14px; color: var(--success); stroke-width: 2.25; }
92
96
 
93
- .tabs { display: flex; gap: 4px; margin-top: 12px; overflow-x: auto; scrollbar-width: none; }
94
- .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; }
95
- .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; }
96
- .tab .t { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
97
- .tab .d { color: var(--text-3); flex: none; }
98
- .tab[aria-selected="true"] { background: var(--muted); color: var(--text); }
99
- .tab[aria-selected="true"] .n { background: var(--inverse); color: var(--on-inverse); }
97
+ /* Every email as a poster: the top of the email, side by side. */
98
+ .rowwrap { position: relative; }
99
+ .row { display: flex; gap: 16px; min-width: 0; }
100
+ .poster { flex: 1 1 0; min-width: 0; max-width: 240px; display: flex; flex-direction: column; gap: 9px; color: var(--text-3); }
101
+ .row.two .poster { max-width: none; }
102
+ .row.two .pic { aspect-ratio: 1 / 1; }
103
+ .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; }
104
+ .row.many .poster { flex: none; width: 184px; scroll-snap-align: start; }
105
+ .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; }
106
+ .pic img { display: block; width: 100%; height: auto; }
107
+ .pic.dim img { opacity: .4; }
108
+ .poster.on .pic { outline: 2px solid var(--text); outline-offset: 3px; }
109
+ .cap { display: flex; gap: 8px; align-items: baseline; min-width: 0; padding: 0 1px; font-size: 13px; }
110
+ .cap b { flex: 1; min-width: 0; font-weight: var(--font-weight-medium, 500); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
111
+ .poster.on .cap b { color: var(--text); font-weight: var(--font-weight-semibold, 600); }
112
+ .cap span { flex: none; }
113
+ .cap .ok { color: var(--success-text); font-weight: var(--font-weight-medium, 500); }
114
+ .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%); }
115
+ .sk { display: block; margin: 14px 14px 0; border-radius: 5px; background: var(--bone); }
116
+ .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; }
117
+ .mid .i { width: 22px; height: 22px; }
118
+ .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); }
119
+ .done { position: absolute; right: 8px; top: 8px; width: 22px; height: 22px; border-radius: 50%; display: grid; place-items: center; background: var(--success); color: #ffffff; }
120
+ .done .i { width: 13px; height: 13px; stroke-width: 2.5; }
121
+ .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%); }
100
122
 
101
- .foot { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 12px; flex-wrap: wrap; }
102
- .asks { display: flex; gap: 6px; flex-wrap: wrap; }
103
- .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); }
104
- .chip:hover { background: var(--muted); }
105
- .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); }
106
- .primary { border: 0; background: var(--inverse); color: var(--on-inverse); margin-left: auto; }
107
- .ghost { border: 0.5px solid var(--line-2); background: transparent; color: var(--text); font-weight: var(--font-weight-medium, 500); margin-left: auto; }
108
- .ghost:hover { background: var(--muted); }
109
- @container (max-width: 420px) { .foot .primary, .foot .ghost { width: 100%; } }
123
+ /* The whole email in place, where the host has no full screen. */
124
+ .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); }
125
+ .whole img { display: block; width: 100%; height: auto; }
110
126
 
111
- .status { display: flex; gap: 8px; align-items: center; margin-bottom: 6px; color: var(--text-2); font-weight: var(--font-weight-medium, 500); }
112
- .dot { width: 8px; height: 8px; border-radius: 50%; flex: none; background: var(--text-3); }
113
- .dot.info { background: var(--info); } .dot.ok { background: var(--success); } .dot.bad { background: var(--danger); }
114
- .time { margin-left: auto; color: var(--text-3); font-variant-numeric: tabular-nums; font-weight: 400; }
115
- .steps { list-style: none; padding: 0; margin-top: 12px; display: grid; gap: 6px; }
116
- .steps li { display: flex; gap: 8px; align-items: center; color: var(--text-3); min-width: 0; }
117
- .steps li span:nth-child(2) { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
118
- .steps li.now { color: var(--text); }
119
- .mark { display: grid; place-items: center; width: 16px; height: 16px; flex: none; }
120
- .ring { width: 10px; height: 10px; border-radius: 50%; border: 1.5px solid var(--line-2); }
121
- .now .ring { border-color: var(--info); background: var(--info); }
122
- .note { margin-top: 12px; color: var(--text-2); overflow-wrap: anywhere; }
123
- .note.bad { color: var(--danger-text); }
124
- .note.warn { margin-top: 4px; color: var(--warning-text); }
125
- .note.small { color: var(--text-3); font-size: 13px; }
127
+ /* One email: its poster beside its subject and the controls. */
128
+ .one { display: flex; gap: 24px; min-width: 0; }
129
+ .one .poster { flex: none; width: 232px; max-width: none; }
130
+ .side { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 14px; }
131
+ .grow { flex: 1; }
126
132
 
127
- .slots { display: flex; gap: 12px; margin-top: 12px; overflow-x: auto; }
128
- .slot { flex: 1 0 72px; min-width: 0; max-width: 200px; display: flex; flex-direction: column; gap: 8px; }
129
- .slot .frame { aspect-ratio: 3 / 4; border-radius: var(--radius-md); background: var(--muted); display: grid; place-items: center; color: var(--text-3); }
130
- .slot.done .frame { color: var(--success); }
131
- .slot .lab { display: flex; flex-wrap: wrap; column-gap: 6px; color: var(--text-2); font-size: 13px; }
132
- .slot .lab span:last-child { color: var(--text-3); margin-left: auto; }
133
+ /* Who gets it, in any order. */
134
+ .to { position: relative; display: flex; gap: 10px; align-items: flex-start; }
135
+ .to .k { flex: none; width: 38px; color: var(--text-3); font-size: 13px; line-height: 32px; }
136
+ .chips { flex: 1; min-width: 0; display: flex; flex-wrap: wrap; gap: 6px; align-items: center; }
137
+ .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; }
138
+ .chip .n { overflow: hidden; text-overflow: ellipsis; }
139
+ .chip small { font-size: 12.5px; font-weight: 400; color: var(--text-3); font-variant-numeric: tabular-nums; overflow: hidden; text-overflow: ellipsis; }
140
+ .chip[aria-pressed="true"] { background: var(--inverse); border-color: var(--inverse); color: var(--on-inverse); }
141
+ .chip[aria-pressed="true"] small, .chip[aria-pressed="true"] .i { color: inherit; opacity: .72; }
142
+ .chip:not([aria-pressed="true"]):hover, .btn.ghost:hover, .ref:hover, .x:hover { background: var(--muted); }
143
+ .chip.more { border-style: dashed; color: var(--text-2); }
144
+ .chip .i { width: 13px; height: 13px; color: var(--text-3); }
145
+ .chip .dot { width: 7px; height: 7px; }
146
+ .ref { width: 32px; height: 32px; flex: none; display: grid; place-items: center; border: 0; border-radius: 50%; background: transparent; color: var(--text-3); }
133
147
 
134
- .line { display: flex; gap: 8px; align-items: center; min-height: 28px; color: var(--text-2); min-width: 0; }
135
- .line .t { color: var(--text); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; min-width: 0; }
136
- .line .s { color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; min-width: 0; }
137
- .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); }
138
- .line .thumb img { display: block; width: 100%; }
139
- .line .ghost, .line .primary { min-height: 30px; padding: 0 10px; font-size: 13px; margin-left: 0; }
140
- .line .ghost:first-of-type { margin-left: auto; }
141
- @container (max-width: 420px) { .line { flex-wrap: wrap; } .line .ghost:first-of-type { margin-left: 48px; } }
148
+ /* The two actions, and what happened. */
149
+ .foot { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
150
+ .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); }
151
+ .btn.primary { border: 0; background: var(--inverse); color: var(--on-inverse); }
152
+ .btn.ghost { border: 0.5px solid var(--line-2); background: transparent; color: var(--text); font-weight: var(--font-weight-medium, 500); }
153
+ .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; }
154
+ .said { margin-left: auto; min-width: 0; display: flex; flex-direction: column; align-items: flex-end; gap: 3px; }
155
+ .said .st { margin-left: 0; }
156
+ .st a { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
157
+ .nums { display: inline-flex; gap: 14px; color: var(--text-3); }
158
+ .nums b { margin-right: 5px; color: var(--text); font-weight: var(--font-weight-semibold, 600); font-variant-numeric: tabular-nums; }
159
+ .steps { list-style: none; padding: 0; display: grid; gap: 6px; color: var(--text-3); font-size: 13.5px; }
160
+ .steps li { display: flex; gap: 8px; align-items: center; min-width: 0; }
161
+ .steps .l { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
162
+ .steps .i { width: 14px; height: 14px; color: var(--success); stroke-width: 2.25; }
163
+ .steps .now { color: var(--text); }
164
+ .steps .now .dot { margin: 0 3px; }
142
165
 
143
- :root:has(.fs), :root:has(.fs) body { height: 100%; }
144
- main:has(.fs) { height: 100%; padding: 0; }
145
- .fs { height: 100%; display: flex; flex-direction: column; }
146
- .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); }
147
- .fs-body { flex: 1; display: flex; min-height: 0; }
148
- .rail { width: 200px; flex: none; padding: 16px; display: flex; flex-direction: column; gap: 12px; border-right: 0.5px solid var(--line); overflow-y: auto; }
149
- .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; }
150
- .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); }
151
- .rail-item .thumb img { display: block; width: 100%; align-self: start; }
152
- .rail-item[aria-current="true"] { background: var(--muted); color: var(--text); }
153
- .fs .stage { flex: 1; height: auto; margin: 0; border-radius: 0; padding: 24px; }
154
- .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); }
155
- .fs .note { margin: 0; padding: 0 20px 12px; }
156
- .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); }
157
- .step-btn.prev { left: 16px; } .step-btn.next { right: 16px; }
158
- .fs-wrap { flex: 1; position: relative; display: flex; min-width: 0; }
159
- .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); }
160
- /* Narrow full screen (Claude's side panel): tabs replace the rail and the arrows over the email. */
161
- @container (max-width: 720px) { .rail, .step-btn { display: none; } .fs .tabs { display: flex; } }
166
+ /* A status check: one line that opens in place. */
167
+ .line { display: flex; gap: 10px; align-items: center; min-height: 36px; min-width: 0; color: var(--text-2); }
168
+ .line .t { min-width: 0; color: var(--text); font-weight: var(--font-weight-semibold, 600); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
169
+ .line .s { min-width: 0; color: var(--text-3); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
170
+ .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); }
171
+ .line .mini img { display: block; width: 100%; }
172
+ .line .btn { min-height: 32px; padding: 0 12px; font-size: 13.5px; flex: none; }
173
+ .line .btn:first-of-type { margin-left: auto; }
162
174
 
163
- /* Ready: one line of status and fact, the email's first screen, the path from ready to sent. */
164
- :root { --pink: light-dark(#e31c5b, #f0587f); }
165
- .ready { display: flex; gap: 8px; align-items: center; min-height: 32px; margin: -6px 0 2px; color: var(--text-2); font-size: 13px; font-weight: var(--font-weight-medium, 500); }
166
- .ready .fact { display: inline-flex; gap: 4px; align-items: center; padding-left: 10px; margin-left: 2px; border-left: 0.5px solid var(--line-2); color: var(--text-3); font-weight: 400; }
167
- .ready .fact .i { width: 14px; height: 14px; color: var(--success); }
168
- .ready .brand { margin-left: auto; display: inline-flex; gap: 6px; align-items: center; color: var(--text-3); font-weight: 400; }
169
- .ready .brand i { width: 12px; height: 12px; border-radius: 3px; background: var(--pink); }
170
- .ready .icon-btn { margin-right: -8px; }
171
- @container (max-width: 420px) { .ready .fact { display: none; } }
172
- .stage.first { height: var(--first-h, 320px); overflow: hidden; }
173
- .stage.open { height: auto; overflow: visible; }
174
- .whole { position: absolute; left: 50%; bottom: 12px; transform: translateX(-50%); min-height: 32px; padding: 0 14px; border: 0.5px solid var(--line-2); border-radius: 999px; background: var(--surface); color: var(--text); font-size: 13px; font-weight: var(--font-weight-medium, 500); white-space: nowrap; box-shadow: 0 2px 8px rgb(0 0 0 / 8%); }
175
- .whole:hover { background: var(--muted); }
176
- .path { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px; margin-top: 12px; list-style: none; padding: 0; }
177
- .path.faded { opacity: .55; }
178
- .step { display: flex; flex-direction: column; gap: 4px; min-height: 72px; padding: 10px 12px; border-radius: var(--radius); background: var(--muted); min-width: 0; }
179
- .step .k { display: flex; gap: 6px; align-items: center; font-size: 13px; font-weight: var(--font-weight-semibold, 600); color: var(--text); }
180
- .step .k .i { width: 14px; height: 14px; }
181
- .step .v { font-size: 12.5px; color: var(--text-3); overflow-wrap: anywhere; }
182
- .step .s { margin-left: auto; display: grid; place-items: center; width: 18px; height: 18px; flex: none; border-radius: 50%; }
183
- .step .s.todo { width: 14px; height: 14px; border: 1.5px solid var(--line-2); }
184
- .step .s.asked { width: 14px; height: 14px; border: 2px solid var(--info); }
185
- .step .s.done { background: var(--success); color: #fff; }
186
- .step .s.done .i { width: 12px; height: 12px; stroke-width: 2.5; }
187
- .step .s.run { width: 14px; height: 14px; border: 2px solid var(--line-2); border-top-color: var(--pink); }
188
- .step .s.warn { width: 10px; height: 10px; background: var(--warning-text); }
189
- .step.warn .v { color: var(--warning-text); }
190
- .step.next { background: var(--surface); box-shadow: 0 0 0 1.5px var(--pink); }
191
- .step.done .v, .step.asked .v { color: var(--text-2); }
192
- @container (max-width: 420px) { .path { grid-template-columns: minmax(0, 1fr); } .step { min-height: 0; } }
193
- .pick { margin-top: 12px; padding: 12px; border-radius: var(--radius); background: var(--muted); display: flex; flex-direction: column; gap: 10px; }
194
- .pick-h { display: flex; justify-content: space-between; flex-wrap: wrap; gap: 4px 8px; font-size: 13px; font-weight: var(--font-weight-semibold, 600); }
195
- .pick-h span { color: var(--text-3); font-weight: 400; }
196
- .opts { display: flex; gap: 6px; flex-wrap: wrap; }
197
- .opt { display: inline-flex; gap: 8px; align-items: center; min-height: 36px; padding: 0 12px; border: 0.5px solid var(--line-2); border-radius: 999px; background: var(--surface); color: var(--text); font-size: 13px; font-weight: var(--font-weight-medium, 500); }
198
- .opt small { color: var(--text-3); font-size: 12px; font-weight: 400; font-variant-numeric: tabular-nums; }
199
- .opt[aria-pressed="true"] { box-shadow: 0 0 0 1.5px var(--text); border-color: transparent; }
200
- .ghost.left { margin-left: 0; }
201
- .facts { margin: 12px 0 0; display: grid; grid-template-columns: 72px 1fr; gap: 6px 12px; padding: 12px; border-radius: var(--radius); background: var(--muted); font-size: 13px; }
202
- .facts dt { color: var(--text-3); }
203
- .facts dd { margin: 0; color: var(--text); overflow-wrap: anywhere; }
204
- .panel .facts { margin: 0; }
205
- .note a.plans { color: inherit; text-decoration: underline; text-underline-offset: 3px; }
175
+ /* The big view (full screen, or the side panel): every email whole, side by side. */
176
+ :root:has(.big), :root:has(.big) body { height: 100%; }
177
+ main:has(.big) { height: 100%; padding: 0; gap: 0; }
178
+ .big { height: 100%; min-height: 0; display: flex; flex-direction: column; }
179
+ .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); }
180
+ .top .h { flex: 1; min-width: 0; font-size: 15px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }
181
+ .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); }
182
+ .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; }
183
+ .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); }
184
+ .strip img { display: block; width: 100%; align-self: start; }
185
+ .strip button[aria-current="true"] { outline: 2px solid var(--text); outline-offset: 2px; }
186
+ .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; }
187
+ .col { width: 340px; flex: none; display: flex; flex-direction: column; gap: 10px; color: var(--text-3); font-size: 13px; }
188
+ .col.only { width: min(600px, 100%); }
189
+ .col .pic { aspect-ratio: auto; max-height: none; min-height: 200px; border-radius: var(--radius-md); background: var(--surface); }
190
+ .col.on .pic { outline: 2px solid var(--text); outline-offset: 3px; }
191
+ .col.only .pic { outline: 0; }
192
+ .col.on .cap b { color: var(--text); font-weight: var(--font-weight-semibold, 600); }
193
+ .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); }
206
194
 
207
- /* Full screen: the whole email, the path in a panel beside it. */
208
- .desk { flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 340px; grid-template-rows: minmax(0, 1fr); min-width: 0; min-height: 0; }
209
- .desk .fs-wrap { min-height: 0; }
210
- .panel { border-left: 0.5px solid var(--line); padding: 20px; display: flex; flex-direction: column; gap: 10px; overflow-y: auto; }
211
- .panel h2 { margin: 0; font-size: 14px; font-weight: var(--font-weight-semibold, 600); }
212
- .panel .path { grid-template-columns: minmax(0, 1fr); margin-top: 0; }
213
- .panel .step { min-height: 0; }
214
- .panel .pick { margin-top: 0; }
215
- .panel .asks { margin-top: auto; padding-top: 12px; }
216
195
  @container (max-width: 720px) {
217
- .desk { grid-template-columns: minmax(0, 1fr); grid-template-rows: minmax(0, 1fr) auto; }
218
- .panel { border-left: 0; border-top: 0.5px solid var(--line); padding: 12px 20px; overflow: visible; }
219
- .panel h2 { display: none; }
220
- .panel .path { grid-template-columns: repeat(3, minmax(0, 1fr)); }
221
- .panel .asks { padding-top: 0; }
196
+ .strip { display: flex; }
197
+ .wall { padding: 20px; }
198
+ .col { display: none; width: 100%; }
199
+ .col.on { display: flex; }
200
+ .col.on .pic { outline: 0; }
201
+ .col .cap { display: none; }
202
+ }
203
+ @container (max-width: 520px) {
204
+ .brand .type { display: none; }
205
+ .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; }
206
+ .row .poster, .row.two .poster, .row.many .poster { flex: none; width: 150px; scroll-snap-align: start; }
207
+ .row.two .pic { aspect-ratio: 3 / 4; }
208
+ .next { display: none; }
209
+ .one { flex-direction: column; gap: 14px; }
210
+ .one .poster { width: 100%; }
211
+ .one .pic { aspect-ratio: 5 / 4; }
212
+ .to { flex-direction: column; gap: 4px; }
213
+ .to .k { width: auto; line-height: 1.4; }
214
+ .to .ref { position: absolute; right: -8px; top: -14px; width: 44px; height: 44px; }
215
+ .chip { min-height: 44px; padding: 0 16px; }
216
+ .btn { min-height: 46px; flex: 1; }
217
+ .line .btn { min-height: 44px; flex: none; }
218
+ .st, .said { order: -1; width: 100%; margin-left: 0; }
219
+ .said { align-items: flex-start; }
220
+ .nums { flex-wrap: wrap; gap: 4px 12px; }
222
221
  }
222
+ @container (max-width: 380px) { .brand .dots { display: none; } }
223
223
 
224
224
  @media (prefers-reduced-motion: no-preference) {
225
- .sk, .now .ring { animation: pulse 1.4s ease-in-out infinite; }
226
- .step .s.run { animation: spin 0.9s linear infinite; }
225
+ .pulse { animation: pulse 1.4s ease-in-out infinite; }
226
+ .spin .i { animation: spin 0.9s linear infinite; }
227
227
  @keyframes spin { to { transform: rotate(360deg); } }
228
- @keyframes pulse { 50% { opacity: .55; } }
228
+ @keyframes pulse { 50% { opacity: .45; } }
229
229
  }
230
230
  </style>
231
231
  </head>
232
232
  <body>
233
233
  <main id="card" aria-busy="true">
234
- <div class="sk" style="height:16px;width:40%"></div>
235
- <div class="sk" style="height:12px;width:70%;margin-top:8px"></div>
236
- <div class="stage short"></div>
234
+ <div class="sk" style="height:16px;width:40%;margin:0"></div>
235
+ <div class="sk" style="height:12px;width:70%;margin:0"></div>
236
+ <div class="sk" style="height:180px;margin:0"></div>
237
237
  </main>
238
238
  <script type="module">
239
239
  const ICON = {
@@ -241,38 +241,48 @@ export const EMAIL_CARD_HTML = `<!doctype html>
241
241
  collapse: '<path d="M4 14h6v6M20 10h-6V4M14 10l7-7M3 21l7-7"/>',
242
242
  out: '<path d="M7 17L17 7M8 7h9v9"/>',
243
243
  check: '<path d="M5 12l5 5L20 7"/>',
244
- prev: '<path d="M15 18l-6-6 6-6"/>',
245
244
  next: '<path d="M9 18l6-6-6-6"/>',
246
245
  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"/>',
247
246
  alert: '<circle cx="12" cy="12" r="9"/><path d="M12 8v4M12 16h.01"/>',
248
- mail: '<path d="M4 6h16v12H4zM4 7l8 6 8-6"/>',
249
- people: '<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20a6.5 6.5 0 0113 0M16 4.5a3.5 3.5 0 010 7M18 14a6 6 0 013.5 6"/>',
250
- send: '<path d="M21 3L10 14M21 3l-7 18-4-7-7-4z"/>',
247
+ refresh: '<path d="M20 11a8 8 0 1 0-2.3 6.3M20 4v7h-7"/>',
251
248
  };
252
249
  const CONTACTS_URL = "https://migma.ai/contacts/imports";
250
+ const SETUP_URL = "https://migma.ai/sending-domains";
251
+ const PLANS_URL = "https://migma.ai/pricing";
253
252
  const EDIT_STEPS = [["Checking the email", ["queued", "checking"]], ["Changing it", ["editing"]], ["Saving", ["saved"]]];
254
253
  const PICTURE_TRIES = 4;
254
+ // Lists and emails are read again when the user comes back to the card, at most this often.
255
+ const REREAD_MS = 30000;
256
+ const TOP_LISTS = 3;
257
+ // Other places an email can go. Out of sight until More is opened.
258
+ const TOOLS = [["tool:klaviyo", "Klaviyo"], ["tool:mailchimp", "Mailchimp"], ["tool:hubspot", "HubSpot"], ["tool:html", "HTML"]];
255
259
  const $ = (id) => document.getElementById(id);
256
260
  const el = (tag, text, attrs = {}) => Object.assign(document.createElement(tag), { textContent: text ?? "" }, attrs);
257
- function icon(name, big) {
261
+ function icon(name) {
258
262
  const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
259
- svg.setAttribute("class", big ? "i big" : "i");
263
+ svg.setAttribute("class", "i");
260
264
  svg.setAttribute("viewBox", "0 0 24 24");
261
265
  svg.setAttribute("aria-hidden", "true");
262
266
  svg.innerHTML = ICON[name];
263
267
  return svg;
264
268
  }
265
- function button(className, label, onclick, attrs = {}) {
269
+ // Every control carries a key, so the one in use keeps the keyboard focus when the card redraws.
270
+ function button(className, label, onclick, key, attrs = {}) {
266
271
  const b = el("button", label, { type: "button", className, ...attrs });
272
+ if (key) b.dataset.k = key;
267
273
  b.addEventListener("click", onclick);
268
274
  return b;
269
275
  }
270
276
  const https = (url) => (typeof url === "string" && url.startsWith("https://") ? url : "");
277
+ const num = (value) => (typeof value === "number" && value > 0 ? value : 0);
271
278
 
272
279
  let host = {}, caps = {}, input = {}, s = null, sel = 0, nextId = 1, timer = 0, ticker = 0, delay = 3000, tries = 0, busy = false;
273
- // The path from ready to sent: each email's steps (a series sends each email on its own), the
274
- // audience being picked, and whether the inline email is open to its full length.
275
- let brand = "", flow = {}, pick = null, whole = false, history = [];
280
+ // Raised by each tool result. A read that started before it belongs to what the card showed
281
+ // then, and its answer is dropped.
282
+ let turn = 0;
283
+ // Nothing here has an order. Each email keeps who it goes to and what happened for each audience;
284
+ // the brand, its lists and its sending addresses are read from Migma, never kept from an earlier look.
285
+ 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 = [];
276
286
  const pending = new Map();
277
287
 
278
288
  function send(msg) { window.parent.postMessage({ jsonrpc: "2.0", ...msg }, "*"); }
@@ -315,11 +325,10 @@ export const EMAIL_CARD_HTML = `<!doctype html>
315
325
  const inset = ctx.safeAreaInsets;
316
326
  if (inset) for (const side of ["top", "right", "bottom", "left"]) root.style.setProperty("--inset-" + side, (inset[side] || 0) + "px");
317
327
  root.dataset.mode = host.displayMode || "inline";
318
- // Inline, the email shows its first screen (no scrolling inside the card); keep the card within
319
- // the height the host allows. While designing or changing, the stage keeps --stage-h.
328
+ // Inline there is no scrolling inside the card: a poster gives up height before the card
329
+ // passes what the host allows.
320
330
  const max = host.containerDimensions?.maxHeight;
321
- root.style.setProperty("--stage-h", (max ? Math.max(240, Math.min(520, max - 200)) : innerWidth < 480 ? 420 : 520) + "px");
322
- root.style.setProperty("--first-h", (max ? Math.max(200, Math.min(340, max - 280)) : 320) + "px");
331
+ root.style.setProperty("--pic-max", max ? Math.max(150, max - 270) + "px" : "none");
323
332
  }
324
333
 
325
334
  // Each tool puts its JSON in one text item among others (a lead sentence, guidance, the Previews list).
@@ -342,11 +351,15 @@ export const EMAIL_CARD_HTML = `<!doctype html>
342
351
  return null;
343
352
  }
344
353
  function toEmail(e = {}, link = "") {
354
+ const picture = https(e.screenshotFullUrl) || https(e.screenshotUrl) || https(e.thumbnailUrl);
345
355
  return {
346
356
  emailId: e.emailId || e.id || "",
357
+ conversationId: typeof e.conversationId === "string" ? e.conversationId : "",
347
358
  subject: e.subject || "",
348
359
  preheader: e.preheader || e.previewText || "",
349
- picture: https(e.screenshotFullUrl) || https(e.screenshotUrl) || https(e.thumbnailUrl),
360
+ picture,
361
+ // Which version of the email this is: when Migma last saved it, or what it shows.
362
+ version: typeof e.updatedAt === "string" && e.updatedAt ? e.updatedAt : (e.subject || "") + "|" + picture,
350
363
  appUrl: https(e.appUrl) || link,
351
364
  failed: e.status === "failed",
352
365
  day: typeof e.sendOffsetDays === "number" ? e.sendOffsetDays : null,
@@ -355,14 +368,15 @@ export const EMAIL_CARD_HTML = `<!doctype html>
355
368
 
356
369
  function onResult(result) {
357
370
  clearTimeout(timer);
358
- sel = 0; tries = 0;
371
+ turn++;
372
+ sel = 0; tries = 0; busy = false;
359
373
  const data = json(result);
360
- // The brand, for reading its audiences: the tool input names it on hosted servers.
374
+ // The brand, for its look, lists and senders: the tool input names it on hosted servers.
361
375
  brand = (typeof input.projectId === "string" && input.projectId) || (typeof data?.projectId === "string" && data.projectId) || "";
362
- flow = {}; pick = null; whole = false; history = [];
376
+ brandInfo = null; brandAsked = false; lists = null; listsOff = false; listsBusy = false; asking = false; known = null; more = false; whole = false; flow = {}; history = [];
363
377
  if (result?.isError || !data || (data.error && !data.conversationId && !data.editId)) {
364
378
  const mode = input.emailId && input.prompt ? "edit" : input.prompt ? "create" : "email";
365
- // Refused before anything started (no credits, a locked email): trying again would only repeat it.
379
+ // Refused before anything started (a limit, a locked email): trying again would only repeat it.
366
380
  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." };
367
381
  render();
368
382
  if (mode === "edit") readBefore();
@@ -393,11 +407,12 @@ export const EMAIL_CARD_HTML = `<!doctype html>
393
407
 
394
408
  function applyStatus(d) {
395
409
  if (d.createdAt) s.createdAt = d.createdAt;
410
+ if (!brand && typeof d.projectId === "string") brand = d.projectId;
396
411
  if (d.status === "failed") { s.phase = "failed"; s.error = d.error || "Migma could not create this email."; return; }
397
412
  if (d.status === "completed") {
398
413
  const r = d.result || {};
399
- const rows = Array.isArray(r.emails) && r.emails.length ? r.emails : [r];
400
- s.emails = rows.map((e) => toEmail(e, s.appUrl));
414
+ const list = Array.isArray(r.emails) && r.emails.length ? r.emails : [r];
415
+ s.emails = list.map((e) => toEmail(e, s.appUrl));
401
416
  s.phase = "ready";
402
417
  return;
403
418
  }
@@ -406,7 +421,7 @@ export const EMAIL_CARD_HTML = `<!doctype html>
406
421
  const done = [...new Set(events.filter((e) => e.status === "complete").map((e) => e.label))];
407
422
  const live = p.now?.label && (p.now.status === "start" || p.now.status === "progress") ? p.now.label : "";
408
423
  s.now = live || events.filter((e) => e.status === "processing").pop()?.label || s.now || "";
409
- s.steps = done.filter((label) => label !== s.now).slice(-3);
424
+ s.steps = done.filter((label) => label !== s.now).slice(-2);
410
425
  if (Array.isArray(p.slots) && p.slots.length) s.slots = p.slots;
411
426
  }
412
427
 
@@ -438,21 +453,24 @@ export const EMAIL_CARD_HTML = `<!doctype html>
438
453
 
439
454
  async function readBefore() {
440
455
  if (!s?.emailId) return;
456
+ const mine = turn;
441
457
  const d = await read("migma_get_email", { emailId: s.emailId });
442
- if (d?.emailId && s.mode !== "email") { s.before = toEmail(d); render(); }
458
+ if (mine !== turn || !d?.emailId || s.mode === "email") return;
459
+ s.before = toEmail(d);
460
+ if (!brand && typeof d.projectId === "string") brand = d.projectId;
461
+ render();
443
462
  }
444
463
 
445
464
  async function poll() {
446
465
  clearTimeout(timer);
447
466
  if (!s || s.phase !== "working" || busy || document.visibilityState !== "visible") return;
448
467
  busy = true;
449
- if (s.mode === "create") {
450
- const d = await read("migma_get_generation_status", { conversationId: s.conversationId });
451
- if (d?.conversationId) applyStatus(d);
452
- } else {
453
- const d = await read("migma_get_email_edit_status", { emailId: s.emailId, editId: s.editId });
454
- if (d?.status) applyEdit(d);
455
- }
468
+ const mine = turn;
469
+ const d = s.mode === "create"
470
+ ? await read("migma_get_generation_status", { conversationId: s.conversationId })
471
+ : await read("migma_get_email_edit_status", { emailId: s.emailId, editId: s.editId });
472
+ if (mine !== turn) return;
473
+ if (s.mode === "create") { if (d?.conversationId) applyStatus(d); } else if (d?.status) applyEdit(d);
456
474
  busy = false;
457
475
  render();
458
476
  if (s.phase === "working") {
@@ -472,19 +490,34 @@ export const EMAIL_CARD_HTML = `<!doctype html>
472
490
  s.noPicture = true;
473
491
  return render();
474
492
  }
493
+ const mine = turn;
475
494
  timer = setTimeout(async () => {
476
495
  tries++;
477
- if (s.mode === "create") {
478
- const d = await read("migma_get_generation_status", { conversationId: s.conversationId });
479
- if (d?.status === "completed") applyStatus(d);
480
- } else {
481
- const d = await read("migma_get_email", { emailId: s.emails[0].emailId });
482
- if (d?.emailId) s.emails = [unchanged(toEmail(d, s.emails[0].appUrl), s.emails[0].stale)];
483
- }
496
+ await readEmails();
497
+ if (mine !== turn) return;
484
498
  render();
485
499
  if (missingPicture()) retryPicture();
486
500
  }, 4000 * 2 ** tries);
487
501
  }
502
+ // The emails as Migma has them now: a change made in the chat, or a picture captured since.
503
+ async function readEmails() {
504
+ const mine = turn;
505
+ if (s.mode === "create") {
506
+ const d = await read("migma_get_generation_status", { conversationId: s.conversationId });
507
+ if (mine === turn && d?.status === "completed") applyStatus(d);
508
+ } else if (s.emails?.[0]?.emailId) {
509
+ const was = s.emails[0];
510
+ const d = await read("migma_get_email", { emailId: was.emailId });
511
+ if (mine === turn && d?.emailId) s.emails = [unchanged(toEmail(d, was.appUrl), was.stale)];
512
+ }
513
+ if (mine !== turn || !s.emails) return;
514
+ sel = Math.min(sel, s.emails.length - 1);
515
+ // A template made from an earlier version of an email is not this email in Klaviyo.
516
+ for (const e of s.emails) {
517
+ const made = flow[keyOf(e)]?.tools["tool:klaviyo"];
518
+ if (made?.state === "done" && made.of !== e.version) { made.state = ""; made.url = ""; }
519
+ }
520
+ }
488
521
 
489
522
  function refreshSoon() { if (s?.phase === "working") { delay = 3000; poll(); } }
490
523
  document.addEventListener("visibilitychange", () => document.visibilityState === "visible" && refreshSoon());
@@ -502,7 +535,124 @@ export const EMAIL_CARD_HTML = `<!doctype html>
502
535
  ticker = setInterval(() => document.querySelectorAll(".time").forEach((t) => { t.textContent = elapsed(); }), 1000);
503
536
  }
504
537
 
505
- // ---- actions ----
538
+ // ---- what the card reads from Migma ----
539
+ // The tool's answer, the error it returned, or null when the host refused the call itself. A call
540
+ // that outlasts the card's patience may still finish: it is an error to try again, never a refusal.
541
+ const SLOW = "CARD_TIMEOUT";
542
+ async function run(name, args) {
543
+ try {
544
+ const result = await request("tools/call", { name, arguments: args }, 60000);
545
+ if (result?.isError) {
546
+ const refusal = json(result);
547
+ return { error: refusal?.error || texts(result)[0] || "Migma could not do this.", code: typeof refusal?.code === "string" ? refusal.code : "" };
548
+ }
549
+ return { data: json(result) ?? {}, list: rows(result) };
550
+ } catch (err) {
551
+ return err?.message === "timeout" ? { error: "This is taking longer than usual. Try again in a moment.", code: SLOW } : null;
552
+ }
553
+ }
554
+
555
+ // The brand the emails were made from. A member who may not read it sees the card without this line.
556
+ async function loadBrand() {
557
+ brandAsked = true;
558
+ const mine = turn;
559
+ const d = await read("migma_get_project", { projectId: brand });
560
+ if (mine !== turn || typeof d?.name !== "string" || !d.name) return;
561
+ const hex = (value) => (typeof value === "string" && /^#[0-9a-f]{3,8}$/i.test(value.trim()) ? value.trim().toLowerCase() : "");
562
+ const c = d.colors || {};
563
+ const colors = [...new Set([hex(c.accent), hex(c.text), hex(c.background?.page), hex(c.background?.container)].filter(Boolean))].slice(0, 4);
564
+ 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);
565
+ // The small square mark first, then the full logo; the card may load neither from every host.
566
+ brandInfo = { name: d.name, logos: [https(d.logoUrls?.favicon), https(d.logoUrls?.primary)].filter(Boolean), colors, fonts };
567
+ if (s) render();
568
+ }
569
+
570
+ // Every list and segment of the brand, biggest first. Read again on each look, so one added in
571
+ // Migma or in the chat is there; those that appeared after the first read are marked.
572
+ async function loadLists() {
573
+ if (!brand || listsBusy) return;
574
+ listsBusy = true;
575
+ const mine = turn;
576
+ const [segments, tags] = await Promise.all([
577
+ run("migma_list_segments", { projectId: brand }),
578
+ run("migma_list_tags", { projectId: brand }),
579
+ ]);
580
+ if (mine !== turn) return;
581
+ listsBusy = false;
582
+ if (!segments?.list && !tags?.list) {
583
+ // Neither could be read: the chat picks the audience with the user.
584
+ if (!lists) listsOff = true;
585
+ return;
586
+ }
587
+ const count = (r) => (typeof r.count === "number" ? r.count : typeof r.subscriberCount === "number" ? r.subscriberCount : null);
588
+ const option = (type) => (r) => ({ type, raw: String(r?.id ?? r?._id ?? ""), name: String(r?.name ?? ""), count: count(r ?? {}) });
589
+ const all = [...(segments?.list ?? []).map(option("segment")), ...(tags?.list ?? []).map(option("list"))]
590
+ .filter((o) => o.raw && o.name)
591
+ .sort((a, b) => (b.count ?? -1) - (a.count ?? -1));
592
+ for (const o of all) { o.id = o.type + ":" + o.raw; o.fresh = !!known && !known.has(o.id); }
593
+ known ||= new Set(all.map((o) => o.id));
594
+ lists = all;
595
+ listsOff = false;
596
+ }
597
+
598
+ // Sending domains belong to the account, not a brand: one sender is used as it is; several are
599
+ // offered as choices; none sends the user to set one up.
600
+ async function loadSenders() {
601
+ if (senders?.length) return senders;
602
+ const r = await run("migma_list_domains", {});
603
+ if (!r || r.error) return null;
604
+ senders = (r.list ?? [])
605
+ .filter((d) => d?.isVerified === true || d?.status === "verified")
606
+ .flatMap((d) => (Array.isArray(d.senders) ? d.senders : []).map((x) => ({ email: String(x?.email ?? ""), name: String(x?.fromName ?? ""), first: x?.isDefault === true })))
607
+ .filter((x) => x.email && x.name)
608
+ .sort((a, b) => Number(b.first) - Number(a.first))
609
+ .slice(0, 6);
610
+ return senders;
611
+ }
612
+
613
+ // What came back for an email, across every send of it Migma tracked (a test counts, and so does
614
+ // every list): never one list's result. Where sends went out as campaigns, their numbers together.
615
+ async function loadMetrics(e) {
616
+ const f = flowOf(e);
617
+ const campaigns = Object.values(f.sends).filter((x) => x.campaignId && x.state === "sent");
618
+ if (campaigns.length) {
619
+ const all = await Promise.all(campaigns.map((x) => read("migma_get_campaign_stats", { campaignId: x.campaignId })));
620
+ const got = all.filter(Boolean);
621
+ 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) };
622
+ } else if (e.emailId) {
623
+ const d = await read("migma_get_email_metrics", { emailId: e.emailId });
624
+ if (d?.summary) f.metrics = { delivered: num(d.summary.delivered), opened: num(d.summary.opened), clicked: num(d.summary.clicked) };
625
+ }
626
+ }
627
+
628
+ // Each tool call opens its own card, so an older card learns of a change made in the chat (a
629
+ // new list, a changed email) only by reading again: when the user comes back to it, or asks.
630
+ const allSends = () => Object.values(flow).flatMap((f) => Object.values(f.sends));
631
+ 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)]);
632
+ async function reread(asked) {
633
+ if (!s || s.phase !== "ready" || s.compact || listsBusy || asking) return;
634
+ if (!asked && Date.now() - rereadAt < REREAD_MS) return;
635
+ rereadAt = Date.now();
636
+ const was = s, before = signature();
637
+ if (asked) { asking = true; render(); }
638
+ const jobs = [loadLists(), readEmails()];
639
+ const e = s.emails[sel];
640
+ if (asked && e && !e.failed) jobs.push(loadMetrics(e));
641
+ // A sending address set up since the card last looked lets a held send go ahead.
642
+ const held = allSends().filter((x) => x.state === "nosender");
643
+ if (held.length) jobs.push(loadSenders().then((list) => { if (list?.length) for (const x of held) x.state = ""; }));
644
+ await Promise.all(jobs);
645
+ asking = false;
646
+ if (s !== was) return;
647
+ tries = 0;
648
+ // Nothing new: the card stays as it is under the pointer.
649
+ if (asked || signature() !== before) render();
650
+ if (missingPicture()) retryPicture();
651
+ }
652
+ document.documentElement.addEventListener("pointerenter", () => reread(false));
653
+ document.addEventListener("focusin", () => reread(false));
654
+
655
+ // ---- what the user can do ----
506
656
  async function openLink(url) {
507
657
  if (!url) return;
508
658
  try { const r = await request("ui/open-link", { url }); if (!r?.isError) return; } catch {}
@@ -526,186 +676,54 @@ export const EMAIL_CARD_HTML = `<!doctype html>
526
676
  }
527
677
  const canFullScreen = () => (host.availableDisplayModes || []).includes("fullscreen");
528
678
  const fullScreen = () => host.displayMode === "fullscreen" && s.phase === "ready" && !s.compact;
679
+ // A host that can neither run tools nor take messages shows the emails and their link.
680
+ const canAct = () => !!(caps.message || caps.serverTools);
529
681
  function select(i) {
530
682
  sel = Math.max(0, Math.min(s.emails.length - 1, i));
531
683
  render();
532
- document.querySelector('[aria-selected="true"], [aria-current="true"]')?.focus();
533
684
  }
534
685
  document.addEventListener("keydown", (event) => {
535
- if (!s || !fullScreen() || s.emails.length < 2 || event.target.closest?.('[role="tab"]')) return;
686
+ if (!s || !fullScreen() || s.emails.length < 2) return;
536
687
  if (event.key === "ArrowLeft") select(sel - 1);
537
688
  if (event.key === "ArrowRight") select(sel + 1);
538
689
  });
539
690
 
540
- // ---- pieces ----
541
691
  const series = () => s.emails.length > 1;
542
692
  const quoted = (e) => (e.subject ? "“" + e.subject + "”" : "this email");
543
- const named = (e, i) => (series() ? "email " + (i + 1) + " of the series, " + quoted(e) + "," : quoted(e));
544
- // An ask is run by the card (a function) or sent to the chat (text, where the host takes messages).
545
- const chip = (label, act) => button("chip", label, () => (typeof act === "function" ? act() : ask(act)));
546
- function asks(list) {
547
- const box = el("div", "", { className: "asks" });
548
- box.append(...list.filter(([, act]) => typeof act === "function" || caps.message).map(([label, act]) => chip(label, act)));
549
- return box;
550
- }
551
- function linkButton(url, primary) {
552
- if (!url) return el("span", "");
553
- const b = button(primary ? "primary" : "ghost", primary ? "Edit in Migma" : "Open in Migma", () => openLink(url));
554
- b.append(icon("out"));
555
- return b;
556
- }
557
- function foot(list, url, primary) {
558
- const f = el("div", "", { className: "foot" });
559
- f.append(asks(list), linkButton(url, primary));
560
- return f;
561
- }
562
- function head(title, pre, tools = []) {
563
- const h = el("div", "", { className: "head" });
564
- const t = el("div", "", { className: "title" });
565
- t.append(el("h1", title));
566
- if (pre) t.append(el("p", pre, { className: "pre", title: pre }));
567
- h.append(t);
568
- if (tools.length) { const box = el("div", "", { className: "tools" }); box.append(...tools); h.append(box); }
569
- return h;
570
- }
571
- function statusLine(label, tone) {
572
- const p = el("p", "", { className: "status" });
573
- p.append(el("span", "", { className: "dot " + tone }), el("span", label));
574
- return p;
575
- }
576
- function steps(items) {
577
- const ul = el("ul", "", { className: "steps" });
578
- ul.setAttribute("aria-live", "polite");
579
- for (const [label, state] of items) {
580
- const li = el("li", "", { className: state });
581
- const mark = el("span", "", { className: "mark" });
582
- mark.append(state === "done" ? icon("check") : el("span", "", { className: "ring" }));
583
- li.append(mark, el("span", label));
584
- if (state === "now") li.append(el("span", elapsed(), { className: "time" }));
585
- ul.append(li);
586
- }
587
- return ul;
588
- }
589
- function skeleton() {
590
- const box = el("div", "", { className: "skel" });
591
- for (const [h, w, m] of [[14, 30, 0], [56, 85, 16], [56, 60, 0], [200, 100, 8]]) {
592
- box.append(el("div", "", { className: "sk", style: "height:" + h + "px;width:" + w + "%;margin-top:" + m + "px" }));
593
- }
594
- return box;
595
- }
596
- function picture(e, dim) {
597
- const shot = el("div", "", { className: dim ? "shot dim" : "shot" });
598
- const img = el("img", "", { alt: (e.subject || "Email") + (dim ? ", before the change" : "") });
599
- img.addEventListener("error", () => { e.picture = ""; render(); if (missingPicture()) retryPicture(); }, { once: true });
600
- img.src = e.picture;
601
- shot.append(img);
602
- return shot;
603
- }
604
- function stageNote(iconName, text) {
605
- const note = el("div", "", { className: "stage-note" });
606
- note.append(icon(iconName, true), el("p", text));
607
- return note;
608
- }
609
- function stage(e, opts = {}) {
610
- const box = el("div", "", { className: opts.short ? "stage short" : opts.first ? (whole ? "stage open" : "stage first") : "stage" });
611
- if (e?.failed) {
612
- const ready = s.emails.filter((x) => !x.failed).length;
613
- box.append(stageNote("alert", "Migma could not create this email." + (ready ? " The other " + (ready === 1 ? "one is" : ready + " are") + " ready." : "")));
614
- } else if (e?.picture && opts.first) {
615
- // Inline, the first screen: no scrolling inside an inline card (host guidance). The whole email
616
- // opens full screen, or in place where the host has no full screen.
617
- box.append(picture(e, opts.dim));
618
- if (!whole) box.append(button("whole", "See the whole email", () => (canFullScreen() ? displayMode("fullscreen") : ((whole = true), render()))));
619
- } else if (e?.picture) {
620
- box.append(picture(e, opts.dim));
621
- box.tabIndex = 0;
622
- box.setAttribute("aria-label", (e.subject || "Email") + ", scroll to read");
623
- } else if (opts.short || !s.noPicture || !e) {
624
- box.append(skeleton());
625
- if (e && !opts.short) {
626
- const note = el("p", "", { className: "stage-note", role: "status" });
627
- const pill = el("span", "", { className: "pill" });
628
- pill.append(el("span", "", { className: "dot info" }), el("span", "Preparing the picture"));
629
- note.append(pill);
630
- box.append(note);
631
- }
632
- } else {
633
- box.append(stageNote("image", "No picture of this email yet. It is ready in Migma."));
634
- }
635
- return box;
636
- }
637
- function tabs() {
638
- const list = el("div", "", { className: "tabs", role: "tablist" });
639
- list.setAttribute("aria-label", "Emails in this series");
640
- s.emails.forEach((e, i) => {
641
- const tab = button("tab", "", () => select(i), { role: "tab" });
642
- tab.setAttribute("aria-selected", String(i === sel));
643
- tab.tabIndex = i === sel ? 0 : -1;
644
- tab.append(el("span", String(i + 1), { className: "n" }), el("span", e.failed ? "Not created" : e.subject || "Email " + (i + 1), { className: "t" }));
645
- if (e.failed) tab.append(el("span", "", { className: "dot bad" }));
646
- else if (e.day !== null) tab.append(el("span", "Day " + e.day, { className: "d" }));
647
- tab.addEventListener("keydown", (event) => {
648
- if (event.key === "ArrowLeft") select(i - 1);
649
- if (event.key === "ArrowRight") select(i + 1);
650
- });
651
- list.append(tab);
652
- });
653
- return list;
654
- }
655
- function readyAsks(e, i) {
656
- if (e.failed) return [["Try this email again", "Try creating email " + (i + 1) + " of the series again."]];
657
- return [
658
- ["Make it shorter", () => shorten(e, i)],
659
- ["Try another version", "Make another version of " + named(e, i).replace(/,$/, "") + "."],
660
- ];
661
- }
662
-
663
- // ---- the path from ready to sent ----
664
- // The card runs each step itself on a click (tools/call): a test to the account's own inbox, the
665
- // audience from the brand's segments and lists, and a send that only prepares an approval, which
666
- // the user approves on migma.ai. A host that refuses the call gets the step as a chat message.
667
- // What the card did is told to the model (ui/update-model-context), so the chat keeps track.
668
- const SETUP_URL = "https://migma.ai/sending-domains";
669
- const PLANS_URL = "https://migma.ai/pricing";
670
- const keyOf = (e) => e.emailId || "email-" + sel;
671
- const blank = () => ({ test: "", sentTo: "", audience: null, send: "", approval: null, change: "", note: "", plans: false });
672
- const flowOf = (e) => (flow[keyOf(e)] ||= blank());
693
+ const subjectOf = (e, i) => (series() ? "email " + (i + 1) + " of the series, " + quoted(e) : quoted(e));
694
+ const keyOf = (e) => e.emailId || "email-" + s.emails.indexOf(e);
695
+ const flowOf = (e) => (flow[keyOf(e)] ||= { to: "me", test: "", sentTo: "", note: "", plans: false, chat: "", sends: {}, tools: {}, metrics: null });
696
+ const sendOf = (f, id) => (f.sends[id] ||= { state: "", approval: null, note: "", plans: false, n: 0, campaignId: "" });
697
+ const toolOf = (f, id) => (f.tools[id] ||= { state: "", url: "", note: "", n: 0 });
698
+ const listOf = (f) => lists?.find((o) => o.id === f.to);
673
699
  const people = (n) => n.toLocaleString("en-US") + (n === 1 ? " person" : " people");
674
- const short = (text) => (text.length > 24 ? text.slice(0, 23) + "…" : text);
675
- const subjectOf = (e, i) => named(e, i).replace(/,$/, "");
676
700
  const target = (e) => (e.emailId ? { emailId: e.emailId } : { conversationId: s.conversationId });
677
- const stamp = () => Date.now().toString(36);
701
+ const hash = (text) => { let h = 5381; for (const ch of text) h = ((h * 33) ^ ch.charCodeAt(0)) >>> 0; return h.toString(36); };
678
702
  // A refusal that names the plan gets the plans page; nothing else in the card mentions plans.
679
703
  const planRefusal = (text) => /\\bplan\\b|upgrade|pricing/i.test(text || "");
680
704
  const waitMs = (ms) => new Promise((done) => setTimeout(done, ms));
681
-
682
- // The tool's answer, the error it returned, or null when the host refused the call itself.
683
- async function run(name, args) {
684
- try {
685
- const result = await request("tools/call", { name, arguments: args }, 60000);
686
- if (result?.isError) {
687
- const refusal = json(result);
688
- return { error: refusal?.error || texts(result)[0] || "Migma could not do this.", code: typeof refusal?.code === "string" ? refusal.code : "" };
689
- }
690
- return { data: json(result) ?? {}, list: rows(result) };
691
- } catch { return null; }
692
- }
705
+ // What the card did is told to the model, so the chat keeps track.
693
706
  function remember(text) {
694
707
  history.push(text);
695
708
  const context = "In the Migma email card, the user " + history.join("; ") + ".";
696
709
  request("ui/update-model-context", { content: [{ type: "text", text: context }] }, 10000).catch(() => {});
697
710
  }
698
- function failed(f, error) {
699
- f.note = error;
700
- f.plans = planRefusal(error);
711
+
712
+ function pickTo(e, id) {
713
+ const f = flowOf(e);
714
+ f.to = id;
715
+ render();
716
+ // Who it is from matters once a list is picked: several sending addresses are offered then.
717
+ if (listOf(f) && !senders) loadSenders().then(() => render());
701
718
  }
702
719
 
720
+ // Just me: a test to the account owner's own inbox. Nothing to approve.
703
721
  async function testIt(e, i) {
704
722
  const f = flowOf(e);
705
- f.test = "running"; f.note = ""; render();
723
+ f.test = "running"; f.note = ""; f.plans = false; render();
706
724
  const r = await run("migma_send_test_email", target(e));
707
725
  if (!r) f.test = (await ask("Send me a test of " + subjectOf(e, i) + ".")) ? "asked" : "";
708
- else if (r.error) { f.test = "warn"; failed(f, r.error); }
726
+ else if (r.error) { f.test = "warn"; f.note = r.error; f.plans = planRefusal(r.error); }
709
727
  else {
710
728
  f.test = "done";
711
729
  f.sentTo = String(r.data.sentTo || "");
@@ -714,326 +732,524 @@ export const EMAIL_CARD_HTML = `<!doctype html>
714
732
  render();
715
733
  }
716
734
 
717
- async function chooseAudience(e, i) {
718
- if (!brand) return askSend(e, i);
719
- const key = keyOf(e);
720
- flowOf(e).note = "";
721
- pick = { key, kind: "audience", loading: true, options: [], chosen: 0 };
722
- render();
723
- const [segments, lists] = await Promise.all([
724
- run("migma_list_segments", { projectId: brand }),
725
- run("migma_list_tags", { projectId: brand }),
726
- ]);
727
- if (pick?.key !== key) return;
728
- // Without either list the chat picks the audience with the user.
729
- if (!segments?.list && !lists?.list) { pick = null; return askSend(e, i); }
730
- const count = (r) => (typeof r.count === "number" ? r.count : typeof r.subscriberCount === "number" ? r.subscriberCount : null);
731
- const option = (type) => (r) => ({ type, id: String(r?.id ?? r?._id ?? ""), name: String(r?.name ?? ""), count: count(r ?? {}) });
732
- pick.options = [...(segments?.list ?? []).map(option("segment")), ...(lists?.list ?? []).map(option("list"))]
733
- .filter((o) => o.id && o.name)
734
- .sort((a, b) => (b.count ?? -1) - (a.count ?? -1))
735
- .slice(0, 6);
736
- pick.loading = false;
737
- render();
738
- }
739
- function useAudience(e) {
740
- const f = flowOf(e);
741
- f.audience = pick.options[pick.chosen];
742
- f.send = ""; f.note = ""; f.plans = false;
743
- pick = null;
744
- render();
745
- }
746
-
747
- // Sending domains belong to the account, not a brand: one sender is used as it is; several are
748
- // offered as choices; none sends the user to set one up.
749
- let senders = null;
750
- async function loadSenders() {
751
- if (senders) return senders;
752
- const r = await run("migma_list_domains", {});
753
- if (!r || r.error) return null;
754
- senders = (r.list ?? [])
755
- .filter((d) => d?.isVerified === true || d?.status === "verified")
756
- .flatMap((d) => (Array.isArray(d.senders) ? d.senders : []).map((x) => ({ email: String(x?.email ?? ""), name: String(x?.fromName ?? ""), first: x?.isDefault === true })))
757
- .filter((x) => x.email && x.name)
758
- .sort((a, b) => Number(b.first) - Number(a.first))
759
- .slice(0, 6);
760
- return senders;
761
- }
762
- async function sendIt(e, i, sender) {
735
+ // A list: the card only prepares the send, and the user approves it on migma.ai. One approval per
736
+ // email, list and sender: a second click shows the one that is waiting, and a new one is asked for
737
+ // only after the last ended (sent, declined, expired or refused).
738
+ const MANAGED_SINGLE_SEND_REFUSED = "WORKSPACE_KEY_SINGLE_SEND_REFUSED";
739
+ const NO_ELIGIBLE_RECIPIENTS = "NO_ELIGIBLE_RECIPIENTS";
740
+ const IDEMPOTENCY_CONFLICT = "IDEMPOTENCY_CONFLICT";
741
+ const IDEMPOTENCY_IN_PROGRESS = "IDEMPOTENCY_IN_PROGRESS";
742
+ const ENDED = ["sent", "scheduled", "declined", "expired", "failed"];
743
+ const OPEN = ["running", "waiting", "sending"];
744
+ // An approved send reads "sent" with result "queued" until it goes out, and can still fail then.
745
+ const queued = (a) => a?.status === "sent" && a.result?.status === "queued" && !a.result.batchId;
746
+ async function sendIt(e, i) {
763
747
  const f = flowOf(e);
764
- const a = f.audience;
765
- if (!a || a.chat) return askSend(e, i);
766
- f.note = ""; f.plans = false;
767
- if (!sender) {
768
- f.send = "running"; render();
769
- const list = await loadSenders();
770
- if (!list) { f.send = ""; return askSend(e, i); }
771
- if (!list.length) { f.send = "nosender"; return render(); }
772
- if (list.length > 1) {
773
- f.send = "";
774
- pick = { key: keyOf(e), kind: "sender", loading: false, options: list, chosen: 0 };
775
- return render();
748
+ const a = listOf(f);
749
+ if (!a) return askSend(e, i);
750
+ const sd = sendOf(f, a.id);
751
+ if (OPEN.includes(sd.state)) return;
752
+ sd.note = ""; sd.plans = false; sd.state = "running"; render();
753
+ const list = await loadSenders();
754
+ if (!list) { sd.state = ""; return askSend(e, i, a); }
755
+ if (!list.length) { sd.state = "nosender"; return render(); }
756
+ const sender = list[Math.min(from, list.length - 1)];
757
+ // The same key within a day returns the approval it made before, also to a later card. One
758
+ // still waiting is this send. One that ended is not, nor is a key used for another subject:
759
+ // those ask again under the next key.
760
+ let r = null, going = false;
761
+ for (let attempt = 0; attempt < 8; attempt++) {
762
+ const key = "card-" + keyOf(e) + "-" + a.raw + "-" + hash(sender.email) + "-" + sd.n;
763
+ r = await run("migma_send_email", {
764
+ recipientType: a.type === "list" ? "tag" : "segment",
765
+ recipientId: a.raw,
766
+ from: sender.email,
767
+ fromName: sender.name,
768
+ subject: e.subject,
769
+ ...target(e),
770
+ idempotency_key: key,
771
+ });
772
+ if (r?.code === MANAGED_SINGLE_SEND_REFUSED) r = await viaCampaign(e, a, sender, key, sd);
773
+ if (!r || (r.error && r.code !== IDEMPOTENCY_CONFLICT)) break;
774
+ if (!r.error) {
775
+ const id = String(r.data.approval?.id ?? "");
776
+ const seen = id ? await run("migma_get_send_approval", { approvalId: id }) : null;
777
+ // Approved earlier and still going out: asking again would send it twice.
778
+ going = queued(seen?.data);
779
+ if (going || !ENDED.includes(seen?.data?.status)) break;
776
780
  }
777
- sender = list[0];
781
+ sd.n++;
782
+ r = { error: "Migma could not prepare this send. Try again.", code: "" };
783
+ }
784
+ if (!r) { sd.state = ""; return askSend(e, i, a); }
785
+ if (r.error) {
786
+ sd.state = "warn";
787
+ sd.note = r.code === NO_ELIGIBLE_RECIPIENTS ? "No one on " + a.name + " can get email. Pick another list."
788
+ : r.code === IDEMPOTENCY_IN_PROGRESS ? "Migma is still preparing this send. Try again in a moment." : r.error;
789
+ sd.plans = planRefusal(r.error);
790
+ // Migma replays a refusal for a day under its key, so the next try needs the next key, or
791
+ // what the user fixed would never be seen. A request still running, or one the card stopped
792
+ // waiting for, may yet prepare its approval: the same key finds it.
793
+ if (r.code !== IDEMPOTENCY_IN_PROGRESS && r.code !== SLOW) sd.n++;
794
+ return render();
778
795
  }
779
- pick = null;
780
- f.send = "running"; render();
781
- const key = "card-" + keyOf(e) + "-" + a.id + "-" + stamp();
782
- let r = await run("migma_send_email", {
783
- recipientType: a.type === "list" ? "tag" : "segment",
784
- recipientId: a.id,
785
- from: sender.email,
786
- fromName: sender.name,
787
- subject: e.subject,
788
- ...target(e),
789
- idempotency_key: key,
790
- });
791
- if (r?.code === MANAGED_SINGLE_SEND_REFUSED) r = await viaCampaign(e, a, sender, key);
792
- if (!r) { f.send = ""; return askSend(e, i); }
793
- if (r.error) { f.send = "warn"; failed(f, r.error); return render(); }
794
796
  const approval = r.data.approval ?? {};
795
797
  const summary = r.data.summary ?? {};
796
- f.approval = {
798
+ sd.approval = {
797
799
  id: String(approval.id ?? ""),
798
800
  url: https(approval.approvalUrl),
799
801
  count: typeof summary.recipients === "number" ? summary.recipients : a.count,
800
- from: (summary.fromName || sender.name) + " <" + (summary.from || sender.email) + ">",
801
- subject: summary.subject || e.subject,
802
802
  warning: Array.isArray(summary.warnings) ? String(summary.warnings[0] ?? "") : "",
803
803
  };
804
- f.send = "waiting";
805
- remember("prepared a send of " + subjectOf(e, i) + " to " + a.name + "; it waits for their approval on migma.ai (" + f.approval.url + ")");
804
+ sd.state = going ? "sending" : "waiting";
805
+ if (!going) remember("prepared a send of " + subjectOf(e, i) + " to " + a.name + "; it waits for their approval on migma.ai (" + sd.approval.url + ")");
806
806
  render();
807
- watchApproval(e, i, f);
807
+ watchApproval(e, i, sd, a);
808
808
  }
809
809
  // A workspace connected through managed sign-in may send only campaigns (their approval re-checks
810
810
  // the member's role), so the same send goes as a campaign draft and its approval, which the user
811
811
  // approves on migma.ai the same way. Null (the host refused, or no brand to save it in) asks the chat.
812
- const MANAGED_SINGLE_SEND_REFUSED = "WORKSPACE_KEY_SINGLE_SEND_REFUSED";
813
- async function viaCampaign(e, a, sender, key) {
814
- if (!brand) return null;
812
+ async function viaCampaign(e, a, sender, key, sd) {
813
+ const conversationId = e.conversationId || s.conversationId;
814
+ if (!brand || !conversationId) return null;
815
815
  const draft = await run("migma_create_campaign", {
816
816
  projectId: brand,
817
817
  name: e.subject || "Email from Migma",
818
- ...target(e),
818
+ conversationId,
819
+ ...(e.emailId ? { emailId: e.emailId } : {}),
819
820
  subject: e.subject,
820
821
  from: sender.email,
821
822
  fromName: sender.name,
822
823
  recipientType: a.type === "list" ? "tag" : "audience",
823
- recipientId: a.id,
824
+ recipientId: a.raw,
824
825
  idempotency_key: key + "-draft",
825
826
  });
826
827
  if (!draft || draft.error) return draft;
827
- if (!draft.data.id) return { error: "Migma could not save the campaign." };
828
- return run("migma_send_campaign", { campaignId: String(draft.data.id), idempotency_key: key + "-send" });
828
+ if (!draft.data.id) return { error: "Migma could not save the campaign.", code: "" };
829
+ sd.campaignId = String(draft.data.id);
830
+ return run("migma_send_campaign", { campaignId: sd.campaignId, idempotency_key: key + "-send" });
829
831
  }
830
- // The approval happens on migma.ai; the card reads it until it is decided.
831
- async function watchApproval(e, i, f) {
832
+ // The approval happens on migma.ai; the card reads it until it is decided, whichever list is in view.
833
+ async function watchApproval(e, i, sd, a) {
834
+ const mine = turn;
835
+ const what = "the send of " + subjectOf(e, i) + " to " + a.name;
832
836
  let wait = 5000;
833
- while (f.send === "waiting" && f.approval?.id) {
837
+ while ((sd.state === "waiting" || sd.state === "sending") && sd.approval?.id) {
834
838
  await waitMs(wait);
839
+ if (mine !== turn) return;
835
840
  wait = Math.min(wait * 1.3, 20000);
836
841
  if (document.visibilityState !== "visible") continue;
837
- const r = await run("migma_get_send_approval", { approvalId: f.approval.id });
842
+ const r = await run("migma_get_send_approval", { approvalId: sd.approval.id });
843
+ if (mine !== turn) return;
838
844
  const status = r?.data?.status;
839
- if (status === "sent" || status === "scheduled") {
840
- f.send = "sent";
841
- remember("approved the send of " + subjectOf(e, i) + " on migma.ai; Migma sent it");
845
+ if (queued(r?.data)) {
846
+ // Approved, and on its way out: not sent until Migma says so.
847
+ if (sd.state === "sending") continue;
848
+ sd.state = "sending";
849
+ } else if (status === "sent" || status === "scheduled") {
850
+ sd.state = "sent"; sd.later = status === "scheduled"; sd.n++;
851
+ remember("approved " + what + " on migma.ai; Migma " + (sd.later ? "scheduled it" : "sent it"));
852
+ render();
853
+ await loadMetrics(e);
842
854
  } else if (status === "declined" || status === "expired" || status === "failed") {
843
- f.send = "warn";
844
- failed(f, status === "declined" ? "The send was declined on migma.ai." : status === "expired" ? "The approval expired before anyone approved it." : r.data.error || "The send did not go out.");
855
+ sd.state = "warn"; sd.n++;
856
+ 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.";
857
+ sd.plans = planRefusal(sd.note);
858
+ 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);
845
859
  } else continue;
846
- return render();
860
+ if (mine === turn) render();
861
+ if (sd.state !== "sending") return;
847
862
  }
848
863
  }
849
- async function askSend(e, i) {
864
+ async function askSend(e, i, a) {
850
865
  const f = flowOf(e);
851
- const a = f.audience;
852
- const to = a && !a.chat ? " to the " + a.name + (a.type === "list" ? " list" : " segment") : " to my audience";
866
+ const to = a ? " to the " + a.name + (a.type === "list" ? " list" : " segment") : " to my audience";
853
867
  if (!(await ask("Send " + subjectOf(e, i) + to + "."))) return;
854
- f.send = "asked";
855
- if (!f.audience) f.audience = { chat: true };
868
+ if (a) sendOf(f, a.id).state = "asked"; else f.chat = "asked";
856
869
  render();
857
870
  }
858
871
 
859
- // "Make it shorter" changes the email in place; the steps start again for the changed email.
860
- async function shorten(e, i) {
861
- if (!e.emailId) return ask("Make " + named(e, i) + " shorter.");
862
- const f = flowOf(e);
863
- f.change = "running"; f.note = ""; pick = null; render();
864
- const r = await run("migma_edit_email", { emailId: e.emailId, prompt: "Make it shorter.", idempotency_key: "card-shorter-" + e.emailId + "-" + stamp() });
865
- if (!r) { f.change = ""; render(); return ask("Make " + named(e, i) + " shorter."); }
866
- if (r.error || !r.data.editId) { f.change = ""; failed(f, r.error || "Migma could not change this email."); return render(); }
867
- let wait = r.data.pollAfterMs || 2000;
868
- for (;;) {
869
- await waitMs(wait);
870
- wait = Math.min(wait * 1.4, 15000);
871
- const d = await run("migma_get_email_edit_status", { emailId: e.emailId, editId: r.data.editId });
872
- if (d?.data?.status === "failed") { f.change = ""; failed(f, d.data.error || "Migma could not change this email."); return render(); }
873
- if (d?.data?.status === "completed") break;
872
+ // Other tools. Klaviyo gets the email as a template in the user's own account; the others are a
873
+ // file, which the chat hands over.
874
+ const TOOL_ASK = {
875
+ "tool:klaviyo": (text) => "Put " + text + " in my Klaviyo as a template.",
876
+ "tool:mailchimp": (text) => "Export " + text + " for Mailchimp.",
877
+ "tool:hubspot": (text) => "Export " + text + " for HubSpot.",
878
+ "tool:html": (text) => "Export " + text + " as HTML.",
879
+ };
880
+ async function askTool(e, i, id) {
881
+ const t = toolOf(flowOf(e), id);
882
+ if (await ask(TOOL_ASK[id](subjectOf(e, i)))) t.state = "asked";
883
+ render();
884
+ }
885
+ async function toKlaviyo(e, i) {
886
+ const t = toolOf(flowOf(e), "tool:klaviyo");
887
+ const conversationId = e.conversationId || s.conversationId;
888
+ if (!conversationId) return askTool(e, i, "tool:klaviyo");
889
+ t.state = "running"; t.note = ""; render();
890
+ // The same key until it works: a retry after a refusal the user fixed returns the one template.
891
+ const r = await run("migma_push_to_klaviyo", { conversationId, ...(e.emailId ? { emailId: e.emailId } : {}), idempotency_key: "card-klaviyo-" + keyOf(e) + "-" + t.n });
892
+ if (!r) { t.state = ""; return askTool(e, i, "tool:klaviyo"); }
893
+ // Still running when the card stopped waiting: the same key returns that one template.
894
+ if (r.code === SLOW) { t.state = ""; t.note = r.error; return render(); }
895
+ // Why Klaviyo refused (not connected, several accounts, the plan) is written for the chat, which
896
+ // can act on it with the user: the request goes there.
897
+ if (r.error) {
898
+ t.state = "";
899
+ if (caps.message) return askTool(e, i, "tool:klaviyo");
900
+ t.note = "Klaviyo did not take it. Ask for it in the chat to see why.";
901
+ return render();
874
902
  }
875
- const at = s.emails.indexOf(e);
876
- const now = await run("migma_get_email", { emailId: e.emailId });
877
- if (at >= 0 && now?.data?.emailId) s.emails[at] = unchanged(toEmail(now.data, e.appUrl), e.picture);
878
- flow[keyOf(e)] = blank();
879
- remember("made " + subjectOf(e, i) + " shorter");
880
- tries = 0;
903
+ t.state = "done"; t.url = https(r.data.editorUrl); t.of = e.version; t.n++;
904
+ remember("put " + subjectOf(e, i) + " in their Klaviyo as a template");
881
905
  render();
882
- if (missingPicture()) retryPicture();
883
906
  }
884
907
 
885
- function pathView(e, opts = {}) {
886
- const f = e ? flowOf(e) : blank();
887
- const a = f.audience;
888
- const picking = e && pick?.key === keyOf(e) && pick.kind === "audience";
889
- const test = {
890
- "": ["", "To your own inbox"], running: ["run", "Sending"], done: ["done", f.sentTo ? "Sent to " + f.sentTo : "In your inbox"],
891
- warn: ["warn", "Not sent"], asked: ["asked", "Asked in the chat"],
892
- }[f.test];
893
- const audience = a
894
- ? (a.chat ? ["asked", "In the chat"] : ["done", a.name + (a.count !== null ? ", " + people(a.count) : "")])
895
- : ["", picking && !pick.loading && !pick.options.length ? "No contacts yet" : picking ? "Pick who gets it" : "Your list, or bring one"];
896
- const send = {
897
- "": ["", "You approve on migma.ai"], running: ["run", "Preparing"], waiting: ["asked", "Waiting for your approval"],
898
- sent: ["done", typeof f.approval?.count === "number" ? "Sent to " + people(f.approval.count) : "Sent"],
899
- warn: ["warn", "Not sent"], nosender: ["warn", "Needs a sending address"], asked: ["asked", "Asked in the chat"],
900
- }[f.send];
901
- const next = opts.faded || f.change ? "" : !test[0] || f.test === "running" ? "test" : !a ? "audience" : f.send !== "sent" && f.send !== "asked" ? "send" : "";
902
- const list = el("ol", "", { className: opts.faded ? "path faded" : "path" });
903
- list.setAttribute("aria-label", "From ready to sent");
904
- for (const [key, label, iconName, [state, value]] of [["test", "Test", "mail", test], ["audience", "Audience", "people", audience], ["send", "Send", "send", send]]) {
905
- const li = el("li", "", { className: "step" + (key === next ? " next" : "") + (state ? " " + state : "") });
906
- if (key === next) li.setAttribute("aria-current", "step");
907
- const mark = el("span", "", { className: "s " + (state || "todo") });
908
- if (state === "done") mark.append(icon("check"));
909
- const k = el("span", "", { className: "k" });
910
- k.append(icon(iconName), el("span", label), mark);
911
- li.append(k, el("span", value, { className: "v" }));
912
- list.append(li);
908
+ // ---- pieces ----
909
+ function linkButton(className, label, url, key) {
910
+ const b = button("btn " + className, label, () => openLink(url), key);
911
+ b.append(icon("out"));
912
+ return b;
913
+ }
914
+ function skeleton() {
915
+ return [[10, 34], [34, 78], [34, 56], [104, 88]].map(([h, w]) => el("span", "", { className: "sk pulse", style: "height:" + h + "px;width:" + w + "%" }));
916
+ }
917
+ function middle(...parts) {
918
+ const box = el("span", "", { className: "mid" });
919
+ box.append(...parts);
920
+ return box;
921
+ }
922
+ function image(e, alt) {
923
+ const img = el("img", "", { alt });
924
+ img.addEventListener("error", () => { e.picture = ""; render(); if (missingPicture()) retryPicture(); }, { once: true });
925
+ img.src = e.picture;
926
+ return img;
927
+ }
928
+ // What a poster or a column shows: the email, why there is none, or that its picture is on its way.
929
+ function fill(pic, e, dim) {
930
+ if (!e) pic.append(...skeleton());
931
+ else if (e.failed) pic.append(middle(icon("alert"), el("span", "Not created")));
932
+ else if (e.picture) { pic.append(image(e, (e.subject || "Email") + (dim ? ", before the change" : ""))); if (dim) pic.classList.add("dim"); }
933
+ else if (s.noPicture) pic.append(middle(icon("image"), el("span", "No picture yet. It is ready in Migma.")));
934
+ else {
935
+ const pill = el("span", "", { className: "pill", role: "status" });
936
+ pill.append(el("span", "", { className: "dot info pulse" }), el("span", "Preparing the picture"));
937
+ pic.append(...skeleton(), middle(pill));
913
938
  }
914
- return list;
915
939
  }
916
- // What the last step left: the approval as it will go out, or why a step stopped.
917
- function stepNote(e) {
918
- const f = flowOf(e);
919
- const parts = [];
920
- if (f.approval && (f.send === "waiting" || f.send === "sent")) {
921
- const facts = el("dl", "", { className: "facts" });
922
- const a = f.audience;
923
- for (const [k, v] of [["To", a.name + (typeof f.approval.count === "number" ? ", " + people(f.approval.count) : "")], ["From", f.approval.from], ["Subject", f.approval.subject]]) {
924
- facts.append(el("dt", k), el("dd", v));
940
+ const sentOf = (e) => Object.values(flowOf(e).sends).filter((x) => x.state === "sent");
941
+ function caption(e, i) {
942
+ const cap = el("div", "", { className: "cap" });
943
+ cap.append(el("b", e.failed ? "Email " + (i + 1) : e.subject || "Email " + (i + 1)));
944
+ const sent = e.failed ? [] : sentOf(e);
945
+ if (sent.length) cap.append(el("span", sent.some((x) => !x.later) ? "Sent" : "Scheduled", { className: "ok" }));
946
+ else if (e.day !== null) cap.append(el("span", "Day " + e.day));
947
+ return cap;
948
+ }
949
+ // One email of the row. A click picks it; a click on the picked one opens the whole email: full
950
+ // screen where the host has it, in place under the row where it has not.
951
+ function poster(e, i) {
952
+ const many = series();
953
+ const on = many && i === sel;
954
+ const box = el("div", "", { className: on ? "poster on" : "poster" });
955
+ const shows = !e.failed && !!e.picture && (on || !many);
956
+ const opens = shows && canFullScreen();
957
+ let pic;
958
+ if (many || shows) {
959
+ pic = button("pic", "", () => (opens ? displayMode("fullscreen") : shows ? ((whole = !whole), render()) : select(i)), "email-" + i);
960
+ const name = e.subject || "email " + (i + 1);
961
+ pic.setAttribute("aria-label", !shows ? "Email " + (i + 1) + (e.subject ? ": " + e.subject : "") : whole && !opens ? "Show less of " + name : "See the whole email: " + name);
962
+ if (many) pic.setAttribute("aria-pressed", String(on));
963
+ if (shows && !opens) pic.setAttribute("aria-expanded", String(whole));
964
+ } else pic = el("div", "", { className: "pic" });
965
+ fill(pic, e);
966
+ if (shows) { const mark = el("span", "", { className: "open" }); mark.append(icon(whole && !opens ? "collapse" : "expand")); pic.append(mark); }
967
+ box.append(pic);
968
+ if (many) box.append(caption(e, i));
969
+ return box;
970
+ }
971
+ function wholeEmail(e) {
972
+ if (!whole || canFullScreen() || e.failed || !e.picture) return [];
973
+ const box = el("div", "", { className: "whole" });
974
+ box.append(image(e, e.subject || "Email"));
975
+ return [box];
976
+ }
977
+ function posters() {
978
+ const n = s.emails.length;
979
+ const row = el("div", "", { className: n === 2 ? "row two" : n > 3 ? "row many" : "row" });
980
+ s.emails.forEach((e, i) => row.append(poster(e, i)));
981
+ if (n <= 3) return row;
982
+ const wrap = el("div", "", { className: "rowwrap" });
983
+ const next = button("next", "", () => {
984
+ const end = row.scrollLeft + row.clientWidth >= row.scrollWidth - 8;
985
+ row.scrollTo({ left: end ? 0 : row.scrollLeft + 400, behavior: "smooth" });
986
+ }, "next", { ariaLabel: "More emails" });
987
+ next.append(icon("next"));
988
+ wrap.append(row, next);
989
+ return wrap;
990
+ }
991
+
992
+ function brandLine() {
993
+ const line = el("div", "", { className: "brand" });
994
+ const b = brandInfo;
995
+ if (b) {
996
+ if (b.logos.length) {
997
+ const img = el("img", "", { className: "logo", alt: "" });
998
+ img.addEventListener("error", () => { b.logos.shift(); render(); }, { once: true });
999
+ img.src = b.logos[0];
1000
+ line.append(img);
1001
+ } else {
1002
+ // No logo the card may load: the brand's initial on its own colour.
1003
+ const tone = b.colors[0] || "";
1004
+ 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;
1005
+ 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)" }));
925
1006
  }
926
- parts.push(facts);
927
- if (f.approval.warning) parts.push(el("p", f.approval.warning, { className: "note warn" }));
928
- }
929
- if (f.send === "nosender") parts.push(el("p", "Emails go out from your own address. Set it up once in Migma.", { className: "note small" }));
930
- if (f.note) {
931
- const p = el("p", f.note, { className: "note warn" });
932
- if (f.plans) {
933
- const plans = el("a", "See plans", { href: PLANS_URL, className: "plans" });
934
- plans.addEventListener("click", (event) => { event.preventDefault(); openLink(PLANS_URL); });
935
- p.append(" ", plans);
1007
+ line.append(el("b", b.name));
1008
+ if (b.colors.length) {
1009
+ const dots = el("span", "", { className: "dots", ariaHidden: "true" });
1010
+ dots.append(...b.colors.map((c) => el("i", "", { style: "background:" + c })));
1011
+ line.append(dots);
936
1012
  }
937
- parts.push(p);
1013
+ if (b.fonts.length) line.append(el("span", b.fonts.join(", "), { className: "type" }));
938
1014
  }
939
- if (f.change === "running") parts.push(el("p", "Making it shorter", { className: "note small", role: "status" }));
940
- return parts;
941
- }
942
- function pickView(e) {
943
- if (!pick || pick.key !== keyOf(e)) return null;
944
- const box = el("div", "", { className: "pick", role: "group" });
945
- box.setAttribute("aria-label", pick.kind === "sender" ? "Sender" : "Audience");
946
- if (pick.loading) {
947
- box.append(el("p", "Who gets it", { className: "pick-h" }), el("div", "", { className: "sk", style: "height:36px;width:60%" }));
948
- return box;
1015
+ const fact = el("span", "", { className: "fact" });
1016
+ fact.append(icon("check"), el("span", "Works in every inbox"));
1017
+ line.append(fact);
1018
+ return line;
1019
+ }
1020
+
1021
+ // Who gets it. Just me first, then the biggest lists; More opens the rest and the other tools.
1022
+ function chip(e, id, label, extra) {
1023
+ const f = flowOf(e);
1024
+ const b = button("chip", "", () => pickTo(e, id), "to-" + id);
1025
+ b.setAttribute("aria-pressed", String(f.to === id));
1026
+ b.append(el("span", label, { className: "n" }));
1027
+ if (extra) b.append(...extra);
1028
+ return b;
1029
+ }
1030
+ function toRows(e) {
1031
+ const f = flowOf(e);
1032
+ const all = lists || [];
1033
+ // A list that is gone from Migma cannot stay picked.
1034
+ if (lists && f.to !== "me" && f.to !== "chat" && !f.to.startsWith("tool:") && !listOf(f)) f.to = "me";
1035
+ const to = el("div", "", { className: "to" });
1036
+ to.append(el("span", "To", { className: "k" }));
1037
+ const chips = el("div", "", { className: "chips", role: "group" });
1038
+ chips.setAttribute("aria-label", "Who gets it");
1039
+ chips.append(chip(e, "me", "Just me"));
1040
+ // The biggest lists, plus any that is new since the card opened, waits for an approval or is picked.
1041
+ const picked = listOf(f);
1042
+ const open = (o) => OPEN.includes(f.sends[o.id]?.state);
1043
+ const shown = more ? all : all.filter((o, n) => n < TOP_LISTS || o.fresh || o === picked || open(o));
1044
+ for (const o of shown) {
1045
+ const extra = [];
1046
+ if (open(o)) extra.push(el("span", "", { className: "dot info" }));
1047
+ else if (o.fresh) extra.push(el("span", "", { className: "dot ok" }));
1048
+ if (o.count !== null) extra.push(el("small", o.count.toLocaleString("en-US")));
1049
+ chips.append(chip(e, o.id, o.name, extra));
949
1050
  }
950
- if (!pick.options.length) {
951
- box.append(
952
- el("p", "No contacts yet", { className: "pick-h" }),
953
- el("p", "Bring your list from Klaviyo, Shopify, Mailchimp or a CSV once, and every send can use it.", { className: "note small", style: "margin:0" }),
954
- );
955
- return box;
1051
+ if (lists && !all.length) {
1052
+ const add = button("chip more", "", () => openLink(CONTACTS_URL), "add");
1053
+ add.append(el("span", "Add contacts", { className: "n" }), icon("out"));
1054
+ chips.append(add);
956
1055
  }
957
- const h = el("p", pick.kind === "sender" ? "Who it is from" : "Who gets it", { className: "pick-h" });
958
- h.append(el("span", pick.kind === "sender" ? "Your sending addresses in Migma" : "From your contacts in Migma"));
959
- const opts = el("div", "", { className: "opts" });
960
- pick.options.forEach((o, n) => {
961
- const b = button("opt", o.name, () => { pick.chosen = n; render(); });
962
- b.setAttribute("aria-pressed", String(n === pick.chosen));
963
- if (pick.kind === "sender") b.append(el("small", o.email));
964
- else if (o.count !== null) b.append(el("small", o.count.toLocaleString("en-US")));
965
- opts.append(b);
966
- });
967
- box.append(h, opts);
968
- return box;
1056
+ // No lists to read (no brand named, or the host refused): the chat picks the audience.
1057
+ if (!lists && (listsOff || !brand) && caps.message) chips.append(chip(e, "chat", "My audience"));
1058
+ chips.append(button("chip more", more ? "Fewer" : "More", () => { more = !more; render(); }, "more", { ariaExpanded: String(more) }));
1059
+ to.append(chips);
1060
+ if (brand) {
1061
+ const again = button(asking ? "ref spin" : "ref", "", () => reread(true), "refresh", { ariaLabel: "Read the lists and emails again" });
1062
+ again.append(icon("refresh"));
1063
+ to.append(again);
1064
+ }
1065
+ const out = [to];
1066
+ // Who it is from, while it can still change: before this list's send is prepared.
1067
+ if (picked && senders && senders.length > 1 && ["", "warn"].includes(sendOf(f, picked.id).state)) {
1068
+ const row = el("div", "", { className: "to" });
1069
+ const group = el("div", "", { className: "chips", role: "group" });
1070
+ group.setAttribute("aria-label", "Who it is from");
1071
+ senders.forEach((x, n) => {
1072
+ const b = button("chip", "", () => { from = n; render(); }, "from-" + n);
1073
+ b.setAttribute("aria-pressed", String(n === Math.min(from, senders.length - 1)));
1074
+ b.append(el("span", x.name, { className: "n" }), el("small", x.email));
1075
+ group.append(b);
1076
+ });
1077
+ row.append(el("span", "From", { className: "k" }), group);
1078
+ out.push(row);
1079
+ }
1080
+ // A file export is of the whole request, so one email of a series can only go to Klaviyo; and
1081
+ // a file is handed over by the chat, so a host that takes no messages offers none.
1082
+ const tools = TOOLS.filter(([id]) => id === "tool:klaviyo" || (caps.message && !series()));
1083
+ if (more || f.to.startsWith("tool:")) {
1084
+ const row = el("div", "", { className: "to" });
1085
+ const group = el("div", "", { className: "chips", role: "group" });
1086
+ group.setAttribute("aria-label", "Other tools");
1087
+ for (const [id, label] of tools) group.append(chip(e, id, label, [icon("out")]));
1088
+ row.append(el("span", "Or in", { className: "k" }), group);
1089
+ out.push(row);
1090
+ }
1091
+ return out;
969
1092
  }
970
- function linkPrimary(label, url) {
971
- const b = button("primary", label, () => openLink(url));
972
- b.append(icon("out"));
973
- return b;
1093
+
1094
+ // The one thing to do next for what is picked. Never a step: picking something else changes it.
1095
+ function primary(e, i) {
1096
+ const f = flowOf(e);
1097
+ const label = series() ? "Send email " + (i + 1) : "Send";
1098
+ if (f.to === "me") return button("btn primary", label, () => testIt(e, i), "primary", { disabled: f.test === "running" });
1099
+ if (f.to === "tool:klaviyo") {
1100
+ const t = toolOf(f, f.to);
1101
+ if (t.state === "done" && t.url) return linkButton("primary", "Open in Klaviyo", t.url, "primary");
1102
+ if (t.state === "asked" || t.state === "done") return null;
1103
+ return button("btn primary", "Create in Klaviyo", () => toKlaviyo(e, i), "primary", { disabled: t.state === "running" });
1104
+ }
1105
+ 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");
1106
+ const a = listOf(f);
1107
+ if (!a) return f.chat === "asked" ? null : button("btn primary", label, () => askSend(e, i), "primary");
1108
+ const sd = sendOf(f, a.id);
1109
+ if (sd.state === "nosender") return linkButton("primary", "Set up sending", SETUP_URL, "primary");
1110
+ if (sd.state === "waiting" && sd.approval?.url) return linkButton("primary", "Approve on migma.ai", sd.approval.url, "primary");
1111
+ if (sd.state === "sent") return sd.approval?.url ? linkButton("ghost", "See results", sd.approval.url, "primary") : null;
1112
+ if (sd.state === "asked" || sd.state === "sending") return null;
1113
+ return button("btn primary", label, () => sendIt(e, i), "primary", { disabled: OPEN.includes(sd.state) });
974
1114
  }
975
- function nextButton(e, i) {
1115
+ // What happened for what is picked, in one line beside the actions; under it, what came back
1116
+ // for the email as a whole, said as that.
1117
+ function status(e, i) {
976
1118
  const f = flowOf(e);
977
- if (f.change) return null;
978
- const p = pick?.key === keyOf(e) ? pick : null;
979
- if (p?.kind === "sender") return button("primary", "Send from " + short(p.options[p.chosen].name), () => sendIt(e, i, p.options[p.chosen]));
980
- if (!f.test || f.test === "running") return button("primary", "Send me a test", () => testIt(e, i), { disabled: f.test === "running" });
981
- if (!f.audience) {
982
- if (!p) return button("primary", "Choose audience", () => chooseAudience(e, i));
983
- if (p.loading) return button("primary", "Choose audience", () => {}, { disabled: true });
984
- if (!p.options.length) return linkPrimary("Add contacts in Migma", CONTACTS_URL);
985
- return button("primary", "Use " + short(p.options[p.chosen].name), () => useAudience(e));
1119
+ const line = (tone, text, plans) => {
1120
+ const p = el("span", "", { className: "st", role: "status" });
1121
+ if (tone) p.append(el("span", "", { className: "dot " + tone }));
1122
+ p.append(el("span", text));
1123
+ if (plans) {
1124
+ const link = el("a", "See plans", { href: PLANS_URL });
1125
+ link.addEventListener("click", (event) => { event.preventDefault(); openLink(PLANS_URL); });
1126
+ p.lastChild.append(" ", link);
1127
+ }
1128
+ return p;
1129
+ };
1130
+ if (f.to === "me") {
1131
+ if (f.test === "running") return line("info pulse", "Sending");
1132
+ if (f.test === "done") return line("ok", f.sentTo ? "Sent to " + f.sentTo : "Sent to your inbox");
1133
+ if (f.test === "warn") return line("bad", f.note, f.plans);
1134
+ if (f.test === "asked") return line("", "Asked in the chat");
1135
+ return null;
986
1136
  }
987
- if (f.send === "nosender") return linkPrimary("Set up sending in Migma", SETUP_URL);
988
- if (f.send === "waiting") return linkPrimary("Approve on migma.ai", f.approval.url);
989
- if (f.send === "sent") return f.approval.url ? linkPrimary("See results", f.approval.url) : null;
990
- if (f.send === "warn" && f.plans) return button("primary", "Choose another list", () => { f.audience = null; f.send = ""; chooseAudience(e, i); });
991
- if (f.send === "warn") return button("primary", "Try the send again", () => sendIt(e, i));
992
- if (f.send === "" || f.send === "running") return button("primary", "Send", () => sendIt(e, i), { disabled: f.send === "running" });
1137
+ if (f.to.startsWith("tool:")) {
1138
+ const t = toolOf(f, f.to);
1139
+ if (t.state === "running") return line("info pulse", "Creating the template");
1140
+ if (t.state === "done") return line("ok", (series() ? "Email " + (i + 1) + " is" : "It is") + " in your Klaviyo");
1141
+ if (t.state === "asked") return line("", "Asked in the chat");
1142
+ return t.note ? line("warn", t.note) : null;
1143
+ }
1144
+ const a = listOf(f);
1145
+ if (!a) return f.chat === "asked" ? line("", "Asked in the chat") : null;
1146
+ const sd = sendOf(f, a.id);
1147
+ if (sd.state === "running") return line("info pulse", "Preparing");
1148
+ if (sd.state === "waiting") return line("info pulse", sd.approval.warning || "Waiting for your approval");
1149
+ if (sd.state === "sending") return line("info pulse", "Sending");
1150
+ if (sd.state === "sent" && sd.later) return line("ok", "Scheduled on migma.ai");
1151
+ if (sd.state === "sent") return line("ok", typeof sd.approval?.count === "number" ? "Sent to " + people(sd.approval.count) : "Sent");
1152
+ if (sd.state === "warn") return line("bad", sd.note, sd.plans);
1153
+ if (sd.state === "nosender") return line("warn", "Needs a sending address");
1154
+ if (sd.state === "asked") return line("", "Asked in the chat");
993
1155
  return null;
994
1156
  }
995
- function pathFoot(e, i) {
1157
+ function numbers(e, i) {
1158
+ const m = flowOf(e).metrics;
1159
+ if (!m || !m.delivered) return null;
1160
+ const p = el("span", "", { className: "st" });
1161
+ const nums = el("span", "", { className: "nums" });
1162
+ nums.append(el("span", series() ? "Email " + (i + 1) + " so far" : "So far"));
1163
+ for (const [value, label] of [[m.delivered, "delivered"], [m.opened, "opened"], [m.clicked, "clicked"]]) {
1164
+ const part = el("span", "");
1165
+ part.append(el("b", value.toLocaleString("en-US")), label);
1166
+ nums.append(part);
1167
+ }
1168
+ p.append(nums);
1169
+ return p;
1170
+ }
1171
+ function foot(e, i) {
996
1172
  const f = el("div", "", { className: "foot" });
997
1173
  const url = e.appUrl || s.appUrl;
998
- if (url) {
999
- const edit = button("ghost left", "Edit in Migma", () => openLink(url));
1000
- edit.append(icon("out"));
1001
- f.append(edit);
1174
+ if (e.failed) {
1175
+ // Nothing to send: the chat can try this one again.
1176
+ 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"));
1177
+ if (url) f.append(linkButton("ghost", "Open in Migma", url, "edit"));
1178
+ const p = el("span", "", { className: "st" });
1179
+ p.append(el("span", "", { className: "dot bad" }), el("span", series() ? "Email " + (i + 1) + " was not created" : "Not created"));
1180
+ f.append(p);
1181
+ return f;
1002
1182
  }
1003
- const next = nextButton(e, i);
1183
+ const next = canAct() ? primary(e, i) : null;
1004
1184
  if (next) f.append(next);
1185
+ if (url) f.append(linkButton(canAct() ? "ghost" : "primary", "Edit in Migma", url, "edit"));
1186
+ const said = canAct() ? [status(e, i), numbers(e, i)].filter(Boolean) : [];
1187
+ if (said.length) {
1188
+ const box = el("div", "", { className: "said" });
1189
+ box.append(...said);
1190
+ f.append(box);
1191
+ }
1005
1192
  return f;
1006
1193
  }
1007
- function readyLine(tools) {
1008
- const line = el("div", "", { className: "ready" });
1009
- const fact = el("span", "", { className: "fact" });
1010
- fact.append(icon("check"), el("span", "Works in every inbox"));
1011
- const mark = el("span", "", { className: "brand" });
1012
- mark.append(el("i", ""), el("span", "Migma"));
1013
- line.append(el("span", "", { className: "dot ok" }), el("span", series() ? "Email designs ready" : "Email design ready"), fact, mark, ...tools);
1014
- return line;
1194
+ const controls = (e, i) => (canAct() && !e.failed ? [...toRows(e), foot(e, i)] : [foot(e, i)]);
1195
+
1196
+ function steps(items) {
1197
+ const ul = el("ul", "", { className: "steps" });
1198
+ ul.setAttribute("aria-live", "polite");
1199
+ for (const [label, state] of items) {
1200
+ const li = el("li", "", { className: state === "now" ? "now" : "" });
1201
+ li.append(state === "done" ? icon("check") : el("span", "", { className: state === "now" ? "dot info pulse" : "dot" }), el("span", label, { className: "l" }));
1202
+ if (state === "now") li.append(el("span", elapsed(), { className: "time" }));
1203
+ ul.append(li);
1204
+ }
1205
+ return ul;
1206
+ }
1207
+ function openFoot(url, label = "Open in Migma") {
1208
+ const f = el("div", "", { className: "foot" });
1209
+ if (url) f.append(linkButton("ghost", label, url, "edit"));
1210
+ return f;
1211
+ }
1212
+ // One email: its poster beside what there is to say about it.
1213
+ function one(pic, ...side) {
1214
+ const box = el("div", "", { className: "one" });
1215
+ const col = el("div", "", { className: "side" });
1216
+ col.append(...side);
1217
+ box.append(pic, col);
1218
+ return box;
1219
+ }
1220
+ function titled(title, pre) {
1221
+ const head = el("div", "");
1222
+ head.append(el("h1", title, { className: "h" }));
1223
+ if (pre) head.append(el("p", pre, { className: "pre", title: pre }));
1224
+ return head;
1225
+ }
1226
+ function plainPoster(e, dim) {
1227
+ const box = el("div", "", { className: "poster" });
1228
+ const pic = el("div", "", { className: "pic" });
1229
+ fill(pic, e, dim);
1230
+ box.append(pic);
1231
+ return box;
1015
1232
  }
1016
- // A host that can neither run tools nor take messages shows the email and its link.
1017
- const hasPath = (e) => !e.failed && !!(caps.message || caps.serverTools);
1018
1233
 
1019
1234
  // ---- views ----
1020
1235
  function compactView() {
1021
1236
  const line = el("div", "", { className: "line", role: "status" });
1022
1237
  const many = (s.count || s.slots?.length || s.emails?.length || 1) > 1;
1023
1238
  if (s.phase === "working") {
1024
- line.append(el("span", "", { className: "dot info" }), el("span", many ? "Designing " + (s.count || s.slots.length) + " emails" : "Designing your email", { className: "t" }));
1239
+ line.append(el("span", "", { className: "dot info pulse" }), el("span", many ? "Designing " + (s.count || s.slots.length) + " emails" : "Designing your email", { className: "t" }));
1025
1240
  if (s.now) line.append(el("span", s.now, { className: "s" }));
1026
1241
  line.append(el("span", elapsed(), { className: "time" }));
1027
1242
  } else if (s.phase === "failed") {
1028
1243
  line.append(el("span", "", { className: "dot bad" }), el("span", "Not created", { className: "t" }), el("span", s.error, { className: "s" }));
1029
1244
  } else {
1030
1245
  const first = s.emails.find((e) => e.picture);
1031
- const thumb = el("span", "", { className: "thumb" });
1032
- if (first) thumb.append(el("img", "", { src: first.picture, alt: "" }));
1033
- line.append(thumb, el("span", many ? s.emails.length + " emails" : s.emails[0].subject || "Your email", { className: "t" }), el("span", "Ready", { className: "s" }));
1034
- const show = button("ghost", "Show", () => { s.compact = false; render(); if (missingPicture()) retryPicture(); });
1035
- show.setAttribute("aria-expanded", "false");
1036
- line.append(show, linkButton(s.emails[0].appUrl || s.appUrl, true));
1246
+ const mini = el("span", "", { className: "mini" });
1247
+ if (first) mini.append(el("img", "", { src: first.picture, alt: "" }));
1248
+ line.append(mini, el("span", many ? s.emails.length + " emails ready" : s.emails[0].subject || "Your email", { className: "t" }));
1249
+ if (!many) line.append(el("span", "Ready", { className: "s" }));
1250
+ line.append(button("btn ghost", "Show", () => { s.compact = false; render(); if (missingPicture()) retryPicture(); }, "show", { ariaExpanded: "false" }));
1251
+ const url = s.emails[0].appUrl || s.appUrl;
1252
+ if (url) line.append(linkButton("primary", "Edit in Migma", url, "edit"));
1037
1253
  }
1038
1254
  return [line];
1039
1255
  }
@@ -1041,138 +1257,132 @@ export const EMAIL_CARD_HTML = `<!doctype html>
1041
1257
  function workingView() {
1042
1258
  if (s.mode === "edit") {
1043
1259
  const at = Math.max(0, EDIT_STEPS.findIndex(([, stages]) => stages.includes(s.stage)));
1044
- return [
1045
- head(s.before?.subject || "Changing your email", input.prompt),
1260
+ return [brandLine(), one(
1261
+ plainPoster(s.before?.picture ? s.before : null, true),
1262
+ titled(s.before?.subject || "Changing your email", input.prompt),
1263
+ el("div", "", { className: "grow" }),
1046
1264
  steps(EDIT_STEPS.map(([label], i) => [label, i < at ? "done" : i === at ? "now" : "todo"])),
1047
- s.before?.picture ? stage(s.before, { dim: true }) : stage(null, { short: true }),
1048
- foot([], s.before?.appUrl || s.appUrl, false),
1049
- ];
1265
+ openFoot(s.before?.appUrl || s.appUrl),
1266
+ )];
1050
1267
  }
1051
1268
  const count = s.count || s.slots?.length || 1;
1052
- const parts = [
1053
- head(count > 1 ? "Designing " + count + " emails" : "Designing your email", input.prompt),
1054
- steps([...(s.steps || []).map((label) => [label, "done"]), [s.now || "Starting", "now"]]),
1055
- ];
1056
- if (count > 1) {
1057
- const slots = el("div", "", { className: "slots" });
1058
- for (let i = 0; i < count; i++) {
1059
- const done = s.slots?.[i] && !s.slots[i].pending;
1060
- const slot = el("div", "", { className: done ? "slot done" : "slot" });
1061
- const frame = el("div", "", { className: "frame" });
1062
- frame.append(done ? icon("check", true) : el("span", "", { className: "dot info" }));
1063
- const lab = el("div", "", { className: "lab" });
1064
- lab.append(el("span", "Email " + (i + 1)), el("span", done ? "Done" : "Designing"));
1065
- slot.append(frame, lab);
1066
- slots.append(slot);
1067
- }
1068
- parts.push(slots);
1069
- } else {
1070
- parts.push(stage(null, { short: true }));
1269
+ const live = steps([...(s.steps || []).map((label) => [label, "done"]), [s.now || "Starting", "now"]]);
1270
+ if (count === 1) return [brandLine(), one(plainPoster(null), titled("Designing your email", input.prompt), el("div", "", { className: "grow" }), live, openFoot(s.appUrl))];
1271
+ const row = el("div", "", { className: count === 2 ? "row two" : count > 3 ? "row many" : "row" });
1272
+ for (let i = 0; i < count; i++) {
1273
+ const done = s.slots?.[i] && !s.slots[i].pending;
1274
+ const box = el("div", "", { className: "poster" });
1275
+ const pic = el("div", "", { className: "pic" });
1276
+ pic.append(...skeleton());
1277
+ if (done) { const mark = el("span", "", { className: "done" }); mark.append(icon("check")); pic.append(mark); }
1278
+ const cap = el("div", "", { className: "cap" });
1279
+ cap.append(el("b", "Email " + (i + 1)), el("span", done ? "Done" : "Designing"));
1280
+ box.append(pic, cap);
1281
+ row.append(box);
1071
1282
  }
1072
- // What comes next, faded, while people wait.
1073
- if (caps.message) parts.push(el("p", "Next, without leaving the chat", { className: "note small" }), pathView(null, { faded: true }));
1074
- parts.push(foot([], s.appUrl, false));
1075
- return parts;
1283
+ return [brandLine(), row, live, openFoot(s.appUrl)];
1076
1284
  }
1077
1285
 
1078
1286
  function failedView() {
1287
+ const retry = (text) => (input.prompt && !s.refused && caps.message ? button("btn primary", "Try again", () => ask(text), "primary") : null);
1288
+ const end = (again, url, label) => {
1289
+ const f = openFoot(url, label);
1290
+ if (again) f.prepend(again);
1291
+ return f;
1292
+ };
1079
1293
  if (s.mode === "edit") {
1080
1294
  const e = s.before;
1081
- const parts = [statusLine("Not changed", "bad"), head(e?.subject || "Your email", input.prompt), el("p", s.error, { className: "note bad" })];
1082
- 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" }));
1083
- if (e?.picture) parts.push(stage(e));
1084
- parts.push(foot(input.prompt && !s.refused ? [["Try again", "Try that change to " + (e ? quoted(e) : "the email") + " again."]] : [], e?.appUrl || s.appUrl, true));
1085
- return parts;
1295
+ const said = [titled("Not changed", e?.subject), el("p", s.error, { className: "why" })];
1296
+ if (s.mayHaveSaved) said.push(el("p", "Some changes may have been saved. Check the email in Migma before you try again.", { className: "why" }));
1297
+ const last = end(retry("Try that change to " + (e ? quoted(e) : "the email") + " again."), e?.appUrl || s.appUrl, "Edit in Migma");
1298
+ return e?.picture ? [one(plainPoster(e), ...said, el("div", "", { className: "grow" }), last)] : [...said, last];
1086
1299
  }
1087
- if (s.mode === "email") return [statusLine("Could not show this email", "bad"), el("p", s.error, { className: "note bad" })];
1300
+ if (s.mode === "email") return [titled("Could not show this email"), el("p", s.error, { className: "why" })];
1088
1301
  const many = (s.count || 1) > 1;
1089
- return [
1090
- statusLine("Not created", "bad"),
1091
- head(many ? "Your emails" : "Your email", input.prompt),
1092
- el("p", s.error, { className: "note bad" }),
1093
- foot(input.prompt && !s.refused ? [["Try again", many ? "Try creating those emails again." : "Try creating that email again."]] : [], s.appUrl, false),
1094
- ];
1302
+ 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)];
1095
1303
  }
1096
1304
 
1097
1305
  function readyView() {
1098
1306
  const e = s.emails[sel];
1099
- const full = canFullScreen() ? [button("icon-btn", "", () => displayMode("fullscreen"), { ariaLabel: "Full screen" })] : [];
1100
- full[0]?.append(icon("expand"));
1101
- const title = e.failed ? "Email " + (sel + 1) + " was not created" : e.subject || "Your email";
1102
- const parts = e.failed ? [head(title, "", full)] : [readyLine(full), head(title, e.preheader)];
1103
- if (series()) parts.push(tabs());
1104
- parts.push(stage(e, { first: true, dim: !e.failed && flowOf(e).change === "running" }));
1105
- if (!hasPath(e)) {
1106
- parts.push(foot(e.failed ? readyAsks(e, sel) : [], e.appUrl || s.appUrl, true));
1107
- return parts;
1108
- }
1109
- parts.push(pathView(e), ...stepNote(e));
1110
- const picking = pickView(e);
1111
- if (picking) parts.push(picking);
1112
- parts.push(pathFoot(e, sel));
1113
- return parts;
1307
+ if (series()) return [brandLine(), posters(), ...wholeEmail(e), ...controls(e, sel)];
1308
+ 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)];
1114
1309
  }
1115
1310
 
1116
- function fullScreenView() {
1311
+ // The big view: every email whole, side by side; the same row and actions under them.
1312
+ function bigView() {
1117
1313
  const e = s.emails[sel];
1118
- const back = button("icon-btn", "", () => displayMode("inline"), { ariaLabel: "Back to the chat" });
1314
+ const box = el("section", "", { className: "big" });
1315
+ const top = el("div", "", { className: "top" });
1316
+ const back = button("x", "", () => displayMode("inline"), "back", { ariaLabel: "Back to the chat" });
1119
1317
  back.append(icon("collapse"));
1120
- const box = el("section", "", { className: "fs" });
1121
- const body = el("div", "", { className: "fs-body" });
1318
+ const count = s.emails.length + " emails";
1319
+ top.append(el("h1", series() ? (brandInfo ? brandInfo.name + ", " + count : count) : e.subject || "Your email", { className: "h" }), back);
1320
+ box.append(top);
1122
1321
  if (series()) {
1123
- const rail = el("nav", "", { className: "rail" });
1124
- rail.setAttribute("aria-label", "Emails in this series");
1322
+ const strip = el("div", "", { className: "strip" });
1125
1323
  s.emails.forEach((x, i) => {
1126
- const item = button("rail-item", "", () => select(i));
1127
- if (i === sel) item.setAttribute("aria-current", "true");
1128
- const thumb = el("div", "", { className: "thumb" });
1129
- thumb.append(x.picture ? el("img", "", { src: x.picture, alt: "" }) : icon(x.failed ? "alert" : "image", true));
1130
- item.append(thumb, el("span", (i + 1) + (x.failed ? " · Not created" : x.day !== null ? " · Day " + x.day : "")));
1131
- rail.append(item);
1324
+ const b = button("", "", () => select(i), "strip-" + i, { ariaLabel: "Email " + (i + 1) + (x.subject ? ": " + x.subject : "") });
1325
+ if (i === sel) b.setAttribute("aria-current", "true");
1326
+ b.append(x.picture ? el("img", "", { src: x.picture, alt: "" }) : icon(x.failed ? "alert" : "image"));
1327
+ strip.append(b);
1132
1328
  });
1133
- body.append(rail);
1134
- }
1135
- const wrap = el("div", "", { className: "fs-wrap" });
1136
- wrap.append(stage(e));
1137
- if (series()) {
1138
- const prev = button("step-btn prev", "", () => select(sel - 1), { ariaLabel: "Previous email", disabled: sel === 0 });
1139
- const next = button("step-btn next", "", () => select(sel + 1), { ariaLabel: "Next email", disabled: sel === s.emails.length - 1 });
1140
- prev.append(icon("prev")); next.append(icon("next"));
1141
- wrap.append(prev, next);
1329
+ box.append(strip);
1142
1330
  }
1143
- const desk = el("div", "", { className: "desk" });
1144
- desk.append(wrap);
1145
- if (hasPath(e)) {
1146
- // The path beside the whole email; changes to the email live here, where there is room.
1147
- const panel = el("aside", "", { className: "panel" });
1148
- panel.setAttribute("aria-label", "From ready to sent");
1149
- panel.append(el("h2", "From ready to sent"), pathView(e), ...stepNote(e));
1150
- const picking = pickView(e);
1151
- if (picking) panel.append(picking);
1152
- panel.append(asks(readyAsks(e, sel)));
1153
- desk.append(panel);
1154
- }
1155
- body.append(desk);
1156
- box.append(head(e.failed ? "Email " + (sel + 1) + " was not created" : e.subject || "Your email", e.failed ? "" : e.preheader, [back]));
1157
- if (series()) box.append(tabs());
1158
- box.append(body, hasPath(e) ? pathFoot(e, sel) : foot(readyAsks(e, sel), e.appUrl || s.appUrl, true));
1159
- if (s.note) box.append(el("p", s.note, { className: "note small" }));
1331
+ const wall = el("div", "", { className: "wall" });
1332
+ s.emails.forEach((x, i) => {
1333
+ const col = el("div", "", { className: series() ? (i === sel ? "col on" : "col") : "col only on" });
1334
+ if (series()) col.append(caption(x, i));
1335
+ let pic;
1336
+ if (series() && i !== sel) {
1337
+ pic = button("pic", "", () => select(i), "email-" + i);
1338
+ pic.setAttribute("aria-label", "Email " + (i + 1) + (x.subject ? ": " + x.subject : ""));
1339
+ } else pic = el("div", "", { className: "pic" });
1340
+ fill(pic, x);
1341
+ col.append(pic);
1342
+ wall.append(col);
1343
+ });
1344
+ const bar = el("div", "", { className: "bar" });
1345
+ bar.append(...controls(e, sel));
1346
+ if (s.note) bar.append(el("p", s.note, { className: "note" }));
1347
+ box.append(wall, bar);
1160
1348
  return [box];
1161
1349
  }
1162
1350
 
1163
- function render() {
1351
+ // A redraw replaces the controls, so one that lands between a press and its release would
1352
+ // swallow the click: it waits for the release.
1353
+ let pressed = 0, redraw = false;
1354
+ function release() {
1355
+ clearTimeout(pressed);
1356
+ pressed = 0;
1357
+ if (redraw) { redraw = false; draw(); }
1358
+ }
1359
+ document.addEventListener("pointerdown", () => { clearTimeout(pressed); pressed = setTimeout(release, 1500); }, true);
1360
+ for (const type of ["pointerup", "pointercancel"]) document.addEventListener(type, () => setTimeout(release, 0), true);
1361
+ function render() { if (pressed) redraw = true; else draw(); }
1362
+ function draw() {
1164
1363
  const main = $("card");
1165
1364
  main.setAttribute("aria-busy", String(s.phase === "working" && !s.compact));
1166
1365
  let parts;
1167
1366
  if (s.compact) parts = compactView();
1168
- else if (fullScreen()) parts = fullScreenView();
1367
+ else if (fullScreen()) parts = bigView();
1169
1368
  else parts = s.phase === "working" ? workingView() : s.phase === "failed" ? failedView() : readyView();
1170
- if (s.note && !fullScreen()) parts.push(el("p", s.note, { className: "note small" }));
1369
+ if (s.note && !fullScreen()) parts.push(el("p", s.note, { className: "note" }));
1370
+ // A redraw keeps where the user was: the control in use, and how far the row was scrolled.
1371
+ const key = document.activeElement?.dataset?.k;
1372
+ const left = main.querySelector(".row")?.scrollLeft || 0;
1373
+ const wall = main.querySelector(".wall");
1374
+ const down = wall?.scrollTop || 0, across = wall?.scrollLeft || 0;
1171
1375
  main.replaceChildren(...parts);
1376
+ if (left) main.querySelector(".row")?.scrollTo({ left });
1377
+ if (down || across) main.querySelector(".wall")?.scrollTo({ top: down, left: across });
1378
+ if (key) main.querySelector('[data-k="' + CSS.escape(key) + '"]')?.focus({ preventScroll: true });
1172
1379
  // ChatGPT's own "Open in" button in full screen opens this card's page unless told otherwise.
1173
1380
  const link = s.emails?.[sel]?.appUrl || s.before?.appUrl || s.appUrl;
1174
1381
  if (link) window.openai?.setOpenInAppUrl?.({ href: link });
1175
1382
  tick();
1383
+ // The brand as soon as it is named; its lists once there is an email to send.
1384
+ if (brand && !brandAsked && !s.compact && s.phase !== "failed") loadBrand();
1385
+ if (s.phase === "ready" && !s.compact && canAct() && brand && !lists && !listsOff && !listsBusy) { rereadAt = Date.now(); loadLists().then(render); }
1176
1386
  }
1177
1387
 
1178
1388
  new ResizeObserver(() => send({ method: "ui/notifications/size-changed", params: { height: Math.ceil(document.documentElement.getBoundingClientRect().height) } }))