Skip to content

feat: @user, dead code cleanup, bug fixes, type safety - #50

Open
goldstac wants to merge 21 commits into
open-devhub:mainfrom
goldstac:feat/bundle
Open

goldstac wants to merge 21 commits into
open-devhub:mainfrom
goldstac:feat/bundle

Conversation

@goldstac

@goldstac goldstac commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

New Feature

  • $usage @user: Show another user's token usage (same pattern as $rank and $stats)

Bug Fixes

  • Added missing await on message.reply() in ping and permission check commands
  • Removed unused member fetch in rank command (unnecessary Discord API call)
  • Removed redundant optional chaining in aiMode and handleCommands
  • Removed redundant CONTEXTS.set() in addToContext
  • Changed let to const in getAllFiles

Dead Code Removal

  • Deleted fileOps.ts (unused module)
  • Deleted regex.ts (unused constants)
  • Removed unused SubcommandCallbackOpts type
  • Removed unused __filename variable
  • Removed redundant dotenv/config imports (already loaded in index.ts)
  • Removed commented-out code in usageCard and help

Type Safety

  • Replaced ctx: any with ctx: CanvasRenderingContext2D in usageCard, leaderboardCard, and statsCard

Files Changed

src/commands/ai/usage.ts, src/commands/ai/rank.ts, src/commands/misc/ping.ts, src/commands/misc/help.ts, src/events/messageCreate/handleCommands.ts, src/events/messageCreate/aiMode.ts, src/utils/ai.ts, src/utils/context.ts, src/utils/getAllFiles.ts, src/types/command.ts, src/visuals/usageCard.ts, src/visuals/leaderboardCard.ts, src/visuals/statsCard.ts
src/utils/fileOps.ts (deleted), src/constants/regex.ts (deleted)

@devhub-bot devhub-bot Bot added chore maintenance, configs, formatting, dependencies feat New feature fix Bug fix labels Sep 4, 2026
@beetle-ai

beetle-ai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary by Beetle

This PR is a comprehensive code cleanup and quality improvement initiative that addresses multiple technical debt items and enhances functionality. The PR consists of 17 commits that:

  1. Enhance the usage command to support viewing other users' token usage (not just your own)
  2. Remove unused code across the codebase (unused modules, constants, types, and variables)
  3. Fix async/await issues where message.reply() calls weren't being awaited
  4. Improve type safety by replacing generic any types with proper TypeScript types
  5. Remove redundant code patterns (optional chaining, null fallbacks, duplicate imports)
  6. Improve code consistency (using const instead of let where appropriate)
    The overall goal is to improve code maintainability, reduce technical debt, and enhance type safety while adding a useful feature to the usage command.

📁 File Changes Summary (Consolidated across all commits):

File Status Changes Description
src/commands/ai/usage.ts Modified +27/-8 Enhanced to support viewing token usage for other users via mentions. Added validation for arguments, member fetching for display names, and improved error logging.
src/utils/fileOps.ts Deleted +0/-9 Removed unused file operations module that wrapped fs/promises functions.
src/constants/regex.ts Deleted +0/-12 Removed unused regex patterns for blocked intents and jailbreak detection.
src/types/command.ts Modified +0/-2 Removed unused SubcommandCallbackOpts type definition.
src/events/messageCreate/handleCommands.ts Modified +1/-4 Removed redundant __filename variable, removed unused dotenv import, and fixed missing await on message.reply() call. Also fixed redundant optional chaining on args.shift().
src/commands/ai/rank.ts Modified +4/-6 Removed unused member fetch operation and removed redundant null fallback in avatarUrl assignment.
src/visuals/usageCard.ts Modified +7/-8 Removed commented-out metrics (messages/images), improved type safety by replacing ctx: any with CanvasRenderingContext2D.
src/commands/misc/help.ts Modified +0/-9 Removed commented-out quickAiHelp code block.
src/commands/misc/ping.ts Modified +1/-1 Fixed missing await on message.reply() call.
src/utils/ai.ts Modified +0/-1 Removed redundant dotenv import.
src/events/messageCreate/aiMode.ts Modified +1/-1 Removed redundant optional chaining on content.split().
src/utils/context.ts Modified +0/-2 Removed redundant CONTEXTS.set() call in addToContext() function.
src/utils/getAllFiles.ts Modified +1/-1 Changed let fileNames to const fileNames for better immutability.
src/visuals/leaderboardCard.ts Modified +7/-2 Improved type safety by importing and using CanvasRenderingContext2D type instead of any.
src/visuals/statsCard.ts Modified +7/-2 Improved type safety by importing and using CanvasRenderingContext2D type instead of any.

