pi-roundtable 0.50.2 → 0.51.1

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.
@@ -0,0 +1,222 @@
1
+ import type { Client } from "discord.js";
2
+ import { boundedBody } from "./context-images.ts";
3
+
4
+ /** Which file `DISCORD.readAttachment` reads: one attachment of one message in a channel the caller names. */
5
+ export interface AttachmentReadRequest {
6
+ /** The channel (or thread) the message is in. A message of another channel is not found. */
7
+ channelId: string;
8
+ /** The message that carries the file; a forward carries the forwarded message's files. */
9
+ messageId: string;
10
+ /** Discord's id of the file, as `AttachmentRef.id` and channel context's attachment lines give it. */
11
+ attachmentId: string;
12
+ /** The most bytes read for this call; it may lower the host's `discord.attachmentRead.maxBytes`, never raise it. */
13
+ maxBytes?: number;
14
+ }
15
+
16
+ /** One file's bytes, read from Discord as it is now. */
17
+ export interface AttachmentBytes {
18
+ /** The file's id, as asked for. */
19
+ id: string;
20
+ name: string;
21
+ /** Empty when Discord does not say. */
22
+ contentType: string;
23
+ /** The number of bytes read, which is `bytes.byteLength`. */
24
+ size: number;
25
+ bytes: Uint8Array;
26
+ /** The title the uploader gave it, when there is one. */
27
+ title?: string;
28
+ /** The description the uploader gave it, such as its alt text, when there is one. */
29
+ description?: string;
30
+ }
31
+
32
+ /**
33
+ * Why a file was not read: `not-found` (no such channel, message, or file on the message, or one
34
+ * the bot cannot see), `too-large` (over the cap, by Discord's size or by what arrived), `gone`
35
+ * (Discord's CDN no longer serves it), `unavailable` (Discord is not connected, did not answer in
36
+ * time, or answered with another error; trying later may work), `invalid` (the call's `maxBytes` is
37
+ * not a positive whole number).
38
+ */
39
+ export type AttachmentReadErrorCode =
40
+ | "invalid"
41
+ | "not-found"
42
+ | "too-large"
43
+ | "gone"
44
+ | "unavailable";
45
+
46
+ /** What `DISCORD.readAttachment` rejects with; `message` names the request, never the file's URL. */
47
+ export class AttachmentReadError extends Error {
48
+ readonly code: AttachmentReadErrorCode;
49
+ constructor(code: AttachmentReadErrorCode, message: string) {
50
+ super(message);
51
+ this.name = "AttachmentReadError";
52
+ this.code = code;
53
+ }
54
+ }
55
+
56
+ /** The host's cap on one read when `discord.attachmentRead.maxBytes` is left out: 10 MiB. */
57
+ export const ATTACHMENT_READ_MAX_BYTES = 10 * 1024 * 1024;
58
+ /** The highest cap a host may set, in its config or in `discordPlugin`'s options: 100 MiB. */
59
+ export const ATTACHMENT_READ_LIMIT_BYTES = 100 * 1024 * 1024;
60
+
61
+ /** Whether `bytes` is a cap a host may set: a whole number from 1 to `ATTACHMENT_READ_LIMIT_BYTES`. */
62
+ export const validReadCap = (bytes: number) =>
63
+ Number.isInteger(bytes) && bytes >= 1 && bytes <= ATTACHMENT_READ_LIMIT_BYTES;
64
+ /** How long one file's download may take. */
65
+ const READ_TIMEOUT_MS = 30_000;
66
+
67
+ /** A file of a message as Discord describes it now, with a fresh, signed URL. */
68
+ export interface AttachmentFacts {
69
+ id: string;
70
+ name: string;
71
+ contentType: string | null;
72
+ size: number;
73
+ url: string;
74
+ title?: string | null;
75
+ description?: string | null;
76
+ }
77
+
78
+ /** Where `readAttachment` looks a message up; replaceable in tests. */
79
+ export interface AttachmentSource {
80
+ /**
81
+ * The message's files, its own and those of a message it forwards; undefined when the channel
82
+ * or the message does not exist, is not a message channel, or the bot cannot read it. Throws
83
+ * when Discord cannot be asked.
84
+ */
85
+ files(
86
+ channelId: string,
87
+ messageId: string,
88
+ ): Promise<readonly AttachmentFacts[] | undefined>;
89
+ }
90
+
91
+ /** The hosts Discord serves attachments from; a URL elsewhere is never fetched. */
92
+ const CDN_HOSTS = new Set(["cdn.discordapp.com", "media.discordapp.net"]);
93
+
94
+ /**
95
+ * One attachment's bytes: the message is fetched again (so its URL is fresh and Discord's, never
96
+ * one a caller or a model supplied), the file is found by its id, and its bytes are downloaded up
97
+ * to `maxBytes`. Rejects with an `AttachmentReadError`.
98
+ */
99
+ export async function readAttachment(
100
+ source: AttachmentSource,
101
+ request: AttachmentReadRequest,
102
+ options: { maxBytes: number; fetchImpl?: typeof fetch; timeoutMs?: number },
103
+ ): Promise<AttachmentBytes> {
104
+ const { channelId, messageId, attachmentId } = request;
105
+ const what = `attachment ${attachmentId} of message ${messageId} in channel ${channelId}`;
106
+ for (const [name, value] of Object.entries({
107
+ channelId,
108
+ messageId,
109
+ attachmentId,
110
+ }))
111
+ if (typeof value !== "string" || !/^\d{1,25}$/.test(value))
112
+ throw new AttachmentReadError("not-found", `${name} is not a Discord id`);
113
+ if (!validReadCap(options.maxBytes))
114
+ throw new RangeError(
115
+ `the host's maxBytes must be a whole number from 1 to ${ATTACHMENT_READ_LIMIT_BYTES}`,
116
+ );
117
+ const asked = request.maxBytes;
118
+ if (asked !== undefined && !(Number.isInteger(asked) && asked >= 1))
119
+ throw new AttachmentReadError(
120
+ "invalid",
121
+ "maxBytes must be a positive whole number",
122
+ );
123
+ const max = Math.min(options.maxBytes, asked ?? Number.POSITIVE_INFINITY);
124
+ let files: readonly AttachmentFacts[] | undefined;
125
+ try {
126
+ files = await source.files(channelId, messageId);
127
+ } catch {
128
+ throw new AttachmentReadError(
129
+ "unavailable",
130
+ `${what}: Discord could not be asked for the message`,
131
+ );
132
+ }
133
+ const file = files?.find((found) => found.id === attachmentId);
134
+ if (!file)
135
+ throw new AttachmentReadError(
136
+ "not-found",
137
+ `${what}: ${files ? "the message has no such file" : "no such message the bot can read"}`,
138
+ );
139
+ const tooLarge = () =>
140
+ new AttachmentReadError("too-large", `${what}: larger than ${max} bytes`);
141
+ if (file.size > max) throw tooLarge();
142
+ const url = safeUrl(file.url);
143
+ if (!url)
144
+ throw new AttachmentReadError(
145
+ "unavailable",
146
+ `${what}: Discord gave no CDN address for it`,
147
+ );
148
+ const signal = AbortSignal.timeout(options.timeoutMs ?? READ_TIMEOUT_MS);
149
+ let bytes: Uint8Array | undefined;
150
+ try {
151
+ const response = await (options.fetchImpl ?? fetch)(url, {
152
+ signal,
153
+ redirect: "error",
154
+ });
155
+ if (!response.ok) {
156
+ await response.body?.cancel();
157
+ throw new AttachmentReadError(
158
+ [403, 404, 410].includes(response.status) ? "gone" : "unavailable",
159
+ `${what}: Discord's CDN answered ${response.status}`,
160
+ );
161
+ }
162
+ bytes = await boundedBody(response, max);
163
+ } catch (error) {
164
+ if (error instanceof AttachmentReadError) throw error;
165
+ throw new AttachmentReadError(
166
+ "unavailable",
167
+ `${what}: the download failed${signal.aborted ? " (timed out)" : ""}`,
168
+ );
169
+ }
170
+ if (!bytes) throw tooLarge();
171
+ return {
172
+ id: file.id,
173
+ name: file.name,
174
+ contentType: file.contentType ?? "",
175
+ size: bytes.byteLength,
176
+ bytes,
177
+ ...(file.title ? { title: file.title } : {}),
178
+ ...(file.description ? { description: file.description } : {}),
179
+ };
180
+ }
181
+
182
+ function safeUrl(raw: string): string | undefined {
183
+ try {
184
+ const url = new URL(raw);
185
+ return url.protocol === "https:" && CDN_HOSTS.has(url.hostname)
186
+ ? url.href
187
+ : undefined;
188
+ } catch {
189
+ return undefined;
190
+ }
191
+ }
192
+
193
+ /** Discord's codes for a channel or message that is not there or not the bot's to read. */
194
+ const MISSING = new Set([10003, 10008, 50001, 50013]);
195
+
196
+ /** The messages of the Discord client, as `readAttachment` looks them up. */
197
+ export function discordAttachmentSource(client: Client): AttachmentSource {
198
+ return {
199
+ files: async (channelId, messageId) => {
200
+ if (!client.isReady()) throw new Error("Discord is not connected");
201
+ try {
202
+ const channel = await client.channels.fetch(channelId);
203
+ if (!channel?.isTextBased()) return undefined;
204
+ // Fetched from Discord, not the cache, so the URLs are freshly signed.
205
+ const message = await channel.messages.fetch({
206
+ message: messageId,
207
+ force: true,
208
+ });
209
+ return [
210
+ ...message.attachments.values(),
211
+ ...[...message.messageSnapshots.values()].flatMap((snapshot) => [
212
+ ...snapshot.attachments.values(),
213
+ ]),
214
+ ];
215
+ } catch (error) {
216
+ const code = (error as { code?: unknown } | null)?.code;
217
+ if (typeof code === "number" && MISSING.has(code)) return undefined;
218
+ throw error;
219
+ }
220
+ },
221
+ };
222
+ }
@@ -32,15 +32,7 @@ export type ContextSourceMessage = ChannelContextSource;
32
32
  /** A file attached to a fetched message, as Discord describes it. */
