1
0
Fork 0

feat(bot): autocomplete changelog versions and add a pending range

This commit is contained in:
Jason Fraley 2026-12-02 10:55:22 -05:00
parent f478f38938
commit 5230c38ec8
8 changed files with 550 additions and 24 deletions

View file

@ -23,7 +23,7 @@ bot/
signup.ts # /signup (DM-only, creates Payload user with temp password)
link.ts # /link (global, links discordId to existing user)
announce.ts # /announce (guild-only, staff only; message omitted = compose modal with channel picker, handler in this file)
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries; edit=true opens a prefilled modal to tweak the copy before posting)
changelog.ts # /changelog (guild-only, staff only; posts a CHANGELOG.md entry to #releases, native markdown, splits long entries; edit=true opens a prefilled modal to tweak the copy before posting; range autocompletes versions and `pending`)
remindEvaluations.ts # /remind-evaluations (guild-only, staff only, manual evaluation-reminder trigger)
rollcall.ts # /rollcall (guild-only, staff only, force-send/refresh a roll-call)
discordPresence.ts # /discord-presence (guild-only, discord:rp:update; view/edit/clear the bot's Rich Presence via a prefilled modal)
@ -69,6 +69,10 @@ bot/
`/changelog` (guild-only, staff only) posts a `CHANGELOG.md` release entry to the releases channel (`DISCORD_CHANGELOG_CHANNEL_ID`, falling back to `DISCORD_ANNOUNCE_CHANNEL_ID`). `/changelog` targets the newest entry; `/changelog v0.4.0` targets a specific version (for catching up on missed posts); `/changelog v0.3.0..v0.5.0` targets a range (inclusive slice, output oldest-to-newest). Either range end is open (`v0.3.0..` to the latest, `..v0.5.0` from the oldest) and a reversed range is normalized. **Edit mode** (`edit=true`): instead of posting, opens a modal prefilled with the target entry's raw markdown so staff can make last-minute copy tweaks right in Discord; submit renders the edited text through the same pipeline and posts it. One-shot by design: the edit shapes only the post about to happen, `CHANGELOG.md` (baked into the deployed image) is never written back. Single-version targets only (ranges are rejected ephemerally), entries over the 4000-char modal input cap refuse edit mode with a pointer to the file. The modal must be the first response, so the edit path checks staff and shows the modal WITHOUT deferring (same pattern as `/announce`); submits route through `bot/index.ts` on the `ptf-changelog-edit:` custom-id prefix and re-check staff. Rendering lives in `bot/lib/changelogRender.ts` (pure, no Discord/Payload deps): entries are split on `# vX.Y.Z` headers, `### ` sections become Discord markdown headings (`### `, the deepest level Discord renders), bullets become `•`, and entries over Discord's 4096-char limit are split across messages at section boundaries. The command reads `CHANGELOG.md` from the repo root relative to the file (works from the deploy server) and posts each version as its own amber embed, the first message of each version carrying the `Changelog vX.Y.Z` title and multi-message versions adding a page footer. Ranges spanning more than `WIDE_RANGE_THRESHOLD` (10) versions post an ephemeral warning but proceed. Idempotency ("don't repost") is intentionally out of scope for the manual command; the same rendering can be reused by a future automatic trigger.
**Autocomplete** (`range` is registered with `setAutocomplete(true)`): `buildRangeChoices` in `bot/lib/changelogRender.ts` offers `pending` first, then versions newest-first, filtered by what has been typed (a leading `v` is optional) and labelled `· posted` or `· pending` from the watermark. Discord allows 25 choices, so the empty-input list is `pending` plus the 24 newest versions; typing a prefix narrows it. `BotCommand.autocomplete` is the optional handler member, and the router in `bot/index.ts` answers `respond([])` whenever a handler rejects or never answers, because an unanswered autocomplete shows "Loading options failed" and its rejection would otherwise escape.
**`pending`** posts everything newer than the last changelog already in the releases channel. The watermark is read back from the bot's own `Changelog vX.Y.Z` embed titles by `detectPostedThrough` (walks back up to 3 x 100 messages, newest match wins so a late backfill never rewinds it), cached per channel for 10 minutes, and refreshed by `postVersion` after any post, which covers the manual command, the edit modal and `/debug live`. The scan needs **Read Message History** in the releases channel; without it the command says so and points at an explicit range. An unknown watermark refuses with a pointer to an explicit range rather than posting the whole file, and `edit=true` rejects `pending` the way it rejects ranges. Gaps below the watermark are not detected: a bounded message scan cannot tell a skipped version from one that aged out of the window.
## Feature flow: debug
`/debug` (guild-only, `isStaff`) re-renders or re-sends bot messages through the production render and send code, so a test exercises what actually ships. Subcommands: `list`, `run action target mode`, `inspect action target`, `delete action target`.
@ -136,7 +140,7 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
| Task | Path |
|------|------|
| Add new slash command | `bot/commands/<name>.ts` + register in `bot/commands/index.ts` |
| Changelog rendering/splitting | `bot/lib/changelogRender.ts` |
| Changelog rendering/splitting/version choices | `bot/lib/changelogRender.ts` |
| Add button interaction | `bot/events/interactionCreate.ts` (RSVP) or `transferInteractions.ts` (transfers) |
| Modify embed lifecycle | `bot/services/missionEmbeds.ts` |
| Force a roll-call manually | `bot/commands/rollcall.ts` + `src/lib/intelligence/rollCall.ts` |
@ -156,6 +160,7 @@ Discord kills an interaction token that is not acknowledged within **3 seconds**
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.
3. **Autocomplete answers or says nothing.** Discord wants 25 choices within the same 3 seconds, and an unanswered autocomplete renders "Loading options failed". Handlers must stay cheap (cache anything network-bound) and the router answers `respond([])` on rejection, so a broken handler shows an empty list instead of a stuck dropdown.
`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).

View file

@ -7,7 +7,9 @@ import {
TextInputBuilder,
TextInputStyle,
type ChatInputCommandInteraction,
type Collection,
type InteractionReplyOptions,
type Message,
type ModalSubmitInteraction,
type TextBasedChannelFields,
type Guild,
@ -20,10 +22,16 @@ import type { BotCommand } from "./index";
import { botConfig } from "@/bot/config";
import { isStaff } from "@/bot/lib/roles";
import {
PENDING_TOKEN,
buildRangeChoices,
changelogEmbedTitle,
compareVersions,
parseChangelog,
resolveChangelog,
resolveChangelogRange,
resolvePendingChangelog,
splitForDiscord,
versionFromEmbedTitle,
type ResolvedChangelog,
type ChangelogBatch,
} from "@/bot/lib/changelogRender";
@ -49,6 +57,32 @@ const ENTRY_INPUT_ID = "entry";
/** Discord caps modal text inputs at 4000 characters. */
const MODAL_INPUT_MAX = 4000;
/** How many 100-message pages the last-posted scan walks back from the newest. */
const POSTED_SCAN_PAGES = 3;
/** How long a resolved watermark is trusted; autocomplete reads it on every keystroke. */
const POSTED_SCAN_TTL_MS = 10 * 60 * 1000;
/**
* The slice of a channel the last-posted scan needs. `TextBasedChannelFields`
* types `messages` as a union of guild and DM managers whose fetch overloads do
* not unify, so the scan takes the narrow shape it actually calls.
*/
export type ChangelogChannel = TextBasedChannelFields & {
id: string;
messages: {
fetch(options: { limit: number; before?: string }): Promise<Collection<string, Message>>;
};
};
interface PostedWatermark {
version: string | null;
at: number;
}
/** Channel id -> newest changelog version known posted there. */
const postedWatermarks = new Map<string, PostedWatermark>();
const ephemeralMsg = (content: string): InteractionReplyOptions => ({
content,
flags: MessageFlags.Ephemeral,
@ -64,18 +98,61 @@ interface VersionPost {
* Returns null (never throws) when unset or unreachable, so a bad channel id
* surfaces as a clear reply instead of a hung interaction.
*/
const resolveChannel = async (guild: Guild): Promise<TextBasedChannelFields | null> => {
const resolveChannel = async (guild: Guild): Promise<ChangelogChannel | null> => {
const channelId = botConfig.changelogChannelId ?? botConfig.announceChannelId;
if (!channelId) return null;
try {
const channel = await guild.channels.fetch(channelId);
if (!channel || !("send" in channel)) return null;
return channel as TextBasedChannelFields;
return channel as unknown as ChangelogChannel;
} catch {
return null;
}
};
/**
* The newest changelog version posted to a channel, read back from the bot's own
* "Changelog vX.Y.Z" embeds. The maximum found in the scanned window wins, so a
* late backfill of an older version never rewinds the watermark. The result is
* cached per channel (autocomplete calls this on every keystroke) and refreshed
* after each post, so the next `pending` sees the version just sent.
*/
const detectPostedThrough = async (
channel: ChangelogChannel,
botUserId: string,
): Promise<string | null> => {
const cached = postedWatermarks.get(channel.id);
if (cached && Date.now() - cached.at < POSTED_SCAN_TTL_MS) return cached.version;
let newest: string | null = null;
let before: string | undefined;
for (let page = 0; page < POSTED_SCAN_PAGES; page += 1) {
const batch = await channel.messages.fetch({ limit: 100, before });
for (const message of batch.values()) {
if (message.author.id !== botUserId) continue;
for (const embed of message.embeds) {
const version = versionFromEmbedTitle(embed.title);
if (version && (newest === null || compareVersions(version, newest) > 0)) {
newest = version;
}
}
}
if (batch.size < 100) break;
before = batch.last()?.id;
if (!before) break;
}
postedWatermarks.set(channel.id, { version: newest, at: Date.now() });
return newest;
};
/** Record a successful post so autocomplete reflects it without rescanning. */
const notePostedVersion = (channelId: string, version: string): void => {
const current = postedWatermarks.get(channelId)?.version ?? null;
const newest = current === null || compareVersions(version, current) > 0 ? version : current;
postedWatermarks.set(channelId, { version: newest, at: Date.now() });
};
/**
* Post one version's messages as amber embeds. The first carries the version
* title; multi-message versions add a page footer so order stays clear.
@ -84,7 +161,7 @@ export const renderVersionEmbeds = (version: string, messages: string[]): EmbedB
const total = messages.length;
return messages.map((message, i) => {
const embed = new EmbedBuilder()
.setTitle(`Changelog v${version}`)
.setTitle(changelogEmbedTitle(version))
.setColor(ANNOUNCE_COLOR)
.setDescription(message);
if (total > 1) {
@ -95,7 +172,7 @@ export const renderVersionEmbeds = (version: string, messages: string[]): EmbedB
};
export const postVersion = async (
channel: TextBasedChannelFields,
channel: TextBasedChannelFields & { id: string },
version: string,
messages: string[],
): Promise<number> => {
@ -104,6 +181,7 @@ export const postVersion = async (
await channel.send({ embeds: [embed] });
posted += 1;
}
notePostedVersion(channel.id, version);
return posted;
};
@ -126,10 +204,10 @@ const openEditModal = async (
await interaction.reply(ephemeralMsg("You don't have permission to post a changelog."));
return;
}
if (rangeArg?.includes("..")) {
if (rangeArg?.includes("..") || rangeArg?.toLowerCase() === PENDING_TOKEN) {
await interaction.reply(
ephemeralMsg(
"Edit mode works on one version at a time. Drop the range or the edit flag.",
"Edit mode works on one version at a time. Name a version instead of a range or pending, or drop the edit flag.",
),
);
return;
@ -263,9 +341,8 @@ export const changelogCommand: BotCommand = {
.addStringOption((option) =>
option
.setName("range")
.setDescription(
"Version or range: v0.4.0, v0.3.0..v0.5.0, open ends (v0.3.0.., ..v0.5.0). Omit for latest.",
),
.setDescription("Version, range (v0.3.0..v0.5.0, open ends), or pending. Omit for latest.")
.setAutocomplete(true),
)
.addBooleanOption((option) =>
option
@ -286,6 +363,7 @@ export const changelogCommand: BotCommand = {
// Edit mode answers with a modal, which must be the first response
// (Discord rejects modals after a defer), so branch BEFORE deferring.
const rangeArg = interaction.options.getString("range")?.trim();
const wantsPending = rangeArg?.toLowerCase() === PENDING_TOKEN;
if (interaction.options.getBoolean("edit")) {
await openEditModal(interaction, interaction.guild, payload, rangeArg);
return;
@ -315,11 +393,57 @@ export const changelogCommand: BotCommand = {
return;
}
// `pending` counts from the newest changelog already in the releases
// channel, so the channel is resolved before the target list is built.
const channel = await resolveChannel(interaction.guild);
if (!channel) {
await interaction.editReply(
"The releases channel isn't configured or isn't reachable (set DISCORD_CHANGELOG_CHANNEL_ID, or DISCORD_ANNOUNCE_CHANNEL_ID as a fallback).",
);
return;
}
// A range uses "from..to" notation; anything else is a single version.
let posts: VersionPost[];
let summaryFrom = "";
let summaryTo = "";
if (rangeArg && rangeArg.includes("..")) {
if (wantsPending) {
const botUserId = interaction.client.user?.id;
let postedThrough: string | null = null;
try {
postedThrough = botUserId ? await detectPostedThrough(channel, botUserId) : null;
} catch (error) {
// Usually a missing Read Message History grant; fall through to the
// same clear reply rather than a generic post failure.
payload.logger.warn(
`[Bot] /changelog pending scan failed: ${
error instanceof Error ? error.message : "Unknown error"
}`,
);
}
if (!postedThrough) {
await interaction.editReply(
`Could not tell which changelog was posted last: no changelog post from this bot turned up in the last ${POSTED_SCAN_PAGES * 100} messages of <#${channel.id}> (the bot needs Read Message History there). Post a version explicitly, or name the range (v0.16.0..v0.21.1).`,
);
return;
}
const batch: ChangelogBatch = resolvePendingChangelog(content, postedThrough);
if (!batch.found) {
await interaction.editReply(
`The last posted changelog was v${postedThrough}, which is not in CHANGELOG.md, so there is no boundary to count from. Name the range explicitly instead.`,
);
return;
}
if (batch.versions.length === 0) {
await interaction.editReply(
`Nothing pending: v${postedThrough} is the newest changelog already posted.`,
);
return;
}
posts = batch.versions.map((version, i) => ({ version, messages: batch.messages[i] }));
summaryFrom = batch.versions[0];
summaryTo = batch.versions[batch.versions.length - 1];
} else if (rangeArg && rangeArg.includes("..")) {
const [fromPart, toPart] = rangeArg.split("..");
const from = fromPart?.trim() || undefined;
const to = toPart?.trim() || undefined;
@ -352,14 +476,6 @@ export const changelogCommand: BotCommand = {
summaryTo = summaryFrom;
}
const channel = await resolveChannel(interaction.guild);
if (!channel) {
await interaction.editReply(
"The releases channel isn't configured or isn't reachable (set DISCORD_CHANGELOG_CHANNEL_ID, or DISCORD_ANNOUNCE_CHANNEL_ID as a fallback).",
);
return;
}
if (posts.length > WIDE_RANGE_THRESHOLD) {
await interaction.editReply(
`⚠️ Posting ${posts.length} changelog(s) (${summaryFrom} → ${summaryTo}). This may take a moment.`,
@ -371,9 +487,10 @@ export const changelogCommand: BotCommand = {
totalMessages += await postVersion(channel, post.version, post.messages);
}
const what = wantsPending ? "pending changelog" : "changelog";
await interaction.editReply(
posts.length > 1
? `Posted ${posts.length} changelog(s) for ${summaryFrom} → ${summaryTo} (${totalMessages} messages).`
? `Posted ${posts.length} ${what}s for ${summaryFrom} → ${summaryTo} (${totalMessages} messages).`
: `Posted **Changelog v${summaryFrom}**.`,
);
} catch (error) {
@ -383,4 +500,42 @@ export const changelogCommand: BotCommand = {
await interaction.editReply(`Changelog post failed: ${message}`).catch(() => {});
}
},
/**
* Version choices for the `range` option: `pending` first, then versions
* newest-first, filtered by what has been typed. The watermark scan is the
* only network call and is cached per channel, so typing stays well inside
* Discord's 3-second autocomplete window.
*/
autocomplete: async (interaction) => {
const focused = interaction.options.getFocused(true);
if (focused.name !== "range") {
await interaction.respond([]);
return;
}
let content: string;
try {
content = readFileSync(CHANGELOG_PATH, "utf8");
} catch {
await interaction.respond([]);
return;
}
// A watermark failure only costs the `pending` entry; the versions still
// list, so a broken scan never leaves staff with an empty dropdown.
let postedThrough: string | null = null;
try {
const botUserId = interaction.client.user?.id;
if (botUserId && interaction.guild) {
const channel = await resolveChannel(interaction.guild);
if (channel) postedThrough = await detectPostedThrough(channel, botUserId);
}
} catch {
postedThrough = null;
}
await interaction.respond(
buildRangeChoices(content, String(focused.value ?? ""), postedThrough),
);
},
};

View file

@ -1,4 +1,8 @@
import type { ChatInputCommandInteraction, SlashCommandBuilder } from "discord.js";
import type {
AutocompleteInteraction,
ChatInputCommandInteraction,
SlashCommandBuilder,
} from "discord.js";
import type { Payload } from "payload";
import { pingCommand } from "./ping";
import { signupCommand } from "./signup";
@ -13,6 +17,13 @@ import { debugCommand } from "./debug";
export interface BotCommand {
builder: SlashCommandBuilder;
execute: (interaction: ChatInputCommandInteraction, payload: Payload) => Promise<void> | void;
/**
* Optional autocomplete handler for any option registered with
* `setAutocomplete(true)`. Discord requires a response within 3 seconds, so
* this path must stay cheap; the router answers with an empty list whenever
* the handler rejects or never answers.
*/
autocomplete?: (interaction: AutocompleteInteraction, payload: Payload) => Promise<void> | void;
/**
* Registration scope. "global" = available in DMs and every guild the bot is
* in; "guild" (default) = only the configured guild. Discord never exposes

View file

@ -58,6 +58,11 @@ const main = async () => {
const commandExecutors = new Map(
commands.map((command) => [command.builder.name, command.execute]),
);
const autocompleteHandlers = new Map(
commands
.filter((command) => command.autocomplete)
.map((command) => [command.builder.name, command.autocomplete!]),
);
client.once(Events.ClientReady, async (readyClient) => {
payload.logger.info(`[Bot] Logged in as ${readyClient.user.tag}`);
@ -110,6 +115,29 @@ const main = async () => {
await handlePresenceModal(interaction, payload);
return;
}
// Autocomplete is answered out of band (Discord expects 25 choices within
// 3 seconds) and must never fall through to the chat-input branch, which
// would treat it as a command run.
if (interaction.isAutocomplete()) {
const autocomplete = autocompleteHandlers.get(interaction.commandName);
if (!autocomplete) {
await interaction.respond([]).catch(() => {});
return;
}
try {
await autocomplete(interaction, payload);
} catch (error) {
payload.logger.error(
`[Bot] Error autocompleting /${interaction.commandName}: ${errorMessageOf(error)}`,
);
// An unanswered autocomplete shows "Loading options failed"; a late
// answer is ignored, so never let the rejection escape.
if (!interaction.responded) {
await interaction.respond([]).catch(() => {});
}
}
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.

View file

@ -69,6 +69,29 @@ const SECTION_HEADER = /^\s*(#{1,3})\s+(.+?)\s*$/;
const BULLET = /^\s*[-*]\s+(.*)$/;
const ORDERED = /^\s*\d+[.)]\s+(.*)$/;
/**
* The version argument meaning "everything newer than the last post". Resolved
* against the releases channel rather than CHANGELOG.md, which carries no
* record of what was announced.
*/
export const PENDING_TOKEN = "pending";
/** Discord caps an autocomplete response at 25 choices. */
export const MAX_AUTOCOMPLETE_CHOICES = 25;
/** The embed title on every posted version; the last-posted scan reads it back. */
export const changelogEmbedTitle = (version: string): string => `Changelog v${version}`;
/**
* Recognize a changelog embed title and return the bare version. Exact match
* only: a member can paste a link whose embed title looks similar, and a
* mistaken watermark would silently skip real releases.
*/
export const versionFromEmbedTitle = (title: string | null | undefined): string | null => {
const match = title?.trim().match(/^Changelog v(\d+\.\d+\.\d+)$/);
return match ? match[1] : null;
};
/**
* Split raw CHANGELOG.md content into version entries. Entries are returned
* newest-first, matching the file's layout (v0.8.0 at the top).
@ -321,3 +344,83 @@ export function resolveChangelogRange(
messages: slice.map((entry) => splitForDiscord(entry.rawBody)),
};
}
/**
* Everything newer than the last changelog already posted to Discord, oldest
* first. `postedThrough` is that last posted version (with or without a leading
* "v"). An unknown watermark reports `found: false` rather than guessing at a
* boundary: posting the whole file because a scan failed is the bad outcome
* this refuses to produce.
*/
export function resolvePendingChangelog(
content: string,
postedThrough?: string | null,
): ChangelogBatch {
const watermark = postedThrough ? postedThrough.replace(/^v/i, "").trim() : "";
if (!watermark) return { found: false, versions: [], messages: [] };
const entries = parseChangelog(content);
if (!entries.some((entry) => entry.version === watermark)) {
return { found: false, versions: [], messages: [] };
}
const slice = entries
.filter((entry) => compareVersions(entry.version, watermark) > 0)
.sort((a, b) => compareVersions(a.version, b.version));
return {
found: true,
versions: slice.map((entry) => entry.version),
messages: slice.map((entry) => splitForDiscord(entry.rawBody)),
};
}
/** One autocomplete choice: what Discord shows, and what it inserts. */
export interface RangeChoice {
name: string;
value: string;
}
/**
* Choices for the `/changelog range` option. `pending` leads the list (it is
* the answer to "catch me up", which is why the option is autocompleted at
* all), followed by versions newest-first, filtered by what has been typed.
* A typed "0.19" matches "v0.19.x" whether or not the "v" is included.
*
* With no known watermark the list carries plain versions and no `pending`
* entry, so a stale scan never advertises a range it cannot resolve.
*/
export function buildRangeChoices(
content: string,
focused = "",
postedThrough?: string | null,
limit: number = MAX_AUTOCOMPLETE_CHOICES,
): RangeChoice[] {
const query = focused.trim().toLowerCase().replace(/^v/, "");
const watermark = postedThrough ? postedThrough.replace(/^v/i, "").trim() : null;
const pending = watermark ? resolvePendingChangelog(content, watermark) : null;
const choices: RangeChoice[] = [];
if (pending?.found && pending.versions.length > 0 && PENDING_TOKEN.startsWith(query)) {
const oldest = pending.versions[0];
const newest = pending.versions[pending.versions.length - 1];
choices.push({
name: `${PENDING_TOKEN} · v${oldest} → v${newest} (${pending.versions.length})`,
value: PENDING_TOKEN,
});
}
for (const entry of parseChangelog(content)) {
if (choices.length >= limit) break;
if (query && !entry.version.startsWith(query)) continue;
const state =
watermark === null
? ""
: compareVersions(entry.version, watermark) > 0
? " · pending"
: " · posted";
choices.push({ name: `v${entry.version}${state}`, value: `v${entry.version}` });
}
return choices.slice(0, limit);
}

View file

@ -4,7 +4,6 @@ import {
type ActionRowBuilder,
type ButtonBuilder,
type Client,
type TextBasedChannelFields,
} from "discord.js";
import { readFileSync } from "node:fs";
import type { Payload } from "payload";
@ -13,6 +12,7 @@ import {
CHANGELOG_PATH,
postVersion,
renderVersionEmbeds,
type ChangelogChannel,
} from "@/bot/commands/changelog";
import {
buildModlistMessage,
@ -372,7 +372,7 @@ export const debugActions: DebugAction[] = [
if (!channel || !("send" in channel)) {
throw new Error(`Releases channel ${channelId} is not a text channel.`);
}
const posted = await postVersion(channel as TextBasedChannelFields, version, messages);
const posted = await postVersion(channel as unknown as ChangelogChannel, version, messages);
return `Posted **Changelog v${version}** to the releases channel (${posted} message(s)).`;
},
},

View file

@ -62,6 +62,68 @@ describe("Bot slash command builders", () => {
});
});
describe("Bot autocomplete wiring", () => {
process.env.DISCORD_TOKEN ||= "regression-test-token";
process.env.DISCORD_GUILD_ID ||= "123456789012345678";
it("/changelog enables autocomplete on range and ships a handler", async () => {
const { changelogCommand } = await import("@/bot/commands/changelog");
const json = changelogCommand.builder.toJSON();
const range = (json.options ?? []).find((option) => option.name === "range") as
{ autocomplete?: boolean } | undefined;
expect(range?.autocomplete).toBe(true);
expect(typeof changelogCommand.autocomplete).toBe("function");
});
it("answers with versions when the releases channel is unavailable", async () => {
const { changelogCommand } = await import("@/bot/commands/changelog");
const responded: { value: string }[][] = [];
const interaction = {
options: { getFocused: () => ({ name: "range", value: "" }) },
client: { user: { id: "123456789012345678" } },
guild: null,
respond: async (choices: { value: string }[]) => {
responded.push(choices);
},
};
await changelogCommand.autocomplete!(
interaction as never,
{
logger: { error: () => undefined },
} as never,
);
expect(responded).toHaveLength(1);
expect(responded[0].length).toBeGreaterThan(0);
// No watermark without a channel, so `pending` is not offered.
expect(responded[0].some((choice) => choice.value === "pending")).toBe(false);
});
it("filters the choices by what has been typed", async () => {
const { changelogCommand } = await import("@/bot/commands/changelog");
const responded: { value: string }[][] = [];
const interaction = {
options: { getFocused: () => ({ name: "range", value: "0.21" }) },
client: { user: { id: "123456789012345678" } },
guild: null,
respond: async (choices: { value: string }[]) => {
responded.push(choices);
},
};
await changelogCommand.autocomplete!(
interaction as never,
{
logger: { error: () => undefined },
} as never,
);
expect(responded[0].length).toBeGreaterThan(0);
expect(responded[0].every((choice) => choice.value.startsWith("v0.21"))).toBe(true);
});
});
/**
* A slash command has three seconds to acknowledge an interaction. Deferring
* after a member fetch and a permission check misses that window often enough

View file

@ -4,12 +4,18 @@ import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
import {
EMPTY_SECTION_FALLBACK,
MAX_AUTOCOMPLETE_CHOICES,
PENDING_TOKEN,
buildRangeChoices,
changelogEmbedTitle,
compareVersions,
formatEntryDiscord,
parseChangelog,
resolveChangelog,
resolveChangelogRange,
resolvePendingChangelog,
splitForDiscord,
versionFromEmbedTitle,
} from "@/bot/lib/changelogRender";
const CHANGELOG_PATH = path.resolve(
@ -287,4 +293,160 @@ describe("real CHANGELOG.md", () => {
expect(batch.versions[batch.versions.length - 1]).toBe(newest);
expect(batch.versions.every((version) => compareVersions(version, "0.6.0") >= 0)).toBe(true);
});
it("counts the pending versions from a posted watermark", () => {
const content = readFileSync(CHANGELOG_PATH, "utf8");
const entries = parseChangelog(content);
const index = entries.findIndex((entry) => entry.version === "0.15.3");
expect(index).toBeGreaterThan(0);
const batch = resolvePendingChangelog(content, "0.15.3");
expect(batch.found).toBe(true);
// The file is newest-first, so everything newer is the slice above it.
expect(batch.versions).toEqual(
entries
.slice(0, index)
.map((entry) => entry.version)
.reverse(),
);
expect(batch.versions.length).toBe(index);
expect(batch.versions[batch.versions.length - 1]).toBe(entries[0].version);
});
});
describe("changelog embed titles", () => {
it("round-trips a version through the title a post carries", () => {
expect(changelogEmbedTitle("0.21.1")).toBe("Changelog v0.21.1");
expect(versionFromEmbedTitle(changelogEmbedTitle("0.21.1"))).toBe("0.21.1");
});
it("ignores anything that is not an exact changelog title", () => {
// A near miss would move the watermark and silently skip real releases.
expect(versionFromEmbedTitle("Changelog v0.21")).toBeNull();
expect(versionFromEmbedTitle("Changelog v0.21.1 (edited)")).toBeNull();
expect(versionFromEmbedTitle("Releases: Changelog v0.21.1")).toBeNull();
expect(versionFromEmbedTitle(undefined)).toBeNull();
expect(versionFromEmbedTitle(null)).toBeNull();
});
});
describe("resolvePendingChangelog", () => {
const content = [
"# Changelog",
"",
"# v0.4.0",
"",
"Newest.",
"",
"# v0.3.0",
"",
"Middle.",
"",
"# v0.2.0",
"",
"Oldest.",
"",
].join("\n");
it("returns everything newer than the watermark, oldest first", () => {
const batch = resolvePendingChangelog(content, "0.2.0");
expect(batch.found).toBe(true);
expect(batch.versions).toEqual(["0.3.0", "0.4.0"]);
expect(batch.messages).toHaveLength(2);
expect(batch.messages[0].join("\n")).toContain("Middle.");
});
it("accepts a leading v on the watermark", () => {
expect(resolvePendingChangelog(content, "v0.3.0").versions).toEqual(["0.4.0"]);
});
it("reports nothing pending once the newest version is posted", () => {
const batch = resolvePendingChangelog(content, "0.4.0");
expect(batch.found).toBe(true);
expect(batch.versions).toEqual([]);
});
it("refuses an unknown or missing watermark instead of posting the whole file", () => {
expect(resolvePendingChangelog(content, "0.9.9")).toEqual({
found: false,
versions: [],
messages: [],
});
expect(resolvePendingChangelog(content, null)).toEqual({
found: false,
versions: [],
messages: [],
});
expect(resolvePendingChangelog(content, " ")).toEqual({
found: false,
versions: [],
messages: [],
});
});
});
describe("buildRangeChoices", () => {
const content = [
"# v0.4.0",
"",
"Newest.",
"",
"# v0.3.0",
"",
"Middle.",
"",
"# v0.2.0",
"",
"Oldest.",
"",
].join("\n");
it("leads with pending and labels every version by its state", () => {
const choices = buildRangeChoices(content, "", "0.2.0");
expect(choices[0]).toEqual({ name: "pending · v0.3.0 → v0.4.0 (2)", value: PENDING_TOKEN });
expect(choices.slice(1)).toEqual([
{ name: "v0.4.0 · pending", value: "v0.4.0" },
{ name: "v0.3.0 · pending", value: "v0.3.0" },
{ name: "v0.2.0 · posted", value: "v0.2.0" },
]);
});
it("offers no pending entry when the watermark is unknown", () => {
const choices = buildRangeChoices(content, "", null);
expect(choices.some((choice) => choice.value === PENDING_TOKEN)).toBe(false);
expect(choices[0]).toEqual({ name: "v0.4.0", value: "v0.4.0" });
});
it("offers no pending entry when nothing is pending", () => {
const choices = buildRangeChoices(content, "", "0.4.0");
expect(choices.some((choice) => choice.value === PENDING_TOKEN)).toBe(false);
expect(choices[0].name).toBe("v0.4.0 · posted");
});
it("filters on what has been typed, with or without the v", () => {
expect(buildRangeChoices(content, "0.3", "0.2.0")).toEqual([
{ name: "v0.3.0 · pending", value: "v0.3.0" },
]);
expect(buildRangeChoices(content, "v0.2", "0.2.0")).toEqual([
{ name: "v0.2.0 · posted", value: "v0.2.0" },
]);
expect(buildRangeChoices(content, "pend", "0.2.0")).toEqual([
{ name: "pending · v0.3.0 → v0.4.0 (2)", value: PENDING_TOKEN },
]);
});
it("caps the list at Discord's 25-choice limit, pending included", () => {
const many = Array.from({ length: 40 }, (_, i) => `# v0.${39 - i}.0\n\nEntry.\n`).join("\n");
const withPending = buildRangeChoices(many, "", "0.0.0");
expect(withPending).toHaveLength(MAX_AUTOCOMPLETE_CHOICES);
expect(withPending[0]).toEqual({
name: "pending · v0.1.0 → v0.39.0 (39)",
value: PENDING_TOKEN,
});
const plain = buildRangeChoices(many, "", "0.39.0");
expect(plain).toHaveLength(MAX_AUTOCOMPLETE_CHOICES);
expect(plain[0].value).toBe("v0.39.0");
});
});