create-heresay 0.2.40 → 0.2.42

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.40",
3
+ "version": "0.2.42",
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.40
1
+ 0.2.42
@@ -23,6 +23,8 @@ export const CHAT_LIMITS = [
23
23
  { limit: 60, windowMs: 3600_000 },
24
24
  { limit: 300, windowMs: 24 * 3600_000 },
25
25
  ];
26
+ /** Chunks added to drafts: each one is a write, so they're limited too. A whole bundle still sends as one request. */
27
+ const APPEND_LIMIT = { limit: 600, windowMs: 3600_000 };
26
28
  // Descriptive, not prescriptive: chat apps flag tool text that tells the model when to ask for
27
29
  // approval or what counts as sensitive ("Suspicious Instruction"). Their own rules cover that.
28
30
  const INSTRUCTIONS = [
@@ -31,7 +33,10 @@ const INSTRUCTIONS = [
31
33
  'apps); nothing is sent. send_draft sends a draft, to the app in the preview or to another one. `text` is the request as',
32
34
  'a teammate would read it; `details` is what the conversation worked out (why it matters, what was considered or ruled',
33
35
  'out, examples, constraints, open questions); both may be Markdown. `document` attaches a Markdown (.md) file, its full',
34
- 'contents as text (a spec, a research handoff, a summary of the whole conversation), up to 100,000 characters. A sent request stays open until someone on the team accepts it; sending',
36
+ 'contents as text (a spec, a research handoff, a summary of the whole conversation), up to 100,000 characters. A longer file',
37
+ 'goes in pieces: append_to_draft adds the next piece to the draft, one call at a time, and the whole thing is sent once as one request;',
38
+ 'never send a file as several requests. Rules that apply to the whole request go once in `details`, not in every piece.',
39
+ 'A sent request stays open until someone on the team accepts it; sending',
35
40
  'does not start any work. my_requests says what happened to the ones this member sent.',
36
41
  ].join(' ');
37
42
  /** How long a draft waits to be sent. */
@@ -49,7 +54,7 @@ const TOOLS = [
49
54
  title: 'Draft a Heresay request',
50
55
  description: 'Prepares a bug, a confusing part, an improvement or an idea for one app\'s Heresay inbox and returns a preview: '
51
56
  + 'the app it would go to, its type and text, and the other apps. Nothing is sent. Without an app it returns the list of apps. '
52
- + 'A Markdown (.md) file can be attached with `document` (its full contents).',
57
+ + 'A Markdown (.md) file can be attached with `document` (its full contents); a file over 100,000 characters is attached in pieces with append_to_draft.',
53
58
  inputSchema: {
54
59
  type: 'object',
55
60
  properties: {
@@ -65,6 +70,24 @@ const TOOLS = [
65
70
  },
66
71
  annotations: { readOnlyHint: true, openWorldHint: false },
67
72
  },
73
+ {
74
+ name: 'append_to_draft',
75
+ title: 'Add the next piece of a file to a Heresay draft',
76
+ description: 'Adds the next piece of the attached Markdown file to a draft from draft_request, for a file too long for one `document`. '
77
+ + 'Pieces are joined exactly as given, in the order of the calls, so call it once per piece and wait for each answer; split at any point. '
78
+ + 'Nothing is sent: send_draft sends the draft, with the whole file, as one request.',
79
+ inputSchema: {
80
+ type: 'object',
81
+ properties: {
82
+ draft_id: { type: 'string', description: 'From draft_request' },
83
+ document: { type: 'string', maxLength: LIMITS.documentMax, description: 'The next piece of the file, up to 100,000 characters.' },
84
+ document_title: { type: 'string', maxLength: LIMITS.documentTitleMax, description: 'The file\'s name or title, if the draft has none yet.' },
85
+ },
86
+ required: ['draft_id', 'document'],
87
+ additionalProperties: false,
88
+ },
89
+ annotations: { readOnlyHint: true, openWorldHint: false },
90
+ },
68
91
  {
69
92
  name: 'send_draft',
70
93
  title: 'Send a Heresay draft',
@@ -174,6 +197,8 @@ async function one(m, member, via, req, deps) {
174
197
  // send_request is what older bridges call; it drafts too, so nothing is sent unseen.
175
198
  if (name === 'draft_request' || name === 'send_request')
176
199
  return rpcResult(msg.id, await draftRequest(args, member, via, deps));
200
+ if (name === 'append_to_draft')
201
+ return rpcResult(msg.id, await appendToDraft(args, member, deps));
177
202
  if (name === 'send_draft')
178
203
  return rpcResult(msg.id, await sendDraft(args, member, req, deps));
179
204
  if (name === 'withdraw_request')
@@ -224,7 +249,7 @@ async function draftRequest(a, member, via, deps) {
224
249
  if (typeof a.document === 'string' && a.document.length > LIMITS.documentMax) {
225
250
  throw new ToolError(`The document is ${a.document.length} characters; the limit is ${LIMITS.documentMax}. Shorten it or split it across requests.`);
226
251
  }
227
- const markdown = typeof a.document === 'string' && a.document.trim() ? a.document.replace(/\r\n/g, '\n').trim() : null;
252
+ const markdown = typeof a.document === 'string' && a.document.trim() ? a.document.replace(/\r\n/g, '\n') : null;
228
253
  const document = markdown ? { title: str(a.document_title, LIMITS.documentTitleMax), markdown } : null;
229
254
  const all = (await deps.store.listProjects()).sort((x, y) => x.created_at.localeCompare(y.created_at));
230
255
  if (!str(a.app, 100)) {
@@ -234,14 +259,14 @@ async function draftRequest(a, member, via, deps) {
234
259
  const id = createHash('sha256').update(`${member.email}${deps.now()}${Math.random()}`).digest('hex').slice(0, 24);
235
260
  await deps.store.putAuth({
236
261
  kind: 'draft', id, expires_at: new Date(deps.now() + DRAFT_TTL_MS).toISOString(),
237
- data: { email: member.email, project_id: project.id, type: a.type, text, details, document, via },
262
+ data: { email: member.email, project_id: project.id, type: a.type, text, details, document, via, pieces: document ? 1 : 0 },
238
263
  });
239
264
  const others = all.filter((p) => p.id !== project.id);
240
265
  return result([
241
266
  `Draft, not sent yet. App: ${project.name} (${project.platform}). Type: ${a.type}.`,
242
267
  `Text: ${text}`,
243
268
  details ? `Details: ${details}` : null,
244
- document ? `Attached document: ${document.title ? `"${document.title}", ` : ''}${document.markdown.length} characters of Markdown.` : null,
269
+ document ? `Attached document: ${document.title ? `"${document.title}", ` : ''}${document.markdown.length} characters of Markdown. A longer file goes on with append_to_draft.` : null,
245
270
  others.length ? `Other apps it could go to instead: ${appNames(others)}.` : null,
246
271
  `send_draft with draft_id ${id} sends it${others.length ? ' (with app set to send it elsewhere)' : ''}. Drafts last two hours.`,
247
272
  ].filter(Boolean).join('\n'), {
@@ -250,6 +275,38 @@ async function draftRequest(a, member, via, deps) {
250
275
  other_apps: others.map((p) => ({ id: p.id, name: p.name, platform: p.platform })),
251
276
  });
252
277
  }
278
+ const trimmed = (d) => (d ? { ...d, markdown: d.markdown.trim() } : null);
279
+ /** The next piece of a draft's document. Refused, with the draft unchanged, if the whole would pass the cap. */
280
+ async function appendToDraft(a, member, deps) {
281
+ const id = str(a.draft_id, 64);
282
+ const d = id ? await deps.store.getAuth('draft', id) : null;
283
+ if (!d || String(d.data.email).toLowerCase() !== member.email.toLowerCase() || Date.parse(d.expires_at ?? '') < deps.now()) {
284
+ throw new ToolError('That draft doesn\'t exist, has expired or was already sent. Make a new one with draft_request.');
285
+ }
286
+ if (typeof a.document !== 'string' || !a.document.trim())
287
+ throw new ToolError('Give the next piece of the file in document.');
288
+ if (a.document.length > LIMITS.documentMax) {
289
+ throw new ToolError(`That piece is ${a.document.length} characters; a piece can be up to ${LIMITS.documentMax}. Split it and add the parts one by one.`);
290
+ }
291
+ const now = deps.now();
292
+ const start = Math.floor(now / APPEND_LIMIT.windowMs) * APPEND_LIMIT.windowMs;
293
+ if (!(await deps.store.hit(`chatappend:${APPEND_LIMIT.windowMs}:${member.email.toLowerCase()}:${start}`, APPEND_LIMIT.limit, start + APPEND_LIMIT.windowMs))) {
294
+ throw new ToolError('That\'s a lot of pieces in a short time. Try again later.');
295
+ }
296
+ const had = d.data.document ?? null;
297
+ const markdown = (had?.markdown ?? '') + a.document.replace(/\r\n/g, '\n');
298
+ const bytes = Buffer.byteLength(markdown, 'utf8');
299
+ // Refused rather than cut, so the end of a long file isn't silently missing.
300
+ if (bytes > LIMITS.documentBundleBytes) {
301
+ throw new ToolError(`With that piece the file would be ${bytes} bytes; the limit is ${LIMITS.documentBundleBytes}. The draft is unchanged: send it as it is, or start a new one with a shorter file.`);
302
+ }
303
+ const document = { title: had?.title ?? str(a.document_title, LIMITS.documentTitleMax), markdown };
304
+ const pieces = Number(d.data.pieces ?? 0) + 1;
305
+ // Each piece keeps the draft alive, so a long file isn't lost half-built.
306
+ await deps.store.putAuth({ ...d, expires_at: new Date(now + DRAFT_TTL_MS).toISOString(), data: { ...d.data, document, pieces } });
307
+ return result(`Added piece ${pieces}. The draft's document is now ${markdown.length} characters (${bytes} of ${LIMITS.documentBundleBytes} bytes allowed). `
308
+ + `Add the next piece, or send_draft with draft_id ${id} to send the whole file as one request.`, { draft_id: id, sent: false, pieces, document: { title: document.title, characters: markdown.length, bytes } });
309
+ }
253
310
  async function sendDraft(a, member, req, deps) {
254
311
  const id = str(a.draft_id, 64);
255
312
  const d = id ? await deps.store.getAuth('draft', id) : null;
@@ -262,7 +319,7 @@ async function sendDraft(a, member, req, deps) {
262
319
  // Once only, however many times it's called.
263
320
  if (!(await deps.store.takeAuth('draft', id)))
264
321
  throw new ToolError('That draft was already sent.');
265
- return createChatReport(project, d.data.type, String(d.data.text), d.data.details ?? null, d.data.document ?? null, member, String(d.data.via ?? 'a chat app'), req, deps);
322
+ return createChatReport(project, d.data.type, String(d.data.text), d.data.details ?? null, trimmed(d.data.document), member, String(d.data.via ?? 'a chat app'), req, deps);
266
323
  }
267
324
  async function createChatReport(project, type, text, details, document, member, via, req, deps) {
268
325
  const now = deps.now();
@@ -18,7 +18,9 @@ export function notificationView(settings) {
18
18
  cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
19
19
  };
20
20
  }
21
- const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled;
21
+ // Also when it's on but the bot has no webhook yet (saved before buttons existed, or a failed attempt),
22
+ // so saving again fixes it without turning Telegram off and on.
23
+ const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled || (b.enabled && !!b.token && !b.webhook_url);
22
24
  class SettingsError extends Error {
23
25
  }
24
26
  const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
@@ -24,6 +24,8 @@ export const LIMITS = {
24
24
  textMax: 2000,
25
25
  detailsMax: 8000,
26
26
  documentMax: 100_000,
27
+ /** A document built up over several append_to_draft calls, in UTF-8 bytes: under Firestore's 1 MiB per document, with room for the rest of the report. */
28
+ documentBundleBytes: 800_000,
27
29
  documentTitleMax: 120,
28
30
  filesMax: 20,
29
31
  pathMax: 300,
@@ -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.40';
2
+ export const VERSION = '0.2.42';
3
3
  //# sourceMappingURL=version.js.map
@@ -506,3 +506,31 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
506
506
 
507
507
  .status.s-withdrawn { background:rgba(127,127,127,.14); color:var(--mute); }
508
508
  .report .reason.withdrawn { color:var(--mute); }
509
+
510
+ /* Notifications: small modules, each one a place alerts go or a thing to choose. */
511
+ .notify { max-width:720px; }
512
+ .module { padding:20px 24px; }
513
+ .module-head { display:flex; align-items:center; gap:12px; margin-bottom:6px; }
514
+ .module-head h2 { margin:0; font-size:18px; }
515
+ .module-head .spacer, .module-row .grow { flex:1; min-width:0; }
516
+ .pill-state { font-size:12px; font-weight:600; padding:3px 10px; border-radius:999px; background:var(--soft); color:var(--mute); }
517
+ .pill-state.on { background:var(--mist); color:var(--deep); }
518
+ .saved-tick { font-size:13px; color:var(--deep); }
519
+ .module-row { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:12px 0; border-top:1px solid var(--line); }
520
+ .module-row:first-of-type { border-top:0; }
521
+ .module-row .grow { color:var(--mute); }
522
+ .module-row .grow.ok-msg { color:var(--deep); }
523
+ .module-row .grow-line { flex-basis:100%; margin:0; }
524
+ .link-code { flex-basis:100%; }
525
+ .module-panel { border-top:1px solid var(--line); padding-top:4px; }
526
+ .module-panel[hidden], .module [hidden] { display:none; }
527
+ .module-more { margin-top:18px; }
528
+ .switch-row { display:flex; align-items:center; justify-content:space-between; gap:16px; padding:13px 0; border-top:1px solid var(--line); cursor:pointer; }
529
+ .switch-row .hint { display:inline; margin:0; }
530
+ .switch { appearance:none; -webkit-appearance:none; width:38px; height:22px; border-radius:999px; background:var(--line); position:relative; cursor:pointer; flex:none; border:0; margin:0; padding:0; transition:background .15s; }
531
+ .switch::after { content:""; position:absolute; top:3px; left:3px; width:16px; height:16px; border-radius:50%; background:#fff; box-shadow:0 1px 2px rgb(0 0 0 / .25); transition:transform .15s; }
532
+ .switch:checked { background:var(--acc); }
533
+ .switch:checked::after { transform:translateX(16px); }
534
+ .switch:focus-visible { outline:2px solid var(--acc); outline-offset:2px; }
535
+ .switch:disabled { opacity:.5; cursor:default; }
536
+ @media (prefers-reduced-motion: reduce) { .switch, .switch::after { transition:none; } }
@@ -1320,6 +1320,8 @@
1320
1320
  view.classList.add('inbox-view');
1321
1321
  var reports = [], ctxs = {}, selected = null, loaded = false, detailSignature = null, loadSerial = 0;
1322
1322
  var product = p ? productOf(p) : 'all', platform = 'all', search = '', type = 'all', source = 'all';
1323
+ // Choosing several open reports to accept together: the keys picked, a confirm step, the last one ticked (for shift-click).
1324
+ var picking = false, picked = {}, confirming = false, bulkBusy = false, lastPick = null;
1323
1325
  var shell = el('div', { class: 'inbox-shell' });
1324
1326
  var list = el('div', { class: 'report-list', 'aria-label': 'Reports' });
1325
1327
  var detail = el('section', { class: 'report-detail', 'aria-label': 'Report details', tabindex: '-1' });
@@ -1339,10 +1341,11 @@
1339
1341
  var controls = el('div', { class: 'inbox-controls' }, [productSelect, platformSelect, filterButton]);
1340
1342
  var productTools = el('details', { class: 'inbox-app-tools', hidden: !p }, [el('summary', { text: 'Manage app' })]);
1341
1343
  var listHead = el('div', { class: 'list-heading' }, [el('b', { text: 'Needs review' }), el('span', { text: 'Type, then most reported' })]);
1344
+ var bulkBar = el('div', { class: 'bulk-bar', hidden: true });
1342
1345
  var master = el('section', { class: 'inbox-master', 'aria-label': 'Report inbox' }, [
1343
1346
  el('div', { class: 'inbox-heading' }, [heading, el('p', { class: 'mute', text: 'A hearing for every report.' })]),
1344
1347
  el('div', { class: 'inbox-search' }, [searchInput, el('kbd', { text: '⌘ K', 'aria-hidden': 'true' })]),
1345
- controls, advanced, productTools, filters, listHead, list,
1348
+ controls, advanced, productTools, filters, listHead, bulkBar, list,
1346
1349
  ]);
1347
1350
  shell.appendChild(master); shell.appendChild(detail); view.appendChild(shell);
1348
1351
  detail.appendChild(loading());
@@ -1402,6 +1405,12 @@
1402
1405
  var shown = here.filter(function (r) { return filter === 'all' || r.status === filter; });
1403
1406
  listHead.firstChild.textContent = filter === 'open' ? 'Needs review' : filter === 'all' ? 'All reports' : STATUS_LABEL[filter] + ' reports';
1404
1407
  if (!shown.some(function (r) { return key(r) === selected; })) selected = shown.length ? key(shown[0]) : null;
1408
+ // Only open reports can be accepted, so choosing is for that tab; whatever left the list drops out of the choice.
1409
+ if (filter !== 'open' || !shown.length) { picking = false; confirming = false; picked = {}; lastPick = null; }
1410
+ Object.keys(picked).forEach(function (k) { if (!shown.some(function (r) { return key(r) === k; })) delete picked[k]; });
1411
+ if (!Object.keys(picked).length) confirming = false;
1412
+ drawBulk(shown);
1413
+ list.classList.toggle('picking', picking);
1405
1414
  list.textContent = '';
1406
1415
  if (!projects.length) {
1407
1416
  list.appendChild(el('div', { class: 'inbox-empty' }, [markImg(48), el('h2', { text: 'Add your first app' }), el('p', { text: 'Connect your app to give every report a hearing.' }), el('a', { class: 'btn primary', href: '#/new', text: 'Add an app' })]));
@@ -1417,7 +1426,20 @@
1417
1426
  el('span', { class: 'preview-meta' }, [sourceTag(r, 'src-label'), (count > 1 ? ' · ' + count + ' reports' : '') + ' · ' + relative(r.created_at)])]),
1418
1427
  el('span', { class: 'pill ' + r.type, text: TYPE_LABEL[r.type] }),
1419
1428
  ]);
1420
- list.appendChild(button);
1429
+ var line = el('div', { class: 'report-row' }, [button]);
1430
+ if (picking) {
1431
+ var box = el('input', { type: 'checkbox', 'aria-label': 'Select: ' + title(r), disabled: bulkBusy });
1432
+ box.checked = !!picked[key(r)];
1433
+ box.addEventListener('click', function (e) {
1434
+ var on = box.checked, at = shown.indexOf(r);
1435
+ // Shift-click ticks everything between this one and the last.
1436
+ var from = e.shiftKey && lastPick !== null ? Math.min(at, lastPick) : at, to = e.shiftKey && lastPick !== null ? Math.max(at, lastPick) : at;
1437
+ shown.slice(from, to + 1).forEach(function (x) { if (on) picked[key(x)] = true; else delete picked[key(x)]; });
1438
+ lastPick = at; confirming = false; render();
1439
+ });
1440
+ line.insertBefore(el('label', { class: 'pick' }, [box]), button);
1441
+ }
1442
+ list.appendChild(line);
1421
1443
  });
1422
1444
  drawDetail(shown, preserveDetail);
1423
1445
  var candidates = focusedReport ? list.querySelectorAll('[data-report]') : focusedStatus ? filters.querySelectorAll('[data-status]') : [];
@@ -1426,6 +1448,54 @@
1426
1448
  return false;
1427
1449
  });
1428
1450
  }
1451
+ /** The bar over the list: start choosing, select all, how many, and the two-step accept. */
1452
+ function drawBulk(shown) {
1453
+ bulkBar.textContent = '';
1454
+ bulkBar.hidden = filter !== 'open' || !shown.length;
1455
+ if (bulkBar.hidden) return;
1456
+ if (!picking) {
1457
+ bulkBar.appendChild(el('button', { class: 'btn ghost', type: 'button', text: 'Select reports…', onclick: function () { picking = true; render(); } }));
1458
+ return;
1459
+ }
1460
+ var n = Object.keys(picked).length;
1461
+ var all = el('input', { type: 'checkbox', 'aria-label': 'Select all ' + shown.length + ' open reports', disabled: bulkBusy });
1462
+ all.checked = n === shown.length; all.indeterminate = n > 0 && n < shown.length;
1463
+ all.addEventListener('click', function () {
1464
+ shown.forEach(function (r) { if (all.checked) picked[key(r)] = true; else delete picked[key(r)]; });
1465
+ confirming = false; render();
1466
+ });
1467
+ bulkBar.appendChild(el('label', { class: 'pick-all' }, [all, ' All ' + shown.length]));
1468
+ bulkBar.appendChild(el('span', { class: 'count', role: 'status', text: bulkBusy ? 'Accepting…' : n ? n + ' selected' : 'None selected' }));
1469
+ bulkBar.appendChild(el('span', { class: 'spacer' }));
1470
+ if (confirming && n) {
1471
+ bulkBar.appendChild(el('span', { class: 'confirm-q', text: 'Make ' + n + (n === 1 ? ' report' : ' reports') + ' available to a coding agent?' }));
1472
+ bulkBar.appendChild(el('button', { class: 'btn primary', type: 'button', disabled: bulkBusy, text: 'Yes, accept ' + n, onclick: function () { acceptPicked(shown); } }));
1473
+ bulkBar.appendChild(el('button', { class: 'btn', type: 'button', disabled: bulkBusy, text: 'Back', onclick: function () { confirming = false; render(); } }));
1474
+ } else {
1475
+ bulkBar.appendChild(el('button', { class: 'btn primary', type: 'button', disabled: !n || bulkBusy, text: n ? 'Accept ' + n + '…' : 'Accept…', onclick: function () { confirming = true; render(); } }));
1476
+ bulkBar.appendChild(el('button', { class: 'btn ghost', type: 'button', disabled: bulkBusy, text: 'Cancel', onclick: function () { picking = false; picked = {}; lastPick = null; render(); } }));
1477
+ }
1478
+ }
1479
+ /** One after another through the same accept a person does on a single report: the default repo, no note. A 409 or an error leaves that one open and the rest go on. */
1480
+ function acceptPicked(shown) {
1481
+ var todo = shown.filter(function (r) { return picked[key(r)]; }), ok = 0, failed = [];
1482
+ bulkBusy = true; confirming = false; render();
1483
+ var step = function (i) {
1484
+ if (i >= todo.length) return Promise.resolve();
1485
+ var r = todo[i];
1486
+ return api('POST', '/projects/' + r.project_id + '/reports/' + r.id + '/accept', {})
1487
+ .then(function (x) { Object.assign(r, x.report || {}); ok++; delete picked[key(r)]; })
1488
+ .catch(function (x) { failed.push(x.message); })
1489
+ .then(function () { return step(i + 1); });
1490
+ };
1491
+ step(0).then(function () {
1492
+ bulkBusy = false;
1493
+ if (!failed.length) { picking = false; lastPick = null; }
1494
+ toast('Accepted ' + ok + (ok === 1 ? ' report' : ' reports') + '. They are waiting for a coding agent.'
1495
+ + (failed.length ? ' ' + failed.length + ' could not be accepted: ' + failed[0] : ''), null, failed.length > 0);
1496
+ selected = null; load(true);
1497
+ });
1498
+ }
1429
1499
  function drawDetail(shown, preserve) {
1430
1500
  var chosen = shown.filter(function (x) { return key(x) === selected; })[0];
1431
1501
  var signature = chosen ? JSON.stringify([chosen, ctxs[chosen.project_id].briefs[chosen.id], ctxs[chosen.project_id].dups[chosen.id], ctxs[chosen.project_id].repos]) : null;
@@ -2045,298 +2115,339 @@
2045
2115
 
2046
2116
  // ---- notifications ---------------------------------------------------------------------
2047
2117
 
2118
+ /** The page is a stack of small modules: where alerts go (one per place), what to send, and your own Telegram link. */
2048
2119
  function notificationsView(view) {
2049
2120
  view.appendChild(el('div', { class: 'head' }, [el('h1', { text: 'Notifications' })]));
2050
- view.appendChild(el('p', { class: 'mute', text: 'Know when a report needs a hearing, or when work moves forward. These settings apply to every app in this Heresay.' }));
2121
+ var content = el('div', { class: 'notify' }, [loading()]);
2122
+ view.appendChild(content);
2051
2123
  if (me.role !== 'owner') {
2052
- 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' })]));
2053
- telegramActions(view);
2124
+ content.textContent = '';
2125
+ content.appendChild(el('p', { class: 'mute', text: 'Owners choose where alerts go.' }));
2126
+ var row = telegramLink({});
2127
+ content.appendChild(el('section', { class: 'card module' }, [el('div', { class: 'module-head' }, [el('h2', { text: 'Telegram' })]), row]));
2054
2128
  return;
2055
2129
  }
2056
- var content = el('div', {}, [loading()]);
2057
- view.appendChild(content);
2058
2130
  api('GET', '/notifications').then(function (b) {
2131
+ content.textContent = '';
2059
2132
  var settings = b.notifications;
2060
- var choices = [
2061
- ['new_report', 'New reports', 'A new report is waiting for a person to review it.'],
2062
- ['accepted', 'Accepted reports', 'A person approved a report for a coding agent.'],
2063
- ['fixed', 'Reports marked fixed', 'A teammate or coding agent marked a report fixed.'],
2064
- ['handoff', 'Agent handoffs', 'An agent handed accepted work to another repo.'],
2065
- ];
2066
- var eventInputs = {};
2067
- var eventsMsg = el('p', { role: 'status' });
2068
- var eventSave = el('button', { class: 'btn primary', type: 'submit', text: 'Save events' });
2069
- var eventsForm = el('form', { class: 'form notification-form' }, choices.map(function (choice) {
2070
- var input = eventInputs[choice[0]] = el('input', { type: 'checkbox', name: choice[0], checked: settings.events[choice[0]] });
2071
- return el('label', { class: 'notification-choice' }, [input, el('span', {}, [el('b', { text: choice[1] }), el('span', { class: 'hint', text: choice[2] })])]);
2072
- }).concat([el('div', { class: 'row' }, [eventSave]), eventsMsg]));
2073
- eventsForm.onsubmit = function (e) {
2074
- e.preventDefault();
2075
- var events = {};
2076
- Object.keys(eventInputs).forEach(function (key) { events[key] = eventInputs[key].checked; eventInputs[key].disabled = true; });
2077
- eventSave.disabled = true;
2078
- eventsMsg.className = 'hint'; eventsMsg.textContent = 'Saving…';
2079
- api('PATCH', '/notifications', { events: events }).then(function () {
2080
- eventsMsg.className = 'ok-msg'; eventsMsg.textContent = 'Notification events saved.';
2081
- }).catch(function (x) { eventsMsg.className = 'err'; eventsMsg.textContent = x.message; }).finally(function () {
2082
- eventSave.disabled = false;
2083
- Object.keys(eventInputs).forEach(function (key) { eventInputs[key].disabled = false; });
2084
- });
2085
- };
2086
- content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
2087
- content.appendChild(el('p', { class: 'hint', text: 'Alerts include the app name, event, report ID, and a link to the dashboard. Reporter text and contact details stay in Heresay.' }));
2088
- destination('telegram', 'Telegram', settings.telegram);
2089
- telegramActions(content);
2090
- destination('cliq', 'Zoho Cliq', settings.cliq);
2091
-
2092
- function destination(provider, title, saved) {
2093
- var telegram = provider === 'telegram', dirty = false;
2094
- var enabled = el('input', { type: 'checkbox', name: provider + '_enabled', checked: saved.enabled });
2095
- var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
2096
- var address = el('input', { type: 'text', name: telegram ? 'chat_id' : 'endpoint', value: telegram ? saved.chat_id : saved.endpoint, maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
2097
- var tokenHint = el('p', { class: 'hint' });
2098
- var message = el('p', { role: 'status' });
2099
- var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save ' + title });
2100
- var test = el('button', { class: 'btn', type: 'button', text: 'Send test notification' });
2101
- var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
2102
- var photo = el('button', { class: 'btn ghost', type: 'button', text: 'Use the Heresay logo as the bot’s picture' });
2103
- var tg = telegram ? telegramGuide() : null;
2104
- var form = el('form', { class: 'form notification-form' }, telegram ? [
2105
- el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
2106
- setupStep(1, 'Make a bot', [
2107
- el('ol', { class: 'guide' }, [
2108
- el('li', {}, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather in Telegram ↗' })]),
2109
- el('li', {}, ['Send ', el('code', { text: '/newbot' }), '. It asks for a name (anything, like “Acme alerts”), then a username that ends in “bot” (like acme_alerts_bot).']),
2110
- el('li', {}, ['It replies with a long token that looks like ', el('code', { text: '123456789:AAH…' }), '. Copy it and paste it here.']),
2111
- ]),
2112
- el('label', {}, ['Bot token', token]), tokenHint, tg.botLine,
2113
- ]),
2114
- setupStep(2, 'Choose where alerts go', [tg.step2]),
2115
- setupStep(3, 'Save and test', [
2116
- el('p', { class: 'hint', text: 'Save, then send a test. It arrives from your bot in a few seconds.' }),
2117
- el('div', { class: 'row tight' }, [save, test, remove]), message,
2118
- el('div', { class: 'row tight' }, [photo, el('span', { class: 'hint', text: 'Replaces the bot’s current picture.' })]),
2119
- ]),
2120
- ] : [
2121
- el('label', { class: 'notification-choice' }, [enabled, el('b', { text: 'Enable ' + title + ' notifications' })]),
2122
- el('label', {}, ['Webhook token', token]), tokenHint,
2123
- el('label', {}, ['Message endpoint', address]),
2124
- 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' })]),
2125
- el('div', { class: 'row' }, [save, test, remove]), message,
2126
- ]);
2127
- /**
2128
- * Telegram has no screen that shows a chat ID, so we never ask for one up front. Once the
2129
- * token checks out, the person picks who gets alerts, follows two or three taps, and this
2130
- * page watches the bot until their chat turns up, then chooses it.
2131
- */
2132
- function telegramGuide() {
2133
- var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }) };
2134
- var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
2135
- var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
2136
- var wait = el('div', { class: 'wait', role: 'status' });
2137
- var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
2138
- var chosen = el('p', { class: 'ok-msg chosen-line' });
2139
- var manual = el('details', { class: 'where', open: !!saved.chat_id }, [
2140
- el('summary', { text: 'Enter a chat ID yourself' }),
2141
- el('label', {}, ['Chat ID or channel username', address]),
2142
- el('p', { class: 'hint', text: 'Only if you already know it, like -1001234567890 or @yourchannel. Picking a chat above fills this in.' }),
2143
- ]);
2144
- var tabs = el('div', { class: 'seg', role: 'tablist', 'aria-label': 'Who gets alerts' });
2145
- var how = el('ol', { class: 'guide' });
2146
- var again = el('button', { class: 'btn', type: 'button', text: 'Look again', onclick: function () { watch(); } });
2147
-
2148
- function link(href, text) { return el('a', { class: 'btn', href: href, target: '_blank', rel: 'noopener noreferrer', text: text }); }
2149
- function drawHow() {
2150
- var at = '@' + bot.username, url = 'https://t.me/' + encodeURIComponent(bot.username);
2151
- how.textContent = '';
2152
- (kind === 'private' ? [
2153
- [link(url, 'Open ' + at + ' in Telegram ↗')],
2154
- ['Tap ', el('b', { text: 'Start' }), ' at the bottom of the chat. No Start button? Send it any message, like “hi”.'],
2155
- ['Come back to this page. It finds the chat by itself.'],
2156
- ] : kind === 'group' ? [
2157
- [link(url + '?startgroup=heresay', 'Add ' + at + ' to a group ↗')],
2158
- ['Telegram asks which group. Pick it and confirm.'],
2159
- ['Come back to this page. It finds the group by itself. If it doesn’t, send ', el('code', { text: '/start' + at }), ' in the group.'],
2160
- ] : [
2161
- ['In Telegram, open your channel and tap its name, then ', el('b', { text: 'Administrators' }), ' → ', el('b', { text: 'Add Admin' }), '.'],
2162
- ['Search for ', el('b', { text: at }), ', add it, and leave ', el('b', { text: 'Post Messages' }), ' on.'],
2163
- ['Post anything in the channel, then come back to this page. It finds the channel by itself.'],
2164
- ]).forEach(function (kids) { how.appendChild(el('li', {}, kids)); });
2165
- }
2166
- function drawTabs() {
2167
- tabs.textContent = '';
2168
- [['private', 'Just me'], ['group', 'A group'], ['channel', 'A channel']].forEach(function (t) {
2169
- tabs.appendChild(el('button', { type: 'button', role: 'tab', 'aria-selected': String(kind === t[0]), text: t[1], onclick: function () {
2170
- kind = t[0]; drawTabs(); drawHow(); drawChats(); watch();
2171
- } }));
2172
- });
2173
- }
2174
- function sameKind(c) { return kind === 'group' ? c.kind === 'group' || c.kind === 'supergroup' : c.kind === kind; }
2175
- function pick(c) {
2176
- address.value = c.id;
2177
- enabled.checked = true;
2178
- form.dispatchEvent(new Event('input'));
2179
- stop();
2180
- drawChats();
2181
- feedback('Chat chosen. Save to start sending alerts there.');
2182
- }
2183
- function drawChats() {
2184
- list.textContent = '';
2185
- var hit = chats.filter(function (c) { return c.id === address.value; })[0];
2186
- chosen.hidden = !address.value;
2187
- chosen.textContent = hit ? '✓ Alerts will go to ' + hit.title + ' (' + KIND[hit.kind].toLowerCase() + ').'
2188
- : address.value ? '✓ Alerts go to chat ' + address.value + '. Pick another below to change it.' : '';
2189
- chats.forEach(function (c) {
2190
- var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
2191
- radio.onchange = function () { pick(c); };
2192
- list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] })])]));
2193
- });
2194
- list.hidden = !chats.length;
2195
- }
2196
- function drawWait(state) {
2197
- wait.textContent = '';
2198
- wait.className = 'wait' + (state === 'idle' ? ' ok idle' : '');
2199
- if (state === 'waiting') wait.appendChild(document.createTextNode('Waiting for ' + (kind === 'private' ? 'your message to' : kind === 'group' ? 'a group with' : 'a channel with') + ' @' + bot.username + '…'));
2200
- else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet. Follow the steps above, then')); wait.appendChild(again); }
2201
- wait.hidden = state === 'none';
2202
- }
2203
- function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
2204
- function watch() {
2205
- clearTimeout(timer);
2206
- until = Date.now() + 5 * 60 * 1000;
2207
- drawWait('waiting');
2208
- poll();
2209
- }
2210
- function poll() {
2211
- if (!form.isConnected) return;
2212
- lookup(true).then(function () {
2213
- var match = chats.filter(sameKind)[0];
2214
- if (match && !address.value) return pick(match); // never replace a chat they already chose
2215
- if (match) return stop();
2216
- if (Date.now() > until) return stop();
2217
- timer = setTimeout(poll, 6000);
2218
- }).catch(stop);
2219
- }
2220
- function lookup(quiet) {
2221
- return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
2222
- var fresh = !bot || bot.username !== b.bot.username;
2223
- bot = b.bot; chats = b.chats; connected = !!b.connected;
2224
- g.botLine.textContent = '';
2225
- g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
2226
- if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [el('p', { class: 'hint', text: 'Who should get the alerts?' }), tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
2227
- drawChats();
2228
- if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
2229
- }).catch(function (x) {
2230
- if (quiet && bot) return;
2231
- g.botLine.textContent = '';
2232
- g.botLine.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2233
- throw x;
2234
- });
2235
- }
2236
- function check() {
2237
- clearTimeout(checking);
2238
- checking = setTimeout(function () {
2239
- lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
2240
- }, 400);
2241
- }
2242
- g.step2.appendChild(el('p', { class: 'hint', text: 'Paste your bot token above first. Then this step shows exactly what to tap.' }));
2243
- g.step2.appendChild(manual);
2244
- token.addEventListener('input', function () { if (/^\d+:[A-Za-z0-9_-]{20,}$/.test(token.value.trim())) check(); });
2245
- if (saved.configured) check();
2246
- return g;
2247
- }
2248
- function refresh() {
2249
- token.placeholder = saved.configured ? 'Leave blank to keep the saved token' : 'Paste your token';
2250
- tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Your token is saved on the server and is never displayed here.';
2251
- test.disabled = dirty || !saved.enabled;
2252
- remove.disabled = !saved.configured;
2253
- photo.disabled = !saved.configured;
2254
- }
2255
- function busy(on) {
2256
- form.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
2257
- if (!on) refresh();
2258
- }
2259
- function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
2260
- form.oninput = function () { dirty = true; test.disabled = true; feedback('Save your changes before sending a test.'); };
2261
- form.onsubmit = function (e) {
2262
- e.preventDefault();
2263
- var patch = { enabled: enabled.checked, token: token.value.trim() };
2264
- patch[telegram ? 'chat_id' : 'endpoint'] = address.value.trim();
2265
- var body = {}; body[provider] = patch;
2266
- busy(true); feedback('Saving…');
2267
- api('PATCH', '/notifications', body).then(function (result) {
2268
- saved = result.notifications[provider]; dirty = false; token.value = '';
2269
- feedback(title + ' settings saved. Send a test to check delivery.');
2270
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2271
- };
2272
- test.onclick = function () {
2273
- busy(true); feedback('Sending a test…');
2274
- api('POST', '/notifications/test', { provider: provider }).then(function () {
2275
- feedback('Test notification sent. Check ' + title + '.');
2276
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2277
- };
2278
- photo.onclick = function () {
2279
- busy(true); photo.textContent = 'Setting the picture…';
2280
- api('POST', '/notifications/telegram/photo', {}).then(function () {
2281
- toast('The bot now uses the Heresay logo. Telegram may take a moment to show it.');
2282
- }).catch(function (x) { toast(x.message, null, true); }).finally(function () {
2283
- photo.textContent = 'Use the Heresay logo as the bot’s picture'; busy(false);
2284
- });
2285
- };
2286
- remove.onclick = function () {
2287
- var body = {}, patch = { enabled: false, token: null };
2288
- patch[telegram ? 'chat_id' : 'endpoint'] = '';
2289
- body[provider] = patch;
2290
- busy(true); feedback('Disconnecting…');
2291
- api('PATCH', '/notifications', body).then(function (result) {
2292
- saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
2293
- feedback(title + ' disconnected. The saved token was removed.');
2294
- }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2295
- };
2296
- refresh();
2297
- content.appendChild(el('section', { class: 'card' }, [el('h2', { text: title }), form]));
2298
- }
2133
+ content.appendChild(destinationModule('telegram', 'Telegram', settings.telegram));
2134
+ content.appendChild(destinationModule('cliq', 'Zoho Cliq', settings.cliq));
2135
+ content.appendChild(eventsModule(settings));
2299
2136
  }).catch(function (x) {
2137
+ content.textContent = '';
2300
2138
  content.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2301
2139
  content.appendChild(el('button', { class: 'btn', text: 'Retry', onclick: function () { route(); } }));
2302
2140
  });
2303
2141
  }
2304
2142
 
2143
+ function statePill(saved) {
2144
+ return el('span', { class: 'pill-state' + (saved.configured && saved.enabled ? ' on' : ''), text: !saved.configured ? 'Not set up' : saved.enabled ? 'On' : 'Paused' });
2145
+ }
2146
+
2147
+ /** What to send: one switch per event, each saved the moment it is flipped. */
2148
+ function eventsModule(settings) {
2149
+ var choices = [
2150
+ ['new_report', 'New reports', 'waiting for review'],
2151
+ ['accepted', 'Accepted', 'sent to an agent'],
2152
+ ['fixed', 'Marked fixed', 'by a person or an agent'],
2153
+ ['handoff', 'Agent handoffs', 'to another repo'],
2154
+ ];
2155
+ var inputs = {}, saved = el('span', { class: 'saved-tick', role: 'status' });
2156
+ var rows = choices.map(function (c) {
2157
+ var input = inputs[c[0]] = el('input', { type: 'checkbox', class: 'switch', name: c[0], checked: settings.events[c[0]] });
2158
+ input.onchange = function () {
2159
+ var events = {};
2160
+ Object.keys(inputs).forEach(function (k) { events[k] = inputs[k].checked; });
2161
+ saved.textContent = 'Saving…';
2162
+ api('PATCH', '/notifications', { events: events }).then(function () { saved.textContent = '✓ Saved'; })
2163
+ .catch(function (x) { input.checked = !input.checked; saved.textContent = ''; toast(x.message, null, true); });
2164
+ };
2165
+ return el('label', { class: 'switch-row' }, [el('span', {}, [el('b', { text: c[1] }), el('span', { class: 'hint', text: ' ' + c[2] })]), input]);
2166
+ });
2167
+ return el('section', { class: 'card module' }, [
2168
+ el('div', { class: 'module-head' }, [el('h2', { text: 'What to send' }), el('span', { class: 'spacer' }), saved]),
2169
+ el('div', {}, rows),
2170
+ el('p', { class: 'hint', text: 'Alerts show the app and a link. Never the report text.' }),
2171
+ ]);
2172
+ }
2173
+
2174
+ /**
2175
+ * One place alerts can go. Closed, it is a name, a state, an on/off switch and a test button; Set up or Edit opens the
2176
+ * form. Telegram's form is three short steps; Cliq's is two fields.
2177
+ */
2178
+ function destinationModule(provider, title, saved) {
2179
+ var telegram = provider === 'telegram', dirty = false, opened = false;
2180
+ var addrKey = telegram ? 'chat_id' : 'endpoint';
2181
+ var enabled = { checked: saved.enabled };
2182
+ var token = el('input', { type: 'password', name: provider + '_token', maxlength: 512, autocomplete: 'new-password', spellcheck: 'false' });
2183
+ var address = el('input', { type: 'text', name: addrKey, value: saved[addrKey], maxlength: telegram ? 100 : 300, autocomplete: 'off', spellcheck: 'false', placeholder: telegram ? '-1001234567890 or @yourchannel' : 'https://cliq.zoho.com/api/v2/channelsbyname/team/message' });
2184
+ var tokenHint = el('p', { class: 'hint' });
2185
+ var message = el('p', { role: 'status' });
2186
+ var save = el('button', { class: 'btn primary', type: 'submit', text: 'Save' });
2187
+ var test = el('button', { class: 'btn', type: 'button', text: 'Send test' });
2188
+ var remove = el('button', { class: 'btn ghost', type: 'button', text: 'Disconnect' });
2189
+ var photo = el('button', { class: 'btn ghost', type: 'button', text: 'Use the Heresay logo as the bot’s picture' });
2190
+ var sw = el('input', { type: 'checkbox', class: 'switch', name: provider + '_enabled', 'aria-label': title + ' alerts on', checked: saved.enabled });
2191
+ var head = el('div', { class: 'module-head' });
2192
+ var edit = el('button', { class: 'btn', type: 'button', 'aria-expanded': 'false' });
2193
+ var panel = el('div', { class: 'module-panel', hidden: true });
2194
+ var tg = telegram ? telegramGuide() : null;
2195
+ var form = el('form', { class: 'form notification-form' }, telegram ? [
2196
+ setupStep(1, 'Make a bot', [
2197
+ el('p', {}, [el('a', { class: 'btn', href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener noreferrer', text: 'Open BotFather ↗' }), ' Send ', el('code', { text: '/newbot' }), ', then paste the token it gives you.']),
2198
+ el('label', {}, ['Bot token', token]), tokenHint, tg.botLine,
2199
+ ]),
2200
+ setupStep(2, 'Pick the chat', [tg.step2]),
2201
+ el('div', { class: 'row tight' }, [save]), message,
2202
+ ] : [
2203
+ el('label', {}, ['Webhook token', token]), tokenHint,
2204
+ el('label', {}, ['Message endpoint', address]),
2205
+ el('p', { class: 'hint' }, ['In Cliq: Bots & Tools → Webhook Tokens. ', el('a', { href: 'https://www.zoho.com/cliq/help/platform/webhook-tokens.html', target: '_blank', rel: 'noopener noreferrer', text: 'Guide ↗' })]),
2206
+ el('div', { class: 'row tight' }, [save]), message,
2207
+ ]);
2208
+ var more = el('div', { class: 'row tight module-more' }, telegram ? [photo, remove] : [remove]);
2209
+ panel.appendChild(form); panel.appendChild(more);
2210
+ var actions = el('div', { class: 'module-row' }, [el('span', { class: 'grow' }), test, edit]);
2211
+ var box = el('section', { class: 'card module' }, [head, actions, panel]);
2212
+ if (telegram) box.insertBefore(telegramLink({ turnOn: function () { return saveSettings({ enabled: true }); }, saved: function () { return saved; } }), panel);
2213
+
2214
+ /**
2215
+ * Telegram has no screen that shows a chat ID, so we never ask for one up front. Once the
2216
+ * token checks out, the person picks who gets alerts, follows two or three taps, and this
2217
+ * page watches the bot until their chat turns up, then chooses it.
2218
+ */
2219
+ function telegramGuide() {
2220
+ var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }), start: function () { if (saved.configured) check(); } };
2221
+ var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
2222
+ var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
2223
+ var wait = el('div', { class: 'wait', role: 'status' });
2224
+ var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
2225
+ var chosen = el('p', { class: 'ok-msg chosen-line' });
2226
+ var manual = el('details', { class: 'where', open: !!saved.chat_id }, [
2227
+ el('summary', { text: 'Enter a chat ID' }),
2228
+ el('label', {}, ['Chat ID or channel username', address]),
2229
+ ]);
2230
+ var tabs = el('div', { class: 'seg', role: 'tablist', 'aria-label': 'Who gets alerts' });
2231
+ var how = el('ol', { class: 'guide' });
2232
+ var again = el('button', { class: 'btn', type: 'button', text: 'Look again', onclick: function () { watch(); } });
2233
+
2234
+ function link(href, text) { return el('a', { class: 'btn', href: href, target: '_blank', rel: 'noopener noreferrer', text: text }); }
2235
+ function drawHow() {
2236
+ var at = '@' + bot.username, url = 'https://t.me/' + encodeURIComponent(bot.username);
2237
+ how.textContent = '';
2238
+ (kind === 'private' ? [
2239
+ [link(url, 'Open ' + at + ' in Telegram ↗')],
2240
+ ['Tap ', el('b', { text: 'Start' }), ' (or send “hi”). This page finds the chat.'],
2241
+ ] : kind === 'group' ? [
2242
+ [link(url + '?startgroup=heresay', 'Add ' + at + ' to a group ↗')],
2243
+ ['Pick the group. This page finds it. Not found? Send ', el('code', { text: '/start' + at }), ' in the group.'],
2244
+ ] : [
2245
+ ['Channel → ', el('b', { text: 'Administrators' }), ' → ', el('b', { text: 'Add Admin' }), ' → ', el('b', { text: at }), '.'],
2246
+ ['Post anything in the channel. This page finds it.'],
2247
+ ]).forEach(function (kids) { how.appendChild(el('li', {}, kids)); });
2248
+ }
2249
+ function drawTabs() {
2250
+ tabs.textContent = '';
2251
+ [['private', 'Just me'], ['group', 'A group'], ['channel', 'A channel']].forEach(function (t) {
2252
+ tabs.appendChild(el('button', { type: 'button', role: 'tab', 'aria-selected': String(kind === t[0]), text: t[1], onclick: function () {
2253
+ kind = t[0]; drawTabs(); drawHow(); drawChats(); watch();
2254
+ } }));
2255
+ });
2256
+ }
2257
+ function sameKind(c) { return kind === 'group' ? c.kind === 'group' || c.kind === 'supergroup' : c.kind === kind; }
2258
+ function pick(c) {
2259
+ address.value = c.id;
2260
+ enabled.checked = true;
2261
+ form.dispatchEvent(new Event('input'));
2262
+ stop();
2263
+ drawChats();
2264
+ feedback('Chat chosen. Save to start sending alerts there.');
2265
+ }
2266
+ function drawChats() {
2267
+ list.textContent = '';
2268
+ var hit = chats.filter(function (c) { return c.id === address.value; })[0];
2269
+ chosen.hidden = !address.value;
2270
+ chosen.textContent = hit ? '✓ Alerts will go to ' + hit.title + ' (' + KIND[hit.kind].toLowerCase() + ').'
2271
+ : address.value ? '✓ Alerts go to chat ' + address.value + '. Pick another below to change it.' : '';
2272
+ chats.forEach(function (c) {
2273
+ var radio = el('input', { type: 'radio', name: 'telegram_chat', value: c.id, checked: address.value === c.id });
2274
+ radio.onchange = function () { pick(c); };
2275
+ list.appendChild(el('label', { class: 'chat-choice' }, [radio, el('span', {}, [el('b', { text: c.title }), el('span', { class: 'mute', text: KIND[c.kind] })])]));
2276
+ });
2277
+ list.hidden = !chats.length;
2278
+ }
2279
+ function drawWait(state) {
2280
+ wait.textContent = '';
2281
+ wait.className = 'wait' + (state === 'idle' ? ' ok idle' : '');
2282
+ if (state === 'waiting') wait.appendChild(document.createTextNode('Waiting for ' + (kind === 'private' ? 'your message to' : kind === 'group' ? 'a group with' : 'a channel with') + ' @' + bot.username + '…'));
2283
+ else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet.')); wait.appendChild(again); }
2284
+ wait.hidden = state === 'none';
2285
+ }
2286
+ function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
2287
+ function watch() {
2288
+ clearTimeout(timer);
2289
+ until = Date.now() + 5 * 60 * 1000;
2290
+ drawWait('waiting');
2291
+ poll();
2292
+ }
2293
+ function poll() {
2294
+ if (!form.isConnected) return;
2295
+ lookup(true).then(function () {
2296
+ var match = chats.filter(sameKind)[0];
2297
+ if (match && !address.value) return pick(match); // never replace a chat they already chose
2298
+ if (match) return stop();
2299
+ if (Date.now() > until) return stop();
2300
+ timer = setTimeout(poll, 6000);
2301
+ }).catch(stop);
2302
+ }
2303
+ function lookup(quiet) {
2304
+ return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
2305
+ var fresh = !bot || bot.username !== b.bot.username;
2306
+ bot = b.bot; chats = b.chats; connected = !!b.connected;
2307
+ g.botLine.textContent = '';
2308
+ g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
2309
+ if (fresh) { g.step2.textContent = ''; drawTabs(); drawHow(); [tabs, how, wait, list, chosen, manual].forEach(function (n) { g.step2.appendChild(n); }); }
2310
+ drawChats();
2311
+ if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
2312
+ }).catch(function (x) {
2313
+ if (quiet && bot) return;
2314
+ g.botLine.textContent = '';
2315
+ g.botLine.appendChild(el('p', { class: 'err', role: 'alert', text: x.message }));
2316
+ throw x;
2317
+ });
2318
+ }
2319
+ function check() {
2320
+ clearTimeout(checking);
2321
+ checking = setTimeout(function () {
2322
+ lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
2323
+ }, 400);
2324
+ }
2325
+ g.step2.appendChild(el('p', { class: 'hint', text: 'Paste the bot token first.' }));
2326
+ g.step2.appendChild(manual);
2327
+ token.addEventListener('input', function () { if (/^\d+:[A-Za-z0-9_-]{20,}$/.test(token.value.trim())) check(); });
2328
+ return g;
2329
+ }
2330
+
2331
+ function draw() {
2332
+ head.textContent = '';
2333
+ head.appendChild(el('h2', { text: title }));
2334
+ head.appendChild(statePill(saved));
2335
+ head.appendChild(el('span', { class: 'spacer' }));
2336
+ if (saved.configured) head.appendChild(sw);
2337
+ sw.checked = enabled.checked = !!saved.enabled;
2338
+ tokenHint.textContent = saved.configured ? 'A token is saved. Paste a new one to replace it.' : 'Kept on the server, never shown here.';
2339
+ token.placeholder = saved.configured ? 'Leave blank to keep it' : 'Paste your token';
2340
+ test.hidden = !saved.configured; test.disabled = dirty || !saved.enabled;
2341
+ remove.disabled = !saved.configured; photo.disabled = !saved.configured;
2342
+ more.hidden = !saved.configured;
2343
+ edit.textContent = opened ? 'Close' : saved.configured ? 'Edit' : 'Set up';
2344
+ edit.classList.toggle('primary', !saved.configured && !opened);
2345
+ edit.setAttribute('aria-expanded', String(opened));
2346
+ panel.hidden = !opened;
2347
+ actions.querySelector('.grow').textContent = saved.configured && !opened ? (saved.enabled ? (telegram ? 'Alerts go to your chat.' : 'Alerts go to your channel.') : 'Paused. Flip the switch to resume.') : (saved.configured ? '' : 'Not set up.');
2348
+ }
2349
+ function busy(on) {
2350
+ box.querySelectorAll('input, button').forEach(function (control) { control.disabled = on; });
2351
+ if (!on) draw();
2352
+ }
2353
+ function feedback(text, bad) { message.className = bad ? 'err' : 'ok-msg'; message.textContent = text; }
2354
+ /** A save with the fields that matter here; a blank token means keep the saved one. */
2355
+ function saveSettings(patch) {
2356
+ var body = {}; body[provider] = Object.assign({ enabled: enabled.checked, token: '' }, patch);
2357
+ if (body[provider][addrKey] === undefined) body[provider][addrKey] = saved[addrKey] || '';
2358
+ return api('PATCH', '/notifications', body).then(function (result) { saved = result.notifications[provider]; return result; });
2359
+ }
2360
+ edit.onclick = function () { opened = !opened; if (opened && telegram && !tg.started) { tg.started = true; tg.start(); } draw(); };
2361
+ sw.onchange = function () {
2362
+ var on = sw.checked;
2363
+ busy(true);
2364
+ saveSettings({ enabled: on }).then(function () { enabled.checked = on; toast(title + (on ? ' alerts are on.' : ' alerts are paused.')); })
2365
+ .catch(function (x) { sw.checked = !on; toast(x.message, null, true); }).finally(function () { busy(false); });
2366
+ };
2367
+ form.oninput = function () { dirty = true; test.disabled = true; feedback('Save, then send a test.'); };
2368
+ form.onsubmit = function (e) {
2369
+ e.preventDefault();
2370
+ var patch = { enabled: true, token: token.value.trim() };
2371
+ patch[addrKey] = address.value.trim();
2372
+ busy(true); feedback('Saving…');
2373
+ var body = {}; body[provider] = patch;
2374
+ api('PATCH', '/notifications', body).then(function (result) {
2375
+ saved = result.notifications[provider]; dirty = false; token.value = ''; enabled.checked = true;
2376
+ feedback('Saved. Send a test to check it.');
2377
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2378
+ };
2379
+ test.onclick = function () {
2380
+ busy(true);
2381
+ api('POST', '/notifications/test', { provider: provider }).then(function () {
2382
+ toast('Test sent. Check ' + title + '.'); feedback('Test sent. Check ' + title + '.');
2383
+ }).catch(function (x) { toast(x.message, null, true); feedback(x.message, true); }).finally(function () { busy(false); });
2384
+ };
2385
+ photo.onclick = function () {
2386
+ busy(true); photo.textContent = 'Setting the picture…';
2387
+ api('POST', '/notifications/telegram/photo', {}).then(function () {
2388
+ toast('The bot now uses the Heresay logo. Telegram may take a moment to show it.');
2389
+ }).catch(function (x) { toast(x.message, null, true); }).finally(function () {
2390
+ photo.textContent = 'Use the Heresay logo as the bot’s picture'; busy(false);
2391
+ });
2392
+ };
2393
+ remove.onclick = function () {
2394
+ var patch = { enabled: false, token: null }; patch[addrKey] = '';
2395
+ var body = {}; body[provider] = patch;
2396
+ busy(true); feedback('Disconnecting…');
2397
+ api('PATCH', '/notifications', body).then(function (result) {
2398
+ saved = result.notifications[provider]; dirty = false; enabled.checked = false; token.value = ''; address.value = '';
2399
+ opened = false; toast(title + ' disconnected.');
2400
+ }).catch(function (x) { feedback(x.message, true); }).finally(function () { busy(false); });
2401
+ };
2402
+ draw();
2403
+ return box;
2404
+ }
2405
+
2305
2406
  /**
2306
2407
  * Tapping Accept or Decline in Telegram only counts for someone who linked their Telegram to their
2307
- * own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only.
2408
+ * own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only. A row inside
2409
+ * the Telegram module for owners, a module of its own for everyone else. `turnOn` (owners): save Telegram again,
2410
+ * which puts the buttons on the bot.
2308
2411
  */
2309
- function telegramActions(host) {
2310
- var body = el('div', {}, [loading()]);
2311
- host.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'Act from Telegram' }), body]));
2412
+ function telegramLink(opts) {
2413
+ var body = el('div', { class: 'module-row link-row' }, [loading()]);
2312
2414
  draw();
2313
2415
  function draw() {
2314
2416
  api('GET', '/telegram/link').then(function (b) {
2315
2417
  body.textContent = '';
2418
+ var msg = el('p', { role: 'status', class: 'grow-line' }), shown = el('div', { class: 'link-code' });
2419
+ var line = el('span', { class: 'grow' });
2420
+ body.appendChild(line);
2316
2421
  if (!b.connected) {
2317
- body.appendChild(el('p', { class: 'hint', text: 'Not connected. Once an owner connects a Telegram bot above and this Heresay has a public https address, new-report alerts get Accept and Decline buttons and you can use them after linking your Telegram here.' }));
2422
+ var s = opts.saved && opts.saved();
2423
+ line.textContent = 'Accept and decline buttons: off.';
2424
+ if (opts.turnOn && s && s.configured && s.enabled) {
2425
+ var on = el('button', { class: 'btn primary', type: 'button', text: 'Turn on' });
2426
+ on.onclick = function () {
2427
+ var done = busyButton(on, 'Turning on…');
2428
+ opts.turnOn().then(function () { draw(); }).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
2429
+ };
2430
+ body.appendChild(on);
2431
+ } else if (!opts.turnOn) line.textContent = 'Accept and decline buttons appear once an owner connects Telegram.';
2432
+ body.appendChild(msg);
2318
2433
  return;
2319
2434
  }
2320
- var msg = el('p', { role: 'status' }), shown = el('div', {});
2321
- var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'Make a new code' : 'Link my Telegram' });
2435
+ line.textContent = b.linked ? '✓ You can accept and decline from Telegram.' : 'Accept and decline from Telegram.';
2436
+ line.className = 'grow' + (b.linked ? ' ok-msg' : '');
2437
+ var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'New code' : 'Link my Telegram' });
2322
2438
  make.onclick = function () {
2323
2439
  var done = busyButton(make, 'Making a code…');
2324
2440
  api('POST', '/telegram/link-code', {}).then(function (c) {
2325
2441
  var at = c.bot_username ? '@' + c.bot_username : 'your Heresay bot';
2326
2442
  shown.textContent = '';
2327
2443
  shown.appendChild(codeBlock('/start ' + c.code));
2328
- shown.appendChild(el('p', {}, ['Send ', el('code', { text: '/start ' + c.code }), ' to ' + at + ', in a private chat or in the alerts group. This code works once and expires ',
2329
- el('b', { text: 'at ' + new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
2330
- if (c.bot_username) shown.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(c.bot_username) + '?start=' + encodeURIComponent(c.code), target: '_blank', rel: 'noopener noreferrer', text: 'Open ' + at + ' in Telegram ↗' }));
2444
+ shown.appendChild(el('p', {}, ['Send it to ' + at + '. Works once, until ',
2445
+ el('b', { text: new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
2446
+ if (c.bot_username) shown.appendChild(el('a', { class: 'btn', href: 'https://t.me/' + encodeURIComponent(c.bot_username) + '?start=' + encodeURIComponent(c.code), target: '_blank', rel: 'noopener noreferrer', text: 'Open ' + at + ' ↗' }));
2331
2447
  msg.textContent = '';
2332
2448
  }).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; }).finally(done);
2333
2449
  };
2334
- var kids = [
2335
- el('p', { class: b.linked ? 'ok-msg' : 'hint', text: b.linked
2336
- ? '✓ Your Telegram is linked. You can accept or decline reports from the alerts. Decline asks you for the reason, which the reporter reads.'
2337
- : 'Link your Telegram to accept or decline reports from the alerts. Only linked team members can; anyone else’s tap is refused.' }),
2338
- el('div', { class: 'row' }, [make]),
2339
- ];
2450
+ body.appendChild(make);
2340
2451
  if (b.linked) {
2341
2452
  var unlink = el('button', { class: 'btn ghost', type: 'button', text: 'Unlink' });
2342
2453
  unlink.onclick = function () {
@@ -2344,12 +2455,12 @@
2344
2455
  api('DELETE', '/telegram/link').then(function () { toast('Your Telegram is unlinked.'); draw(); })
2345
2456
  .catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
2346
2457
  };
2347
- kids[1].appendChild(unlink);
2458
+ body.appendChild(unlink);
2348
2459
  }
2349
- kids.push(shown, msg);
2350
- kids.forEach(function (k) { body.appendChild(k); });
2460
+ body.appendChild(msg); body.appendChild(shown);
2351
2461
  }).catch(function (x) { body.textContent = ''; body.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); });
2352
2462
  }
2463
+ return body;
2353
2464
  }
2354
2465
 
2355
2466
  // ---- team ------------------------------------------------------------------------------
@@ -99,6 +99,15 @@ h3 { font-size:15px; margin:0 0 14px; font-weight:700; }
99
99
  .list-heading { display:flex; align-items:baseline; justify-content:space-between; gap:12px; padding:18px 24px; font-size:12px; }
100
100
  .list-heading b { font-size:13px; }
101
101
  .list-heading > span { font-size:10px; color:var(--mute); }
102
+ .report-row { position:relative; }
103
+ .report-row > .pick { position:absolute; left:0; top:0; bottom:0; width:42px; display:flex; align-items:center; justify-content:center; z-index:1; cursor:pointer; }
104
+ .report-list.picking .report-preview { padding-left:46px; }
105
+ .bulk-bar { display:flex; align-items:center; gap:10px; flex-wrap:wrap; padding:8px 24px 12px; border-bottom:1px solid var(--line); font-size:12px; }
106
+ .bulk-bar[hidden] { display:none; }
107
+ .bulk-bar .pick-all { display:flex; align-items:center; gap:6px; font-weight:500; cursor:pointer; }
108
+ .bulk-bar .count { color:var(--mute); }
109
+ .bulk-bar .spacer { flex:1; }
110
+ .bulk-bar .confirm-q { font-weight:500; }
102
111
  .report-preview { --type:var(--mute); display:grid; grid-template-columns:23px minmax(0,1fr) auto; gap:12px; width:100%; text-align:left; border:0; border-bottom:1px solid var(--line); background:var(--bg); font:inherit; padding:20px 22px 20px 24px; cursor:pointer; position:relative; color:var(--fg); }
103
112
  .report-preview:hover { background:var(--rowhover); }
104
113
  .report-preview[aria-current=true] { background:var(--rowsel); }