1
0
Fork 0

Compare commits

...

4 commits

Author SHA1 Message Date
9f192a8159 v0.15.1 - fix Discord bot crash on stale interactions 2026-11-03 12:51:35 -05:00
8108465354 docs: add v0.15.1 changelog entry 2026-11-03 12:50:36 -05:00
6ee32f5085 docs(bot): record the interaction ack and error-path rules 2026-11-03 12:50:29 -05:00
c4cbe43c4f fix(bot): survive a stale Discord interaction instead of crashing
A manual /rollcall took the bot down: the command fetched the guild member
and ran the staff check before acknowledging, missed Discord's 3 second ack
window, then died on "Unknown interaction" when it tried to defer (and again
when the error path tried to reply). discord.js re-emits a rejected event
listener on the client as an 'error' event, and with no handler attached Node
threw and exited the process.

Ack first, protect the error paths:
- /rollcall, /remind-evaluations and /debug defer immediately and report
  permission denials through editReply.
- safeEphemeralReply (bot/lib/interactions.ts) never rethrows, and the RSVP
  and transfer handlers use the same guarded behaviour.
- client.on(Events.Error) logs instead of exiting. The entrypoint restarts a
  dead bot after 5 seconds, so the previous symptom was a silent gap.
2026-11-03 12:50:29 -05:00
11 changed files with 202 additions and 53 deletions

View file

@ -1,5 +1,14 @@
# Changelog
# v0.15.1
### Fixes
- Roll-call buttons and Discord DMs no longer go quiet when a bot command fails.
- Various bug fixes and improvements.
---
# v0.15.0
Mission detail is restyled as bordered dossier cards with classification strips, a new command-chain editor lets staff assign command hierarchy and drive command reviews, and faction chips become links with cover-image backgrounds.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.15.0",
"version": "0.15.1",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -48,6 +48,7 @@ bot/
lib/
debugActions.ts # /debug action registry: each action builds the production message and sends it live
interactions.ts # safeEphemeralReply: error-path reply that never throws (stale interaction = 10062)
roles.ts # isStaff check
resolve.ts # discordId ↔ Payload user lookups
transferMessaging.ts # Transfer embed builders + delivery keys
@ -132,9 +133,20 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |
| Rich Presence reconcile loop / mapping | `bot/services/discordPresence.ts` + `bot/lib/presence.ts` |
## Interaction reliability
Discord kills an interaction token that is not acknowledged within **3 seconds**: the user sees "The application did not respond", and every later reply (`deferReply` included) fails with `DiscordAPIError: Unknown interaction` (10062). Two rules follow, both enforced by `tests/int/bot-commands.int.spec.ts`:
1. **Ack first, then work.** Guild commands must `deferReply` as their first Discord call, before `guild.members.fetch()` and `isStaff()`. `/rollcall`, `/remind-evaluations`, and `/debug` defer up front and report permission denials through `editReply`. Commands that must open a modal (`/announce`, `/changelog edit=true`, `/discord-presence edit`) cannot defer, so their staff check runs before the modal and the modal is the very next call.
2. **Error paths never reply unguarded.** A reply inside a `catch` throws whenever the interaction is already dead, and that rejection is what crashed the process on 2026-11-03. Use `safeEphemeralReply()` (`lib/interactions.ts`) or a local try/catch.
`client.on(Events.Error)` in `index.ts` is the last line of defence: discord.js re-emits any rejected event listener on the client, and without a handler Node throws and the whole bot exits (the entrypoint then restarts it after 5s, so the symptom is a silent gap, not a visible crash).
## Anti-patterns
- **NEVER** run bot and web app with separate database connections without connection pooling — they share PostgreSQL
- **NEVER** register guild-only commands if the command needs to work in DMs (signup, link, ping must be global)
- **NEVER** assume DM delivery succeeded — `/signup` uses ephemeral reply as primary delivery path
- **NEVER** modify `discordId` directly in Payload admin — use the `/link` command or the resolve helper
- **NEVER** fetch the guild member or run `isStaff` before `deferReply` on a guild command; that is a 3-second ack race and produces "The application did not respond"
- **NEVER** `await interaction.reply(...)` directly inside a catch block; use `safeEphemeralReply` so a stale interaction (10062) cannot take the bot down

