Skip to content

allow alliance extension Fixes #491 - #1314

Merged
evanpelle merged 2 commits into
mainfrom
evan-alliance-extension
Jul 2, 2025
Merged

evanpelle merged 2 commits into
mainfrom
evan-alliance-extension

Conversation

@evanpelle

@evanpelle evanpelle commented Jul 1, 2025 •

Copy link
Copy Markdown
Collaborator

Description:

About 30s before an alliance is about to expire, both players receive a prompt to extend the alliance. If both players agree the alliance is extended.

Please complete the following:

  • I have added screenshots for all UI updates
  • I process any text displayed to the user through translateText() and I've added it to the en.json file
  • I have added relevant tests to the test directory
  • I confirm I have thoroughly tested these changes and take full responsibility for any bugs introduced
  • I understand that submitting code with bugs that could have been caught through manual testing blocks releases and new features for all contributors

Please put your Discord username so you can be contacted if a bug or regression is found:

evan

@coderabbitai

coderabbitai Bot commented Jul 1, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

This update introduces alliance expiration and renewal features to the game. Alliances now have unique IDs, expiration times, and can be extended if both players agree. New intent types and execution logic support alliance extension requests. The client displays proactive warnings for expiring alliances and allows players to request renewals.

Changes

File(s) Change Summary
src/client/Transport.ts Added SendAllianceExtensionIntentEvent and handling for sending alliance extension intents.
src/client/Utils.ts Mapped RENEW_ALLIANCE message type to warning color in message type classes.
src/client/graphics/layers/EventsDisplay.ts Added proactive warnings for expiring alliances and UI for extension requests.
src/client/graphics/layers/PlayerPanel.ts Changed alliance expiry calculation to use allianceExpiresAt instead of creation tick.
src/core/GameRunner.ts Updated player actions to use allianceExpiresAt instead of allianceCreatedAtTick.
src/core/Schemas.ts Added AllianceExtensionIntent type and schema to intent system.
src/core/configuration/Config.ts, src/core/configuration/DefaultConfig.ts Added config for alliance extension prompt offset (default 300 ticks/30 seconds).
src/core/execution/ExecutionManager.ts Added support for "allianceExtension" intent in execution manager.
src/core/execution/PlayerExecution.ts Changed alliance expiration check to use expiration tick.
src/core/execution/alliance/AllianceExtensionExecution.ts Added new execution class handling alliance extension logic.
src/core/game/AllianceImpl.ts Added extension requests, expiration, and renewal logic to alliances.
src/core/game/Game.ts Updated interfaces to support alliance expiration, extension, and renewal.
src/core/game/GameImpl.ts Added unique alliance IDs and prevented duplicate alliances.
src/core/game/GameUpdates.ts Added alliance extension update types, alliance view, and update tracking for alliances.
src/core/game/GameView.ts Added method to get alliances from player view.
src/core/game/PlayerImpl.ts Tracked expired alliances and included alliance info in player updates.
tests/AllianceExtensionExecution.test.ts Added tests for alliance extension scenarios.
resources/lang/en.json Added localized strings for alliance expiration and renewal messages and actions.

Sequence Diagram(s)

sequenceDiagram
    participant PlayerA
    participant PlayerB
    participant Client
    participant Server
    participant Game

    PlayerA->>Client: Receives warning about expiring alliance
    Client->>PlayerA: Shows "Renew Alliance?" prompt
    PlayerA->>Client: Clicks "Request Renewal"
    Client->>Server: Sends AllianceExtensionIntent (with PlayerB)
    Server->>Game: Processes intent
    Game->>Game: Checks if both players requested extension
    alt Both players requested
        Game->>Game: Extends alliance expiration
        Game->>PlayerA: Sends renewal confirmation
        Game->>PlayerB: Sends renewal confirmation
    else Only one player requested
        Game->>Game: Waits for other player's request
    end
Loading

Possibly related PRs

Suggested labels

Feature - Revision

Suggested reviewers

  • scottanderson

Poem

Alliances tick down, the timer is tight,
But now you can ask for a few more nights.
Warnings will show when time’s running low,
Click “Renew” and let friendship grow!
With IDs unique and timers anew,
Extending alliances is easy to do.
⏳🤝✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error Exit handler never called!
npm error This is an error with npm itself. Please report this error at:
npm error https://github.com/npm/cli/issues
npm error A complete log of this run can be found in: /.npm/_logs/2025-07-02T22_25_12_531Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dec1e06 and a6fea8d.

📒 Files selected for processing (3)
  • resources/lang/en.json (1 hunks)
  • src/core/configuration/DefaultConfig.ts (1 hunks)
  • src/core/game/Game.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/core/configuration/DefaultConfig.ts
  • resources/lang/en.json
  • src/core/game/Game.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Deploy to openfront.dev

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/core/execution/alliance/AllianceExtensionExecution.ts (1)

31-47: Consider message type and logging approach.

The extension logic is correct, but consider these improvements:

  1. MessageType.ALLIANCE_ACCEPTED might not be semantically correct for alliance renewals - consider a more specific message type like ALLIANCE_RENEWED.
  2. Console logging should use the game's logging system for consistency.
src/client/graphics/layers/EventsDisplay.ts (1)

54-54: Consider removing the unused tags field.

The tags? field is added to the GameEvent interface but doesn't appear to be used anywhere in the codebase.

-  tags?: string[];
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4e48eba and 2c99a15.

📒 Files selected for processing (19)
  • src/client/Transport.ts (3 hunks)
  • src/client/Utils.ts (1 hunks)
  • src/client/graphics/layers/EventsDisplay.ts (6 hunks)
  • src/client/graphics/layers/PlayerPanel.ts (1 hunks)
  • src/core/GameRunner.ts (1 hunks)
  • src/core/Schemas.ts (4 hunks)
  • src/core/configuration/Config.ts (1 hunks)
  • src/core/configuration/DefaultConfig.ts (1 hunks)
  • src/core/configuration/DevConfig.ts (1 hunks)
  • src/core/execution/ExecutionManager.ts (2 hunks)
  • src/core/execution/PlayerExecution.ts (1 hunks)
  • src/core/execution/alliance/AllianceExtensionExecution.ts (1 hunks)
  • src/core/game/AllianceImpl.ts (2 hunks)
  • src/core/game/Game.ts (6 hunks)
  • src/core/game/GameImpl.ts (4 hunks)
  • src/core/game/GameUpdates.ts (4 hunks)
  • src/core/game/GameView.ts (2 hunks)
  • src/core/game/PlayerImpl.ts (4 hunks)
  • tests/AllianceExtensionExecution.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (13)
📓 Common learnings
Learnt from: andrewNiziolek
PR: openfrontio/OpenFrontIO#1007
File: resources/lang/de.json:115-115
Timestamp: 2025-06-02T14:27:37.609Z
Learning: For OpenFrontIO project: When localization keys are renamed in language JSON files, the maintainers separate technical changes from translation content updates. They wait for community translators to update the actual translation values rather than attempting to translate in the same PR. This allows technical changes to proceed while ensuring accurate translations from native speakers.
src/core/GameRunner.ts (1)
Learnt from: Ble4Ch
PR: openfrontio/OpenFrontIO#1063
File: src/core/configuration/PastelThemeDark.ts:53-53
Timestamp: 2025-06-10T09:56:44.473Z
Learning: In ColorAllocator class in src/core/configuration/Colors.ts, the correct method names are assignColor(id: string): Colord for general color assignment and assignTeamColor(team: Team): Colord for team-specific colors. There are no assignPlayerColor() or assignBotColor() methods.
src/client/graphics/layers/PlayerPanel.ts (3)
Learnt from: 1brucben
PR: openfrontio/OpenFrontIO#977
File: src/core/execution/AttackExecution.ts:123-125
Timestamp: 2025-05-31T18:15:03.445Z
Learning: The removeTroops function in PlayerImpl.ts already prevents negative troop counts by using minInt(this._troops, toInt(troops)) to ensure it never removes more troops than available.
Learnt from: Ble4Ch
PR: openfrontio/OpenFrontIO#1063
File: src/core/configuration/PastelThemeDark.ts:53-53
Timestamp: 2025-06-10T09:56:44.473Z
Learning: In ColorAllocator class in src/core/configuration/Colors.ts, the correct method names are assignColor(id: string): Colord for general color assignment and assignTeamColor(team: Team): Colord for team-specific colors. There are no assignPlayerColor() or assignBotColor() methods.
Learnt from: VariableVince
PR: openfrontio/OpenFrontIO#1110
File: src/client/Main.ts:293-295
Timestamp: 2025-06-09T02:20:43.637Z
Learning: In src/client/Main.ts, during game start in the handleJoinLobby callback, UI elements are hidden using direct DOM manipulation with classList.add("hidden") for consistency. This includes modals, buttons, and error divs. The codebase follows this pattern rather than using component APIs for hiding elements during game transitions.
src/core/game/GameView.ts (3)
Learnt from: its-sii
PR: openfrontio/OpenFrontIO#1168
File: src/core/execution/WinCheckExecution.ts:157-176
Timestamp: 2025-06-13T20:53:16.380Z
Learning: In the alliance system, coalitions for peace voting are formed by taking each player with allies and creating a group of [player, ...player.allies()]. This means players can be in the same coalition even if they're not all directly allied with each other, as long as they share a common ally. For example, if A.allies()=[B], B.allies()=[A,C], and C.allies()=[B], then B, A, and C should be considered one coalition for voting purposes.
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1000
File: src/core/configuration/Config.ts:83-83
Timestamp: 2025-06-02T01:42:57.407Z
Learning: PlayerView implements the Player interface, so methods accepting Player parameters can also accept PlayerView arguments without issue.
Learnt from: VariableVince
PR: openfrontio/OpenFrontIO#1110
File: src/client/Main.ts:293-295
Timestamp: 2025-06-09T02:20:43.637Z
Learning: In src/client/Main.ts, during game start in the handleJoinLobby callback, UI elements are hidden using direct DOM manipulation with classList.add("hidden") for consistency. This includes modals, buttons, and error divs. The codebase follows this pattern rather than using component APIs for hiding elements during game transitions.
src/core/configuration/DevConfig.ts (1)
Learnt from: Ble4Ch
PR: openfrontio/OpenFrontIO#1063
File: src/core/configuration/PastelThemeDark.ts:53-53
Timestamp: 2025-06-10T09:56:44.473Z
Learning: In ColorAllocator class in src/core/configuration/Colors.ts, the correct method names are assignColor(id: string): Colord for general color assignment and assignTeamColor(team: Team): Colord for team-specific colors. There are no assignPlayerColor() or assignBotColor() methods.
src/core/execution/PlayerExecution.ts (1)
Learnt from: its-sii
PR: openfrontio/OpenFrontIO#1168
File: src/core/execution/WinCheckExecution.ts:157-176
Timestamp: 2025-06-13T20:53:16.380Z
Learning: In the alliance system, coalitions for peace voting are formed by taking each player with allies and creating a group of [player, ...player.allies()]. This means players can be in the same coalition even if they're not all directly allied with each other, as long as they share a common ally. For example, if A.allies()=[B], B.allies()=[A,C], and C.allies()=[B], then B, A, and C should be considered one coalition for voting purposes.
src/core/execution/ExecutionManager.ts (1)
Learnt from: Egraveline
PR: openfrontio/OpenFrontIO#1012
File: src/core/execution/UpgradeStructureExecution.ts:49-54
Timestamp: 2025-06-05T02:34:45.899Z
Learning: In the upgrade system, gold deduction for structure upgrades is handled internally by the `upgradeUnit` method in PlayerImpl, not in the UpgradeStructureExecution class. The UpgradeStructureExecution only needs to check if the player has sufficient gold before calling `upgradeUnit`.
src/core/Schemas.ts (4)
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: In Zod, when a schema has `.optional()` applied at the object level, the TypeScript type inferred using `z.infer` already includes `undefined` in the union type. Therefore, when using such a type as a return type annotation, there's no need to explicitly add `| undefined`.
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:189-209
Timestamp: 2025-05-18T23:43:38.150Z
Learning: When working with zod schemas in the OpenFrontIO project, values can be marked as possibly undefined by zod even if logic suggests they should always be defined. It's better to preserve the `| undefined` union types in method signatures to align with zod's type inference, even if runtime checks throw errors for invalid cases.
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:34-38
Timestamp: 2025-05-21T04:10:33.435Z
Learning: In the codebase, PlayerStats is defined as `z.infer<typeof PlayerStatsSchema>` where PlayerStatsSchema has `.optional()` applied at the object level, making PlayerStats a union type that already includes undefined (PlayerStats | undefined).
src/core/game/GameImpl.ts (4)
Learnt from: Ble4Ch
PR: openfrontio/OpenFrontIO#1063
File: src/core/configuration/PastelThemeDark.ts:53-53
Timestamp: 2025-06-10T09:56:44.473Z
Learning: In ColorAllocator class in src/core/configuration/Colors.ts, the correct method names are assignColor(id: string): Colord for general color assignment and assignTeamColor(team: Team): Colord for team-specific colors. There are no assignPlayerColor() or assignBotColor() methods.
Learnt from: 1brucben
PR: openfrontio/OpenFrontIO#977
File: src/core/execution/AttackExecution.ts:123-125
Timestamp: 2025-05-31T18:15:03.445Z
Learning: The removeTroops function in PlayerImpl.ts already prevents negative troop counts by using minInt(this._troops, toInt(troops)) to ensure it never removes more troops than available.
Learnt from: its-sii
PR: openfrontio/OpenFrontIO#1168
File: src/core/execution/WinCheckExecution.ts:157-176
Timestamp: 2025-06-13T20:53:16.380Z
Learning: In the alliance system, coalitions for peace voting are formed by taking each player with allies and creating a group of [player, ...player.allies()]. This means players can be in the same coalition even if they're not all directly allied with each other, as long as they share a common ally. For example, if A.allies()=[B], B.allies()=[A,C], and C.allies()=[B], then B, A, and C should be considered one coalition for voting purposes.
Learnt from: devalnor
PR: openfrontio/OpenFrontIO#1248
File: src/client/graphics/layers/TerritoryInfoLayer.ts:20-20
Timestamp: 2025-06-22T21:51:14.990Z
Learning: In TerritoryInfoLayer.ts, the highlightedTerritory field uses both null and undefined intentionally: undefined represents initial state or inactive layer (Ctrl released), while null represents active layer with no territory being highlighted at cursor position. This distinction is important for proper state change detection.
src/core/game/GameUpdates.ts (1)
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.
src/core/game/PlayerImpl.ts (2)
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#784
File: src/core/game/StatsImpl.ts:44-53
Timestamp: 2025-05-21T04:10:59.706Z
Learning: The PlayerStats type from ArchiveSchemas already includes undefined in its definition, making explicit union types with undefined (PlayerStats | undefined) redundant.
Learnt from: its-sii
PR: openfrontio/OpenFrontIO#1168
File: src/core/execution/WinCheckExecution.ts:157-176
Timestamp: 2025-06-13T20:53:16.380Z
Learning: In the alliance system, coalitions for peace voting are formed by taking each player with allies and creating a group of [player, ...player.allies()]. This means players can be in the same coalition even if they're not all directly allied with each other, as long as they share a common ally. For example, if A.allies()=[B], B.allies()=[A,C], and C.allies()=[B], then B, A, and C should be considered one coalition for voting purposes.
src/client/graphics/layers/EventsDisplay.ts (1)
Learnt from: VariableVince
PR: openfrontio/OpenFrontIO#1110
File: src/client/Main.ts:293-295
Timestamp: 2025-06-09T02:20:43.637Z
Learning: In src/client/Main.ts, during game start in the handleJoinLobby callback, UI elements are hidden using direct DOM manipulation with classList.add("hidden") for consistency. This includes modals, buttons, and error divs. The codebase follows this pattern rather than using component APIs for hiding elements during game transitions.
src/core/game/Game.ts (3)
Learnt from: its-sii
PR: openfrontio/OpenFrontIO#1168
File: src/core/execution/WinCheckExecution.ts:157-176
Timestamp: 2025-06-13T20:53:16.380Z
Learning: In the alliance system, coalitions for peace voting are formed by taking each player with allies and creating a group of [player, ...player.allies()]. This means players can be in the same coalition even if they're not all directly allied with each other, as long as they share a common ally. For example, if A.allies()=[B], B.allies()=[A,C], and C.allies()=[B], then B, A, and C should be considered one coalition for voting purposes.
Learnt from: Ble4Ch
PR: openfrontio/OpenFrontIO#1063
File: src/core/configuration/PastelThemeDark.ts:53-53
Timestamp: 2025-06-10T09:56:44.473Z
Learning: In ColorAllocator class in src/core/configuration/Colors.ts, the correct method names are assignColor(id: string): Colord for general color assignment and assignTeamColor(team: Team): Colord for team-specific colors. There are no assignPlayerColor() or assignBotColor() methods.
Learnt from: devalnor
PR: openfrontio/OpenFrontIO#1248
File: src/client/graphics/layers/TerritoryInfoLayer.ts:20-20
Timestamp: 2025-06-22T21:51:14.990Z
Learning: In TerritoryInfoLayer.ts, the highlightedTerritory field uses both null and undefined intentionally: undefined represents initial state or inactive layer (Ctrl released), while null represents active layer with no territory being highlighted at cursor position. This distinction is important for proper state change detection.
🧬 Code Graph Analysis (6)
src/client/graphics/layers/PlayerPanel.ts (1)
src/core/game/AllianceImpl.ts (1)
  • expiresAt (66-68)
src/core/game/GameView.ts (1)
src/core/game/GameUpdates.ts (1)
  • AllianceView (165-170)
src/core/game/GameUpdates.ts (1)
src/core/game/Game.ts (2)
  • PlayerID (14-14)
  • Tick (15-15)
src/core/game/PlayerImpl.ts (2)
src/core/game/Game.ts (1)
  • Alliance (337-343)
src/core/game/GameUpdates.ts (1)
  • AllianceView (165-170)
src/client/graphics/layers/EventsDisplay.ts (5)
src/core/game/GameView.ts (2)
  • myPlayer (474-479)
  • PlayerView (145-328)
src/core/game/AllianceImpl.ts (1)
  • other (19-24)
src/client/Utils.ts (1)
  • translateText (79-98)
src/client/graphics/layers/Leaderboard.ts (1)
  • GoToPlayerEvent (20-22)
src/client/Transport.ts (1)
  • SendAllianceExtensionIntentEvent (70-72)
src/core/game/AllianceImpl.ts (3)
src/core/game/Game.ts (3)
  • Tick (15-15)
  • Game (598-672)
  • Player (466-596)
src/core/Schemas.ts (1)
  • Player (109-109)
src/core/game/GameImpl.ts (1)
  • player (429-435)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: 🏗️ Build
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Deploy to openfront.dev
🔇 Additional comments (50)
src/core/configuration/DefaultConfig.ts (1)

841-843: LGTM! Clean implementation of alliance extension prompt timing.

The method correctly implements the interface requirement and the 30-second offset before expiration is a reasonable default for user experience.

src/core/game/GameView.ts (2)

27-27: LGTM! Proper import for alliance view functionality.

The import follows the established pattern and is necessary for the new alliance access method.


295-297: LGTM! Clean accessor method following established patterns.

The alliances() method follows the same pattern as other accessor methods in this class (allies(), targets(), etc.) and provides necessary access to alliance data for the extension feature.

src/core/configuration/Config.ts (1)

161-161: LGTM! Well-named interface method for alliance extension timing.

The method signature is clear and follows established naming conventions in the Config interface.

src/client/Utils.ts (1)

144-144: LGTM! Appropriate warning message styling for alliance notifications.

The MessageType.WARN case is properly grouped with other warning-type messages and uses the appropriate yellow warning color.

src/core/execution/ExecutionManager.ts (2)

5-5: LGTM! Import follows established patterns.

The import is correctly placed with other alliance execution imports.


115-118: LGTM! Intent handling follows consistent patterns.

The new alliance extension case correctly follows the same pattern as other alliance intents, taking the player and recipient parameters.

src/core/execution/PlayerExecution.ts (1)

75-75: Good improvement! Simplified alliance expiration logic.

Using precomputed expiration timestamps is cleaner and more efficient than calculating elapsed time on each tick. The logic correctly expires alliances when current ticks reach the expiration time.

src/core/configuration/DevConfig.ts (1)

53-59: LGTM! Development configuration values are reasonable.

The alliance duration of 30 seconds and prompt offset of 10 seconds provide good testing values. The 30 * 10 calculation clearly shows the intent (30 seconds at 10 ticks per second).

src/client/graphics/layers/PlayerPanel.ts (1)

179-181: LGTM! Correctly adapts to new alliance expiration tracking.

Using allianceExpiresAt directly is more reliable than calculating from creation time plus duration. This aligns well with the server-side changes to precompute expiration timestamps.

src/client/Transport.ts (3)

70-72: LGTM! Event class follows established patterns.

The SendAllianceExtensionIntentEvent correctly follows the same pattern as other alliance events with a simple recipient property.


201-203: LGTM! Event registration follows consistent pattern.

The event bus registration correctly follows the same pattern as other intent events in the constructor.


429-437: LGTM! Handler implementation follows established patterns.

The alliance extension intent handler correctly follows the same structure as other alliance intent handlers, sending the appropriate intent with client ID and recipient.

tests/AllianceExtensionExecution.test.ts (2)

55-89: Excellent test coverage for the happy path scenario.

The test properly verifies that alliance extension maintains the same alliance instance while updating expiration. The assertion checking allianceAfter.id() === allianceBefore.id() is particularly important for ensuring alliance identity preservation.


91-97: Good defensive test for non-existent alliance scenario.

This test ensures the system gracefully handles attempts to extend alliances that don't exist, which is essential for robust error handling.

src/core/game/PlayerImpl.ts (3)

93-93: Well-named field following existing conventions.

The _expiredAlliances field follows the established naming pattern and properly tracks expired alliances for the player.


175-183: Proper alliance view serialization with complete data.

The alliance mapping correctly provides all required fields from the AllianceView interface including ID, other player, and expiration timing. The use of satisfies AllianceView ensures type safety.


360-362: Clean getter method following established patterns.

The expiredAlliances() method correctly returns a defensive copy of the expired alliances array, following the same pattern as other similar methods in the class.

src/core/game/GameImpl.ts (3)

81-82: Good addition of unique alliance ID tracking.

The nextAllianceID field enables proper alliance identification for extension functionality. The initialization to 0 is appropriate.


154-156: Consistent public accessor method.

The alliances() method follows the established pattern of exposing internal collections and correctly returns the typed MutableAlliance[].


256-256: Proper unique ID assignment for new alliances.

The use of this.nextAllianceID++ correctly assigns unique IDs to each alliance and increments the counter for the next alliance.

src/core/Schemas.ts (4)

28-28: Proper addition to Intent union type.

The AllianceExtensionIntent is correctly added to the Intent union type, maintaining alphabetical ordering with other alliance-related intents.


71-73: Consistent type export pattern.

The type export follows the established pattern using z.infer and maintains consistency with other intent type exports in the file.


220-223: Well-structured schema definition.

The AllianceExtensionIntentSchema correctly extends BaseIntentSchema with the appropriate type literal and recipient field, following the same pattern as AllianceRequestIntentSchema.


366-366: Proper integration with discriminated union.

The schema is correctly added to the discriminated union array, enabling proper validation and type discrimination.

src/core/execution/alliance/AllianceExtensionExecution.ts (2)

15-29: Solid validation logic with proper error handling.

The validation correctly checks for player existence and alliance existence before proceeding. The early returns prevent unnecessary processing when preconditions aren't met.


50-61: Standard execution interface implementation.

The execution interface methods are properly implemented with appropriate return values for this type of one-time execution.

src/core/game/GameUpdates.ts (5)

39-39: Clean addition to the enum.

The new AllianceExtension enum value follows the existing naming convention and fits well with other alliance-related types.


64-64: Proper integration into the union type.

The AllianceExtensionUpdate type is correctly added to the GameUpdate union, maintaining type safety.


160-160: Good addition of alliance data to player updates.

Adding the alliances array to PlayerUpdate provides clients with the necessary alliance expiration information.


165-170: Well-designed AllianceView interface.

The interface is clean and provides all necessary data for tracking alliance expiration. The naming is consistent with other view interfaces in the codebase.


197-201: Simple and focused update interface.

The AllianceExtensionUpdate interface contains exactly the data needed for alliance extension events. Good adherence to the single responsibility principle.

src/core/game/AllianceImpl.ts (6)

4-7: Good state tracking for extension requests.

The boolean flags for tracking extension requests from both players are clear and the expiresAt_ field properly manages alliance expiration timing.


13-17: Proper constructor updates with expiration calculation.

The constructor correctly calculates the expiration time by adding the alliance duration to the creation time. The alliance ID parameter addition supports proper tracking.


42-48: Clean extension request handling.

The method correctly identifies which player is making the request and sets the appropriate flag. The logic is straightforward and handles both requestor and recipient cases.


50-54: Simple and effective extension eligibility check.

The canExtend() method requires both players to have requested extension, which is the expected behavior for mutual agreement.


60-64: Proper extension implementation.

The extend() method correctly resets the extension request flags and updates the expiration time to the current game tick plus the alliance duration.


66-68: Simple getter method.

The expiresAt() method provides clean access to the expiration timestamp.

src/client/graphics/layers/EventsDisplay.ts (5)

35-35: Proper import for alliance extension events.

The import follows the existing pattern and provides access to the alliance extension intent event.


80-81: Smart spam prevention with alliance tracking.

The alliancesCheckedAt map prevents repeated warnings for the same alliance, which improves user experience.


188-188: Good integration into the tick cycle.

Calling checkForAllianceExpirations() at the beginning of the tick ensures timely warnings before other updates are processed.


243-292: Well-implemented alliance expiration checking.

The method correctly:

  • Checks each alliance for upcoming expiration
  • Prevents duplicate warnings using the tracking map
  • Creates user-friendly warning events with appropriate buttons
  • Uses proper translation keys for internationalization

The logic for determining when to show warnings is sound.


516-537: Clean alliance expiration event handling.

The handler correctly identifies which player the current user had an alliance with and displays an appropriate message. The logic handles edge cases well.

src/core/game/Game.ts (7)

341-341: Good addition of expiration tracking to Alliance interface.

Adding expiresAt() method to the base Alliance interface provides consistent access to expiration information across the codebase.


348-351: Well-designed extension methods for MutableAlliance.

The new methods provide a complete API for alliance extension:

  • canExtend() for checking eligibility
  • addExtensionRequest() for tracking requests
  • extend() for performing the extension
  • id() for alliance identification

The interface follows good design principles with focused, single-purpose methods.


543-543: Useful addition of expired alliance tracking.

Adding expiredAlliances() to the Player interface allows tracking of alliance history, which could be useful for UI and game logic.


620-621: Proper alliance management methods in Game interface.

The alliances() and expireAlliance() methods provide necessary game-level alliance management capabilities.


704-704: Smart migration from creation time to expiration time.

Changing from allianceCreatedAtTick to allianceExpiresAt in PlayerInteraction makes the timing information more directly useful for UI display and warning logic.


739-739: Appropriate addition of WARN message type.

The new WARN message type fills a gap in the messaging system for alliance expiration warnings and other non-critical alerts.


770-770: Correct categorization of WARN messages.

Placing WARN messages in the ALLIANCE category makes sense since the primary use case is alliance expiration warnings.

Comment thread src/core/GameRunner.ts
const alliance = player.allianceWith(other as Player);
if (alliance) {
actions.interaction.allianceCreatedAtTick = alliance.createdAt();
actions.interaction.allianceExpiresAt = alliance.expiresAt();

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.

💡 Verification agent

🧩 Analysis chain

Verify property name change consistency and method existence.

The property name change from allianceCreatedAtTick to allianceExpiresAt aligns with the alliance extension feature. However, ensure that client-side code expecting this property has been updated accordingly.


🏁 Script executed:

#!/bin/bash
# Description: Verify that the property name change is consistent and the expiresAt() method exists

# Test 1: Check for any remaining references to the old property name
echo "=== Checking for remaining references to allianceCreatedAtTick ==="
rg "allianceCreatedAtTick" --type ts

# Test 2: Check for usage of the new property name
echo "=== Checking usage of allianceExpiresAt ==="
rg "allianceExpiresAt" --type ts -A 2

# Test 3: Verify expiresAt method exists on alliance objects
echo "=== Checking for expiresAt method definition ==="
ast-grep --pattern 'expiresAt() {
  $$$
}'

Length of output: 1098


Add missing expiresAt() method to Alliance

We’ve confirmed that:

  • There are no remaining references to the old allianceCreatedAtTick.
  • The new allianceExpiresAt property is used consistently in:
    • src/core/GameRunner.ts
    • src/core/game/Game.ts
    • src/client/graphics/layers/PlayerPanel.ts
  • However, we didn’t find any implementation of expiresAt() on the alliance object, so calling alliance.expiresAt() will fail at runtime.

Please implement the expiresAt(): Tick method (or equivalent) on your Alliance type/class—e.g. in src/core/game/Alliance.ts or wherever you define Alliance—so that the client and server both have a valid expiration timestamp.

🤖 Prompt for AI Agents
In src/core/GameRunner.ts at line 199, the code calls alliance.expiresAt(), but
the Alliance class lacks this method, causing runtime errors. To fix this, add
an expiresAt(): Tick method to the Alliance class, likely in
src/core/game/Alliance.ts, that returns the expiration timestamp of the
alliance. This ensures the property allianceExpiresAt is correctly set and
consistent across client and server.

Comment thread src/core/game/GameImpl.ts Outdated
Comment on lines +243 to +248
// TODO: remove this or throw error?
// Remove any existing alliance between the requestor and recipient
const existing = requestor.allianceWith(recipient);
if (existing) {
this.alliances_ = this.alliances_.filter((a) => a !== existing);
}

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.

💡 Verification agent

🧩 Analysis chain

Address the TODO comment about existing alliance removal.

The code removes existing alliances before creating new ones, but the TODO suggests uncertainty about this behavior. This logic might be incorrect - typically alliance requests should be rejected if an alliance already exists rather than replacing it.


🏁 Script executed:

#!/bin/bash
# Search for other alliance creation logic to understand expected behavior
rg -A 10 -B 5 "allianceWith.*existing|existing.*alliance" --type ts

Length of output: 3278


Clarify and remove the TODO in alliance‐extension logic

The removal of an existing alliance is intentional (see the “Successfully extends existing alliance” test), so delete the // TODO and update the comment to explain that you’re replacing an old alliance to extend it.

• File: src/core/game/GameImpl.ts
Lines ~243–248
– Remove the // TODO: remove this or throw error? line
– Change the comment above existing to something like:
// Extend any existing alliance by removing it before creating a new one

Suggested diff:

-    // TODO: remove this or throw error?
-    // Remove any existing alliance between the requestor and recipient
+    // Extend an existing alliance by removing it before creating a new one
     const existing = requestor.allianceWith(recipient);
     if (existing) {
       this.alliances_ = this.alliances_.filter((a) => a !== existing);
     }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// TODO: remove this or throw error?
// Remove any existing alliance between the requestor and recipient
const existing = requestor.allianceWith(recipient);
if (existing) {
this.alliances_ = this.alliances_.filter((a) => a !== existing);
}
// Extend an existing alliance by removing it before creating a new one
const existing = requestor.allianceWith(recipient);
if (existing) {
this.alliances_ = this.alliances_.filter((a) => a !== existing);
}
🤖 Prompt for AI Agents
In src/core/game/GameImpl.ts around lines 243 to 248, remove the TODO comment
"// TODO: remove this or throw error?" and update the existing comment to
clarify the intent by explaining that the code removes any existing alliance to
extend it. Change the comment to something like "// Extend any existing alliance
by removing it before creating a new one" to clearly document the purpose of
this logic.

@github-project-automation github-project-automation Bot moved this from Triage to Development in OpenFront Release Management Jul 1, 2025
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from 2c99a15 to b267006 Compare July 1, 2025 15:48
@evanpelle evanpelle changed the title allow alliance extension allow alliance extension Fixes #491 Jul 2, 2025
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from b267006 to c892868 Compare July 2, 2025 14:57
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from c892868 to 9c2cfc9 Compare July 2, 2025 15:44
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from 9c2cfc9 to 6a54da4 Compare July 2, 2025 17:17
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from 6a54da4 to c1aa97c Compare July 2, 2025 17:31
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from c1aa97c to c25d57d Compare July 2, 2025 17:32
@evanpelle
evanpelle marked this pull request as ready for review July 2, 2025 17:33
@evanpelle
evanpelle requested a review from a team as a code owner July 2, 2025 17:33
@evanpelle evanpelle added this to the v24 milestone Jul 2, 2025
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from 3bf9ca3 to 5359168 Compare July 2, 2025 17:33
@evanpelle
evanpelle force-pushed the evan-alliance-extension branch from 5359168 to dec1e06 Compare July 2, 2025 22:10
@evanpelle
evanpelle merged commit 5b5ac7b into main Jul 2, 2025
@evanpelle
evanpelle deleted the evan-alliance-extension branch July 2, 2025 22:25
@github-project-automation github-project-automation Bot moved this from Development to Complete in OpenFront Release Management Jul 2, 2025

This branch was previously deployed

1 inactive deployment
staging — a6fea8df Deployed Jul 2, 2025 by openfrontio[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Complete

Development

Successfully merging this pull request may close these issues.

1 participant