33
33
  export type ContextSourceAttachment = ChannelContextSourceAttachment;
34
34
 
35
- function attachmentLabel(contentType: string | null | undefined): string {
36
- const type = contentType ?? "";
37
- if (type.startsWith("image/")) return "image";
38
- if (type.startsWith("video/")) return "video";
39
- if (type.startsWith("audio/")) return "audio";
40
- return "file";
41
- }
42
-
43
- /** The facts of a fetched Discord message channel context reads: mentions by name, stickers and files as text, never their bytes. */
35
+ /** The facts of a fetched Discord message channel context reads: mentions by name and stickers as text, its files described, never their bytes. */
44
36
  export function contextSourceOf(
45
37
  message: Message,
46
38
  { botId, applicationId }: BotIdentity,
@@ -55,10 +47,6 @@ export function contextSourceOf(
55
47
  const parts = [text.trim(), embeds].filter(Boolean);
56
48
  for (const sticker of message.stickers.values())
57
49
  parts.push(`[sticker: ${sticker.name}]`);
58
- for (const file of message.attachments.values())
59
- parts.push(
60
- `[${attachmentLabel(file.contentType)}: ${file.name} ${file.url}]`,
61
- );
62
50
  const ownWebhook =
63
51
  message.webhookId !== null &&
64
52
  message.applicationId !== null &&
@@ -78,7 +66,10 @@ export function contextSourceOf(
78
66
  at: message.createdTimestamp,
79
67
  text: parts.join(" "),
80
68
  attachments: [...message.attachments.values()].map((file) => ({
69
+ id: file.id,
81
70
  name: file.name,
71
+ ...(file.title ? { title: file.title } : {}),
72
+ ...(file.description ? { description: file.description } : {}),
82
73
  contentType: file.contentType ?? "",
83
74
  size: file.size,
84
75
  url: file.url,
@@ -111,9 +102,22 @@ function similarity(a: string, b: string): number {
111
102
  return longest / longer.length;
112
103
  }
113
104
 
105
+ /** Whether two messages carry the same files, by name and size: a repost's files have new ids. */
106
+ function sameFiles(a: ContextSourceMessage, b: ContextSourceMessage): boolean {
107
+ const files = (message: ContextSourceMessage) =>
108
+ (message.attachments ?? []).map((file) => `${file.name}\u0000${file.size}`);
109
+ const [x, y] = [files(a), files(b)];
110
+ return x.length === y.length && x.every((file, i) => file === y[i]);
111
+ }
112
+
113
+ /** A message that says something: text, or a file. */
114
+ const saysSomething = (message: ContextSourceMessage) =>
115
+ message.text !== "" || (message.attachments?.length ?? 0) > 0;
116
+
114
117
  /**
115
- * Consecutive messages of one author at least `threshold` alike become the later one. A `foreign`
116
- * message is one of a webhook that carries many people, so it also needs the same name.
118
+ * Consecutive messages of one author at least `threshold` alike, with the same files, become the
119
+ * later one. A `foreign` message is one of a webhook that carries many people, so it also needs
120
+ * the same name.
117
121
  */
118
122
  function merged(
119
123
  messages: readonly ContextSourceMessage[],
@@ -127,6 +131,7 @@ function merged(
127
131
  last &&
128
132
  last.authorId === message.authorId &&
129
133
  (!foreign(message) || last.authorName === message.authorName) &&
134
+ sameFiles(last, message) &&
130
135
  similarity(last.text, message.text) >= threshold
131
136
  )
132
137
  out[out.length - 1] = message;
@@ -150,7 +155,7 @@ export interface ChannelContextSelection {
150
155
  /**
151
156
  * The thread's opening message when `ChannelContextOptions.starter` asked for it: it comes first,
152
157
  * outside `keep`, whether or not the fetched window holds it, unless a filter drops it (the
153
- * `authors` verdict, the assistant's own post, an empty text, a message delivered before).
158
+ * `authors` verdict, the assistant's own post, a message with neither text nor files, a message delivered before).
154
159
  */
155
160
  starter?: ContextSourceMessage;
156
161
  /** What the selection reads of the settings; without `foreignWebhook` every webhook of the application is the assistant's. */
@@ -186,7 +191,7 @@ function limitOf(
186
191
 
187
192
  /**
188
193
  * The window of fetched messages (all before the addressed one): those after the assistant's
189
- * latest post, without its own posts, those already delivered, and empty ones; near repeats merged,
194
+ * latest post, without its own posts, those already delivered, and those with neither text nor files; near repeats merged,
190
195
  * the newest `keep`, oldest first. `window` is every message it considered, kept or not.
191
196
  */
192
197
  export function selectChannelContext(
@@ -224,7 +229,7 @@ export function selectChannelContext(
224
229
  const opening =
225
230
  starter &&
226
231
  !seen.has(starter.id) &&
227
- starter.text !== "" &&
232
+ saysSomething(starter) &&
228
233
  verdict(starter) === "keep"
229
234
  ? [{ ...starter, text: cut(starter.text, limitOf(starter, selection)) }]
230
235
  : [];
@@ -237,7 +242,7 @@ export function selectChannelContext(
237
242
  message.id !== starter?.id &&
238
243
  !assistants(message) &&
239
244
  !seen.has(message.id) &&
240
- message.text !== "",
245
+ saysSomething(message),
241
246
  )
242
247
  .map((message) => ({
243
248
  ...message,
@@ -28,7 +28,7 @@ const DEADLINE_MS = 20_000;
28
28
  const CONCURRENCY = 2;
29
29
 
30
30
  /** The bytes of a response, or undefined once they pass `max`. */
31
- async function boundedBody(
31
+ export async function boundedBody(
32
32
  response: Response,
33
33
  max: number,
34
34
  ): Promise<Uint8Array | undefined> {
@@ -46,7 +46,7 @@ import { readMessagesBefore, readThreadStarter } from "./context-reading.ts";
46
46
  import { DiscordThreadHost } from "./dispatch-thread-host.ts";
47
47
  import { DISCORD_FORMATTING, pickFormatting } from "./formatting.ts";
48
48
  import { DEFAULT_FRESH_MARKER, postFreshMarker } from "./fresh-marker.ts";
49
- import { lateAnswerMessage } from "./inbound-message.ts";
49
+ import { lateAnswerMessage, threadOf } from "./inbound-message.ts";
50
50
  import type { IntercomTexts } from "./intercom-cards.ts";
51
51
  import {
52
52
  explainIntents,
@@ -409,8 +409,10 @@ export class DiscordSurface
409
409
  /** Where the owner's cards in a channel are posted. */
410
410
  async cardChannel(channelId: string): Promise<CardChannel> {
411
411
  const target = await this.#sendable(`${PREFIX}${channelId}`);
412
+ const parent = await threadOf(target);
412
413
  return {
413
414
  thread: target.isThread(),
415
+ ...(parent ? { parent } : {}),
414
416
  send: async (payload) => {
415
417
  const message = await target.send(payload);
416
418
  return { edit: (change) => message.edit(change) };
@@ -18,14 +18,20 @@ export interface BotIdentity {
18
18
  applicationId: string | undefined;
19
19
  }
20
20
 
21
+ /** The files of `message`, carried by the message `carrier` (a forward's by the forwarding message). */
21
22
  function attachmentRefs(
22
23
  message: Pick<Message, "attachments">,
24
+ carrier: string,
23
25
  ): AttachmentRef[] {
24
26
  return [...message.attachments.values()].map((attachment) => ({
25
27
  url: attachment.url,
26
28
  name: attachment.name,
27
29
  ...(attachment.contentType ? { contentType: attachment.contentType } : {}),
28
30
  size: attachment.size,
31
+ id: attachment.id,
32
+ messageId: carrier,
33
+ ...(attachment.title ? { title: attachment.title } : {}),
34
+ ...(attachment.description ? { description: attachment.description } : {}),
29
35
  }));
30
36
  }
31
37
 
@@ -34,7 +40,7 @@ function referenceOf(referenced: Message, mention: RegExp) {
34
40
  text: withEmbeds(referenced.content, referenced.embeds)
35
41
  .replace(mention, "")
36
42
  .trim(),
37
- attachments: attachmentRefs(referenced),
43
+ attachments: attachmentRefs(referenced, referenced.id),
38
44
  authorId: referenced.author.id,
39
45
  ...(referenced.webhookId
40
46
  ? { webhookName: referenced.author.username }
@@ -42,16 +48,12 @@ function referenceOf(referenced: Message, mention: RegExp) {
42
48
  };
43
49
  }
44
50
 
45
- /** What a thread's parent is: a text channel, a forum, or something else (also a parent that cannot be read). */
46
- export async function threadOf(
47
- channel: Channel | null | undefined,
48
- ): Promise<InboundMessage["thread"] | undefined> {
49
- if (!channel?.isThread() || !channel.parentId) return undefined;
50
- const parent =
51
- channel.parent ??
52
- (await channel.guild.channels.fetch(channel.parentId).catch(() => null));
51
+ function threadFacts(
52
+ parentId: string,
53
+ parent: Pick<Channel, "type"> | null | undefined,
54
+ ): NonNullable<InboundMessage["thread"]> {
53
55
  return {
54
- parentId: channel.parentId,
56
+ parentId,
55
57
  parentKind:
56
58
  parent?.type === ChannelType.GuildText
57
59
  ? "text"
@@ -61,6 +63,28 @@ export async function threadOf(
61
63
  };
62
64
  }
63
65
 
66
+ /** What a thread's parent is: a text channel, a forum, or something else (also a parent that cannot be read). */
67
+ export async function threadOf(
68
+ channel: Channel | null | undefined,
69
+ ): Promise<InboundMessage["thread"] | undefined> {
70
+ if (!channel?.isThread() || !channel.parentId) return undefined;
71
+ const parent =
72
+ channel.parent ??
73
+ (await channel.guild.channels.fetch(channel.parentId).catch(() => null));
74
+ return threadFacts(channel.parentId, parent);
75
+ }
76
+
77
+ /**
78
+ * `threadOf` from the client's cache alone, never fetching: for an interaction, which must answer
79
+ * Discord within three seconds. A parent that is not cached reads as "other".
80
+ */
81
+ export function cachedThreadOf(
82
+ channel: Channel | null | undefined,
83
+ ): InboundMessage["thread"] | undefined {
84
+ if (!channel?.isThread() || !channel.parentId) return undefined;
85
+ return threadFacts(channel.parentId, channel.parent);
86
+ }
87
+
64
88
  /**
65
89
  * The facts of one Discord message, as the neutral `InboundMessage`; undefined for the bot's own
66
90
  * messages and before the client is ready. A forward reports the channel it came from as a
@@ -132,8 +156,8 @@ export async function toInbound(
132
156
  .replace(mention, "")
133
157
  .trim(),
134
158
  attachments: [
135
- ...attachmentRefs(message),
136
- ...(forward ? attachmentRefs(forward) : []),
159
+ ...attachmentRefs(message, message.id),
160
+ ...(forward ? attachmentRefs(forward, message.id) : []),
137
161
  ],
138
162
  ...(forward && reference?.channelId
139
163
  ? {
@@ -9,6 +9,7 @@ import {
9
9
  formFields,
10
10
  previewReplies,
11
11
  questionnaireModal,
12
+ type Written,
12
13
  } from "./owner-card-questionnaire.ts";
13
14
  import {
14
15
  answeredLine,
@@ -23,7 +24,12 @@ const ephemeral = (content: string) => ({
23
24
  flags: MessageFlags.Ephemeral as const,
24
25
  });
25
26
 
26
- /** The single-question card's controls: a menu pick, "Write answer…", and the answer form. */
27
+ /**
28
+ * The single-question card's controls: a menu pick, "Write answer…", and the answer form. A press
29
+ * that opens the form shows it at once, before anything is read (Discord takes no deferral in
30
+ * front of a form); whoever submits it is checked then. Any other press is deferred before the
31
+ * audience is read, and someone the card is not for is told so with the card unchanged.
32
+ */
27
33
  export async function answerSingle(
28
34
  card: OpenCard,
29
35
  id: string,
@@ -33,8 +39,9 @@ export async function answerSingle(
33
39
  ): Promise<void> {
34
40
  const question = card.question;
35
41
  if (!question) return;
42
+ const userId = by.user.id;
36
43
  if (interaction.isButton() && action === "write") {
37
- card.picked = [];
44
+ card.picked.set(userId, []);
38
45
  await interaction.showModal(answerModal(id));
39
46
  return;
40
47
  }
@@ -44,24 +51,42 @@ export async function answerSingle(
44
51
  values.includes(String(i)) ? [option.label] : [],
45
52
  );
46
53
  if (values.includes(OTHER)) {
47
- card.picked = choices;
54
+ card.picked.set(userId, choices);
48
55
  await interaction.showModal(answerModal(id));
49
56
  return;
50
57
  }
58
+ await interaction.deferUpdate();
59
+ if (!(await card.audience.allows(by.user))) {
60
+ await interaction.followUp(ephemeral(card.audience.refusal));
61
+ // Their menu shows the refused pick until the card is drawn again.
62
+ if (card.isOpen())
63
+ await interaction.editReply(card.view(card.footer, false));
64
+ return;
65
+ }
51
66
  const answer = { choices };
52
- card.end(answer, by);
53
- await interaction.update(card.view(answeredLine(answer)));
67
+ if (!card.end(answer, by)) {
68
+ await interaction.followUp(ephemeral(messages().cardInactive));
69
+ return;
70
+ }
71
+ await interaction.editReply(card.view(answeredLine(answer)));
54
72
  return;
55
73
  }
56
74
  if (interaction.isModalSubmit() && action === "text") {
75
+ await interaction.deferUpdate();
76
+ if (!(await card.audience.allows(by.user))) {
77
+ await interaction.followUp(ephemeral(card.audience.refusal));
78
+ return;
79
+ }
57
80
  const answer = {
58
- choices: card.picked ?? [],
81
+ choices: card.picked.get(userId) ?? [],
59
82
  text: interaction.fields.getTextInputValue(TEXT_FIELD),
60
83
  };
61
- card.end(answer, by);
84
+ if (!card.end(answer, by)) {
85
+ await interaction.followUp(ephemeral(messages().cardInactive));
86
+ return;
87
+ }
62
88
  if (interaction.isFromMessage())
63
- await interaction.update(card.view(answeredLine(answer)));
64
- else await interaction.deferUpdate();
89
+ await interaction.editReply(card.view(answeredLine(answer)));
65
90
  }
66
91
  }
67
92
 
@@ -143,9 +168,11 @@ export async function answerDeferred(
143
168
  const { texts, note } = formFields(form, (field) =>
144
169
  interaction.fields.getTextInputValue(field),
145
170
  );
171
+ const own: Written = { texts: [] };
146
172
  for (const [i, value] of texts)
147
- form.draft.texts[i] = value.trim() || undefined;
148
- form.draft.note = note.trim() || undefined;
173
+ form.draft.texts[i] = own.texts[i] = value.trim() || undefined;
174
+ form.draft.note = own.note = note.trim() || undefined;
175
+ form.written.set(by.user.id, own);
149
176
  }
150
177
  if (!submits) {
151
178
  card.touch();
@@ -164,17 +191,22 @@ export async function answerDeferred(
164
191
  await interaction.editReply(card.view(endedFooter(card)));
165
192
  }
166
193
 
167
- /** "Write answers / note…": opens the form, which a modal cannot defer; the audience was checked. */
194
+ /**
195
+ * "Write answers / note…": opens the form at once, since nothing may be awaited before a form is
196
+ * shown; the audience is checked when it is submitted (`answerDeferred`). The form holds only
197
+ * what this user wrote before, so it shows no one else's unsent text.
198
+ */
168
199
  export async function answerForm(
169
200
  card: OpenCard,
170
201
  id: string,
171
202
  action: string,
172
203
  interaction: Interaction,
204
+ by: Answerer,
173
205
  ): Promise<void> {
174
206
  if (!card.form || !interaction.isButton() || action !== "notes") return;
175
207
  if (!card.isOpen()) {
176
208
  await interaction.reply(ephemeral(messages().cardInactive));
177
209
  return;
178
210
  }
179
- await interaction.showModal(questionnaireModal(id, card.form));
211
+ await interaction.showModal(questionnaireModal(id, card.form, by.user.id));
180
212
  }
@@ -117,6 +117,7 @@ export function askPrompts(args: {
117
117
  const form: QuestionnaireForm = {
118
118
  questionnaire,
119
119
  draft: newDraft(questionnaire.questions.length),
120
+ written: new Map(),
120
121
  };
121
122
  return post<QuestionnaireAnswer | "pending" | "declined" | undefined>(
122
123
  channelId,
@@ -0,0 +1,108 @@
1
+ import { type Interaction, MessageFlags } from "discord.js";
2
+ import { messages } from "../i18n/index.ts";
3
+ import type { Logger } from "../kernel/log.ts";
4
+ import type { DiscordUser } from "./discord-owners.ts";
5
+ import type { Answerer, OpenCard } from "./owner-card-types.ts";
6
+
7
+ const ephemeral = (content: string) => ({
8
+ content,
9
+ flags: MessageFlags.Ephemeral as const,
10
+ });
11
+
12
+ /** The interaction methods one of which is a press's first response to Discord. */
13
+ const RESPONSES = [
14
+ "reply",
15
+ "update",
16
+ "showModal",
17
+ "deferUpdate",
18
+ "deferReply",
19
+ ] as const;
20
+
21
+ /**
22
+ * Calls `first` once, as the press makes its first response to Discord, whichever it is. Discord
23
+ * drops a press with no response within three seconds ("This interaction failed"), so this is
24
+ * what the card's press log times.
25
+ */
26
+ export function onFirstResponse(
27
+ interaction: Interaction,
28
+ first: () => void,
29
+ ): void {
30
+ let called = false;
31
+ const target = interaction as unknown as Record<string, unknown>;
32
+ for (const name of RESPONSES) {
33
+ const method = target[name];
34
+ if (typeof method !== "function") continue;
35
+ target[name] = (...args: unknown[]) => {
36
+ if (!called) {
37
+ called = true;
38
+ first();
39
+ }
40
+ return (method as (...a: unknown[]) => unknown).apply(interaction, args);
41
+ };
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Approve or Decline on an approval card. The press is deferred before the audience and the
47
+ * approver are read, which may take a while; someone else is told so and the card is unchanged.
48
+ */
49
+ export async function answerApproval(
50
+ card: OpenCard,
51
+ approved: boolean,
52
+ interaction: Interaction,
53
+ user: DiscordUser,
54
+ by: Answerer,
55
+ logger: Logger,
56
+ ): Promise<void> {
57
+ if (!interaction.isButton()) return;
58
+ await interaction.deferUpdate();
59
+ if (!(await card.audience.allows(user))) {
60
+ await interaction.followUp(ephemeral(card.audience.refusal));
61
+ return;
62
+ }
63
+ const approver = approved
64
+ ? await card.audience.approver?.(user).catch((error: unknown) => {
65
+ logger.warn(
66
+ { err: error },
67
+ "could not tell who approved; the call runs without an approver",
68
+ );
69
+ return undefined;
70
+ })
71
+ : undefined;
72
+ const accepted = card.end(
73
+ approved ? "approved" : "declined",
74
+ approver ? { ...by, approver } : by,
75
+ );
76
+ // The plugin withdrew the call, or another press answered, while this one was being checked.
77
+ if (!accepted) {
78
+ await interaction.followUp(ephemeral(messages().cardInactive));
79
+ return;
80
+ }
81
+ await interaction.editReply(
82
+ card.view(
83
+ approved
84
+ ? (card.outcomes?.approved ?? messages().cardApproved)
85
+ : (card.outcomes?.declined ?? messages().cardDeclined),
86
+ ),
87
+ );
88
+ }
89
+
90
+ /** A question card's Cancel, deferred before the audience is read. */
91
+ export async function cancelQuestion(
92
+ card: OpenCard,
93
+ interaction: Interaction,
94
+ user: DiscordUser,
95
+ ): Promise<void> {
96
+ if (!interaction.isButton()) return;
97
+ await interaction.deferUpdate();
98
+ if (!(await card.audience.allows(user))) {
99
+ await interaction.followUp(ephemeral(card.audience.refusal));
100
+ return;
101
+ }
102
+ // Another press, a stop or a withdrawal ended it while this one was being checked.
103
+ if (!card.decline()) {
104
+ await interaction.followUp(ephemeral(messages().cardInactive));
105
+ return;
106
+ }
107
+ await interaction.editReply(card.view(messages().cardQuestionCancelled));
108
+ }