create-heresay 0.2.39 → 0.2.41

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.39",
3
+ "version": "0.2.41",
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.39
1
+ 0.2.41
@@ -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();
@@ -6,6 +6,7 @@ import { mcp } from './chat.js';
6
6
  import { withdraw } from './withdraw.js';
7
7
  import { alsoReported, duplicatesOf, follow, merge, parseFixRef, stampFix, unmerge } from './duplicates.js';
8
8
  import { notificationSettings, notify } from './notifications.js';
9
+ import { linkRoutes, telegramWebhook } from './telegram.js';
9
10
  import { LIMITS, PLATFORMS, REPORT_ORDER, REPORT_TYPES, isFramework, isPlatform, isReportType, isSignIn, toReporterView, } from './types.js';
10
11
  const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?Z$/;
11
12
  /**
@@ -192,6 +193,9 @@ async function route(req, deps) {
192
193
  return withdrawMine(req, deps);
193
194
  if (p[0] === 'reports' && req.method === 'OPTIONS')
194
195
  return preflight(req);
196
+ // Telegram calls this itself, from its servers: no Origin, no sign-in (ADR 0016).
197
+ if (p[0] === 'telegram' && p[1] === 'webhook' && p.length === 3 && req.method === 'POST')
198
+ return telegramWebhook(p[2], req, deps, triage);
195
199
  // Chat apps (ChatGPT and other MCP clients): OAuth with the member's own sign-in, then MCP.
196
200
  if (p[0] === 'mcp' && p.length === 1)
197
201
  return mcp(req, deps);
@@ -239,6 +243,8 @@ async function route(req, deps) {
239
243
  return json(403, { error: 'Only an owner can manage notifications.' });
240
244
  return notificationSettings(p, req, deps, parseBody(req.body));
241
245
  }
246
+ if (p[0] === 'telegram' && p[1] === 'link-code' || p[0] === 'telegram' && p[1] === 'link')
247
+ return linkRoutes(p, member, req, deps);
242
248
  if (p[0] === 'agent-tokens')
243
249
  return tokens(p, member, req, deps, parseBody(req.body));
244
250
  // The dashboard's "Allow this chat app?" page, and the chat apps a member has connected.
@@ -645,7 +651,7 @@ function transitionRes(t) {
645
651
  // Two tabs triaging the same report: the second is told what the first did.
646
652
  return json(409, { error: `this report is already ${t.status}`, status: t.status });
647
653
  }
648
- async function triage(project, report_id, action, uid, req, deps) {
654
+ export async function triage(project, report_id, action, uid, req, deps) {
649
655
  const body = parseBody(req.body);
650
656
  const at = new Date(deps.now()).toISOString();
651
657
  let t;
@@ -1,4 +1,5 @@
1
1
  import { BOT_LOGO_JPEG_BASE64 } from './bot-logo.js';
2
+ import { reportKeyboard, syncWebhook } from './telegram.js';
2
3
  export const NOTIFICATION_EVENTS = ['new_report', 'accepted', 'fixed', 'handoff'];
3
4
  export class TelegramLookupError extends Error {
4
5
  }
@@ -17,6 +18,7 @@ export function notificationView(settings) {
17
18
  cliq: { enabled: settings.cliq.enabled, configured: !!settings.cliq.token, endpoint: settings.cliq.endpoint },
18
19
  };
19
20
  }
21
+ const telegramChanged = (a, b) => (a?.token ?? null) !== b.token || (a?.enabled ?? false) !== b.enabled;
20
22
  class SettingsError extends Error {
21
23
  }
22
24
  const TELEGRAM_TOKEN = /^\d+:[A-Za-z0-9_-]{20,}$/;
@@ -106,7 +108,8 @@ export async function notificationSettings(p, req, deps, body) {
106
108
  }
107
109
  if (p.length === 1 && req.method === 'PATCH') {
108
110
  try {
109
- const before = (await deps.store.getInstance())?.notifications?.telegram.token ?? null;
111
+ const beforeTelegram = (await deps.store.getInstance())?.notifications?.telegram;
112
+ const before = beforeTelegram?.token ?? null;
110
113
  const instance = await deps.store.updateInstance((cur) => ({
111
114
  ...cur, notifications: patchNotifications(cur.notifications ?? defaultNotifications(), body),
112
115
  }));
@@ -121,7 +124,10 @@ export async function notificationSettings(p, req, deps, body) {
121
124
  deps.log('api.telegram_photo', { ok: false });
122
125
  } // never log the error: it may carry the token URL
123
126
  }
124
- return json(200, { notifications: notificationView(instance.notifications) });
127
+ // Buttons in Telegram need our webhook on the bot (or off it). Never fatal either.
128
+ if (telegramChanged(beforeTelegram, instance.notifications.telegram))
129
+ await syncWebhook(beforeTelegram, req, deps);
130
+ return json(200, { notifications: notificationView((await deps.store.getInstance()).notifications) });
125
131
  }
126
132
  catch (error) {
127
133
  // Validation messages are ours; never expose backend exceptions or credentials.
@@ -143,6 +149,19 @@ export async function notificationSettings(p, req, deps, body) {
143
149
  if (!await deps.store.hit(`notification-lookup:telegram:${start}`, 30, start + 60_000)) {
144
150
  return json(429, { error: 'Wait a minute before looking again.' });
145
151
  }
152
+ // Telegram refuses getUpdates once a webhook is set, and ours is. Say so instead of failing.
153
+ const saved = (await deps.store.getInstance()).notifications?.telegram;
154
+ if (saved?.token === token && saved.webhook_url && deps.telegramApi) {
155
+ const me = await deps.telegramApi(token, 'getMe', {});
156
+ const bot = me.result;
157
+ if (me.ok) {
158
+ return json(200, {
159
+ bot: { username: typeof bot?.username === 'string' ? bot.username : '', name: typeof bot?.first_name === 'string' ? bot.first_name.slice(0, 120) : '' },
160
+ chats: [], connected: true,
161
+ note: 'Telegram is connected; to pick a different chat, enter its chat ID.',
162
+ });
163
+ }
164
+ }
146
165
  if (!deps.telegramLookup)
147
166
  return json(503, { error: 'Telegram lookup is unavailable.' });
148
167
  try {
@@ -195,6 +214,7 @@ export async function notificationSettings(p, req, deps, body) {
195
214
  }
196
215
  return json(404, { error: 'not found' });
197
216
  }
217
+ const actionsReady = (tg) => !!(tg.webhook_secret && tg.webhook_url);
198
218
  /** Metadata only: open reports and reporter details must never flow into an integration. */
199
219
  export async function notify(event, project, reportId, deps) {
200
220
  try {
@@ -212,7 +232,9 @@ export async function notify(event, project, reportId, deps) {
212
232
  if (!settings[provider].enabled)
213
233
  return;
214
234
  try {
215
- await deps.sendNotification(provider, settings[provider], text);
235
+ const markup = provider === 'telegram' && event === 'new_report' && actionsReady(settings.telegram)
236
+ ? reportKeyboard(project.id, reportId) : null;
237
+ await deps.sendNotification(provider, settings[provider], text, markup ? { telegram_markup: markup } : undefined);
216
238
  deps.log('api.notification_sent', { provider, notification_event: event, project_id: project.id, report_id: reportId });
217
239
  }
218
240
  catch {
@@ -228,13 +250,13 @@ export async function notify(event, project, reportId, deps) {
228
250
  }
229
251
  /** Shared HTTP transport; a backend adapter supplies this to the portable core. */
230
252
  export function notificationSender(http = fetch) {
231
- return async (provider, destination, text) => {
253
+ return async (provider, destination, text, extra) => {
232
254
  let url, body;
233
255
  if (!destination.token)
234
256
  throw new Error('Notification token missing.');
235
257
  if (provider === 'telegram' && 'chat_id' in destination) {
236
258
  url = `https://api.telegram.org/bot${destination.token}/sendMessage`;
237
- body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true } };
259
+ body = { chat_id: destination.chat_id, text, link_preview_options: { is_disabled: true }, ...(extra?.telegram_markup ? { reply_markup: extra.telegram_markup } : {}) };
238
260
  }
239
261
  else if (provider === 'cliq' && 'endpoint' in destination && validCliqEndpoint(destination.endpoint)) {
240
262
  const u = new URL(destination.endpoint);
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Acting on notifications from Telegram (ADR 0016). Telegram calls the webhook; a tap only counts
3
+ * if the Telegram user was linked, with a one-time code, to someone who is still on the team.
4
+ * Accept and decline go through the same `triage` the dashboard uses, so nothing is duplicated:
5
+ * a report still reaches an agent only through a person's accept, and declining still needs a reason.
6
+ * Everything here is plain text (no parse_mode): reporter text is untrusted.
7
+ */
8
+ import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
9
+ import { baseUrl } from './oauth.js';
10
+ import { LIMITS } from './types.js';
11
+ export function telegramApi(http = fetch) {
12
+ return async (token, method, body) => {
13
+ try {
14
+ const response = await http(`https://api.telegram.org/bot${token}/${method}`, {
15
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
16
+ signal: AbortSignal.timeout(5000), redirect: 'error',
17
+ });
18
+ const result = await response.json().catch(() => ({}));
19
+ return { ok: response.ok && result.ok === true, result: result.result };
20
+ }
21
+ catch {
22
+ return { ok: false };
23
+ } // the error may carry the token URL
24
+ };
25
+ }
26
+ const LINK_TTL_MS = 10 * 60_000;
27
+ const DECLINE_TTL_MS = 10 * 60_000;
28
+ const TEXT_MAX = 4096;
29
+ const CODE_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // no 0/O, 1/I
30
+ const sha = (s) => createHash('sha256').update(s).digest('hex');
31
+ const json = (status, body) => ({ status, body, headers: { 'cache-control': 'no-store' } });
32
+ // ---- the keyboard on a "new report" notification -------------------------------------------
33
+ /** a = accept, d = decline, t = full text; then the project and report ids. Null if it would pass 64 bytes. */
34
+ export function reportKeyboard(project_id, report_id) {
35
+ const data = (a) => `${a}|${project_id}|${report_id}`;
36
+ if (Buffer.byteLength(data('a')) > 64)
37
+ return null;
38
+ return { inline_keyboard: [[
39
+ { text: 'Accept', callback_data: data('a') },
40
+ { text: 'Decline', callback_data: data('d') },
41
+ { text: 'Show full text', callback_data: data('t') },
42
+ ]] };
43
+ }
44
+ // ---- keeping Telegram's webhook in step with the saved bot ----------------------------------
45
+ /** The secret in the webhook URL. A second value, derived from it, goes in Telegram's header. */
46
+ export const headerSecret = (secret) => createHash('sha256').update('heresay-telegram-header:' + secret).digest('base64url');
47
+ export const actionsConnected = (tg) => !!(tg?.enabled && tg.token && tg.webhook_secret && tg.webhook_url);
48
+ /**
49
+ * After notification settings are saved: point the bot's webhook at us, or take it away. Skipped
50
+ * silently when the public address isn't https (the emulator). Never fails the save and never logs
51
+ * the token or the secret.
52
+ */
53
+ export async function syncWebhook(before, req, deps) {
54
+ try {
55
+ const api = deps.telegramApi;
56
+ const tg = (await deps.store.getInstance())?.notifications?.telegram;
57
+ if (!api || !tg)
58
+ return;
59
+ const old = before?.token ?? null;
60
+ const want = tg.enabled && !!tg.token;
61
+ const setUrl = (url) => deps.store.updateInstance((cur) => {
62
+ const n = structuredClone(cur.notifications);
63
+ n.telegram.webhook_url = url;
64
+ return { ...cur, notifications: n };
65
+ });
66
+ if (old && (!want || old !== tg.token)) {
67
+ const r = await api(old, 'deleteWebhook', {});
68
+ deps.log('api.telegram_webhook', { action: 'delete', ok: r.ok });
69
+ }
70
+ if (!want) {
71
+ if (tg.webhook_url)
72
+ await setUrl(null);
73
+ return;
74
+ }
75
+ const base = baseUrl(req, deps);
76
+ if (!base.startsWith('https://'))
77
+ return;
78
+ let secret = tg.webhook_secret;
79
+ if (!secret) {
80
+ secret = randomBytes(24).toString('base64url');
81
+ const fresh = secret;
82
+ const inst = await deps.store.updateInstance((cur) => {
83
+ const n = structuredClone(cur.notifications);
84
+ n.telegram.webhook_secret = n.telegram.webhook_secret ?? fresh; // once per instance
85
+ return { ...cur, notifications: n };
86
+ });
87
+ secret = inst.notifications.telegram.webhook_secret;
88
+ }
89
+ const url = `${base}/v1/telegram/webhook/${secret}`;
90
+ if (tg.webhook_url === url && old === tg.token)
91
+ return;
92
+ const r = await api(tg.token, 'setWebhook', {
93
+ url, secret_token: headerSecret(secret), allowed_updates: ['message', 'callback_query'],
94
+ });
95
+ deps.log('api.telegram_webhook', { action: 'set', ok: r.ok });
96
+ if (r.ok)
97
+ await setUrl(url);
98
+ }
99
+ catch {
100
+ deps.log('api.telegram_webhook', { action: 'sync', ok: false });
101
+ }
102
+ }
103
+ // ---- linking: dashboard side ----------------------------------------------------------------
104
+ const normEmail = (e) => e.trim().toLowerCase();
105
+ const normCode = (c) => c.toUpperCase().replace(/[^A-Z0-9]/g, '');
106
+ const codeId = (c) => sha('heresay-telegram-link:' + normCode(c));
107
+ async function minute(deps, bucket, limit) {
108
+ const start = Math.floor(deps.now() / 60_000) * 60_000;
109
+ return deps.store.hit(`${bucket}:${start}`, limit, start + 60_000);
110
+ }
111
+ /** Member-level (any signed-in member): link status, a one-time code, and unlink. */
112
+ export async function linkRoutes(p, me, req, deps) {
113
+ const tg = (await deps.store.getInstance())?.notifications?.telegram;
114
+ const mine = (l) => Object.values(l ?? {}).some((e) => normEmail(e) === normEmail(me.email));
115
+ if (p[1] === 'link' && p.length === 2 && req.method === 'GET') {
116
+ return json(200, { connected: actionsConnected(tg), linked: mine(tg?.links) });
117
+ }
118
+ if (p[1] === 'link-code' && p.length === 2 && req.method === 'POST') {
119
+ if (!actionsConnected(tg)) {
120
+ return json(409, { error: 'Telegram isn’t connected for actions yet. An owner connects a bot under Notifications, on this Heresay’s public https address.' });
121
+ }
122
+ const start = Math.floor(deps.now() / 600_000) * 600_000;
123
+ if (!await deps.store.hit(`tg-link-code:${normEmail(me.email)}:${start}`, 5, start + 600_000)) {
124
+ return json(429, { error: 'Wait a few minutes before making another code.' });
125
+ }
126
+ for (const old of await deps.store.listAuth('link')) {
127
+ if (old.data.email === normEmail(me.email))
128
+ await deps.store.deleteAuth('link', old.id);
129
+ }
130
+ let code = '';
131
+ for (let i = 0; i < 8; i++)
132
+ code += CODE_ALPHABET[randomInt(CODE_ALPHABET.length)];
133
+ const expires = new Date(deps.now() + LINK_TTL_MS).toISOString();
134
+ await deps.store.putAuth({ kind: 'link', id: codeId(code), data: { email: normEmail(me.email) }, expires_at: expires });
135
+ let bot_username = null;
136
+ const bot = await deps.telegramApi?.(tg.token, 'getMe', {});
137
+ const name = bot?.result?.username;
138
+ if (bot?.ok && typeof name === 'string')
139
+ bot_username = name;
140
+ return json(200, { code, expires_at: expires, bot_username });
141
+ }
142
+ if (p[1] === 'link' && p.length === 2 && req.method === 'DELETE') {
143
+ await deps.store.updateInstance((cur) => {
144
+ const n = cur.notifications;
145
+ if (!n?.telegram.links)
146
+ return cur;
147
+ const next = structuredClone(n);
148
+ for (const [id, e] of Object.entries(next.telegram.links))
149
+ if (normEmail(e) === normEmail(me.email))
150
+ delete next.telegram.links[id];
151
+ return { ...cur, notifications: next };
152
+ });
153
+ for (const old of await deps.store.listAuth('link')) {
154
+ if (old.data.email === normEmail(me.email))
155
+ await deps.store.deleteAuth('link', old.id);
156
+ }
157
+ return json(200, { ok: true });
158
+ }
159
+ return json(404, { error: 'not found' });
160
+ }
161
+ const same = (a, b) => {
162
+ const x = createHash('sha256').update(a).digest(), y = createHash('sha256').update(b).digest();
163
+ return timingSafeEqual(x, y);
164
+ };
165
+ const label = (s) => ({ accepted: 'accepted', declined: 'declined', fixed: 'fixed', withdrawn: 'withdrawn', open: 'open' }[s] ?? s);
166
+ /** Telegram counts UTF-16 units; never leave half a character at the cut. */
167
+ export function capText(s, max = TEXT_MAX) {
168
+ if (s.length <= max)
169
+ return s;
170
+ let cut = s.slice(0, max - 1);
171
+ if (/[\ud800-\udbff]$/.test(cut))
172
+ cut = cut.slice(0, -1);
173
+ return cut + '…';
174
+ }
175
+ export async function telegramWebhook(secret, req, deps, triage) {
176
+ const notFound = () => ({ status: 404, body: null });
177
+ // Before anything else, so a flood of guesses is cheap. Telegram's own servers are few; generous.
178
+ if (!await minute(deps, `tg-hook-ip:${sha(req.ip)}`, 1200))
179
+ return { status: 429, body: null };
180
+ const instance = await deps.store.getInstance();
181
+ const tg = instance?.notifications?.telegram;
182
+ if (!tg?.enabled || !tg.token || !tg.webhook_secret)
183
+ return notFound();
184
+ // Both, always evaluated, in constant time.
185
+ const pathOk = same(secret, tg.webhook_secret);
186
+ const headerOk = same(req.headers['x-telegram-bot-api-secret-token'] ?? '', headerSecret(tg.webhook_secret));
187
+ if (!(pathOk && headerOk))
188
+ return notFound();
189
+ try {
190
+ const body = req.body instanceof Uint8Array ? JSON.parse(Buffer.from(req.body).toString('utf8')) : req.body;
191
+ if (body && typeof body === 'object')
192
+ await handleUpdate(body, instance.members, tg, deps, triage);
193
+ }
194
+ catch {
195
+ deps.log('api.telegram_update', { ok: false }); // never the error: it may carry the token URL
196
+ }
197
+ return { status: 200, body: { ok: true } }; // Telegram retries anything else
198
+ }
199
+ const isConfiguredChat = (chat, tg) => String(chat.id) === tg.chat_id || (!!chat.username && tg.chat_id.toLowerCase() === '@' + chat.username.toLowerCase());
200
+ async function handleUpdate(u, members, tg, deps, triage) {
201
+ const token = tg.token;
202
+ const api = deps.telegramApi;
203
+ if (!api)
204
+ return;
205
+ const msg = u.callback_query?.message ?? u.message;
206
+ const from = u.callback_query?.from ?? u.message?.from;
207
+ if (!msg?.chat || !from || from.is_bot)
208
+ return;
209
+ if (!await minute(deps, `tg-hook-chat:${msg.chat.id}`, 60))
210
+ return;
211
+ const say = (text, extra = {}) => api(token, 'sendMessage', { chat_id: msg.chat.id, text: capText(text), link_preview_options: { is_disabled: true }, ...extra });
212
+ // A person tapping a button.
213
+ if (u.callback_query) {
214
+ const cb = u.callback_query;
215
+ if (!cb.message || !isConfiguredChat(cb.message.chat, tg))
216
+ return; // somewhere we never posted
217
+ const answer = (text, alert = false) => api(token, 'answerCallbackQuery', { callback_query_id: cb.id, ...(text ? { text: text.slice(0, 200), show_alert: alert } : {}) });
218
+ const m = /^([adt])\|([\w-]{1,40})\|([\w-]{1,40})$/.exec(cb.data ?? '');
219
+ if (!m) {
220
+ await answer();
221
+ return;
222
+ }
223
+ const email = actor(members, tg, from.id);
224
+ if (!email) {
225
+ await answer('Link your Telegram first: Heresay dashboard > Notifications', true);
226
+ return;
227
+ }
228
+ const project = await deps.store.getProject(m[2]);
229
+ const report = project ? await deps.store.getReport(project.id, m[3]) : null;
230
+ if (!project || !report) {
231
+ await answer('That report no longer exists.', true);
232
+ return;
233
+ }
234
+ // A decided report: say so, tidy the message, change nothing.
235
+ async function alreadyOrFail(res, pr, id, ans, message) {
236
+ const status = res.body?.status;
237
+ if (res.status === 409 && status) {
238
+ const r = await deps.store.getReport(pr.id, id);
239
+ const verdict = r ? decided(r) : null;
240
+ await ans(verdict ?? `Already ${label(status)}.`, true);
241
+ if (verdict && (status === 'accepted' || status === 'declined'))
242
+ await finish(api, token, message, verdict.replace(/^Already /, '').replace(/^./, (c) => c.toUpperCase()));
243
+ return;
244
+ }
245
+ await ans(res.status === 409 ? 'This report was merged into another. Decide it in the dashboard.' : 'That didn’t work. Try the dashboard.', true);
246
+ }
247
+ if (m[1] === 't') {
248
+ await answer();
249
+ await say(`${report.type} · ${project.name}\n\n${report.text}`, { reply_parameters: { message_id: cb.message.message_id } });
250
+ return;
251
+ }
252
+ if (m[1] === 'a') {
253
+ const res = await triage(project, report.id, 'accept', email, fakeReq(), deps);
254
+ if (res.status === 200) {
255
+ await answer('Accepted');
256
+ await finish(api, token, cb.message, `Accepted by ${email}`);
257
+ return;
258
+ }
259
+ await alreadyOrFail(res, project, report.id, answer, cb.message);
260
+ return;
261
+ }
262
+ // Decline: ask for the reason first; the reporter reads it.
263
+ if (report.status !== 'open') {
264
+ await alreadyOrFail({ status: 409, body: { status: report.status } }, project, report.id, answer, cb.message);
265
+ return;
266
+ }
267
+ await answer('Reply to the next message with your reason.');
268
+ const prompt = await say('Reply with why you’re declining this (the reporter will read it)', {
269
+ reply_parameters: { message_id: cb.message.message_id },
270
+ reply_markup: { force_reply: true, selective: true, input_field_placeholder: 'Why?' },
271
+ });
272
+ const pid = prompt.result?.message_id;
273
+ if (prompt.ok && typeof pid === 'number') {
274
+ await deps.store.putAuth({
275
+ kind: 'decline', id: `${cb.message.chat.id}:${pid}`, expires_at: new Date(deps.now() + DECLINE_TTL_MS).toISOString(),
276
+ data: { user: from.id, project: project.id, report: report.id, message_id: cb.message.message_id, text: cb.message.text ?? '' },
277
+ });
278
+ }
279
+ return;
280
+ }
281
+ // A message: a link code, or the reason for a decline.
282
+ const text = msg.text?.trim() ?? '';
283
+ const cmd = /^\/(?:start|link)(?:@\w+)?(?:\s+(.+))?$/i.exec(text);
284
+ if (cmd) {
285
+ const inPrivate = msg.chat.type === 'private';
286
+ if (!inPrivate && !isConfiguredChat(msg.chat, tg))
287
+ return;
288
+ if (!cmd[1]) {
289
+ if (inPrivate)
290
+ await say('To link your Telegram: in the Heresay dashboard open Notifications, tap “Link my Telegram”, then send me /start and the code.');
291
+ return;
292
+ }
293
+ const start = Math.floor(deps.now() / 3600_000) * 3600_000;
294
+ if (!await deps.store.hit(`tg-link-try:${from.id}:${start}`, 10, start + 3600_000)) {
295
+ await say('Too many tries. Wait an hour, then make a new code.');
296
+ return;
297
+ }
298
+ const rec = await deps.store.takeAuth('link', codeId(cmd[1])); // one use, however many try at once
299
+ const email = rec && rec.expires_at && Date.parse(rec.expires_at) > deps.now() ? String(rec.data.email) : null;
300
+ const member = email ? members.find((x) => normEmail(x.email) === email) : null;
301
+ if (!email || !member) {
302
+ await say('That code didn’t work, or it expired. Make a new one in the Heresay dashboard under Notifications.');
303
+ return;
304
+ }
305
+ await deps.store.updateInstance((cur) => {
306
+ const n = structuredClone(cur.notifications);
307
+ n.telegram.links = { ...(n.telegram.links ?? {}), [String(from.id)]: member.email };
308
+ return { ...cur, notifications: n };
309
+ });
310
+ deps.log('api.telegram_linked', { ok: true });
311
+ await say(`Linked as ${member.email}`);
312
+ return;
313
+ }
314
+ const replyTo = msg.reply_to_message?.message_id;
315
+ if (replyTo === undefined || !isConfiguredChat(msg.chat, tg))
316
+ return;
317
+ const key = `${msg.chat.id}:${replyTo}`;
318
+ const pending = await deps.store.getAuth('decline', key);
319
+ if (!pending || pending.data.user !== from.id)
320
+ return; // someone else's prompt, or not ours
321
+ const reply = (t) => say(t, { reply_parameters: { message_id: msg.message_id } });
322
+ if (!pending.expires_at || Date.parse(pending.expires_at) <= deps.now()) {
323
+ await deps.store.deleteAuth('decline', key);
324
+ await reply('That took too long. Tap Decline on the report again.');
325
+ return;
326
+ }
327
+ const email = actor(members, tg, from.id);
328
+ if (!email) {
329
+ await reply('Link your Telegram first: Heresay dashboard > Notifications');
330
+ return;
331
+ }
332
+ if (!text) {
333
+ await reply('Send the reason as text.');
334
+ return;
335
+ }
336
+ if (text.length > LIMITS.reasonMax) {
337
+ await reply(`That reason is ${text.length} characters; the limit is ${LIMITS.reasonMax}. Send a shorter one.`);
338
+ return;
339
+ }
340
+ const project = await deps.store.getProject(String(pending.data.project));
341
+ if (!project) {
342
+ await deps.store.deleteAuth('decline', key);
343
+ return;
344
+ }
345
+ const res = await triage(project, String(pending.data.report), 'decline', email, fakeReq({ reason: text }), deps);
346
+ const original = { message_id: Number(pending.data.message_id), chat: msg.chat, text: String(pending.data.text ?? '') };
347
+ if (res.status === 200) {
348
+ await deps.store.deleteAuth('decline', key);
349
+ await finish(api, token, original, `Declined by ${email}: ${text}`);
350
+ await reply('Declined. The reporter will see your reason.');
351
+ return;
352
+ }
353
+ if (res.status === 400) {
354
+ await reply('A reason is needed to decline. Send it as a reply.');
355
+ return;
356
+ } // stays pending
357
+ await deps.store.deleteAuth('decline', key);
358
+ const status = res.body?.status;
359
+ const r = await deps.store.getReport(project.id, String(pending.data.report));
360
+ await reply(r && status ? (decided(r) ?? `Already ${label(status)}.`) : 'This report was merged into another. Decide it in the dashboard.');
361
+ }
362
+ /** Telegram user id -> the member they're linked to, only while that person is still on the team. */
363
+ function actor(members, tg, telegramId) {
364
+ const linked = tg.links?.[String(telegramId)];
365
+ return linked ? members.find((m) => normEmail(m.email) === normEmail(linked))?.email ?? null : null;
366
+ }
367
+ /** "Already accepted by x" for a report somebody decided, else null. */
368
+ function decided(r) {
369
+ if (r.status === 'open')
370
+ return null;
371
+ const by = r.triaged_by ? ` by ${r.triaged_by}` : '';
372
+ return `Already ${label(r.status)}${by}${r.status === 'declined' && r.decline_reason ? `: ${r.decline_reason}` : ''}`;
373
+ }
374
+ const fakeReq = (body = {}) => ({ method: 'POST', path: '', query: {}, headers: {}, ip: '', body });
375
+ /** Append the outcome to the notification and take the buttons away. */
376
+ async function finish(api, token, message, line) {
377
+ await api(token, 'editMessageText', {
378
+ chat_id: message.chat.id, message_id: message.message_id,
379
+ text: capText(`${(message.text ?? '').replace(/\n\n(Accepted|Declined) by [\s\S]*$/, '')}\n\n${line}`.trim()),
380
+ link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [] },
381
+ });
382
+ }
383
+ //# sourceMappingURL=telegram.js.map
@@ -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.39';
2
+ export const VERSION = '0.2.41';
3
3
  //# sourceMappingURL=version.js.map
@@ -9,6 +9,7 @@ import { FirestoreStore } from './firestore-store.js';
9
9
  import { handle } from '../../core/handler.js';
10
10
  import { VERSION } from '../../core/version.js';
11
11
  import { notificationSender, telegramLookup, telegramPhoto } from '../../core/notifications.js';
12
+ import { telegramApi } from '../../core/telegram.js';
12
13
  const deps = {
13
14
  store: new FirestoreStore(db),
14
15
  async verifyIdToken(token) {
@@ -27,6 +28,7 @@ const deps = {
27
28
  sendNotification: notificationSender(),
28
29
  telegramLookup: telegramLookup(),
29
30
  telegramPhoto: telegramPhoto(),
31
+ telegramApi: telegramApi(),
30
32
  };
31
33
  function selfOrigins() {
32
34
  const id = process.env.GCLOUD_PROJECT;
@@ -9,7 +9,7 @@
9
9
  "scripts": {
10
10
  "build": "tsc -p tsconfig.json",
11
11
  "typecheck": "tsc -p tsconfig.json --noEmit",
12
- "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js'",
12
+ "test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js' 'lib-test/test/telegram.test.js'",
13
13
  "build:test": "tsc -p tsconfig.test.json"
14
14
  },
15
15
  "dependencies": {
@@ -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;
@@ -2050,6 +2120,7 @@
2050
2120
  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.' }));
2051
2121
  if (me.role !== 'owner') {
2052
2122
  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' })]));
2123
+ telegramActions(view);
2053
2124
  return;
2054
2125
  }
2055
2126
  var content = el('div', {}, [loading()]);
@@ -2085,6 +2156,7 @@
2085
2156
  content.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'When to notify' }), eventsForm]));
2086
2157
  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.' }));
2087
2158
  destination('telegram', 'Telegram', settings.telegram);
2159
+ telegramActions(content);
2088
2160
  destination('cliq', 'Zoho Cliq', settings.cliq);
2089
2161
 
2090
2162
  function destination(provider, title, saved) {
@@ -2129,7 +2201,7 @@
2129
2201
  */
2130
2202
  function telegramGuide() {
2131
2203
  var g = { botLine: el('div', { class: 'bot-line', 'aria-live': 'polite' }), step2: el('div', { class: 'tg-step2' }) };
2132
- var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null;
2204
+ var bot = null, kind = 'private', chats = [], timer = null, until = 0, checking = null, connected = false;
2133
2205
  var KIND = { private: 'Private chat', group: 'Group', supergroup: 'Group', channel: 'Channel' };
2134
2206
  var wait = el('div', { class: 'wait', role: 'status' });
2135
2207
  var list = el('div', { class: 'chat-list', role: 'radiogroup', 'aria-label': 'Send alerts to' });
@@ -2198,7 +2270,7 @@
2198
2270
  else if (state === 'idle') { wait.appendChild(document.createTextNode('Nothing yet. Follow the steps above, then')); wait.appendChild(again); }
2199
2271
  wait.hidden = state === 'none';
2200
2272
  }
2201
- function stop() { clearTimeout(timer); timer = null; if (bot) drawWait(address.value ? 'none' : 'idle'); }
2273
+ function stop() { clearTimeout(timer); timer = null; if (bot && !connected) drawWait(address.value ? 'none' : 'idle'); }
2202
2274
  function watch() {
2203
2275
  clearTimeout(timer);
2204
2276
  until = Date.now() + 5 * 60 * 1000;
@@ -2218,11 +2290,12 @@
2218
2290
  function lookup(quiet) {
2219
2291
  return api('POST', '/notifications/telegram/lookup', { token: token.value.trim() }).then(function (b) {
2220
2292
  var fresh = !bot || bot.username !== b.bot.username;
2221
- bot = b.bot; chats = b.chats;
2293
+ bot = b.bot; chats = b.chats; connected = !!b.connected;
2222
2294
  g.botLine.textContent = '';
2223
2295
  g.botLine.appendChild(el('p', { class: 'ok-msg' }, [el('b', { text: '✓ Token works. ' }), document.createTextNode('Your bot is ' + (bot.name || 'ready') + ' (@' + bot.username + ').')]));
2224
2296
  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); }); }
2225
2297
  drawChats();
2298
+ if (b.note) g.botLine.appendChild(el('p', { class: 'hint', text: b.note }));
2226
2299
  }).catch(function (x) {
2227
2300
  if (quiet && bot) return;
2228
2301
  g.botLine.textContent = '';
@@ -2233,7 +2306,7 @@
2233
2306
  function check() {
2234
2307
  clearTimeout(checking);
2235
2308
  checking = setTimeout(function () {
2236
- lookup().then(function () { if (!address.value) watch(); else stop(); }).catch(function () {});
2309
+ lookup().then(function () { if (!address.value && !connected) watch(); else stop(); }).catch(function () {});
2237
2310
  }, 400);
2238
2311
  }
2239
2312
  g.step2.appendChild(el('p', { class: 'hint', text: 'Paste your bot token above first. Then this step shows exactly what to tap.' }));
@@ -2299,6 +2372,56 @@
2299
2372
  });
2300
2373
  }
2301
2374
 
2375
+ /**
2376
+ * Tapping Accept or Decline in Telegram only counts for someone who linked their Telegram to their
2377
+ * own sign-in: a one-time code, sent to the bot. Any member can do this; it isn't owner-only.
2378
+ */
2379
+ function telegramActions(host) {
2380
+ var body = el('div', {}, [loading()]);
2381
+ host.appendChild(el('section', { class: 'card' }, [el('h2', { text: 'Act from Telegram' }), body]));
2382
+ draw();
2383
+ function draw() {
2384
+ api('GET', '/telegram/link').then(function (b) {
2385
+ body.textContent = '';
2386
+ if (!b.connected) {
2387
+ 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.' }));
2388
+ return;
2389
+ }
2390
+ var msg = el('p', { role: 'status' }), shown = el('div', {});
2391
+ var make = el('button', { class: 'btn' + (b.linked ? '' : ' primary'), type: 'button', text: b.linked ? 'Make a new code' : 'Link my Telegram' });
2392
+ make.onclick = function () {
2393
+ var done = busyButton(make, 'Making a code…');
2394
+ api('POST', '/telegram/link-code', {}).then(function (c) {
2395
+ var at = c.bot_username ? '@' + c.bot_username : 'your Heresay bot';
2396
+ shown.textContent = '';
2397
+ shown.appendChild(codeBlock('/start ' + c.code));
2398
+ 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 ',
2399
+ el('b', { text: 'at ' + new Date(c.expires_at).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' }) }), '.']));
2400
+ 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 ↗' }));
2401
+ msg.textContent = '';
2402
+ }).catch(function (x) { msg.className = 'err'; msg.textContent = x.message; }).finally(done);
2403
+ };
2404
+ var kids = [
2405
+ el('p', { class: b.linked ? 'ok-msg' : 'hint', text: b.linked
2406
+ ? '✓ Your Telegram is linked. You can accept or decline reports from the alerts. Decline asks you for the reason, which the reporter reads.'
2407
+ : 'Link your Telegram to accept or decline reports from the alerts. Only linked team members can; anyone else’s tap is refused.' }),
2408
+ el('div', { class: 'row' }, [make]),
2409
+ ];
2410
+ if (b.linked) {
2411
+ var unlink = el('button', { class: 'btn ghost', type: 'button', text: 'Unlink' });
2412
+ unlink.onclick = function () {
2413
+ var done = busyButton(unlink, 'Unlinking…');
2414
+ api('DELETE', '/telegram/link').then(function () { toast('Your Telegram is unlinked.'); draw(); })
2415
+ .catch(function (x) { msg.className = 'err'; msg.textContent = x.message; done(); });
2416
+ };
2417
+ kids[1].appendChild(unlink);
2418
+ }
2419
+ kids.push(shown, msg);
2420
+ kids.forEach(function (k) { body.appendChild(k); });
2421
+ }).catch(function (x) { body.textContent = ''; body.appendChild(el('p', { class: 'err', role: 'alert', text: x.message })); });
2422
+ }
2423
+ }
2424
+
2302
2425
  // ---- team ------------------------------------------------------------------------------
2303
2426
 
2304
2427
  /** One numbered step of a setup, in the same style as the install steps. */
@@ -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); }