pi-roundtable 0.50.2 → 0.51.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.
@@ -1,5 +1,12 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import { type Interaction, MessageFlags, TextDisplayBuilder } from "discord.js";
2
+ import {
3
+ type ButtonInteraction,
4
+ type Interaction,
5
+ MessageFlags,
6
+ type ModalSubmitInteraction,
7
+ type StringSelectMenuInteraction,
8
+ TextDisplayBuilder,
9
+ } from "discord.js";
3
10
  import { parseChannelKey } from "../contract/surface.ts";
4
11
  import type { ChannelKey } from "../domain/conversation.ts";
5
12
  import { messages } from "../i18n/index.ts";
@@ -12,7 +19,7 @@ import type { Logger } from "../kernel/log.ts";
12
19
  import { type CardAudienceOptions, CardAudiences } from "./card-audience.ts";
13
20
  import { CardCopies, copyReply, offeredCopy } from "./card-copies.ts";
14
21
  import { DiscordOwners, discordUser } from "./discord-owners.ts";
15
- import { threadOf } from "./inbound-message.ts";
22
+ import { cachedThreadOf } from "./inbound-message.ts";
16
23
  import type { InteractionModule } from "./interaction-module.ts";
17
24
  import {
18
25
  answerDeferred,
@@ -21,6 +28,11 @@ import {
21
28
  showPreviews,
22
29
  } from "./owner-card-answers.ts";
23
30
  import { askPrompts } from "./owner-card-asks.ts";
31
+ import {
32
+ answerApproval,
33
+ cancelQuestion,
34
+ onFirstResponse,
35
+ } from "./owner-card-press.ts";
24
36
  import {
25
37
  approvalRows,
26
38
  CARD_PREFIX,
@@ -274,6 +286,8 @@ export class OwnerCards implements InteractionModule {
274
286
  timer = arm();
275
287
  },
276
288
  audience: card.audience,
289
+ picked: new Map(),
290
+ footer: card.footer,
277
291
  end: (value, by) => {
278
292
  // Withdrawn or answered already: this answer changes nothing.
279
293
  if (!this.#open.has(id)) return false;
@@ -314,6 +328,7 @@ export class OwnerCards implements InteractionModule {
314
328
  .channel(channelId)
315
329
  .then((channel) => {
316
330
  open.mention = channel.thread === true;
331
+ if (channel.parent) open.thread = channel.parent;
317
332
  return channel.send(view(card.footer, false));
318
333
  })
319
334
  .then((posted) => {
@@ -360,6 +375,37 @@ export class OwnerCards implements InteractionModule {
360
375
  const [id = "", action = "", index = ""] = interaction.customId
361
376
  .slice(CARD_PREFIX.length)
362
377
  .split(":");
378
+ const started = performance.now();
379
+ let firstResponseMs: number | undefined;
380
+ onFirstResponse(interaction, () => {
381
+ firstResponseMs = Math.round(performance.now() - started);
382
+ });
383
+ try {
384
+ await this.#press(interaction, id, action, Number(index));
385
+ } finally {
386
+ // Which card and control, and how soon Discord heard back; never what was answered.
387
+ this.#options.logger.debug(
388
+ { cardId: id, action, firstResponseMs },
389
+ "card press",
390
+ );
391
+ }
392
+ return true;
393
+ }
394
+
395
+ /**
396
+ * One press of a card's control. Its first response to Discord comes before anything that can
397
+ * take a while: a press that opens a form shows it at once, and every other one is answered or
398
+ * deferred before the audience, the thread or anything else is read.
399
+ */
400
+ async #press(
401
+ interaction:
402
+ | ButtonInteraction
403
+ | StringSelectMenuInteraction
404
+ | ModalSubmitInteraction,
405
+ id: string,
406
+ action: string,
407
+ index: number,
408
+ ): Promise<void> {
363
409
  // Copying answers nothing: anyone who sees the card may copy, as often as they like, also
364
410
  // once the card has ended or the process restarted.
365
411
  if (interaction.isButton() && action === "copy") {
@@ -369,7 +415,7 @@ export class OwnerCards implements InteractionModule {
369
415
  ? { content: messages().cardCopyGone, flags: MessageFlags.Ephemeral }
370
416
  : copyReply(text),
371
417
  );
372
- return true;
418
+ return;
373
419
  }
374
420
  const card = this.#open.get(id);
375
421
  if (!card) {
@@ -377,14 +423,12 @@ export class OwnerCards implements InteractionModule {
377
423
  content: messages().cardInactive,
378
424
  flags: MessageFlags.Ephemeral,
379
425
  });
380
- return true;
381
- }
382
- if (action === "previews") {
383
- await showPreviews(card, interaction);
384
- return true;
426
+ return;
385
427
  }
428
+ if (action === "previews") return showPreviews(card, interaction);
386
429
  const user = discordUser(interaction);
387
- const thread = await threadOf(interaction.channel);
430
+ // The thread as it was when the card was posted, else the client's cache: never a fetch.
431
+ const thread = card.thread ?? cachedThreadOf(interaction.channel);
388
432
  const by: Answerer = {
389
433
  user,
390
434
  ...(interaction.message ? { messageId: interaction.message.id } : {}),
@@ -392,67 +436,20 @@ export class OwnerCards implements InteractionModule {
392
436
  isDirect: !interaction.inGuild(),
393
437
  ...(thread ? { thread } : {}),
394
438
  };
395
- // A menu pick or Submit is deferred before the audience is looked up, which may take a while.
396
- if (
397
- card.form &&
398
- (action === "qpick" || action === "submit" || action === "qtext")
399
- ) {
400
- await answerDeferred(card, action, Number(index), interaction, by);
401
- return true;
402
- }
403
- if (!(await card.audience.allows(user))) {
404
- await interaction.reply({
405
- content: card.audience.refusal,
406
- flags: MessageFlags.Ephemeral,
407
- });
408
- return true;
409
- }
410
- if (interaction.isButton() && (action === "yes" || action === "no")) {
411
- const approved = action === "yes";
412
- const approver = approved
413
- ? await card.audience.approver?.(user).catch((error: unknown) => {
414
- this.#options.logger.warn(
415
- { err: error },
416
- "could not tell who approved; the call runs without an approver",
417
- );
418
- return undefined;
419
- })
420
- : undefined;
421
- const accepted = card.end(
422
- approved ? "approved" : "declined",
423
- approver ? { ...by, approver } : by,
424
- );
425
- // The plugin withdrew the call, or another press answered, while this one was being checked.
426
- if (!accepted) {
427
- await interaction.reply({
428
- content: messages().cardInactive,
429
- flags: MessageFlags.Ephemeral,
430
- });
431
- return true;
432
- }
433
- await interaction.update(
434
- card.view(
435
- approved
436
- ? (card.outcomes?.approved ?? messages().cardApproved)
437
- : (card.outcomes?.declined ?? messages().cardDeclined),
438
- ),
439
+ if (interaction.isButton() && (action === "yes" || action === "no"))
440
+ return answerApproval(
441
+ card,
442
+ action === "yes",
443
+ interaction,
444
+ user,
445
+ by,
446
+ this.#options.logger,
439
447
  );
440
- return true;
441
- }
442
- if (interaction.isButton() && action === "cancel") {
443
- // Another press, a stop or a withdrawal ended it while this one was being checked.
444
- if (!card.decline()) {
445
- await interaction.reply({
446
- content: messages().cardInactive,
447
- flags: MessageFlags.Ephemeral,
448
- });
449
- return true;
450
- }
451
- await interaction.update(card.view(messages().cardQuestionCancelled));
452
- return true;
453
- }
454
- if (card.form) await answerForm(card, id, action, interaction);
455
- else await answerSingle(card, id, action, interaction, by);
456
- return true;
448
+ if (interaction.isButton() && action === "cancel")
449
+ return cancelQuestion(card, interaction, user);
450
+ if (!card.form) return answerSingle(card, id, action, interaction, by);
451
+ if (action === "qpick" || action === "submit" || action === "qtext")
452
+ return answerDeferred(card, action, index, interaction, by);
453
+ return answerForm(card, id, action, interaction);
457
454
  }
458
455
  }
@@ -173,6 +173,9 @@ function discordAssembly(
173
173
  ...(discord.voice ? { voice: true } : {}),
174
174
  cardGraceMs: discord.cardGraceSeconds * 1_000,
175
175
  cardCopies: discord.cardCopies,
176
+ ...(discord.attachmentRead
177
+ ? { attachmentRead: discord.attachmentRead }
178
+ : {}),
176
179
  }),
177
180
  admin: discord.admin ? [discordAdminPlugin({ owner })] : [],
178
181
  };
@@ -1,4 +1,9 @@
1
1
  import { DISCORD, type DiscordServices } from "../builtin/discord.ts";
2
+ import {
3
+ ATTACHMENT_READ_MAX_BYTES,
4
+ type AttachmentFacts,
5
+ readAttachment,
6
+ } from "../discord/attachment-read.ts";
2
7
  import { CommandCollection } from "../discord/command-collection.ts";
3
8
  import type { ComposedCommands } from "../discord/compose-commands.ts";
4
9
  import type {
@@ -29,14 +34,82 @@ export interface FakeDiscord {
29
34
  compose(): ComposedCommands;
30
35
  }
31
36
 
37
+ /**
38
+ * A file `fakeDiscord`'s `readAttachment` serves, as if posted with a message in a channel. Its
39
+ * `channelId`, `messageId` and `id` are Discord ids, digits only, as the real call requires.
40
+ */
41
+ export interface FakeDiscordAttachment {
42
+ channelId: string;
43
+ messageId: string;
44
+ /** The file's id, as `AttachmentRef.id` gives it. */
45
+ id: string;
46
+ name: string;
47
+ contentType?: string;
48
+ /** Its bytes; a string is UTF-8. */
49
+ bytes: Uint8Array | string;
50
+ title?: string;
51
+ description?: string;
52
+ /** Discord's CDN no longer serves it: a read rejects as `gone`. */
53
+ gone?: boolean;
54
+ }
55
+
56
+ /**
57
+ * `DISCORD.readAttachment` over `files`, with the real one's checks and errors (an id that is no
58
+ * Discord id, a file not on its message, a message of another channel, over `maxBytes`, gone),
59
+ * downloading from a stand-in CDN.
60
+ */
61
+ function fakeAttachmentReader(
62
+ files: readonly FakeDiscordAttachment[],
63
+ maxBytes: number,
64
+ ): DiscordServices["readAttachment"] {
65
+ const bytesOf = (file: FakeDiscordAttachment) =>
66
+ typeof file.bytes === "string"
67
+ ? new TextEncoder().encode(file.bytes)
68
+ : file.bytes;
69
+ const url = (file: FakeDiscordAttachment) =>
70
+ `https://cdn.discordapp.com/attachments/${file.channelId}/${file.id}/${encodeURIComponent(file.name)}`;
71
+ const fetchImpl = (async (address: string) => {
72
+ const file = files.find((f) => url(f) === address);
73
+ return file && !file.gone
74
+ ? new Response(bytesOf(file).slice())
75
+ : new Response(null, { status: 404 });
76
+ }) as unknown as typeof fetch;
77
+ return (request) =>
78
+ readAttachment(
79
+ {
80
+ files: async (channelId, messageId) => {
81
+ const on = files.filter(
82
+ (f) => f.channelId === channelId && f.messageId === messageId,
83
+ );
84
+ if (on.length === 0) return undefined;
85
+ return on.map(
86
+ (f): AttachmentFacts => ({
87
+ id: f.id,
88
+ name: f.name,
89
+ contentType: f.contentType ?? null,
90
+ size: bytesOf(f).byteLength,
91
+ url: url(f),
92
+ title: f.title ?? null,
93
+ description: f.description ?? null,
94
+ }),
95
+ );
96
+ },
97
+ },
98
+ request,
99
+ { maxBytes, fetchImpl },
100
+ );
101
+ }
102
+
32
103
  /**
33
104
  * A `DISCORD` service for a plugin that adds slash commands, without a Discord connection: the
34
105
  * plugin's `commands.add` calls are recorded, and `compose()` shows the tree Discord would get.
35
106
  * `rootCommand` is the root command's name, `roundtable` by default. `channelContext` is what
36
107
  * `DISCORD.channelContext` answers, by default no context, as on a host with it off. `voice` is
37
108
  * what `DISCORD.voice` is, such as a `fakeDiscordVoice()`; without it the plugin reads none, as on
38
- * a host with `discord.voice` off. Only `commands`, `guard`, `poster`, `channelContext`, and
39
- * `voice` are given; reading another member throws.
109
+ * a host with `discord.voice` off. `attachments` are the files `DISCORD.readAttachment` serves,
110
+ * none by default, read at most `attachmentMaxBytes` (default 10 MiB) as the host's
111
+ * `discord.attachmentRead.maxBytes` caps them. Only `commands`, `guard`, `poster`,
112
+ * `channelContext`, `readAttachment` and `voice` are given; reading another member throws.
40
113
  */
41
114
  export function fakeDiscord(
42
115
  options: {
@@ -45,6 +118,8 @@ export function fakeDiscord(
45
118
  channelContext?: DiscordServices["channelContext"];
46
119
  poster?: DiscordPoster;
47
120
  voice?: DiscordVoice;
121
+ attachments?: readonly FakeDiscordAttachment[];
122
+ attachmentMaxBytes?: number;
48
123
  } = {},
49
124
  ): FakeDiscord {
50
125
  const collection = new CommandCollection();
@@ -61,6 +136,10 @@ export function fakeDiscord(
61
136
  guard,
62
137
  poster,
63
138
  channelContext: options.channelContext ?? (async () => undefined),
139
+ readAttachment: fakeAttachmentReader(
140
+ options.attachments ?? [],
141
+ options.attachmentMaxBytes ?? ATTACHMENT_READ_MAX_BYTES,
142
+ ),
64
143
  voice: options.voice,
65
144
  }),
66
145
  poster,
@@ -12,6 +12,7 @@ export type {
12
12
  ChannelContextOptions,
13
13
  } from "../core/contract/channel-context.ts";
14
14
  export {
15
+ CONTEXT_ATTACHMENT_LINES,
15
16
  withChannelContext,
16
17
  withChannelContextImages,
17
18
  } from "../core/contract/channel-context.ts";
@@ -28,6 +29,15 @@ export type {
28
29
  export { agentPanel } from "../core/discord/agent-panel.ts";
29
30
  export type { DiscordPlaceProviderOptions } from "../core/discord/agent-places.ts";
30
31
  export { discordPlaceProvider } from "../core/discord/agent-places.ts";
32
+ export type {
33
+ AttachmentBytes,
34
+ AttachmentReadErrorCode,
35
+ AttachmentReadRequest,
36
+ } from "../core/discord/attachment-read.ts";
37
+ export {
38
+ ATTACHMENT_READ_MAX_BYTES,
39
+ AttachmentReadError,
40
+ } from "../core/discord/attachment-read.ts";
31
41
  export {
32
42
  CHANNEL_CONTEXT_DEFAULTS,
33
43
  formatChannelContext,
package/src/testing.ts CHANGED
@@ -85,7 +85,10 @@ export {
85
85
  testDatabaseUrl,
86
86
  } from "./core/testing/database.ts";
87
87
  export { eagerText, useEagerCatalog } from "./core/testing/eager-catalog.ts";
88
- export type { FakeDiscord } from "./core/testing/fake-discord.ts";
88
+ export type {
89
+ FakeDiscord,
90
+ FakeDiscordAttachment,
91
+ } from "./core/testing/fake-discord.ts";
89
92
  export { fakeDiscord } from "./core/testing/fake-discord.ts";
90
93
  export type {
91
94
  FakeDiscordPoster,