Total Changes: 15 files changed, +64 additions, -57 deletions

🗺️ Walkthrough:

graph TD
A["User Command: usage"] -->|"Check for mentions"| B{"Has mention or args?"}
B -->|"Args but no mention"| C["Reply with usage help"]
B -->|"Has mention"| D["Fetch target user"]
B -->|"No args/mention"| E["Use current user"]
D --> F["Fetch guild member for display name"]
E --> F
F --> G["Build card options"]
G --> H["Render usage card"]
H --> I["Send attachment with user ID"]
I --> J["Success"]
C --> K["Return early"]
L["Code Quality Improvements"] -->|"Type Safety"| M["Replace any with CanvasRenderingContext2D"]
L -->|"Async/Await"| N["Add missing await on message.reply"]
L -->|"Remove Dead Code"| O["Delete unused modules and constants"]
L -->|"Redundancy"| P["Remove duplicate imports and logic"]
Loading

🎯 Key Changes:

  • Feature Enhancement: The usage command now supports viewing other users' token usage by mentioning them ($usage @user), with proper validation and helpful error messages when used incorrectly.
  • Type Safety Improvements: Replaced generic any types with proper CanvasRenderingContext2D type in three visual card modules (usageCard.ts, leaderboardCard.ts, statsCard.ts), improving IDE support and catching potential type errors at compile time.
  • Async/Await Fixes: Fixed three instances where message.reply() calls were not being awaited (ping.ts, handleCommands.ts permission check), ensuring proper error handling and execution flow.
  • Dead Code Removal: Eliminated unused modules (fileOps.ts), unused constants (regex.ts with blocked intent and jailbreak patterns), and unused type definitions (SubcommandCallbackOpts).
  • Code Simplification: Removed redundant optional chaining operators, null fallbacks, and duplicate imports (dotenv in two files), making code more readable and maintainable.
  • Immutability Improvement: Changed let fileNames to const fileNames in getAllFiles.ts to enforce immutability where the variable isn't reassigned.

📊 Impact Assessment:

  • Security:
  • ✅ Positive: Removal of unused regex patterns for blocked intents and jailbreak detection reduces potential confusion about what security measures are actually in place.
  • ⚠️ Neutral: The new mention feature in the usage command doesn't introduce security risks as it only displays token usage information (likely already visible to users).
  • Performance:
  • ✅ Positive: Removal of unused modules and dead code reduces bundle size and import overhead.
  • ✅ Positive: Removing redundant CONTEXTS.set() call eliminates unnecessary map operations.
  • ✅ Positive: Fixing missing await statements prevents potential race conditions and improves reliability.
  • Maintainability:
  • ✅ Highly Positive: Comprehensive removal of dead code, commented-out sections, and unused imports significantly improves codebase clarity.
  • ✅ Highly Positive: Type safety improvements with CanvasRenderingContext2D provide better IDE autocomplete and catch errors earlier.
  • ✅ Positive: Consistent use of const over let enforces immutability patterns and reduces cognitive load.
  • ✅ Positive: Removal of redundant optional chaining makes code intent clearer and easier to understand.
  • Testing:
  • ⚠️ Requires Attention: The new mention feature in the usage command should have test coverage for:
  • Valid mention scenarios
  • Invalid argument scenarios (args without mention)
  • Guild member fetching edge cases
  • Fallback to username when display name is unavailable
  • ✅ Positive: Removal of dead code reduces test maintenance burden.
  • ✅ Positive: Type safety improvements reduce the need for runtime type checking tests.
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

Follow us: Beetle · X · LinkedIn

@devhub-bot

devhub-bot Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Note

Linting checks passed successfully 🎉

All formatting and code quality checks are clean.

You're good to merge 🚀

Comment thread src/utils/context.ts
Comment on lines 39 to 40
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The removal of CONTEXTS.set(userId, history); breaks the core functionality of the addToContext function. Without this line, the context is never persisted to the CONTEXTS map, making all the history management logic (size limiting, etc.) ineffective. This will cause context retrieval to fail for all users.

Confidence: 5/5

Suggested Fix
Suggested change
}
export function addToContext(
userId: string,
message: Message,
role: "user" | "assistant"
) {
if (!CONTEXTS.has(userId)) {
CONTEXTS.set(userId, []);
}
const history = CONTEXTS.get(userId)!;
history.push({
role,
content: message,
});
if (history.length > MAX_MESSAGES) {
history.shift();
}
CONTEXTS.set(userId, history);
}

Restore the CONTEXTS.set(userId, history); line at the end of the function to persist the updated history back to the map.

Prompt for AI

Copy this prompt to your AI IDE to fix this issue locally:

