diff --git a/src/bot/AGENTS.md b/src/bot/AGENTS.md index ec561e81..054d5cfd 100644 --- a/src/bot/AGENTS.md +++ b/src/bot/AGENTS.md @@ -98,6 +98,10 @@ An NPC `event` node with the `poll` effect raises a unit-wide poll: `launchDialo **Ties**: `tallyPoll` weights votes by the highest matching role tier, then `resolvePollTally` gives a tie to the conversation initiator when exactly one tied option is on their ballot. Otherwise the poll parks in `pending_decision` with the tally frozen, the buttons disable, and a superuser settles it on `/polls/[id]`; `resolveDeadlineTie` picks a random tied option once `tieGraceHours` passes. Only a resolved poll writes its `resultFlag`. +## Button routing (never-miss) + +The `InteractionCreate` dispatcher in `index.ts` forwards a button only when its customId matches a prefix the handler claims. That list lives with the handler (`UNIT_BUTTON_PREFIXES` / `isUnitButtonCustomId` in `events/interactionCreate.ts`) and the dispatcher reads it, so adding a branch there is enough. Do not re-check a prefix by hand in the dispatcher: poll buttons shipped handled-but-unrouted, which left every press unacknowledged and Discord answered the member with "This interaction failed" while the same vote worked on the web. A `ptf-` button nothing claims now replies with a toast and logs `[Bot] Unhandled button interaction`, so the next gap is loud instead of silent. Any button that runs a database call must `deferReply` first; the interaction token dies at 3 seconds. + ## Feature flow: notifications `notificationBridge` polls `user-notifications` (cursor = last seen id; cap 5 DMs/tick). DMs opted-in users (`preferences.discord.enabled`, not in `mutedTypes`). Remaining polish: the web preferences UI does not yet expose the `preferences.discord` toggles — they exist on the Users collection and are read by the bridge, but are currently only settable in the Payload admin panel. diff --git a/src/bot/events/interactionCreate.ts b/src/bot/events/interactionCreate.ts index f9880cdf..4e968083 100644 --- a/src/bot/events/interactionCreate.ts +++ b/src/bot/events/interactionCreate.ts @@ -19,6 +19,25 @@ import { setMissionAttendance, } from "@/lib/attendance"; +/** + * customId prefixes this handler answers to. The InteractionCreate dispatcher + * in `index.ts` routes exactly these here, and it reads this same list, so a + * prefix cannot be handled below and unreachable above: an unrouted button is + * never acknowledged, and Discord shows the user "This interaction failed". + */ +const BARE_PREFIX = { + attendance: "ptf-att", + poll: "ptf-poll", + rating: "ptf-rate", +} as const; + +export const UNIT_BUTTON_PREFIXES: readonly string[] = Object.values(BARE_PREFIX).map( + (prefix) => `${prefix}:`, +); + +export const isUnitButtonCustomId = (customId: string): boolean => + UNIT_BUTTON_PREFIXES.some((prefix) => customId.startsWith(prefix)); + const ATTENDANCE_LABELS: Record = { yes: "Yes", no: "No", @@ -38,7 +57,7 @@ export const handleButtonInteraction = async ( const parts = interaction.customId.split(":"); // Post-op survey rating prompt: link back to the mission page to rate. - if (parts.length === 3 && parts[0] === "ptf-rate") { + if (parts.length === 3 && parts[0] === BARE_PREFIX.rating) { const missionId = Number(parts[1]); if (!Number.isInteger(missionId)) return; try { @@ -57,7 +76,7 @@ export const handleButtonInteraction = async ( // Unit poll buttons. Acknowledge first: resolving the Discord member to a // Payload user is a database call, and the interaction token dies at 3s. - if (parts.length === 3 && parts[0] === "ptf-poll") { + if (parts.length === 3 && parts[0] === BARE_PREFIX.poll) { const pollId = Number(parts[1]); const optionKey = parts[2]; if (!Number.isInteger(pollId) || !optionKey) return; @@ -146,7 +165,7 @@ export const handleButtonInteraction = async ( } // Attendance roll-call buttons. - if (parts.length !== 3 || parts[0] !== "ptf-att") { + if (parts.length !== 3 || parts[0] !== BARE_PREFIX.attendance) { return; } const missionId = Number(parts[1]); diff --git a/src/bot/index.ts b/src/bot/index.ts index 655e41a8..435cde67 100644 --- a/src/bot/index.ts +++ b/src/bot/index.ts @@ -7,7 +7,7 @@ import { handleAnnounceModal } from "./commands/announce"; import { handleChangelogEditModal } from "./commands/changelog"; import { handlePresenceModal } from "./commands/discordPresence"; import { services } from "./services"; -import { handleButtonInteraction } from "./events/interactionCreate"; +import { handleButtonInteraction, isUnitButtonCustomId } from "./events/interactionCreate"; import { handleTransferInteraction } from "./events/transferInteractions"; import { safeEphemeralReply } from "./lib/interactions"; @@ -85,7 +85,9 @@ const main = async () => { }); client.on(Events.InteractionCreate, async (interaction) => { - if (interaction.isButton() && interaction.customId.startsWith("ptf-att:")) { + // The handler owns the prefix list, so a button it answers to can never be + // filtered out here first (that silent gap is what made poll buttons fail). + if (interaction.isButton() && isUnitButtonCustomId(interaction.customId)) { await handleButtonInteraction(interaction, payload); return; } @@ -108,6 +110,16 @@ const main = async () => { await handlePresenceModal(interaction, payload); return; } + // A ptf button no branch above claimed. Acknowledge it so the user sees a + // sentence instead of Discord's "This interaction failed", and log the id + // so a prefix missing from the routing above is visible instead of silent. + if (interaction.isButton() && interaction.customId.startsWith("ptf-")) { + payload.logger.warn( + `[Bot] Unhandled button interaction: ${interaction.customId.slice(0, 80)}`, + ); + await safeEphemeralReply(interaction, payload, "This button is no longer handled."); + return; + } if (!interaction.isChatInputCommand()) { return; } diff --git a/tests/int/bot-button-routing.int.spec.ts b/tests/int/bot-button-routing.int.spec.ts new file mode 100644 index 00000000..e133a8b7 --- /dev/null +++ b/tests/int/bot-button-routing.int.spec.ts @@ -0,0 +1,90 @@ +import { beforeAll, describe, expect, it } from "vitest"; + +// The bot modules validate their environment at import time. +process.env.DISCORD_TOKEN ||= "routing-test-token"; +process.env.DISCORD_GUILD_ID ||= "1"; +process.env.APP_URL ||= "https://polaris.test"; + +import type { Poll } from "@/payload-types"; + +type InteractionCreate = typeof import("@/bot/events/interactionCreate"); +type PollEmbeds = typeof import("@/bot/services/pollEmbeds"); + +let routing: InteractionCreate; +let embeds: PollEmbeds; + +beforeAll(async () => { + routing = await import("@/bot/events/interactionCreate"); + embeds = await import("@/bot/services/pollEmbeds"); +}); + +const poll = (): Poll => + ({ + id: 9, + title: "Question", + options: [ + { key: "agree", label: "Agree", emoji: null, description: null, id: "a" }, + { key: "decline", label: "Decline", emoji: null, description: null, id: "b" }, + ], + status: "open", + closesAt: new Date(Date.now() + 3_600_000).toISOString(), + multiSelect: false, + anonymity: "public", + defaultWeight: 1, + weightTiers: [], + tieGraceHours: 24, + sourceKey: "1:node", + openedAt: new Date().toISOString(), + initiatedBy: 1, + eligibleRoles: [], + updatedAt: "", + createdAt: "", + }) as unknown as Poll; + +/** + * The bot dispatcher only forwards buttons whose customId it recognises, and an + * unrecognised button is never acknowledged: Discord then tells the member + * "This interaction failed". Poll buttons shipped without being added to that + * routing list, so they did exactly that in production while the web page kept + * working. These cases pin the two halves together. + */ +describe("Bot button routing", () => { + it("routes every prefix the button handler answers to", () => { + for (const customId of ["ptf-att:1:yes", "ptf-poll:1:agree", "ptf-rate:112:rate"]) { + expect(routing.isUnitButtonCustomId(customId)).toBe(true); + } + expect(routing.UNIT_BUTTON_PREFIXES).toEqual([ + "ptf-att:", + "ptf-poll:", + "ptf-rate:", + ]); + }); + + it("routes the exact customIds the poll message builds", () => { + const rows = embeds.buildPollRows(poll()).map((row) => row.toJSON()); + + const customIds = rows.flatMap((row) => + row.components.map((component) => String((component as { custom_id?: string }).custom_id)), + ); + expect(customIds).toEqual(["ptf-poll:9:agree", "ptf-poll:9:decline"]); + for (const customId of customIds) { + expect(routing.isUnitButtonCustomId(customId)).toBe(true); + } + }); + + it("leaves the other handlers' buttons to their own branches", () => { + for (const customId of [ + "ptf-xfer:4:accept", + "ptf-announce:compose", + "ptf-changelog-edit:abc", + "ptf-rp-edit", + ]) { + expect(routing.isUnitButtonCustomId(customId)).toBe(false); + } + }); + + it("ignores anything without a ptf prefix", () => { + expect(routing.isUnitButtonCustomId("something-else")).toBe(false); + expect(routing.isUnitButtonCustomId("")).toBe(false); + }); +});