View file

@ -171,9 +171,7 @@ const runDelete = async (
const runList = (): string =>
debugActions
.map((action) => {
const modes = ["preview", action.live ? "live" : null, "sandbox"]
.filter(Boolean)
.join(", ");
const modes = ["preview", action.live ? "live" : null, "sandbox"].filter(Boolean).join(", ");
return `**${action.name}**: ${action.description}\n target: ${action.targetHint}\n modes: ${modes}`;
})
.join("\n\n");
@ -188,9 +186,7 @@ export const debugCommand: BotCommand = {
builder: new SlashCommandBuilder()
.setName("debug")
.setDescription("Preview, sandbox, or live-repost bot messages (staff only)")
.addSubcommand((sub) =>
sub.setName("list").setDescription("List the debuggable bot actions"),
)
.addSubcommand((sub) => sub.setName("list").setDescription("List the debuggable bot actions"))
.addSubcommand((sub) =>
sub
.setName("run")
@ -221,10 +217,7 @@ export const debugCommand: BotCommand = {
option
.setName("method")
.setDescription("Live roll-call only: edit the existing message, or repost a fresh one")
.addChoices(
{ name: "edit", value: "edit" },
{ name: "repost", value: "repost" },
),
.addChoices({ name: "edit", value: "edit" }, { name: "repost", value: "repost" }),
),
)
.addSubcommand((sub) =>
@ -262,22 +255,22 @@ export const debugCommand: BotCommand = {
return;
}
// Ack before the member fetch + permission check so a slow Discord REST
// call cannot expire the interaction (see /rollcall).
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!(await isStaff(member, payload))) {
await interaction.reply({
content: "You don't have permission to use debug.",
flags: MessageFlags.Ephemeral,
});
await interaction.editReply("You don't have permission to use debug.");
return;
}
const subcommand = interaction.options.getSubcommand();
if (subcommand === "list") {
await interaction.reply({ content: runList(), flags: MessageFlags.Ephemeral });
await interaction.editReply({ content: runList() });
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const client = interaction.client as Client;
const actionName = interaction.options.getString("action", true);
const target = interaction.options.getString("target")?.trim() || undefined;
@ -300,9 +293,7 @@ export const debugCommand: BotCommand = {
return;
}
const state = await action.inspect(payload, target);
await interaction.editReply(
"```json\n" + JSON.stringify(state, null, 2) + "\n```",
);
await interaction.editReply("```json\n" + JSON.stringify(state, null, 2) + "\n```");
return;
}

View file

@ -64,17 +64,16 @@ export const remindEvaluationsCommand: BotCommand = {
return;
}
// Ack before the member fetch + permission check so a slow Discord REST
// call cannot expire the interaction (see /rollcall).
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!(await isStaff(member, payload))) {
await interaction.reply({
content: "You don't have permission to trigger evaluation reminders.",
flags: MessageFlags.Ephemeral,
});
await interaction.editReply("You don't have permission to trigger evaluation reminders.");
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const client = interaction.client as Client;
const missionInput = interaction.options.getString("mission")?.trim();

View file

@ -31,17 +31,17 @@ export const rollCallCommand: BotCommand = {
return;
}
// Acknowledge before the member fetch and permission check: Discord drops an
// interaction that is not acked within 3 seconds, and deferring afterwards
// fails with "Unknown interaction" (10062) even for a legitimate caller.
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const member = await interaction.guild.members.fetch(interaction.user.id);
if (!(await isStaff(member, payload))) {
await interaction.reply({
content: "You don't have permission to trigger roll-calls.",
flags: MessageFlags.Ephemeral,
});
await interaction.editReply("You don't have permission to trigger roll-calls.");
return;
}
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
const client = interaction.client as Client;
const missionInput = interaction.options.getString("mission")?.trim();

View file

@ -1,6 +1,7 @@
import { type ButtonInteraction, MessageFlags } from "discord.js";
import type { Payload } from "payload";
import { findUserByDiscordId } from "@/bot/lib/resolve";
import { safeEphemeralReply } from "@/bot/lib/interactions";
import {
attendanceHash,
buildAttendanceRow,
@ -112,10 +113,11 @@ export const handleButtonInteraction = async (
`[Bot] RSVP interaction failed for mission #${missionId}: ${errorMessage(error)}`,
);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: "Something went wrong while updating your attendance.",
flags: MessageFlags.Ephemeral,
});
await safeEphemeralReply(
interaction,
payload,
"Something went wrong while updating your attendance.",
);
}
}
};

View file

@ -43,8 +43,18 @@ const parseTransferInteraction = (customId: string): ParsedTransferInteraction |
return { requestId, action };
};
const replyEphemeral = (interaction: TransferInteraction, content: string): Promise<unknown> =>
interaction.reply({ content, flags: MessageFlags.Ephemeral });
// Interaction replies fail with DiscordAPIError 10062 "Unknown interaction" once
// Discord has dropped the token (a stale button press, or a click that arrives
// after the 15 minute window). Never let that surface as an unhandled rejection:
// discord.js re-emits it on the client as an 'error' event.
const replyEphemeral = async (interaction: TransferInteraction, content: string): Promise<void> => {
try {
await interaction.reply({ content, flags: MessageFlags.Ephemeral });
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
console.error(`[Bot] Could not deliver a transfer interaction reply: ${message}`);
}
};
const currentLeaderSide = async (
payload: Payload,
@ -102,16 +112,17 @@ const editOutcome = async ({
}: OutcomeEdit): Promise<void> => {
if (!interaction.message) return;
const row =
outcome === "appealed"
? appealRow(requestId, true)
: transferDecisionRow(requestId, true);
outcome === "appealed" ? appealRow(requestId, true) : transferDecisionRow(requestId, true);
await interaction.message.edit({
embeds: [decisionOutcomeEmbed(outcome, status, reason)],
components: [row],
});
};
const showRejectModal = async (interaction: ButtonInteraction, requestId: number): Promise<void> => {
const showRejectModal = async (
interaction: ButtonInteraction,
requestId: number,
): Promise<void> => {
const reason = new TextInputBuilder()
.setCustomId(REJECTION_REASON_ID)
.setStyle(TextInputStyle.Paragraph)

View file

@ -1,4 +1,4 @@
import { Client, Events, GatewayIntentBits, MessageFlags } from "discord.js";
import { Client, Events, GatewayIntentBits } from "discord.js";
import { getPayload } from "payload";
import config from "@payload-config";
import { botConfig } from "./config";
@ -9,9 +9,13 @@ import { handlePresenceModal } from "./commands/discordPresence";
import { services } from "./services";
import { handleButtonInteraction } from "./events/interactionCreate";
import { handleTransferInteraction } from "./events/transferInteractions";
import { safeEphemeralReply } from "./lib/interactions";
// Usage: `bun run bot`. Standalone long-running process; connects to Discord
// and shares the Postgres database with the web app via the Payload config.
const errorMessageOf = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const main = async () => {
const payload = await getPayload({ config });
@ -19,6 +23,15 @@ const main = async () => {
intents: [GatewayIntentBits.Guilds],
});
// discord.js emits 'error' on the client whenever an event listener rejects
// (interactions, gateway hiccups, REST failures). Node's default for an
// unhandled 'error' event is to throw, which took the whole process down: a
// single stale interaction (DiscordAPIError 10062 "Unknown interaction")
// killed the bot for a minute. Log and keep running instead.
client.on(Events.Error, (error) => {
payload.logger.error(`[Bot] Discord client error: ${errorMessageOf(error)}`);
});
let shuttingDown = false;
const shutdown = async (signal: NodeJS.Signals): Promise<void> => {
if (shuttingDown) {
@ -105,13 +118,15 @@ const main = async () => {
try {
await execute(interaction, payload);
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
payload.logger.error(`[Bot] Error executing /${interaction.commandName}: ${message}`);
payload.logger.error(
`[Bot] Error executing /${interaction.commandName}: ${errorMessageOf(error)}`,
);
if (!interaction.replied && !interaction.deferred) {
await interaction.reply({
content: "Something went wrong while running this command.",
flags: MessageFlags.Ephemeral,
});
await safeEphemeralReply(
interaction,
payload,
"Something went wrong while running this command.",
);
}
}
});

View file

@ -0,0 +1,32 @@
import { MessageFlags, type RepliableInteraction } from "discord.js";
import type { Payload } from "payload";
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
/**
* Reply ephemerally without ever letting the reply itself throw.
*
* Discord invalidates an interaction token once it has been answered (or once
* the 15-minute window closes), so a second reply - or any reply to an
* interaction Discord already dropped - fails with `DiscordAPIError: Unknown
* interaction` (10062). An unguarded reply inside a catch block turns that into
* an unhandled rejection which discord.js re-emits on the client, and the
* missing `client.on(Events.Error)` handler then killed the whole bot process.
* Error paths must never take the bot down with them, so this swallows (and
* logs) delivery failures.
*/
export const safeEphemeralReply = async (
interaction: RepliableInteraction,
payload: Payload,
content: string,
): Promise<void> => {
const label = interaction.isChatInputCommand() ? `/${interaction.commandName}` : "interaction";
try {
await interaction.reply({ content, flags: MessageFlags.Ephemeral });
} catch (error) {
payload.logger.error(
`[Bot] Could not deliver an ephemeral reply for ${label}: ${errorMessage(error)}`,
);
}
};

View file

@ -39,16 +39,19 @@ describe("Bot slash command builders", () => {
const { commands } = await import("@/bot/commands");
const registered = new Set(commands.map((c) => c.builder.name));
const files = fs
.readdirSync(dir)
.filter((file) => file.endsWith(".ts") && file !== "index.ts");
const files = fs.readdirSync(dir).filter((file) => file.endsWith(".ts") && file !== "index.ts");
expect(files.length).toBeGreaterThanOrEqual(7);
for (const file of files) {
const mod = (await import(path.join(dir, file))) as Record<string, unknown>;
for (const value of Object.values(mod)) {
const candidate = value as { builder?: { name?: string }; execute?: unknown };
if (candidate && typeof candidate === "object" && candidate.builder?.name && candidate.execute) {
if (
candidate &&
typeof candidate === "object" &&
candidate.builder?.name &&
candidate.execute
) {
expect(
registered.has(candidate.builder.name),
`/${candidate.builder.name} (${file}) is not in the commands registry`,
@ -58,3 +61,78 @@ describe("Bot slash command builders", () => {
}
});
});
/**
* A slash command has three seconds to acknowledge an interaction. Deferring
* after a member fetch and a permission check misses that window often enough
* that Discord drops the token: the command then fails with "This application
* did not respond" and any later reply throws DiscordAPIError 10062,
* "Unknown interaction". That unhandled rejection used to kill the bot process
* (see the 2026-11-03 /rollcall crash).
*/
describe("Bot interaction acknowledgement", () => {
process.env.DISCORD_TOKEN ||= "regression-test-token";
process.env.DISCORD_GUILD_ID ||= "123456789012345678";
const fakePayload = {
logger: { error: () => undefined, info: () => undefined, warn: () => undefined },
};
it("/rollcall defers before the member fetch and permission check", async () => {
const { rollCallCommand } = await import("@/bot/commands/rollcall");
const calls: string[] = [];
const interaction = {
inGuild: () => true,
guild: {
members: {
fetch: async () => {
calls.push("members.fetch");
throw new Error("Discord REST call timed out");
},
},
},
user: { id: "123456789012345678" },
client: {},
deferReply: async () => {
calls.push("deferReply");
},
editReply: async () => {
calls.push("editReply");
},
reply: async () => {
calls.push("reply");
},
options: { getString: () => null },
};
await expect(
rollCallCommand.execute(interaction as never, fakePayload as never),
).rejects.toThrow("Discord REST call timed out");
expect(calls[0]).toBe("deferReply");
expect(calls).not.toContain("reply");
});
it("safeEphemeralReply never rethrows a stale-interaction failure", async () => {
const { safeEphemeralReply } = await import("@/bot/lib/interactions");
const logged: string[] = [];
const interaction = {
commandName: "rollcall",
isChatInputCommand: () => true,
reply: async () => {
throw new Error("Unknown interaction");
},
};
await expect(
safeEphemeralReply(
interaction as never,
{
logger: { error: (line: string) => logged.push(line) },
} as never,
"Something went wrong while running this command.",
),
).resolves.toBeUndefined();
expect(logged.join("\n")).toContain("Unknown interaction");
});
});