In src/utils/context.ts around line 40, the line CONTEXTS.set(userId, history);
was accidentally removed, which breaks context persistence. Restore this line at
the end of the addToContext function to ensure the updated history is saved back
to the CONTEXTS map.

📍 This suggestion applies to lines 39-40

@goldstac goldstac changed the title feat: add @user, cleanup dead code, fix bugs, improve type safety feat: @user, dead code cleanup, bug fixes, type safety Sep 4, 2026
@beetle-ai

beetle-ai Bot commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor

Summary by Beetle

This PR fixes a critical bug in the context management system where the addToContext function was failing to persist conversation history updates to the CONTEXTS Map. The function was adding messages to the local history array but not synchronizing those changes back to the persistent storage, causing conversation context to be lost. This one-line fix restores the CONTEXTS.set() call that was accidentally removed or missing.

📁 File Changes Summary (Consolidated across all commits):

File Status Changes Description
src/utils/context.ts Modified +2/-0 Bug Fix: Restored missing CONTEXTS.set(userId, history) call in addToContext() function. The function was updating the local history array but failing to persist changes back to the CONTEXTS Map, causing conversation history to be lost between function calls. This fix ensures that all message additions are properly synchronized to persistent storage.

Total Changes: 1 file changed, +2 additions, -0 deletions

🎯 Key Changes:

  • Restored Persistence Logic: Added back the critical CONTEXTS.set(userId, history) call at the end of the addToContext() function
  • Bug Impact: Without this line, the function was performing all the correct operations (message validation, history trimming) but failing to save the updated history back to the CONTEXTS Map
  • Minimal, Focused Fix: This is a surgical fix that addresses the root cause without introducing unnecessary changes
  • No Breaking Changes: The fix restores intended behavior without modifying the function signature or logic flow

📊 Impact Assessment:

  • Security: ✅ Positive - Ensures conversation context is properly maintained and not lost, which is important for maintaining conversation integrity and preventing context confusion between users
  • Performance: ✅ Neutral - The added line is a simple Map operation with O(1) complexity; no performance degradation
  • Maintainability: ✅ Positive - Fixes a critical bug that would have caused confusion during debugging; the code now matches its intended behavior as evidenced by the function's structure (message validation, history trimming, then persistence)
  • Testing: ⚠️ Concern - This bug suggests existing tests may not have caught the missing persistence. Recommend adding integration tests that verify conversation history is maintained across multiple addToContext() calls for the same user
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

Follow us: Beetle · X · LinkedIn

@beetle-ai

beetle-ai Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

✅ You're good to merge this PR! No issues found. Great job!

Settings
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

@devhub-bot

devhub-bot Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Note

Linting checks passed successfully 🎉

All formatting and code quality checks are clean.

You're good to merge 🚀

@beetle-ai

beetle-ai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary by Beetle

This PR removes the ability for users to query token usage for other users via the @user mention feature. The change restricts the /usage command to only show the current user's own token usage, simplifying the command logic and enforcing a privacy-focused approach where users can only view their own consumption metrics.

📁 File Changes Summary (Consolidated across all commits):

File Status Changes Description
src/commands/ai/usage.ts Modified +9/-21 Removed @user mention functionality and multi-user support. Command now exclusively displays the current user's token usage. Simplified logic by removing argument parsing, member fetching, and display name resolution for other users. Updated command description and error messaging to reflect self-only usage.

Total Changes: 1 file changed, +9 additions, -21 deletions

🎯 Key Changes:

  • Removed multi-user query support: Eliminated the ability to mention another user (@user) to view their token usage
  • Simplified command logic: Removed argument parsing (args parameter) and conditional branching for handling mentions
  • Removed guild member resolution: Eliminated the message.guild.members.fetch() call that was used to get display names for other users
  • Updated user feedback: Changed error message from instructional ("Use $usage to see your usage, or $usage @user to see someone else's") to restrictive ("You can only view your own usage")
  • Hardcoded self-reference: All user data now exclusively comes from message.author instead of a dynamic target variable
  • Simplified attachment naming: Changed from usage-${target.id}.png to static usage.png
  • Updated command description: Changed from "Show current token usage for yourself or another user" to "Show your current token usage"

📊 Impact Assessment:

  • Security: ✅ Positive Impact - Restricting usage queries to self-only prevents information disclosure about other users' token consumption. This is a privacy-preserving change that prevents potential abuse or unauthorized monitoring of other users' API usage patterns.
  • Performance: ✅ Positive Impact - Removes unnecessary database/API calls (message.guild.members.fetch()), reducing latency and server load. The command now executes faster with fewer external dependencies.
  • Maintainability: ✅ Positive Impact - Code is significantly simpler with fewer conditional branches and edge cases. Removing the target variable and related logic reduces cognitive complexity. The command is now more straightforward to understand and maintain.
  • Testing: ⚠️ Requires Update - Existing tests that verify multi-user query functionality will need to be updated or removed. New tests should verify that attempting to query another user's usage is properly rejected. Test coverage should ensure the error message is correctly displayed when mentions are attempted.
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

Follow us: Beetle · X · LinkedIn

Comment thread src/commands/ai/usage.ts Outdated
async execute({ message }: CommandCallbackOpts) {
if (message.author.bot) return;

if (message.mentions.users.first()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code accesses message.mentions.users.first() without optional chaining, but the original code used message.mentions?.users?.first(). This could throw a runtime error if message.mentions or message.mentions.users is undefined or null.

Confidence: 4/5

Suggested Fix
Suggested change
if (message.mentions.users.first()) {
if (message.mentions?.users?.first()) {

The optional chaining operator (?.) safely accesses nested properties and returns undefined if any part of the chain is null or undefined, preventing runtime errors.

Prompt for AI

Copy this prompt to your AI IDE to fix this issue locally:

In src/commands/ai/usage.ts around line 14, the code accesses message.mentions.users.first()
without optional chaining, which could throw a runtime error if message.mentions or
message.mentions.users is undefined. Change it to use optional chaining:
message.mentions?.users?.first() to safely handle cases where these properties don't exist.

@devhub-bot

devhub-bot Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Note

Linting checks passed successfully 🎉

All formatting and code quality checks are clean.

You're good to merge 🚀

@beetle-ai

beetle-ai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Summary by Beetle

This PR addresses a potential null reference error in the AI usage command by adding optional chaining operators to the message.mentions property access chain. The fix prevents runtime errors that could occur when the mentions property is undefined or null, making the code more defensive and robust.

📁 File Changes Summary (Consolidated across all commits):

File Status Changes Description
src/commands/ai/usage.ts Modified +1/-1 Added optional chaining operators (?.) to safely access message.mentions.users.first(). Changed from message.mentions.users.first() to message.mentions?.users?.first() to prevent potential null reference errors when the mentions property is undefined.

Total Changes: 1 file changed, +1 additions, -1 deletions

🎯 Key Changes:

  • Optional Chaining Implementation: Replaced direct property access with optional chaining (?.) on the message.mentions chain to safely handle cases where mentions or users might be undefined or null.
  • Defensive Programming: This change follows defensive programming practices by preventing potential runtime errors that could crash the command if Discord.js returns a message without a mentions collection.
  • Minimal, Focused Fix: The change is surgical and focused—only modifying the specific line that needed protection without altering any other logic or behavior.

📊 Impact Assessment:

  • Security: ✅ Low Risk - This is a defensive fix that prevents potential crashes. No security vulnerabilities are introduced or resolved. The change makes the code more resilient to unexpected input states.
  • Performance: ✅ No Impact - Optional chaining has negligible performance overhead in modern JavaScript/TypeScript. The runtime cost is essentially identical to the original code, with the added benefit of preventing exceptions.
  • Maintainability: ✅ Improved - The code is now more defensive and follows modern JavaScript best practices. Optional chaining makes the intent clear: "safely access this property chain, returning undefined if any step fails." This reduces cognitive load for future maintainers.
  • Testing: ⚠️ Consideration - While this fix prevents crashes, it's important to verify that:
  • The command still functions correctly when mentions are present
  • The command gracefully handles cases where message.mentions is undefined or users is empty
  • Edge cases with Discord.js message objects are covered by existing tests
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

Follow us: Beetle · X · LinkedIn

@beetle-ai

beetle-ai Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

✅ You're good to merge this PR! No issues found. Great job!

Settings
⚙️ Settings

Severity Threshold: Medium — Balanced feedback — medium and high severity issues only. — Change in Settings
Custom Rules: Define your own review rules — Set Custom Rules
PR Summary: Configure PR summary — Change in Settings

📖 User Guide
  • Once repos are connected, PR analysis is automatically enabled. You can disable analysis for this repo from beetleai.dev/analysis
  • Comment @beetle on any PR to start analysis manually
  • Comment @beetle stop to stop any ongoing analysis

@devhub-bot

devhub-bot Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Note

Linting checks passed successfully 🎉

All formatting and code quality checks are clean.

You're good to merge 🚀

@goldstac

goldstac commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

wait
@calebephrem beetle has been revewing for 2 hours

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

chore maintenance, configs, formatting, dependencies feat New feature fix Bug fix

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant