Skip to content

Add pending-action timeouts, persistent menu helpers, group-linking & link normalization, and expand tests - #98

Merged
gamblecodezcom merged 2 commits into
mainfrom
codex/perform-full-audit-and-implementation-for-runewager-bot
Feb 26, 2026
Merged

Add pending-action timeouts, persistent menu helpers, group-linking & link normalization, and expand tests#98
gamblecodezcom merged 2 commits into
mainfrom
codex/perform-full-audit-and-implementation-for-runewager-bot

Conversation

@gamblecodezcom

@gamblecodezcom gamblecodezcom commented Feb 26, 2026

Copy link
Copy Markdown
Owner

User description

Motivation

  • Improve robustness of user pending-input flows by enforcing a clear 15-minute timeout boundary and showing friendly labels on expiration.
  • Reduce stale menu clutter and ensure single-active-menu behavior across flows by adding menu lifecycle helpers.
  • Add deterministic link handling (Discord/Telegram/browser vs mini-app routing) and group-linking admin tools to support giveaways and broadcasts.

Description

  • Implemented pending-action timeout helpers: added PENDING_ACTION_TIMEOUT_MS, ACTION_LABELS, and evaluatePendingActionTimeout() to normalize and expire pending states while preserving the exact-15-minute boundary semantics.
  • Introduced persistent menu helpers: clearOldMenus(), replyMenu() and user fields lastMenuMsgId/lastMenuChatId, and updated sendMainMenu() / sendSettingsMenu() / /cancel to use them to keep only one active menu per user.
  • Added link utilities: unwrapTelegramUrl(), getDiscordLink(), getBrowserLink(), getWebAppLink(), getStartAppLink(), and getPlayLink() and wired LINKS to sanitize/normalize Discord and Telegram links and drive deterministic play button behavior.
  • Added group-linking admin flows and UI: menu callbacks and handlers for linking, viewing, removing, and testing group permissions, plus renderGroupLinkingTools() and keyboard definitions.
  • Various UX and feature touches: miniAppPlayButton() now respects user play mode and labels, settings keyboard exposes Group Linking Tools, and test giveaway/menu flows use replyMenu.
  • Updated .env.example to document new/used env keys (BOT_PRIVACY_MODE/compat BOTPRIVACYMODE, TELEGRAM_*_LINK, HTTPS_CERT_PATH, HTTPS_KEY_PATH, LOG_LEVEL, WEBAPP_HMAC_KEY, etc.).
  • Expanded and hardened tests in test/smoke.test.js and test/unit.test.js to cover pending-action boundaries, command/callback extraction, catch-all regex handling, env docs, menu/menu-clear behavior, group-linking callbacks, play-link routing, and testall summary output.

Testing

  • Ran the automated test suite covering test/unit.test.js and test/smoke.test.js (via the repo test runner); all tests passed.
  • Smoke checks validate command/callback coverage, catch-all regex exclusion, .env.example documentation of core runtime vars, and testall final summary formatting, and they succeeded.
  • Unit tests validate pending-action timeout semantics, play-link routing behavior, and helper utility normalization, and they succeeded.

Codex Task


CodeAnt-AI Description

Add single-active menus, deterministic Play links, Discord/Telegram link normalization, and admin group-linking tools

What Changed

  • Menus now remove previous transient menu card before showing a new one so users only see one active menu per chat (menu navigation uses clearOldMenus/replyMenu).
  • Play/Open button and related flows return either an external browser URL or a Telegram mini-app deep link based on the user's Play Mode; the button label changes to indicate "Browser" or "Mini App".
  • Discord and Telegram links are normalized: Telegram-wrapped links are unwrapped and Discord URLs are forced to safe external https links; fallback Discord join link provided if input is invalid.
  • Admin "Group Linking Tools" added to Settings and admin dashboards to link/view/remove/test linked groups and test bot permissions; linking uses a simple forward workflow and removal/testing UIs.
  • /testall and unit/smoke tests expanded to validate pending-action timeout boundaries, menu helper presence, link behavior, group-linking callbacks, and test summary/warning reporting.
  • .env.example and documentation updated to list new runtime keys (HTTPS cert/key, BOT_PRIVACY_MODE variants, webapp HMAC key) and note single-active-menu and link-routing expectations.

Impact

✅ Clearer Play button behavior for browser vs mini-app users
✅ Fewer stale menus shown to users
✅ Clearer and safer external Discord/Telegram links

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • New Features

    • Added admin group linking management tools for viewing and managing linked groups.
    • Introduced dynamic play link routing that adapts based on user preferences (browser vs. mini-app modes).
    • Enhanced test diagnostics with warnings tracking and detailed summary reporting.
  • Improvements

    • Improved Discord and Telegram URL handling for consistency and safety.
    • Refined menu navigation with better cleanup and replacement behavior.
  • Configuration

    • Added environment variables for privacy mode, HTTPS certification, logging levels, and Telegram integration settings.

…nks, group linking tools, TestAll engine, full navigation hardening, env/doc/detection sync
@codeant-ai

codeant-ai Bot commented Feb 26, 2026

Copy link
Copy Markdown

CodeAnt AI is reviewing your PR.


Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@gamblecodezcom
gamblecodezcom merged commit 7fa5c30 into main Feb 26, 2026
1 check passed
@gamblecodezcom
gamblecodezcom deleted the codex/perform-full-audit-and-implementation-for-runewager-bot branch February 26, 2026 22:34
@coderabbitai

coderabbitai Bot commented Feb 26, 2026

Copy link
Copy Markdown

Warning

Rate limit exceeded

@gamblecodezcom has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between f1e8f65 and f4eb611.

📒 Files selected for processing (6)
  • .env.example
  • CLAUDE.md
  • RUNEWAGER_FUNCTIONALITY_MAP.md
  • index.js
  • test/smoke.test.js
  • test/unit.test.js
📝 Walkthrough

Walkthrough

This PR refactors URL/link handling across the bot, introduces menu lifecycle management helpers, adds group linking administration tools, updates environment configuration, and expands test coverage with new smoke and unit tests validating the updated behavior.

Changes

Cohort / File(s) Summary
Environment Configuration
.env.example
Added security and deployment variables: BOT_PRIVACY_MODE/BOTPRIVACYMODE, HTTPS_CERT_PATH/HTTPS_KEY_PATH, LOG_LEVEL. Repositioned WEBAPP_HMAC_KEY. Added PROMO_ENTRY_IMAGE_URL. Reordered Telegram-related variables (TELEGRAM_BOT_TOKEN, TELEGRAM_GROUP_ID, TELEGRAM_CHANNEL_LINK). Surface area increased with more explicit configuration entries.
Documentation & Guidance
CLAUDE.md, RUNEWAGER_FUNCTIONALITY_MAP.md
Added rules for menu transitions via clearOldMenus(ctx), deterministic link routing (browser vs. Telegram mini-app), Discord link sanitization, and TestAll summary format requirements. Documented single active menu enforcement, play-link routing behavior, group linking tools, and environment variable usage.
Core Link/URL Routing & Menu Management
index.js
Introduced URL normalization helpers (unwrapTelegramUrl, getDiscordLink) and link generation utilities (getBrowserLink, getStartAppLink, getPlayLink). Added menu lifecycle helpers: clearOldMenus(ctx, user), replyMenu(ctx, user, text, extra), getContextChatId(ctx). Refactored button/keyboard rendering to use route-aware helpers. Enhanced miniAppPlayButton signature to accept (user, route). Updated Discord link references to use getDiscordLink for consistency.
Group Linking Administration
index.js (Admin Tools)
Added dedicated group linking tooling: groupLinkingToolsKeyboard(returnCallback), renderGroupLinkingTools(ctx, returnCallback). Introduced 6 new admin action callbacks: settings_group_linking_tools, group_link_start, group_link_view, group_link_remove_menu, group_link_remove_<id>, group_link_test_permissions. Consolidated group linking behind a module-specific keyboard.
TestAll Enhancements
index.js
Extended testall flow to collect warnings and emit structured summary: "TestAll complete — X passed, Y warnings, Z failures." Added warnings array and warn(...) helper to track non-critical issues alongside pass/fail counts.
Test Coverage
test/smoke.test.js, test/unit.test.js
Added 3 smoke tests validating menu navigation with clearOldMenus, group linking callback presence, and TestAll summary format. Added 5 unit tests covering URL helpers (unwrapTelegramUrl, getDiscordLink, getBrowserLink, getStartAppLink, getPlayLink) with browser vs. Telegram mode routing validation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Bot
    participant PlayLinkResolver as getPlayLink()
    participant BrowserLink as Browser
    participant TelegramApp as Telegram MiniApp

    User->>Bot: Request play action
    Bot->>PlayLinkResolver: getPlayLink(user, route)
    
    alt User playMode === 'browser'
        PlayLinkResolver->>BrowserLink: getBrowserLink(route)
        BrowserLink-->>PlayLinkResolver: External gamble-codez URL
        PlayLinkResolver-->>Bot: Browser URL
        Bot->>BrowserLink: Redirect user
    else User playMode === 'telegram'
        PlayLinkResolver->>TelegramApp: getStartAppLink(route)
        TelegramApp-->>PlayLinkResolver: Telegram /start?app_url=route
        PlayLinkResolver-->>Bot: MiniApp URL
        Bot->>TelegramApp: Open MiniApp
    end
Loading
sequenceDiagram
    participant Admin
    participant BotUI as Bot Interface
    participant SettingsMenu as Settings Handler
    participant GroupLinkingTools as Group Linking Tools
    participant GroupDB as Group Database

    Admin->>BotUI: Tap Settings
    BotUI->>SettingsMenu: sendSettingsMenu()
    SettingsMenu->>BotUI: Display with settings_group_linking_tools button
    
    Admin->>BotUI: Tap Group Linking Tools
    BotUI->>GroupLinkingTools: renderGroupLinkingTools(ctx)
    GroupLinkingTools->>GroupDB: Query linked groups
    GroupDB-->>GroupLinkingTools: Current groups list
    GroupLinkingTools->>BotUI: Display groups with actions (view/remove/test)
    
    alt Admin removes group
        Admin->>BotUI: Tap group_link_remove_<id>
        BotUI->>GroupDB: Delete group link
        GroupDB-->>BotUI: Confirmed
        BotUI->>BotUI: Refresh group linking tools view
    else Admin tests permissions
        Admin->>BotUI: Tap group_link_test_permissions
        BotUI->>GroupDB: Validate bot permissions
        GroupDB-->>BotUI: Permission status
        BotUI->>Admin: Display test results
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested labels

size:XL, feature, refactor, documentation


🐰 Through menus we hop with care so clear,
Links routing true, both far and near,
Old menus swept, new tools appear,
Group linking shines, the path is here!
A rabbit's quest for order's cheer. 🌿

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch codex/perform-full-audit-and-implementation-for-runewager-bot

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codeant-ai codeant-ai Bot added the size:L This PR changes 100-499 lines, ignoring generated files label Feb 26, 2026
@codeant-ai

codeant-ai Bot commented Feb 26, 2026

Copy link
Copy Markdown

Nitpicks 🔍

🔒 No security issues identified
⚡ Recommended areas for review

  • Pending Timeout
    The new evaluatePendingActionTimeout mutates user.pendingAction.createdAt when missing and clears user.pendingAction on expiry. Verify the deterministic seeding behavior, Number() coercion of createdAt (handles string timestamps), and that the <= 15-minute boundary semantics (exact 15 minutes does not expire) are what callers expect across flows. Ensure callers that rely on createdAt not being mutated are updated.

  • URL parsing
    unwrapTelegramUrl passes raw strings to the URL constructor which requires an absolute URL. Inputs like t.me/iv?url=... (no scheme) will throw and be returned raw. Consider normalizing (prepend https://) or handling additional Telegram wrapper shapes so wrapped links are consistently unwrapped.

  • Link normalization
    getDiscordLink only accepts a small set of hostnames and requires https. It omits other valid Discord domains (e.g., discordapp.com) and doesn't explicitly strip tracking/search params. Confirm intended whitelist, whether non-https links should be allowed, and whether query params should be preserved/removed for privacy.

  • URL encoding
    getStartAppLink interpolates route directly into a query parameter. If route contains special characters the resulting URL may be invalid or behave unexpectedly. Consider encoding/validating the route.

  • Fragile formatting checks
    The test uses exact source.includes(...) checks for await replyMenu(ctx, user, lines and for /cancel handler clearing menus. These string matches depend on precise whitespace, argument names and nearby code layout and can break when code is refactored (e.g. different param names, line breaks, or removed local variable lines).

@codeant-ai

codeant-ai Bot commented Feb 26, 2026

Copy link
Copy Markdown

CodeAnt AI finished reviewing your PR.

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

Labels

codex size:L This PR changes 100-499 lines, ignoring generated files

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant