create-heresay 0.2.15 → 0.2.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-heresay",
3
- "version": "0.2.15",
3
+ "version": "0.2.17",
4
4
  "description": "Set up your own Heresay: in-app feedback that every report gets a hearing. Creates a Firebase project in your Google account and deploys the dashboard, API and SDK to it.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/release/VERSION CHANGED
@@ -1 +1 @@
1
- 0.2.15
1
+ 0.2.17
@@ -1,4 +1,6 @@
1
1
  export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
2
+ export class TelegramLookupError extends Error {
3
+ }
2
4
  export const defaultNotifications = () => ({
3
5
  events: { new_report: true, accepted: false, fixed: true, handoff: true },
4
6
  telegram: { enabled: false, token: null, chat_id: '' },
@@ -14,6 +16,7 @@ export function notificationView(settings) {
14
16
  }
15
17
  class SettingsError extends Error {
16
18
  }
19
+ const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
17
20
  const object = (v) => {
18
21
  if (!v || typeof v !== 'object' || Array.isArray(v))
19
22
  throw new SettingsError('Invalid notification settings.');
@@ -67,7 +70,7 @@ export function patchNotifications(current, body) {
67
70
  else if (patch.token !== undefined) {
68
71
  const token = field(patch.token, 512);
69
72
  if (token) {
70
- if (provider === 'telegram' ? !/^\d+:[A-Za-z0-9_-]{20,}$/.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
73
+ if (provider === 'telegram' ? !TELEGRAM_TOKEN.test(token) : !/^[A-Za-z0-9._-]+$/.test(token)) {
71
74
  throw new SettingsError(`Invalid ${provider === 'telegram' ? 'Telegram bot' : 'Cliq webhook'} token.`);
72
75
  }
73
76
  target.token = token;
@@ -113,6 +116,27 @@ export async function notificationSettings(p, req, deps, body) {
113
116
  throw error;
114
117
  }
115
118
  }
119
+ if (p.length === 3 && p[1] === 'telegram' && p[2] === 'lookup' && req.method === 'POST') {
120
+ // A pasted token, or the saved one. The token goes only to Telegram and never comes back.
121
+ const pasted = typeof body.token === 'string' ? body.token.trim() : '';
122
+ const token = pasted || ((await deps.store.getInstance()).notifications ?? defaultNotifications()).telegram.token;
123
+ if (!token)
124
+ return json(400, { error: 'Paste the bot token from BotFather first.' });
125
+ if (!TELEGRAM_TOKEN.test(token))
126
+ return json(400, { error: 'That doesn’t look like a bot token. BotFather sends one like 123456789:AAH…' });
127
+ const now = deps.now(), start = Math.floor(now / 60_000) * 60_000;
128
+ if (!await deps.store.hit(`notification-lookup:telegram:${start}`, 12, start + 60_000)) {
129
+ return json(429, { error: 'Wait a minute before looking again.' });
130
+ }
131
+ if (!deps.telegramLookup)
132
+ return json(503, { error: 'Telegram lookup is unavailable.' });
133
+ try {
134
+ return json(200, await deps.telegramLookup(token));
135
+ }
136
+ catch (error) {
137
+ return json(502, { error: error instanceof TelegramLookupError ? error.message : 'Could not reach Telegram. Try again in a moment.' });
138
+ }
139
+ }
116
140
  if (p.length === 2 && p[1] === 'test' && req.method === 'POST') {
117
141
  const provider = body.provider;
118
142
  if (provider !== 'telegram' && provider !== 'cliq')
@@ -202,4 +226,50 @@ export function notificationSender(http = fetch) {
202
226
  }
203
227
  };
204
228
  }
229
+ /**
230
+ * Telegram has no "list my chats". A bot sees the chats that wrote to it (or added it) in the
231
+ * last day, through getUpdates; that is enough to offer the right one. Read-only: no offset is
232
+ * confirmed, so nothing is consumed.
233
+ */
234
+ export function telegramLookup(http = fetch) {
235
+ const call = async (token, method, body) => {
236
+ const response = await http(`https://api.telegram.org/bot${token}/${method}`, {
237
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body ?? {}),
238
+ signal: AbortSignal.timeout(5000), redirect: 'error',
239
+ });
240
+ const result = await response.json().catch(() => ({}));
241
+ return { status: response.status, ...result };
242
+ };
243
+ return async (token) => {
244
+ const me = await call(token, 'getMe');
245
+ if (me.status === 401 || me.status === 404)
246
+ throw new TelegramLookupError('Telegram doesn’t recognise this token. Copy it again from BotFather.');
247
+ if (!me.ok)
248
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
249
+ const bot = me.result;
250
+ const updates = await call(token, 'getUpdates', { limit: 100, timeout: 0, allowed_updates: ['message', 'channel_post', 'my_chat_member'] });
251
+ if (updates.status === 409) {
252
+ throw new TelegramLookupError('This bot already sends its messages to another service (a webhook), so Heresay can’t see its chats. Enter the chat ID yourself, or use a new bot.');
253
+ }
254
+ if (!updates.ok)
255
+ throw new TelegramLookupError('Telegram didn’t answer. Try again in a moment.');
256
+ const seen = new Map();
257
+ for (const u of updates.result ?? []) {
258
+ const chat = (u.message ?? u.channel_post ?? u.my_chat_member)?.chat;
259
+ if (!chat || (typeof chat.id !== 'number' && typeof chat.id !== 'string'))
260
+ continue;
261
+ const kind = String(chat.type);
262
+ if (!['private', 'group', 'supergroup', 'channel'].includes(kind))
263
+ continue;
264
+ const title = kind === 'private'
265
+ ? [chat.first_name, chat.last_name].filter((x) => typeof x === 'string').join(' ') || (typeof chat.username === 'string' ? '@' + chat.username : 'You')
266
+ : typeof chat.title === 'string' ? chat.title : 'Untitled';
267
+ seen.set(String(chat.id), { id: String(chat.id), title: title.slice(0, 120), kind });
268
+ }
269
+ return {
270
+ bot: { username: typeof bot?.username === 'string' ? bot.username : '', name: typeof bot?.first_name === 'string' ? bot.first_name.slice(0, 120) : '' },
271
+ chats: [...seen.values()].reverse(), // the latest first
272
+ };
273
+ };
274
+ }
205
275
  //# sourceMappingURL=notifications.js.map
@@ -1,3 +1,3 @@
1
1
  /** The Heresay release. Bumped by the release script; the CLI and /v1/health report it. */
2
- export const VERSION = '0.2.15';
2
+ export const VERSION = '0.2.17';
3
3
  //# sourceMappingURL=version.js.map
@@ -8,7 +8,7 @@ import { auth, db } from './admin.js';
8
8
  import { FirestoreStore } from './firestore-store.js';
9
9
  import { handle } from '../../core/handler.js';
10
10
  import { VERSION } from '../../core/version.js';
11
- import { notificationSender } from '../../core/notifications.js';
11
+ import { notificationSender, telegramLookup } from '../../core/notifications.js';
12
12
  const deps = {
13
13
  store: new FirestoreStore(db),
14
14
  async verifyIdToken(token) {
@@ -25,6 +25,7 @@ const deps = {
25
25
  version: VERSION,
26
26
  selfOrigins: selfOrigins(),
27
27
  sendNotification: notificationSender(),
28
+ telegramLookup: telegramLookup(),
28
29
  };
29
30
  function selfOrigins() {
30
31
  const id = process.env.GCLOUD_PROJECT;
@@ -10,10 +10,10 @@
10
10
  <link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:opsz,wght@12..96,700;12..96,800&family=Figtree:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
11
11
  <link rel="stylesheet" href="/dashboard.css">
12
12
  </head>
13
- <body>
13
+ <body class="booting pending">
14
14
 
15
- <!-- Until sign-in state is known -->
16
- <div id="boot" class="loading boot" role="status" aria-label="Loading"><img src="/loader.svg" alt=""></div>
15
+ <!-- The one loader: from first paint until a page has everything it needs -->
16
+ <div id="loader" class="app-loader on" role="status" aria-label="Loading"><img src="/loader.svg" alt="" width="96" height="96"></div>
17
17
 
18
18
  <!-- Signed out -->
19
19
  <div id="gate" class="gate" hidden>
@@ -132,29 +132,76 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
132
132
  .wait.ok .btn { margin-left:auto; }
133
133
  @keyframes pulse { 0%, 100% { opacity:.25; transform:scale(.8); } 50% { opacity:1; transform:scale(1); } }
134
134
  @media (prefers-reduced-motion: reduce) { .wait::before { animation:none; } }
135
- /* loading: the Glance mark, faded in late so quick loads never flash it */
136
- .loading { display:grid; place-items:center; padding:12vh 0; animation:loading-in .2s .3s both; }
137
- .loading img { width:96px; height:96px; }
138
- .loading.boot { padding-top:30vh; }
139
- .loading:not(.boot):not(:only-child) { display:none; }
135
+ /* loading: one Glance mark, fixed in place, faded in late so quick loads never flash it */
136
+ .app-loader { position:fixed; left:50%; top:38vh; z-index:20; width:96px; height:96px; margin:-48px 0 0 -48px; pointer-events:none;
137
+ opacity:0; visibility:hidden; transition:opacity .25s ease, visibility 0s .25s; }
138
+ .app-loader.on { opacity:1; visibility:visible; transition:opacity .25s ease; }
139
+ .booting .app-loader.on { animation:loading-in .25s .3s both; }
140
+ .app-loader img { display:block; width:96px; height:96px; }
140
141
  @keyframes loading-in { from { opacity:0; } }
142
+ /* What a view still waits for. While one is alone in its box, the page stays out of sight. */
143
+ .loading { display:block; min-height:40vh; list-style:none; }
144
+ .loading:not(:only-child) { display:none; }
145
+ #app, #view { transition:opacity .25s ease; }
146
+ .booting.pending #app, .pending #view { opacity:0; visibility:hidden; transition:none; }
147
+ @media (prefers-reduced-motion: reduce) { #app, #view, .app-loader, .app-loader.on { transition:none; } }
141
148
 
142
149
  /* reports */
143
150
  .filters { display:flex; gap:6px; flex-wrap:wrap; margin-bottom:14px; }
144
151
  .filters button { font:inherit; font-weight:600; border:1px solid var(--line); background:none; color:var(--mute); border-radius:999px; padding:4px 12px; cursor:pointer; }
145
152
  .filters button .n { font-weight:500; }
146
153
  .filters button[aria-pressed=true] { color:var(--deep); border-color:var(--acc); background:var(--mist); }
147
- .report { border:1px solid var(--line); border-radius:14px; padding:16px 18px; margin-bottom:10px; }
154
+ .report { position:relative; border:1px solid var(--line); border-radius:14px; padding:16px 18px 16px 20px; margin-bottom:10px; overflow:hidden;
155
+ transition:border-color .2s, box-shadow .2s, background-color .3s, opacity .3s, height .3s ease, margin .3s ease, padding .3s ease; }
156
+ .report { --strip:var(--line); box-shadow:inset 3px 0 0 var(--strip); }
157
+ .report.t-broken { --strip:var(--broken); } .report.t-confusing { --strip:var(--confusing); }
158
+ .report.t-improvement { --strip:var(--improvement); } .report.t-idea { --strip:var(--idea); }
159
+ .report:hover { border-color:#cfd4da; box-shadow:inset 3px 0 0 var(--strip), 0 1px 3px rgb(21 23 28 / .06); }
160
+ .report.working { background:var(--soft); }
161
+ .report.settled { border-color:var(--acc); background:var(--mist); box-shadow:inset 3px 0 0 var(--strip), 0 0 0 3px var(--mist); }
162
+ .report.leaving { opacity:0; margin-bottom:0; padding-top:0; padding-bottom:0; border-width:0; }
148
163
  .report .meta { display:flex; gap:10px; align-items:center; font-size:13px; color:var(--mute); flex-wrap:wrap; }
149
164
  .pill { font-weight:700; font-size:12px; letter-spacing:.02em; }
165
+ .report .pill:first-child { padding:1px 9px; border-radius:999px; background:var(--soft); }
150
166
  .pill.broken { color:var(--broken); } .pill.confusing { color:var(--confusing); }
151
167
  .pill.improvement { color:var(--improvement); } .pill.idea { color:var(--idea); }
152
- .status { margin-left:auto; font-weight:600; }
168
+ .report .pill.broken { background:#fbeceb; } .report .pill.confusing { background:#fbf1e3; }
169
+ .report .pill.improvement { background:#eaf0fa; } .report .pill.idea { background:#f1edf9; }
170
+ .status { margin-left:auto; font-weight:600; font-size:12px; padding:1px 9px; border-radius:999px; background:var(--soft); transition:background-color .3s, color .3s; }
171
+ .s-open { color:var(--fg); }
153
172
  .s-accepted { color:var(--deep); }
173
+ .status.s-accepted { background:var(--mist); }
174
+ .status.s-fixed { color:#fff; background:var(--acc); }
175
+ .status.s-declined { color:var(--mute); }
154
176
  .report .text { margin:8px 0 6px; white-space:pre-wrap; word-break:break-word; font-size:16px; }
155
177
  .ctx { font-size:13px; color:var(--mute); }
156
178
  .actions { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; align-items:flex-start; }
157
179
  .actions textarea { flex:1 1 100%; min-height:70px; }
180
+ .done-line { display:flex; align-items:center; gap:8px; font-weight:600; font-size:14px; color:var(--deep); animation:pop-in .25s ease-out; }
181
+ .done-line.s-declined { color:var(--fg); }
182
+ .done-tick, .toast-tick { width:20px; height:20px; flex:none; border-radius:50%; background:var(--acc) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='3' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='M5 12l5 5L19 7'/%3E%3C/svg%3E") center/12px no-repeat; }
183
+ .done-line.s-declined .done-tick { background-color:var(--fg); }
184
+ @keyframes pop-in { from { opacity:0; transform:translateY(4px); } }
185
+
186
+ /* a button at work */
187
+ .btn { transition:background-color .15s, border-color .15s, color .15s, transform .1s; }
188
+ .btn:active:not(:disabled) { transform:scale(.97); }
189
+ .btn.busy, .btn.busy:disabled { opacity:1; cursor:progress; }
190
+ .btn.busy::before { content:""; width:14px; height:14px; border-radius:50%; border:2px solid currentColor; border-right-color:transparent; animation:spin .7s linear infinite; }
191
+
192
+ /* toast */
193
+ .toast { position:fixed; left:50%; bottom:24px; z-index:10; display:flex; align-items:center; gap:12px; max-width:calc(100vw - 32px);
194
+ padding:10px 12px 10px 14px; border-radius:12px; background:var(--fg); color:#fff; font-size:14px; font-weight:500;
195
+ box-shadow:0 10px 30px rgb(21 23 28 / .25); transform:translate(-50%, 16px); opacity:0; pointer-events:none; transition:opacity .2s, transform .2s; }
196
+ .toast.on { opacity:1; transform:translate(-50%, 0); pointer-events:auto; }
197
+ .toast button { font:inherit; font-weight:700; color:#7dd3c8; background:none; border:0; padding:4px 6px; border-radius:6px; cursor:pointer; }
198
+ .toast button:hover { background:rgb(255 255 255 / .1); }
199
+ .toast button:focus-visible { outline:2px solid #7dd3c8; }
200
+ @media (prefers-reduced-motion: reduce) {
201
+ .report, .toast, .btn { transition:none; }
202
+ .done-line { animation:none; }
203
+ .btn.busy::before { animation-duration:2s; }
204
+ }
158
205
  .reason { margin-top:8px; font-size:14px; padding:10px 12px; border-radius:10px; background:var(--soft); }
159
206
  .empty { text-align:center; color:var(--mute); padding:40px 0; }
160
207
 
@@ -336,6 +383,25 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
336
383
  .notification-choice .hint { display:block; margin:2px 0 0; }
337
384
  .notification-form input[type=text], .notification-form input[type=password] { width:100%; min-width:0; }
338
385
  .notification-form .row { margin-top:22px; }
386
+ /* a guided setup inside a card */
387
+ .setup-step { margin-top:22px; }
388
+ .setup-step .test-head b { font-size:16px; }
389
+ .setup-body { margin:6px 0 0 34px; }
390
+ .setup-body > .row.tight { margin-top:10px; }
391
+ .setup-body label { margin-top:14px; }
392
+ .chat-finder:empty { display:none; }
393
+ .chat-finder { margin-top:12px; }
394
+ .chat-finder p { margin:0 0 8px; }
395
+ .chat-list { display:flex; flex-direction:column; gap:6px; }
396
+ .notification-form .chat-choice { display:flex; align-items:center; gap:12px; margin:0; padding:10px 14px; border:1px solid var(--line); border-radius:12px; cursor:pointer; font-weight:400; }
397
+ .chat-choice:hover { border-color:var(--acc); }
398
+ .chat-choice:has(input:checked) { border-color:var(--acc); background:var(--mist); }
399
+ .notification-form .chat-choice input:focus { outline:none; }
400
+ .chat-choice:has(input:focus-visible) { outline:2px solid var(--acc); outline-offset:2px; }
401
+ .notification-form .chat-choice input { display:inline-block; width:auto; flex:none; accent-color:var(--acc); margin:0; }
402
+ .chat-choice b { display:block; }
403
+ .chat-choice .mute { font-size:13px; }
404
+ @media (max-width:600px) { .setup-body { margin-left:0; } }
339
405
  @media (max-width:600px) {
340
406
  .top { flex-wrap:wrap; gap:8px 12px; padding:12px 16px; }
341
407
  .top .tabs { order:5; width:100%; }
@@ -42,13 +42,34 @@
42
42
  }
43
43
 
44
44
  function show(which) {
45
- ['boot', 'gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
45
+ ['gate', 'blocked', 'app'].forEach(function (id) { $(id).hidden = id !== which; });
46
+ syncLoader();
46
47
  }
47
48
 
48
- /** The Glance loader. It shows only while it is alone in its box, so a view's first content hides it. */
49
- function loading() {
50
- return el('div', { class: 'loading', role: 'status', 'aria-label': 'Loading' }, [el('img', { src: '/loader.svg', alt: '' })]);
49
+ /**
50
+ * One Glance loader for the whole dashboard, from the first paint until a page is ready. It is
51
+ * never recreated, so the animation never restarts. A view marks what it is still waiting for
52
+ * with loading(); while any of those is alone in its box the view stays hidden, then the page
53
+ * appears in one go.
54
+ */
55
+ var loader = $('loader'), loaderTimer = null;
56
+ function loading(tag) {
57
+ return el(tag || 'div', { class: 'loading', 'aria-hidden': 'true' });
58
+ }
59
+ function syncLoader() {
60
+ // Signed in: wait for the view. Otherwise wait until we know who this is (sign-in or blocked).
61
+ var waiting = !$('app').hidden ? !!$('view').querySelector('.loading:only-child') : $('gate').hidden && $('blocked').hidden;
62
+ document.body.classList.toggle('pending', waiting);
63
+ if (!waiting) document.body.classList.remove('booting');
64
+ if (waiting && !loader.classList.contains('on')) {
65
+ // A quick page never flashes the loader; it just appears.
66
+ if (!loaderTimer) loaderTimer = setTimeout(function () { loaderTimer = null; loader.classList.add('on'); }, 250);
67
+ } else if (!waiting) {
68
+ clearTimeout(loaderTimer); loaderTimer = null;
69
+ loader.classList.remove('on');
70
+ }
51
71
  }
72
+ new MutationObserver(syncLoader).observe($('view'), { childList: true, subtree: true });
52
73
 
53
74
  function copyButton(getText, label) {
54
75
  var b = el('button', { class: 'btn', type: 'button', text: label || 'Copy' });
@@ -65,6 +86,33 @@
65
86
  return el('div', { class: 'code' }, [el('pre', { text: text }), copyButton(function () { return text; })]);
66
87
  }
67
88
 
89
+ /** One message at a time, bottom of the screen, with an optional action. Read out by screen readers. */
90
+ var toastBox = null, toastTimer = null;
91
+ function toast(text, action) {
92
+ if (!toastBox) {
93
+ toastBox = el('div', { class: 'toast', role: 'status', 'aria-live': 'polite' });
94
+ document.body.appendChild(toastBox);
95
+ }
96
+ clearTimeout(toastTimer);
97
+ toastBox.textContent = '';
98
+ toastBox.appendChild(el('span', { class: 'toast-tick', 'aria-hidden': 'true' }));
99
+ toastBox.appendChild(el('span', { text: text }));
100
+ if (action) toastBox.appendChild(el('button', { type: 'button', text: action.label, onclick: function () { hideToast(); action.run(); } }));
101
+ toastBox.classList.add('on');
102
+ toastTimer = setTimeout(hideToast, 6000);
103
+ }
104
+ function hideToast() { if (toastBox) toastBox.classList.remove('on'); }
105
+
106
+ /** A button that is working: spinner, a new label, and no second click. */
107
+ function busyButton(b, label) {
108
+ var was = b.textContent;
109
+ b.disabled = true;
110
+ b.classList.add('busy');
111
+ b.setAttribute('aria-busy', 'true');
112
+ b.textContent = label;
113
+ return function () { b.disabled = false; b.classList.remove('busy'); b.removeAttribute('aria-busy'); b.textContent = was; };
114
+ }
115
+
68
116
  function stopTimer() { if (timer) { clearInterval(timer); timer = null; } }
69
117
  function every(ms, fn) {
70
118
  stopTimer();
@@ -130,8 +178,8 @@
130
178
  api('GET', '/me').then(function (b) {
131
179
  me = b;
132
180
  $('who').textContent = b.email;
181
+ route(); // first, so the view is already waiting when the app is shown
133
182
  show('app');
134
- route();
135
183
  checkForUpdate(b);
136
184
  }).catch(function (x) {
137
185
  show('blocked');
@@ -1245,6 +1293,11 @@
1245
1293
  reports = triageSort([].concat.apply([], sibs.map(function (x) { return ctxs[x.id].reports; })));
1246
1294
  drawPlatforms();
1247
1295
  render();
1296
+ }).catch(function (x) {
1297
+ if (reports.length) return; // a background refresh failed: keep what is on screen
1298
+ list.textContent = '';
1299
+ list.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
1300
+ list.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
1248
1301
  });
1249
1302
  }
1250
1303
 
@@ -1260,14 +1313,7 @@
1260
1313
  });
1261
1314
  }
1262
1315
  var here = reports.filter(function (r) { return where === 'all' || r.project_id === where; });
1263
- filters.textContent = '';
1264
- ['open', 'accepted', 'fixed', 'declined', 'all'].forEach(function (f) {
1265
- var n = f === 'all' ? here.length : here.filter(function (r) { return r.status === f; }).length;
1266
- filters.appendChild(el('button', {
1267
- 'aria-pressed': String(filter === f),
1268
- onclick: function () { filter = f; render(); },
1269
- }, [(f === 'all' ? 'All' : STATUS_LABEL[f]) + ' ', el('span', { class: 'n', text: String(n) })]));
1270
- });
1316
+ drawFilters(here);
1271
1317
  list.textContent = '';
1272
1318
  var shown = here.filter(function (r) { return filter === 'all' || r.status === filter; });
1273
1319
  empty.hidden = shown.length > 0;
@@ -1278,13 +1324,48 @@
1278
1324
  } else empty.textContent = filter === 'open' ? 'Nothing waiting. Every report has had its hearing.' : 'Nothing here.';
1279
1325
  shown.forEach(function (r) {
1280
1326
  var c = ctxs[r.project_id];
1281
- list.appendChild(row(c.project, r, load, c, many));
1327
+ list.appendChild(row(c.project, r, settled, c, many));
1282
1328
  });
1283
1329
  }
1284
1330
 
1331
+ function drawFilters(here) {
1332
+ here = here || reports.filter(function (r) { return where === 'all' || r.project_id === where; });
1333
+ filters.textContent = '';
1334
+ ['open', 'accepted', 'fixed', 'declined', 'all'].forEach(function (f) {
1335
+ var n = f === 'all' ? here.length : here.filter(function (r) { return r.status === f; }).length;
1336
+ filters.appendChild(el('button', {
1337
+ 'aria-pressed': String(filter === f),
1338
+ onclick: function () { filter = f; render(); },
1339
+ }, [(f === 'all' ? 'All' : STATUS_LABEL[f]) + ' ', el('span', { class: 'n', text: String(n) })]));
1340
+ });
1341
+ }
1342
+
1343
+ /**
1344
+ * A report moved. The card says so where the click was, the counts move at once, and only
1345
+ * then does it leave this filter, so nothing vanishes without a word.
1346
+ */
1347
+ function settled(r, card, done) {
1348
+ if (!done) return load(); // someone else got there first: show what they did
1349
+ drawFilters();
1350
+ var to = r.status;
1351
+ toast(DONE_TOAST[to], filter === to || filter === 'all' ? null : {
1352
+ label: 'View ' + STATUS_LABEL[to].toLowerCase(), run: function () { filter = to; render(); window.scrollTo(0, 0); },
1353
+ });
1354
+ card.classList.add('settled');
1355
+ setTimeout(function () {
1356
+ if (!card.isConnected) return;
1357
+ if (filter === 'all' || filter === to) return load(); // it stays in this list
1358
+ card.style.height = card.offsetHeight + 'px';
1359
+ card.getBoundingClientRect();
1360
+ card.classList.add('leaving');
1361
+ card.style.height = '0px';
1362
+ setTimeout(load, 320);
1363
+ }, 2200);
1364
+ }
1365
+
1285
1366
  load();
1286
- // Reports arrive while you read. Don't refresh under someone typing a decline reason.
1287
- every(30000, function () { if (!list.querySelector('textarea')) load(); });
1367
+ // Reports arrive while you read. Don't refresh under someone typing, or a card on its way out.
1368
+ every(30000, function () { if (!list.querySelector('textarea, .report.settled, .report .busy')) load(); });
1288
1369
  }
1289
1370
 
1290
1371
  function ctxLine(c) {
@@ -1313,41 +1394,88 @@
1313
1394
  ]);
1314
1395
  }
1315
1396
 
1316
- function row(p, r, reload, ctx, showPlatform) {
1397
+ var DONE_TOAST = {
1398
+ accepted: 'Accepted. It is waiting for a coding agent.',
1399
+ declined: 'Declined. They will see your reason.',
1400
+ fixed: 'Marked fixed. They will see it in “Your reports”.',
1401
+ };
1402
+ var BUSY_LABEL = { accept: 'Accepting…', decline: 'Declining…', fixed: 'Saving…' };
1403
+
1404
+ function row(p, r, settled, ctx, showPlatform) {
1317
1405
  var brief = ctx.briefs[r.id];
1318
- var err = el('span', { class: 'err' });
1406
+ var err = el('span', { class: 'err', role: 'alert' });
1319
1407
  var actions = el('div', { class: 'actions' });
1320
- var act = function (action, body) {
1408
+ var card, sentTo = null;
1409
+ var act = function (action, body, b) {
1410
+ if (action === 'accept') sentTo = (body && body.repo) || ctx.repos[0] || null;
1321
1411
  err.textContent = '';
1412
+ var undo = busyButton(b, BUSY_LABEL[action]);
1413
+ actions.querySelectorAll('button, select, textarea').forEach(function (c) { if (c !== b) c.disabled = true; });
1414
+ card.classList.add('working');
1322
1415
  return api('POST', '/projects/' + p.id + '/reports/' + r.id + '/' + action, body)
1323
- .then(reload)
1324
- .catch(function (x) { err.textContent = x.message; if (x.status === 409) reload(); });
1416
+ .then(function (x) {
1417
+ Object.assign(r, x.report || {});
1418
+ card.classList.remove('working');
1419
+ showDone();
1420
+ settled(r, card, true);
1421
+ })
1422
+ .catch(function (x) {
1423
+ undo();
1424
+ card.classList.remove('working');
1425
+ actions.querySelectorAll('button, select, textarea').forEach(function (c) { c.disabled = false; });
1426
+ err.textContent = x.message;
1427
+ if (x.status === 409) settled(r, card, false);
1428
+ });
1325
1429
  };
1326
1430
 
1431
+ /** In place of the buttons: what just happened, in the colour of the new status. */
1432
+ function showDone() {
1433
+ status.className = 'status s-' + r.status;
1434
+ status.textContent = STATUS_LABEL[r.status];
1435
+ var line = r.status === 'accepted'
1436
+ ? 'Accepted. Waiting for an agent' + (sentTo ? ' in ' + sentTo : '') + '.'
1437
+ : r.status === 'declined' ? 'Declined. They will read your reason.' : 'Marked fixed. They will see it.';
1438
+ actions.textContent = '';
1439
+ actions.appendChild(el('div', { class: 'done-line s-' + r.status }, [
1440
+ el('span', { class: 'done-tick', 'aria-hidden': 'true' }), document.createTextNode(line),
1441
+ ]));
1442
+ }
1443
+
1444
+ function submitOnCmdEnter(area, go) {
1445
+ area.addEventListener('keydown', function (e) { if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); go.click(); } });
1446
+ }
1447
+
1327
1448
  function buttons() {
1328
1449
  actions.textContent = '';
1329
1450
  if (r.status === 'open') {
1330
1451
  // Several repos hold this app's code: say where the fix goes, defaulting to the first.
1331
1452
  var pick = ctx.repos.length > 1 ? el('select', { 'aria-label': 'Where the fix goes' },
1332
1453
  ctx.repos.map(function (x) { return el('option', { value: x, text: 'Fix in ' + x }); })) : null;
1333
- actions.appendChild(el('button', { class: 'btn primary', text: 'Accept', onclick: function () {
1334
- act('accept', pick ? { repo: pick.value } : undefined);
1454
+ actions.appendChild(el('button', { class: 'btn primary', type: 'button', text: 'Accept', onclick: function (e) {
1455
+ act('accept', pick ? { repo: pick.value } : undefined, e.currentTarget);
1335
1456
  } }));
1336
1457
  if (pick) actions.appendChild(pick);
1337
- actions.appendChild(el('button', { class: 'btn', text: 'Decline…', onclick: declineForm }));
1458
+ actions.appendChild(el('button', { class: 'btn', type: 'button', text: 'Decline…', onclick: declineForm }));
1338
1459
  }
1339
1460
  if (r.status === 'accepted') {
1340
1461
  actions.appendChild(el('button', {
1341
1462
  class: 'btn primary', text: 'Copy prompt for agent',
1463
+ type: 'button',
1342
1464
  onclick: function (e) {
1343
- var b = e.target;
1465
+ var b = e.currentTarget;
1466
+ var undo = busyButton(b, 'Copying…');
1344
1467
  api('GET', '/projects/' + p.id + '/reports/' + r.id + '/prompt')
1345
1468
  .then(function (x) { return navigator.clipboard.writeText(x.prompt); })
1346
- .then(function () { b.textContent = 'Copied'; })
1347
- .catch(function (x) { err.textContent = x.message; });
1469
+ .then(function () {
1470
+ undo();
1471
+ b.textContent = 'Copied ✓';
1472
+ toast('Prompt copied. Paste it into your coding agent.');
1473
+ setTimeout(function () { b.textContent = 'Copy prompt for agent'; }, 2000);
1474
+ })
1475
+ .catch(function (x) { undo(); err.textContent = x.message; });
1348
1476
  },
1349
1477
  }));
1350
- actions.appendChild(el('button', { class: 'btn', text: 'Mark fixed…', onclick: fixedForm }));
1478
+ actions.appendChild(el('button', { class: 'btn', type: 'button', text: 'Mark fixed…', onclick: fixedForm }));
1351
1479
  }
1352
1480
  actions.appendChild(err);
1353
1481
  }
@@ -1355,11 +1483,13 @@
1355
1483
  function fixedForm() {
1356
1484
  actions.textContent = '';
1357
1485
  var note = el('textarea', { placeholder: 'What changed, in their words. The person who sent this will read it. Optional.', 'aria-label': 'Note for the reporter' });
1486
+ var go = el('button', { class: 'btn primary', type: 'button', text: 'Mark fixed', onclick: function (e) {
1487
+ act('fixed', note.value.trim() ? { note: note.value } : undefined, e.currentTarget);
1488
+ } });
1489
+ submitOnCmdEnter(note, go);
1358
1490
  actions.appendChild(note);
1359
- actions.appendChild(el('button', { class: 'btn primary', text: 'Mark fixed', onclick: function () {
1360
- act('fixed', note.value.trim() ? { note: note.value } : undefined);
1361
- } }));
1362
- actions.appendChild(el('button', { class: 'btn ghost', text: 'Cancel', onclick: buttons }));
1491
+ actions.appendChild(go);
1492
+ actions.appendChild(el('button', { class: 'btn ghost', type: 'button', text: 'Cancel', onclick: buttons }));
1363
1493
  actions.appendChild(err);
1364
1494
  note.focus();
1365
1495
  }
@@ -1367,23 +1497,26 @@
1367
1497
  function declineForm() {
1368
1498
  actions.textContent = '';
1369
1499
  var reason = el('textarea', { placeholder: 'Why? The person who sent this will read it.', 'aria-label': 'Reason for declining' });
1370
- actions.appendChild(reason);
1371
- actions.appendChild(el('button', { class: 'btn', text: 'Decline', onclick: function () {
1500
+ var go = el('button', { class: 'btn primary', type: 'button', text: 'Decline', onclick: function (e) {
1372
1501
  if (!reason.value.trim()) { err.textContent = 'Give a reason. They will see it.'; reason.focus(); return; }
1373
- act('decline', { reason: reason.value });
1374
- } }));
1375
- actions.appendChild(el('button', { class: 'btn ghost', text: 'Cancel', onclick: buttons }));
1502
+ act('decline', { reason: reason.value }, e.currentTarget);
1503
+ } });
1504
+ submitOnCmdEnter(reason, go);
1505
+ actions.appendChild(reason);
1506
+ actions.appendChild(go);
1507
+ actions.appendChild(el('button', { class: 'btn ghost', type: 'button', text: 'Cancel', onclick: buttons }));
1376
1508
  actions.appendChild(err);
1377
1509
  reason.focus();
1378
1510
  }
1379
1511
  buttons();
1380
1512
 
1381
- return el('article', { class: 'report' }, [
1513
+ var status = el('span', { class: 'status s-' + r.status, text: STATUS_LABEL[r.status] });
1514
+ card = el('article', { class: 'report t-' + r.type }, [
1382
1515
  el('div', { class: 'meta' }, [
1383
1516
  el('span', { class: 'pill ' + r.type, text: TYPE_LABEL[r.type] }),
1384
1517
  showPlatform ? el('span', { class: 'pill platform-pill', text: platformOf(p.platform).label }) : null,
1385
1518
  el('time', { datetime: r.created_at, text: new Date(r.created_at).toLocaleString() }),
1386
- el('span', { class: 'status s-' + r.status, text: STATUS_LABEL[r.status] }),
1519
+ status,
1387
1520
  ]),
1388
1521
  el('p', { class: 'text', text: r.text }),
1389
1522
  el('div', { class: 'ctx', text: ctxLine(r.context) }),
@@ -1398,6 +1531,7 @@
1398
1531
  .concat(brief.notes.map(function (n) { return el('p', {}, [el('span', { class: 'mute', text: n.by.replace(/^agent:/, '') + ' · ' + new Date(n.at).toLocaleString() + ': ' }), n.text]); }))) : null,
1399
1532
  r.status === 'fixed' || r.status === 'declined' ? null : actions,
1400
1533
  ]);
1534
+ return card;
1401
1535
  }
1402
1536
 
1403
1537
  // ---- delete an app ---------------------------------------------------------------------
@@ -1547,7 +1681,7 @@
1547
1681
  view.appendChild(el('section', { class: 'card' }, [el('p', { text: 'An owner can connect Telegram or Zoho Cliq and choose which events your team receives.' }), el('a', { href: '#/team', text: 'See team owners' })]));
1548
1682
  return;
1549
1683
  }
1550
- var content = el('div');
1684
+ var content = el('div', {}, [loading()]);
1551
1685
  view.appendChild(content);
1552
1686
  api('GET', '/notifications').then(function (b) {
1553
1687
  var settings = b.notifications;
@@ -1592,13 +1726,64 @@
1592
1726
  var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
1593
1727
  var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
1594
1728
  var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
1595
- var form = el('form', { class: 'form notification-form' }, [
1729
+ // Telegram only: find the chat for them, from the chats that have messaged the bot.
1730
+ var find = el('button', { class: 'btn primary', type: 'button', text: 'Find my chats' });
1731
+ var found = el('div', { class: 'chat-finder', 'aria-live': 'polite' });
1732
+ var botLinks = el('div', { class: 'row tight', hidden: true });
1733
+ find.onclick = function () {
1734
+ found.textContent = '';
1735
+ var undo = busyButton(find, 'Looking…');
1736
+ api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
1737
+ var bot = b.bot.username;
1738
+ botLinks.textContent = '';
1739
+ if (bot) {
1740
+ botLinks.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(bot), target: '_blank', rel: 'noopener noreferrer', text: 'Open @' + bot + ' ↗' }));
1741
+ botLinks.appendChild(el('a', { class: 'btn ghost', href: 'https://t.me/' + encodeURIComponent(bot) + '?startgroup=heresay', target: '_blank', rel: 'noopener noreferrer', text: 'Add it to a group ↗' }));
1742
+ botLinks.hidden = false;
1743
+ }
1744
+ found.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ ' + (b.bot.name || 'Your bot') + (bot ? ' (@' + bot + ')' : '') }), document.createTextNode(' is ready.')]));
1745
+ if (!b.chats.length) {
1746
+ found.appendChild(el('p', { class: 'hint', text: 'No chats yet. Open the bot and press Start, or add it to a group and send a message, then press Find my chats again. Telegram only shows the last day.' }));
1747
+ return;
1748
+ }
1749
+ var KIND = { private: 'You', group: 'Group', supergroup: 'Group', channel: 'Channel' };
1750
+ var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
1751
+ b.chats.forEach(function (c) {
1752
+ var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
1753
+ radio.onchange = function () {
1754
+ address.value = c.id;
1755
+ enabled.checked = true;
1756
+ form.dispatchEvent(new Event('input'));
1757
+ feedback('Chat chosen. Save to start sending alerts there.');
1758
+ };
1759
+ list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] + ' · ' + c.id })])]));
1760
+ });
1761
+ found.appendChild(list);
1762
+ if (b.chats.length === 1 && !address.value) list.querySelector('input').click();
1763
+ }).catch(function (x) { found.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); }).finally(undo);
1764
+ };
1765
+ var form = el('form', { class: 'form notification-form' }, telegram ? [
1766
+ el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1767
+ setupStep(1, 'Make a bot', [
1768
+ el('p', { class: 'hint' }, ['In Telegram, open BotFather and send ', el('code', { text: '/newbot' }),
1769
+ '. Give it any name, then a username that ends in “bot”. BotFather replies with a token: copy it and paste it here.']),
1770
+ el('div', { class: 'row tight' }, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather ↗' })]),
1771
+ el('label', {}, ['Bot token', token]), tokenHint,
1772
+ ]),
1773
+ setupStep(2, 'Choose where alerts go', [
1774
+ el('p', { class: 'hint', text: 'Say hello to your bot so it knows the chat: press Start in a chat with it, or add it to a group and send any message there. For a channel, add it as an administrator and post once.' }),
1775
+ botLinks,
1776
+ el('div', { class: 'row tight' }, [find]),
1777
+ found,
1778
+ el('label', {}, ['Chat ID or channel username', address]),
1779
+ el('p', { class: 'hint', text: 'Filled in when you pick a chat above. You can also type one, like -1001234567890 or @yourchannel.' }),
1780
+ ]),
1781
+ setupStep(3, 'Save and test', [el('div', { class: 'row tight' }, [save, test, remove]), message]),
1782
+ ] : [
1596
1783
  el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
1597
- el('label', {}, [telegram ? 'Bot token' : 'Webhook token', token]), tokenHint,
1598
- el('label', {}, [telegram ? 'Chat ID or channel username' : 'Message endpoint', address]),
1599
- el('p', { class: 'hint' }, telegram
1600
- ? ['Create a bot with BotFather, start a conversation with it (or add it to your group), and enter the target chat ID. For a channel, add the bot as an administrator. ', el('a', { href: 'https://core.telegram.org/bots/tutorial', target: '_blank', rel: 'noopener noreferrer', text: 'Telegram setup guide' })]
1601
- : ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1784
+ el('label', {}, ['Webhook token', token]), tokenHint,
1785
+ el('label', {}, ['Message endpoint', address]),
1786
+ el('p', { class: 'hint' }, ['In Cliq, open Bots & Tools → Webhook Tokens and generate a token. Use the bot or channel message endpoint from Get Webhook URL, without the ?zapikey part. Use your region’s Cliq domain. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Cliq setup guide' })]),
1602
1787
  el('div', { class: 'row' }, [save, test, remove]), message,
1603
1788
  ]);
1604
1789
  function refresh() {
@@ -1651,9 +1836,17 @@
1651
1836
 
1652
1837
  // ---- team ------------------------------------------------------------------------------
1653
1838
 
1839
+ /** One numbered step of a setup, in the same style as the install steps. */
1840
+ function setupStep(n, title, kids) {
1841
+ return el('div', { class: 'setup-step' }, [
1842
+ el('div', { class: 'test-head' }, [el('span', { class: 'stepnum', text: String(n) }), el('b', { text: title })]),
1843
+ el('div', { class: 'setup-body' }, kids),
1844
+ ]);
1845
+ }
1846
+
1654
1847
  function teamView(view) {
1655
1848
  var owner = me.role === 'owner';
1656
- var list = el('ul', { class: 'members' });
1849
+ var list = el('ul', { class: 'members' }, [loading('li')]);
1657
1850
  var err = el('p', { class: 'err', role: 'alert' });
1658
1851
  view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Team' })]));
1659
1852
  view.appendChild(el('p', { class: 'mute', text: 'Everyone here can read and answer reports for every app. Owners can also change the team.' }));