@operad-io/telegram 0.1.0 → 0.2.0

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/src/state.ts CHANGED
@@ -5,9 +5,10 @@
5
5
  * and the event key keeps it one.
6
6
  */
7
7
 
8
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
- import { dirname, join } from "node:path";
8
+ import { readFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
10
  import { isRecord } from "@operad-io/engine";
11
+ import { writeJsonAtomicSync } from "@operad-io/engine/platform";
11
12
 
12
13
  /** The directory the plugin keeps its own files in. */
13
14
  export function telegramStateDirectory(home: string): string {
@@ -34,11 +35,7 @@ export function readOffset(home: string): number {
34
35
 
35
36
  /** Records the next offset and the time it was written. */
36
37
  export function writeOffset(home: string, offset: number, at: number): void {
37
- const path = telegramStatePath(home);
38
- mkdirSync(dirname(path), { recursive: true });
39
- const temporary = `${path}.${process.pid}.tmp`;
40
- writeFileSync(temporary, `${JSON.stringify({ offset, at })}\n`, "utf8");
41
- renameSync(temporary, path);
38
+ writeJsonAtomicSync(telegramStatePath(home), { offset, at });
42
39
  }
43
40
 
44
41
  /** What was sent of one assistant message. */
@@ -51,11 +48,13 @@ export interface SentRecord {
51
48
  readonly done: boolean;
52
49
  /** Sending gave up; the chat's history says so. */
53
50
  readonly failed?: true | undefined;
51
+ /** When the message was recorded, epoch milliseconds; missing on an older record. */
52
+ readonly at?: number | undefined;
54
53
  }
55
54
 
56
55
  /** What the reply side remembers: since when it counts, and what it sent. */
57
56
  export interface SentState {
58
- /** Epoch milliseconds the reply side first ran; older messages are not new. */
57
+ /** Epoch milliseconds before which a message is no longer new; a full sweep moves it forward. */
59
58
  readonly since: number;
60
59
  readonly sent: Readonly<Record<string, SentRecord>>;
61
60
  }
@@ -72,9 +71,32 @@ function recordOf(value: unknown): SentRecord | undefined {
72
71
  done: value.done,
73
72
  ...(typeof value.telegramId === "number" ? { telegramId: value.telegramId } : {}),
74
73
  ...(value.failed === true ? { failed: true as const } : {}),
74
+ ...(typeof value.at === "number" ? { at: value.at } : {}),
75
75
  };
76
76
  }
77
77
 
78
+ /** How long a done record stays behind `since`; older done records are dropped. */
79
+ export const SENT_STATE_MARGIN_MS = 24 * 60 * 60 * 1_000;
80
+
81
+ /**
82
+ * A bounded sent state: a send that is not done stays (so it can finish), and a
83
+ * done record stays while it is within the margin before `since`. A record from
84
+ * before `since` belongs to a message the sweep no longer reads, so dropping it
85
+ * cannot send anything again; a missing `at` is treated as at `since`, keeping
86
+ * a record written before this field existed.
87
+ */
88
+ export function pruneSent(state: SentState, margin = SENT_STATE_MARGIN_MS): SentState {
89
+ const cutoff = state.since - margin;
90
+ const entries = Object.entries(state.sent);
91
+ const kept = entries.filter(
92
+ ([, record]) => record.done !== true || (record.at ?? state.since) >= cutoff,
93
+ );
94
+ if (kept.length === entries.length) return state;
95
+ const sent: Record<string, SentRecord> = {};
96
+ for (const [key, record] of kept) sent[key] = record;
97
+ return { since: state.since, sent };
98
+ }
99
+
78
100
  /** The recorded sends; `undefined` when the file is missing or unusable. */
79
101
  export function readSent(home: string): SentState | undefined {
80
102
  let parsed: unknown;
@@ -87,18 +109,17 @@ export function readSent(home: string): SentState | undefined {
87
109
  const sent: Record<string, SentRecord> = {};
88
110
  for (const [key, value] of Object.entries(parsed.sent)) {
89
111
  const record = recordOf(value);
90
- if (record !== undefined) sent[key] = record;
112
+ if (record === undefined) continue;
113
+ // A record written before `at` existed belongs to a message at or after
114
+ // `since`; keeping that time lets a later full sweep drop it safely.
115
+ sent[key] = record.at === undefined ? { ...record, at: parsed.since } : record;
91
116
  }
92
- return { since: parsed.since, sent };
117
+ return pruneSent({ since: parsed.since, sent });
93
118
  }
94
119
 
95
120
  /** Records the sends, replacing the file whole. */
96
121
  export function writeSent(home: string, state: SentState): void {
97
- const path = telegramSentPath(home);
98
- mkdirSync(dirname(path), { recursive: true });
99
- const temporary = `${path}.${process.pid}.tmp`;
100
- writeFileSync(temporary, `${JSON.stringify(state)}\n`, "utf8");
101
- renameSync(temporary, path);
122
+ writeJsonAtomicSync(telegramSentPath(home), state);
102
123
  }
103
124
 
104
125
  /** One thing a message of the pending side offers. */
@@ -107,10 +128,12 @@ export interface SentOption {
107
128
  readonly label: string;
108
129
  /** `act` runs an action, `choice` answers one of the question's choices, `free` takes any text. */
109
130
  readonly how: "act" | "choice" | "free";
131
+ /** The raw choice an answer sends; `label` when unset. */
132
+ readonly choice?: string | undefined;
110
133
  /** The action's `<plugin>:<action>` for `act`. */
111
134
  readonly action?: string | undefined;
112
- /** The action needs a note, so it is answered by replying. */
113
- readonly note?: true | undefined;
135
+ /** The answer needs a note, or may carry one, so a reply to the message is a note. */
136
+ readonly note?: "required" | "optional" | undefined;
114
137
  }
115
138
 
116
139
  /** One pending item as it was sent to one Telegram chat. */
@@ -141,11 +164,17 @@ export function telegramPendingPath(home: string): string {
141
164
  function optionOf(value: unknown): SentOption | undefined {
142
165
  if (!isRecord(value) || typeof value.label !== "string") return undefined;
143
166
  if (value.how !== "act" && value.how !== "choice" && value.how !== "free") return undefined;
167
+ const note = value.note === true || value.note === "required"
168
+ ? "required"
169
+ : value.note === "optional"
170
+ ? "optional"
171
+ : undefined;
144
172
  return {
145
173
  label: value.label,
146
174
  how: value.how,
175
+ ...(typeof value.choice === "string" ? { choice: value.choice } : {}),
147
176
  ...(typeof value.action === "string" ? { action: value.action } : {}),
148
- ...(value.note === true ? { note: true as const } : {}),
177
+ ...(note === undefined ? {} : { note }),
149
178
  };
150
179
  }
151
180
 
@@ -178,6 +207,30 @@ function itemOf(value: unknown): SentItem | undefined {
178
207
  };
179
208
  }
180
209
 
210
+ /** How many pending messages the state file keeps; older answered ones are dropped. */
211
+ export const PENDING_STATE_MAX = 100;
212
+
213
+ /** A bounded pending state: open items first, then the newest answered ones. */
214
+ export function prunePending(
215
+ state: PendingState,
216
+ keep = PENDING_STATE_MAX,
217
+ ): PendingState {
218
+ const entries = Object.entries(state);
219
+ if (entries.length <= keep) return state;
220
+ const open = entries.filter(([, item]) => item.answered === undefined).slice(-keep);
221
+ const answered = entries.filter(([, item]) => item.answered !== undefined);
222
+ const room = Math.max(0, keep - open.length);
223
+ const kept = new Set([
224
+ ...open.map(([key]) => key),
225
+ ...answered.slice(-room).map(([key]) => key),
226
+ ]);
227
+ const bounded: Record<string, SentItem> = {};
228
+ for (const [key, item] of entries) {
229
+ if (kept.has(key)) bounded[key] = item;
230
+ }
231
+ return bounded;
232
+ }
233
+
181
234
  /** The recorded pending sends; empty when the file is missing or unusable. */
182
235
  export function readPending(home: string): PendingState {
183
236
  let parsed: unknown;
@@ -192,14 +245,161 @@ export function readPending(home: string): PendingState {
192
245
  const item = itemOf(value);
193
246
  if (item !== undefined) items[key] = item;
194
247
  }
195
- return items;
248
+ return prunePending(items);
196
249
  }
197
250
 
198
251
  /** Records the pending sends, replacing the file whole. */
199
252
  export function writePending(home: string, state: PendingState): void {
200
- const path = telegramPendingPath(home);
201
- mkdirSync(dirname(path), { recursive: true });
202
- const temporary = `${path}.${process.pid}.tmp`;
203
- writeFileSync(temporary, `${JSON.stringify(state)}\n`, "utf8");
204
- renameSync(temporary, path);
253
+ writeJsonAtomicSync(telegramPendingPath(home), state);
254
+ }
255
+
256
+ /** One command sent without its one choice, as it waits for a tap. */
257
+ export interface SentCommand {
258
+ /** The operad chat the command runs on. */
259
+ readonly chatId: string;
260
+ /** The Telegram chat the keyboard is in. */
261
+ readonly target: number;
262
+ readonly messageId: number;
263
+ /** The text as sent; "chosen: X" is added to it. */
264
+ readonly text: string;
265
+ /** The command's name, without the slash. */
266
+ readonly name: string;
267
+ /** The choices, in order, as the action's schema lists them. */
268
+ readonly choices: readonly string[];
269
+ /** The page of choices the keyboard shows now. */
270
+ readonly page: number;
271
+ /** The choice the command ran with; set once the message was changed. */
272
+ readonly chosen?: string | undefined;
273
+ }
274
+
275
+ /** What the command side remembers, by the Telegram chat and message of each keyboard. */
276
+ export type CommandState = Readonly<Record<string, SentCommand>>;
277
+
278
+ /** The file the choice keyboards are recorded in. */
279
+ export function telegramCommandsPath(home: string): string {
280
+ return join(telegramStateDirectory(home), "commands.json");
281
+ }
282
+
283
+ function commandOf(value: unknown): SentCommand | undefined {
284
+ if (
285
+ !isRecord(value) ||
286
+ typeof value.chatId !== "string" ||
287
+ typeof value.target !== "number" ||
288
+ typeof value.messageId !== "number" ||
289
+ typeof value.text !== "string" ||
290
+ typeof value.name !== "string" ||
291
+ typeof value.page !== "number" ||
292
+ !Array.isArray(value.choices)
293
+ ) {
294
+ return undefined;
295
+ }
296
+ const choices = value.choices.filter((choice): choice is string => typeof choice === "string");
297
+ return {
298
+ chatId: value.chatId,
299
+ target: value.target,
300
+ messageId: value.messageId,
301
+ text: value.text,
302
+ name: value.name,
303
+ choices,
304
+ page: Number.isInteger(value.page) && value.page >= 0 ? value.page : 0,
305
+ ...(typeof value.chosen === "string" ? { chosen: value.chosen } : {}),
306
+ };
307
+ }
308
+
309
+ /** How many choice keyboards the state file keeps; older answered ones are dropped. */
310
+ export const COMMAND_STATE_MAX = 100;
311
+
312
+ /** A bounded command state: unanswered keyboards first, then the newest answered ones. */
313
+ export function pruneCommands(
314
+ state: CommandState,
315
+ keep = COMMAND_STATE_MAX,
316
+ ): CommandState {
317
+ const entries = Object.entries(state);
318
+ if (entries.length <= keep) return state;
319
+ const open = entries.filter(([, command]) => command.chosen === undefined).slice(-keep);
320
+ const chosen = entries.filter(([, command]) => command.chosen !== undefined);
321
+ const room = Math.max(0, keep - open.length);
322
+ const kept = new Set([
323
+ ...open.map(([key]) => key),
324
+ ...chosen.slice(-room).map(([key]) => key),
325
+ ]);
326
+ const bounded: Record<string, SentCommand> = {};
327
+ for (const [key, command] of entries) {
328
+ if (kept.has(key)) bounded[key] = command;
329
+ }
330
+ return bounded;
331
+ }
332
+
333
+ /** The recorded choice keyboards; empty when the file is missing or unusable. */
334
+ export function readCommands(home: string): CommandState {
335
+ let parsed: unknown;
336
+ try {
337
+ parsed = JSON.parse(readFileSync(telegramCommandsPath(home), "utf8"));
338
+ } catch {
339
+ return {};
340
+ }
341
+ if (!isRecord(parsed)) return {};
342
+ const commands: Record<string, SentCommand> = {};
343
+ for (const [key, value] of Object.entries(parsed)) {
344
+ const command = commandOf(value);
345
+ if (command !== undefined) commands[key] = command;
346
+ }
347
+ return pruneCommands(commands);
348
+ }
349
+
350
+ /** Records the choice keyboards, replacing the file whole. */
351
+ export function writeCommands(home: string, state: CommandState): void {
352
+ writeJsonAtomicSync(telegramCommandsPath(home), state);
353
+ }
354
+
355
+ /** One progress message a reply is shown in: where it lives and what it last said. */
356
+ export interface ProgressRecord {
357
+ /** The Telegram chat the message is in. */
358
+ readonly target: number;
359
+ /** The Telegram `message_id` to edit and to delete when the reply ends. */
360
+ readonly messageId: number;
361
+ /** The reduced Markdown that was last sent, so an unchanged text is not edited. */
362
+ readonly text: string;
363
+ }
364
+
365
+ /** The progress messages still alive, by the chat they belong to. */
366
+ export type ProgressState = Readonly<Record<string, ProgressRecord>>;
367
+
368
+ /** The file the progress messages are recorded in. */
369
+ export function telegramProgressPath(home: string): string {
370
+ return join(telegramStateDirectory(home), "progress.json");
371
+ }
372
+
373
+ function progressOf(value: unknown): ProgressRecord | undefined {
374
+ if (
375
+ !isRecord(value) ||
376
+ typeof value.target !== "number" ||
377
+ typeof value.messageId !== "number" ||
378
+ typeof value.text !== "string"
379
+ ) {
380
+ return undefined;
381
+ }
382
+ return { target: value.target, messageId: value.messageId, text: value.text };
383
+ }
384
+
385
+ /** The recorded progress messages; empty when the file is missing or unusable. */
386
+ export function readProgress(home: string): ProgressState {
387
+ let parsed: unknown;
388
+ try {
389
+ parsed = JSON.parse(readFileSync(telegramProgressPath(home), "utf8"));
390
+ } catch {
391
+ return {};
392
+ }
393
+ if (!isRecord(parsed)) return {};
394
+ const found: Record<string, ProgressRecord> = {};
395
+ for (const [key, value] of Object.entries(parsed)) {
396
+ const record = progressOf(value);
397
+ if (record !== undefined) found[key] = record;
398
+ }
399
+ return found;
400
+ }
401
+
402
+ /** Records the progress messages, replacing the file whole. */
403
+ export function writeProgress(home: string, state: ProgressState): void {
404
+ writeJsonAtomicSync(telegramProgressPath(home), state);
205
405
  }
package/src/typing.ts ADDED
@@ -0,0 +1,328 @@
1
+ /**
2
+ * The typing side of the Telegram plugin: a chat bound to Telegram shows the
3
+ * bot as typing while a reply run is writing one.
4
+ *
5
+ * It wakes on the client API's `events()`, which names a chat whenever it
6
+ * changes, and reads whether that chat still has a message to answer and a run
7
+ * working on it. The run flags come from `list`, one read for a burst of
8
+ * events, not a detail page per event. It reads a bound chat's channels from
9
+ * the plugin's store, as the reply side does. Telegram shows the indicator for
10
+ * about five seconds, so it is sent again while the reply is written; it stops
11
+ * when the reply or a failure line is recorded, even if its run goes on. A
12
+ * failed send is logged once and is not written to history.
13
+ */
14
+
15
+ import { CHAT_TYPE, allEntries, allMessages, chatData, unanswered } from "@operad-io/chat";
16
+ import { messageOf, type ClientApi, type SourceContext } from "@operad-io/engine";
17
+ import type { BotApi } from "./api.ts";
18
+ import { TelegramEvents, type TelegramEvent } from "./events.ts";
19
+ import { telegramChatsOf } from "./replies.ts";
20
+ import { delay } from "./source.ts";
21
+
22
+ /** How often the indicator is renewed; Telegram shows it for about five seconds. */
23
+ export const TYPING_INTERVAL_MS = 4_000;
24
+
25
+ export { EVENT_RETRY_MS } from "./events.ts";
26
+
27
+ export interface TypingSenderOptions {
28
+ readonly api: BotApi;
29
+ readonly clock?: (() => number) | undefined;
30
+ readonly intervalMs?: number | undefined;
31
+ /** Waits `ms` unless `signal` aborts first; a test gives one it moves itself. */
32
+ readonly wait?: ((ms: number, signal: AbortSignal) => Promise<void>) | undefined;
33
+ }
34
+
35
+ /** One chat's indicator, and the loop that renews it. */
36
+ interface Typing {
37
+ readonly controller: AbortController;
38
+ readonly loop: Promise<void>;
39
+ /** A run has been seen working on this chat since the indicator started. */
40
+ seenRunning: boolean;
41
+ }
42
+
43
+ export class TypingSender {
44
+ private readonly ctx: SourceContext;
45
+ private readonly api: BotApi;
46
+ private readonly client: ClientApi;
47
+ private readonly clock: () => number;
48
+ private readonly intervalMs: number;
49
+ private readonly wait: (ms: number, signal: AbortSignal) => Promise<void>;
50
+ private readonly controller = new AbortController();
51
+ private readonly active = new Map<string, Typing>();
52
+ private readonly loops = new Set<Promise<void>>();
53
+ /** Chat ids whose state should be read next; repeated ids coalesce. */
54
+ private readonly wanted = new Set<string>();
55
+ /** Open chats with a message still to answer, the only ones a periodic pass reads. */
56
+ private readonly queued = new Set<string>();
57
+ private checking: Promise<void> | undefined;
58
+ private reconciling: Promise<void> | undefined;
59
+ private following: { readonly stop: () => Promise<void> } | undefined;
60
+ private stopped = false;
61
+ private watching: Promise<void> = Promise.resolve();
62
+
63
+ constructor(ctx: SourceContext, options: TypingSenderOptions) {
64
+ this.ctx = ctx;
65
+ this.api = options.api;
66
+ this.client = ctx.client;
67
+ this.clock = options.clock ?? ctx.clock;
68
+ this.intervalMs = options.intervalMs ?? TYPING_INTERVAL_MS;
69
+ this.wait = options.wait ?? delay;
70
+ const abort = (): void => {
71
+ this.controller.abort();
72
+ for (const typing of this.active.values()) typing.controller.abort();
73
+ };
74
+ if (ctx.signal.aborted) abort();
75
+ else ctx.signal.addEventListener("abort", abort, { once: true });
76
+ }
77
+
78
+ /** Checks every bound chat once, then follows changes, alone or through the plugin's one loop. */
79
+ start(events?: TelegramEvents): { readonly stop: () => Promise<void>; readonly ready: Promise<void> } {
80
+ const local = events === undefined ? new TelegramEvents(this.ctx, { wait: this.wait }) : undefined;
81
+ const initial = this.syncAll().catch((error: unknown) => this.log(`could not show typing: ${messageOf(error)}`));
82
+ this.watching = (async () => {
83
+ await initial;
84
+ if (this.stopped) return;
85
+ this.following = local?.start({
86
+ typing: (event) => this.handleEvent(event),
87
+ });
88
+ // The periodic pass also ends an indicator whose run-end event was lost
89
+ // by a bounded event stream.
90
+ await this.reconcile();
91
+ })();
92
+ return {
93
+ ready: initial,
94
+ stop: async () => {
95
+ this.stopped = true;
96
+ this.controller.abort();
97
+ for (const typing of this.active.values()) typing.controller.abort();
98
+ await this.following?.stop();
99
+ await this.watching.catch(() => undefined);
100
+ while (this.checking !== undefined) await this.checking.catch(() => undefined);
101
+ await Promise.all([...this.loops]);
102
+ },
103
+ };
104
+ }
105
+
106
+ /** One stored change of a chat, as the plugin's one event loop hands it over. */
107
+ handleEvent(event: TelegramEvent): void {
108
+ if (event.section !== undefined) return;
109
+ void this.syncChat(event.id).catch((error: unknown) => this.log(`could not show typing: ${messageOf(error)}`));
110
+ }
111
+
112
+ /** Checks only chats with an indicator or an open message still to answer, once per interval. */
113
+ private async reconcile(): Promise<void> {
114
+ while (!this.stopped) {
115
+ try {
116
+ await this.wait(this.intervalMs, this.controller.signal);
117
+ } catch {
118
+ return;
119
+ }
120
+ if (this.stopped) return;
121
+ const ids = new Set([...this.active.keys(), ...this.queued]);
122
+ if (ids.size === 0) continue;
123
+ const pass = Promise.all([...ids].map((id) => this.syncChat(id)))
124
+ .then(() => undefined)
125
+ .catch((error: unknown) => this.log(`could not show typing: ${messageOf(error)}`));
126
+ this.reconciling = pass;
127
+ try {
128
+ await pass;
129
+ } finally {
130
+ if (this.reconciling === pass) this.reconciling = undefined;
131
+ }
132
+ }
133
+ }
134
+
135
+ /** Checks every chat bound to Telegram once. */
136
+ async syncAll(): Promise<void> {
137
+ const ids: string[] = [];
138
+ let cursor: string | undefined;
139
+ do {
140
+ const page = await this.ctx.store.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
141
+ for (const object of page.objects) {
142
+ const data = chatData(object.data);
143
+ if (!data.closed && telegramChatsOf(data.channels).length > 0) ids.push(object.id);
144
+ }
145
+ cursor = page.next;
146
+ } while (cursor !== undefined);
147
+ await Promise.all(ids.map((id) => this.syncChat(id)));
148
+ }
149
+
150
+ /** Starts the indicator for an accepted message, before its run is reported. */
151
+ received(chatId: string, target: number): void {
152
+ if (this.stopped) return;
153
+ this.startTyping(chatId, target);
154
+ }
155
+
156
+ /** Shows or stops the indicator of one chat, as the answer now stands. */
157
+ syncChat(chatId: string): Promise<void> {
158
+ this.wanted.add(chatId);
159
+ return this.scheduleChecks();
160
+ }
161
+
162
+ /** Waits for the checks asked so far, including one just woken by an event. */
163
+ async settled(): Promise<void> {
164
+ // A watcher woken by the same event queues its check in a following turn.
165
+ await Promise.resolve();
166
+ while (this.checking !== undefined || this.reconciling !== undefined) {
167
+ const work = this.checking ?? this.reconciling;
168
+ if (work === undefined) return;
169
+ await work.catch(() => undefined);
170
+ }
171
+ }
172
+
173
+ private scheduleChecks(): Promise<void> {
174
+ const existing = this.checking;
175
+ if (existing !== undefined) return existing;
176
+ const run = this.drainChecks().finally(() => {
177
+ if (this.checking === run) {
178
+ this.checking = undefined;
179
+ if (!this.stopped && this.wanted.size > 0) void this.scheduleChecks();
180
+ }
181
+ });
182
+ this.checking = run;
183
+ return run;
184
+ }
185
+
186
+ private async drainChecks(): Promise<void> {
187
+ while (!this.stopped && this.wanted.size > 0) {
188
+ const ids = [...this.wanted];
189
+ this.wanted.clear();
190
+ await this.checkChats(ids);
191
+ }
192
+ }
193
+
194
+ /** Reads the chats named by one burst of events, with one list read for their run flags. */
195
+ private async checkChats(ids: readonly string[]): Promise<void> {
196
+ const bound: { readonly chatId: string; readonly target: number }[] = [];
197
+ for (const chatId of ids) {
198
+ if (this.stopped) return;
199
+ const stored = await this.ctx.store.get(CHAT_TYPE, chatId);
200
+ if (stored === undefined) {
201
+ this.queued.delete(chatId);
202
+ continue;
203
+ }
204
+ const data = chatData(stored.data);
205
+ const target = telegramChatsOf(data.channels)[0];
206
+ if (target === undefined || data.closed) {
207
+ this.queued.delete(chatId);
208
+ await this.stopTyping(chatId);
209
+ continue;
210
+ }
211
+ bound.push({ chatId, target });
212
+ }
213
+ if (this.stopped || bound.length === 0) return;
214
+ let running: ReadonlyMap<string, boolean>;
215
+ try {
216
+ running = await this.runningOf(bound.map((chat) => chat.chatId));
217
+ } catch (error) {
218
+ await this.log(`could not show typing: ${messageOf(error)}`);
219
+ for (const chat of bound) await this.stopTyping(chat.chatId);
220
+ return;
221
+ }
222
+ for (const chat of bound) {
223
+ if (this.stopped) return;
224
+ // The reply is recorded on the chat before its run ends. Once it answers
225
+ // every message, writing is over even if the run goes on.
226
+ const messages = allMessages(this.ctx.store, chat.chatId);
227
+ let lastUser = 0;
228
+ for (const message of messages) {
229
+ if (message.role === "user") lastUser = Math.max(lastUser, message.sequence);
230
+ }
231
+ // A rerun after a failure writes new entries; only a failure that is
232
+ // still the last thing after the person's message means writing is over.
233
+ const entries = allEntries(this.ctx.store, chat.chatId);
234
+ let lastEntry = 0;
235
+ let lastFailure = 0;
236
+ for (const entry of entries) {
237
+ lastEntry = Math.max(lastEntry, entry.sequence);
238
+ if (entry.kind === "failure") lastFailure = Math.max(lastFailure, entry.sequence);
239
+ }
240
+ const failed = lastFailure > lastUser && lastFailure === lastEntry;
241
+ if (unanswered(messages).length === 0 || failed) {
242
+ this.queued.delete(chat.chatId);
243
+ await this.stopTyping(chat.chatId);
244
+ continue;
245
+ }
246
+ this.queued.add(chat.chatId);
247
+ if (running.get(chat.chatId) === true) {
248
+ this.startTyping(chat.chatId, chat.target);
249
+ const active = this.active.get(chat.chatId);
250
+ if (active !== undefined) active.seenRunning = true;
251
+ continue;
252
+ }
253
+ // A message accepted before its run is reported keeps the indicator
254
+ // going. A run that was seen and has ended without a reply ends it.
255
+ if (this.active.get(chat.chatId)?.seenRunning === true) await this.stopTyping(chat.chatId);
256
+ }
257
+ }
258
+
259
+ /** The running flags of the named chats from a list read, not a detail page per event. */
260
+ private async runningOf(ids: readonly string[]): Promise<ReadonlyMap<string, boolean>> {
261
+ const wanted = new Set(ids);
262
+ const found = new Map<string, boolean>();
263
+ let cursor: string | undefined;
264
+ do {
265
+ const page = await this.client.list(CHAT_TYPE, { ...(cursor === undefined ? {} : { cursor }) });
266
+ for (const row of page.rows) {
267
+ if (wanted.has(row.id)) found.set(row.id, row.running);
268
+ }
269
+ cursor = page.next;
270
+ } while (cursor !== undefined && found.size < wanted.size);
271
+ return found;
272
+ }
273
+
274
+ private startTyping(chatId: string, target: number): void {
275
+ if (this.active.has(chatId) || this.stopped) return;
276
+ const controller = new AbortController();
277
+ const loop = (async () => {
278
+ try {
279
+ await this.type(chatId, target, controller);
280
+ } catch (error) {
281
+ if (!controller.signal.aborted && !this.stopped) {
282
+ await this.log(`could not show typing in chat ${chatId}: ${messageOf(error)}`);
283
+ }
284
+ } finally {
285
+ if (this.active.get(chatId)?.controller === controller) this.active.delete(chatId);
286
+ }
287
+ })();
288
+ this.active.set(chatId, { controller, loop, seenRunning: false });
289
+ this.loops.add(loop);
290
+ void loop.then(
291
+ () => this.loops.delete(loop),
292
+ () => this.loops.delete(loop),
293
+ );
294
+ }
295
+
296
+ /** Sends the indicator now, then again after each interval, until stopped. */
297
+ private async type(chatId: string, target: number, controller: AbortController): Promise<void> {
298
+ let next = this.clock();
299
+ let warned = false;
300
+ while (!controller.signal.aborted && !this.stopped) {
301
+ const wait = next - this.clock();
302
+ if (wait > 0) await this.wait(wait, controller.signal);
303
+ if (controller.signal.aborted || this.stopped) return;
304
+ try {
305
+ await this.api.sendChatAction({ chatId: target, action: "typing", signal: controller.signal });
306
+ } catch (error) {
307
+ if (!controller.signal.aborted && !this.stopped && !warned) {
308
+ warned = true;
309
+ void this.log(`could not show typing in chat ${chatId}: ${messageOf(error)}`).catch(() => undefined);
310
+ }
311
+ }
312
+ next = this.clock() + this.intervalMs;
313
+ }
314
+ }
315
+
316
+ /** Ends the indicator of one chat and waits for its loop to finish. */
317
+ private async stopTyping(chatId: string): Promise<void> {
318
+ const typing = this.active.get(chatId);
319
+ if (typing === undefined) return;
320
+ this.active.delete(chatId);
321
+ typing.controller.abort();
322
+ await typing.loop;
323
+ }
324
+
325
+ private async log(message: string): Promise<void> {
326
+ await this.ctx.logger.write(message);
327
+ }
328
+ }
@@ -7,18 +7,21 @@
7
7
  "properties": {
8
8
  "users": {
9
9
  "type": "array",
10
+ "title": "Allowed users",
10
11
  "items": { "type": "integer", "minimum": 1 },
11
12
  "default": [],
12
13
  "description": "The Telegram user ids whose private messages become chat messages. A message from anyone else is recorded and answered with nothing."
13
14
  },
14
15
  "bot": {
15
16
  "type": "string",
17
+ "title": "Default bot",
16
18
  "minLength": 1,
17
19
  "default": "default",
18
20
  "description": "The bot a chat is opened on when a listed user writes first."
19
21
  },
20
22
  "pending": {
21
23
  "type": "array",
24
+ "title": "Forward pending",
22
25
  "items": { "type": "string", "minLength": 1 },
23
26
  "default": [],
24
27
  "description": "The plugins whose pending items are also sent to Telegram, such as [\"dev\"]. Items of a chat bound to Telegram are always sent."