Skip to content

Ai building weights rework and upgrades - #2197

Closed
Hiphex wants to merge 15 commits into
openfrontio:mainfrom
Hiphex:feature/fake-human-build-revamp
Closed

Hiphex wants to merge 15 commits into
openfrontio:mainfrom
Hiphex:feature/fake-human-build-revamp

Conversation

@Hiphex

@Hiphex Hiphex commented Oct 14, 2025

Copy link
Copy Markdown
Contributor

Description:

-Reworks AI build heuristics so AI weighs defense, economy, and missile options with spacing-aware cluster rules, and applies unbiased tie-breakers.

-Adds infrastructure clustering logic, complementary placement scoring, and documentation/comments explaining the new multipliers and upgrade paths.

-Tightens BuildMenu wiring in src/client/graphics/layers/BuildMenu.ts so UI reflects the priorities, and updates src/client/Utils.ts helpers (including translate placeholders) to support the new behaviour.

-Expands structureSpawnTileValue tests to cover clustering scenarios, fixing mock contracts and making the test harness match the stricter TypeScript expectations

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

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

Hiphex

@coderabbitai

coderabbitai Bot commented Oct 14, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds client utilities (number/time rendering, canvas, keys, resilient storage, translation fallback), extends BuildMenu with lifecycle/affordability, refactors FakeHumanExecution into an urgency/budget-driven action loop, enhances structure spawn scoring with cluster-awareness, and adds tests and an English translation entry.

Changes

Cohort / File(s) Summary
Client utilities & i18n
src/client/Utils.ts, resources/lang/en.json, tests/client/Utils.translate.test.ts
New formatting helpers (renderNumber, renderTroops, renderDuration), canvas factory, key-label helpers, resilient localStorage (getGamesPlayed, incrementGamesPlayed), iframe check, translation cache reset, non-browser translateText fallback using resources/lang/en.json, added Severity type and severityColors. Adds build_menu.desc.unavailable. Tests for translation fallback and placeholder handling.
Build menu UI / behavior
src/client/graphics/layers/BuildMenu.ts
Exposes eventBus, playerActions, styles; adds lifecycle (init, tick), visibility controls (showMenu, hideMenu, isVisible), refresh/filtering, affordability checks and badge rendering, cost/count helpers, sendBuildOrUpgrade integration.
AI execution & action budgeting
src/core/execution/FakeHumanExecution.ts
Rewrites handleUnits() to return boolean and run a prioritized, urgency-driven action loop; adds economic budget (maxEconomicActions), ordering (determineNeedDrivenOrder), action builders, multipliers, many urgency metrics, upgraded spawn/upgrade flow, maybeSpawnWarship(force) signature change, and imports UpgradeStructureExecution.
Placement scoring & tests
src/core/execution/nation/structureSpawnTileValue.ts, tests/core/execution/structureSpawnTileValue.test.ts
Adds cluster-aware placement scoring (complementary placement, cluster tiles, SAM protection awareness, stable-ground and spacing logic), unified closestTile usage, exports scorer factory structureSpawnTileValue. Adds test asserting higher city spawn score when ports are present nearby.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant P as Player
  participant EB as EventBus
  participant BM as BuildMenu
  participant PA as PlayerActions
  participant G as Game

  P->>EB: ShowBuildMenuEvent(tile)
  EB-->>BM: event
  BM->>BM: showMenu(tile) / refresh()
  BM->>BM: getBuildableUnits() & canBuildOrUpgrade()
  P->>BM: click Build/Upgrade
  BM->>PA: sendBuildOrUpgrade(unit, tile)
  PA->>G: enqueue action
  BM->>BM: hideMenu() (optional)
Loading
sequenceDiagram
  autonumber
  participant T as Tick
  participant FH as FakeHumanExecution
  participant G as Game
  participant U as UpgradeExecution
  participant S as SpawnExecution

  T->>FH: handleUnits()
  FH->>FH: determineNeedDrivenOrder()
  FH->>FH: maxEconomicActions()
  loop up to max actions
    FH->>FH: buildActionsForTypes()
    alt upgrade path
      FH->>U: maybeUpgradeStructure(type)
      U-->>FH: success?
    else spawn path
      FH->>G: structureSpawnTile(type)
      FH->>S: spawn at tile
      S-->>FH: success?
    end
    opt naval urgency
      FH->>FH: maybeSpawnWarship(force)
    end
  end
  FH-->>T: didAct (boolean)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

Suggested labels

Feature - AI, Feature - Simulation, Feature - Frontend, Balance Tweak

Suggested reviewers

  • scottanderson
  • TheGiraffe3
  • evanpelle

Poem

Numbers round and clocks condense,
A canvas opens, wide and dense.
Menus show what coins permit,
AI plots each urgent bit.
Clusters nudge where cities go —
Translations hum, “Now watch it flow.”

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed The pull request title "Ai building weights rework and upgrades" directly relates to the primary changes in the changeset. The title accurately reflects the core objective of reworking AI build heuristics (the "building weights") and introducing upgrade support via the new maybeUpgradeStructure method in FakeHumanExecution.ts. The title is concise, specific, and avoids vague terminology, making it clear to a reader scanning history that this PR involves AI decision-making improvements and new upgrade functionality.
Description Check ✅ Passed The pull request description is clearly related to the changeset and describes real, meaningful aspects of the changes. It mentions reworking AI build heuristics with defense, economy, and missile options; adding infrastructure clustering and complementary placement scoring; tightening BuildMenu wiring; updating Utils.ts helpers; and expanding tests—all of which correspond directly to the actual file modifications in FakeHumanExecution.ts, structureSpawnTileValue.ts, BuildMenu.ts, Utils.ts, and the new test files. The description is substantive and conveys useful information about the PR's purpose and scope.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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.

@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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/client/Utils.ts (1)

89-104: Fix ReferenceError when crypto is absent (use typeof/globalThis).

Directly referencing crypto will throw in non‑browser runtimes. Guard with typeof and reuse a local cryptoObj.

Apply:

-  // Type guard to check if randomUUID is available
-  if (crypto !== undefined && "randomUUID" in crypto) {
-    return crypto.randomUUID();
-  }
+  // Type guard to check if randomUUID is available
+  const cryptoObj: any =
+    typeof crypto !== "undefined" ? crypto : (typeof globalThis !== "undefined" ? (globalThis as any).crypto : undefined);
+  if (cryptoObj && typeof cryptoObj.randomUUID === "function") {
+    return cryptoObj.randomUUID();
+  }
@@
-  // Fallback using crypto.getRandomValues
-  if (crypto !== undefined && "getRandomValues" in crypto) {
+  // Fallback using crypto.getRandomValues
+  if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
     return (([1e7] as any) + -1e3 + -4e3 + -8e3 + -1e11).replace(
       /[018]/g,
       (c: number): string =>
         (
           c ^
-          (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
+          (cryptoObj.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))
         ).toString(16),
     );
   }
🧹 Nitpick comments (10)
src/client/Utils.ts (3)

147-153: Avoid dynamic RegExp; use split/join to substitute placeholders.

This removes ReDoS concerns and is simpler.

Based on static analysis hints

-    // Simple placeholder substitution
-    for (const [paramKey, paramValue] of Object.entries(params)) {
-      const pattern = new RegExp(`\\{${escapeRegex(paramKey)}\\}`, "g");
-      message = message.replace(pattern, String(paramValue));
-    }
+    // Simple placeholder substitution without RegExp
+    for (const [paramKey, paramValue] of Object.entries(params)) {
+      const token = `{${paramKey}}`;
+      message = message.split(token).join(String(paramValue));
+    }

258-265: Guard navigator for non‑browser envs.

Prevent ReferenceError in tests/SSR.

-export function getModifierKey(): string {
-  const isMac = /Mac/.test(navigator.userAgent);
+export function getModifierKey(): string {
+  const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
+  const isMac = /Mac/.test(ua);
@@
-export function getAltKey(): string {
-  const isMac = /Mac/.test(navigator.userAgent);
+export function getAltKey(): string {
+  const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
+  const isMac = /Mac/.test(ua);

Also applies to: 270-277


70-82: Consider sizing canvas for devicePixelRatio.

Setting only CSS size can blur rendering on HiDPI. Optionally set width/height attributes to innerWidth/innerHeight × DPR and scale context.

src/core/execution/nation/structureSpawnTileValue.ts (3)

82-85: Guard Infinity from empty borderTiles before scoring.

If borderTiles is empty, closestBorderDist is Infinity and adds an unintended max bonus. Align with other branches’ checks.

-        const [, closestBorderDist] = closestTile(mg, borderTiles, tile);
-        w += Math.min(closestBorderDist, borderSpacing);
+        const [, closestBorderDist] = closestTile(mg, borderTiles, tile);
+        if (Number.isFinite(closestBorderDist)) {
+          w += Math.min(closestBorderDist, borderSpacing);
+        }

156-158: Same Infinity guard for MissileSilo border distance.

Mirror the check to avoid accidental bonus.

-        const [, closestBorderDist] = closestTile(mg, borderTiles, tile);
-        w += Math.min(closestBorderDist, borderSpacing * 1.5);
+        const [, closestBorderDist] = closestTile(mg, borderTiles, tile);
+        if (Number.isFinite(closestBorderDist)) {
+          w += Math.min(closestBorderDist, borderSpacing * 1.5);
+        }

196-199: Consider consistent handling when no same‑type structures exist.

Currently, Port gets full spacing bonus when none exist; other types only add when distance is finite. Pick one behavior and apply across types for predictability.

tests/core/execution/structureSpawnTileValue.test.ts (1)

56-68: Nice focused harness. Add euclideanDistSquared stub for future SAM tests.

Preempt breakage if SAM cases are added. Low effort.

src/client/graphics/layers/BuildMenu.ts (2)

174-179: Throttle refresh while visible to reduce churn.

Refreshing every tick can spam actions() calls. Debounce to ~200–300ms.

   tick() {
-    if (!this._hidden) {
-      this.refresh();
-    }
+    if (this._hidden) return;
+    (this as any)._lastRefreshTs ??= 0;
+    const now = Date.now();
+    if (now - (this as any)._lastRefreshTs > 250) {
+      (this as any)._lastRefreshTs = now;
+      this.refresh();
+    }
   }

522-525: Disabled tooltip may be misleading.

“Not enough money” might be wrong when the tile/unit is unavailable for other reasons. Consider a more generic message or compute reason.

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

413-471: Track a per‑tick “planned” gold budget to avoid overspending across multiple actions.

addExecution defers cost deduction; multiple builds/upgrades can exceed available gold within the same tick. Track a local budget and pass it through checks to keep scheduling consistent.

Proposed approach:

  • In handleUnits(), set let remaining = this.player.gold();
  • When an action succeeds, decrement remaining by the action’s cost.
  • Have maybeSpawnStructure accept an optional remaining parameter (or closure capturing remaining) and compare against perceivedCost; similar for upgrades if costs are exposed.

Also applies to: 799-821

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5f6b85e and 5aaf34e.

📒 Files selected for processing (5)
  • src/client/Utils.ts (11 hunks)
  • src/client/graphics/layers/BuildMenu.ts (16 hunks)
  • src/core/execution/FakeHumanExecution.ts (4 hunks)
  • src/core/execution/nation/structureSpawnTileValue.ts (6 hunks)
  • tests/core/execution/structureSpawnTileValue.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-23T08:03:44.914Z
Learnt from: ElMelchizedek
PR: openfrontio/OpenFrontIO#1876
File: src/core/execution/FakeHumanExecution.ts:547-592
Timestamp: 2025-08-23T08:03:44.914Z
Learning: In OpenFrontIO, FakeHumanExecution is used for AI-controlled nations that simulate human behavior, which is distinct from PlayerType.Bot. FakeHumanExecution players are not PlayerType.Bot - they represent more sophisticated AI that mimics human nation behavior, while PlayerType.Bot represents basic AI players.

Applied to files:

  • src/core/execution/FakeHumanExecution.ts
🧬 Code graph analysis (5)
src/core/execution/nation/structureSpawnTileValue.ts (3)
src/core/game/Game.ts (1)
  • Game (653-737)
src/core/game/GameMap.ts (1)
  • TileRef (3-3)
src/core/execution/Util.ts (1)
  • closestTile (9-24)
tests/core/execution/structureSpawnTileValue.test.ts (3)
src/core/game/GameMap.ts (1)
  • TileRef (3-3)
src/core/game/Game.ts (1)
  • Unit (427-502)
src/core/execution/nation/structureSpawnTileValue.ts (1)
  • structureSpawnTileValue (45-361)
src/client/Utils.ts (4)
src/core/game/GameView.ts (2)
  • troops (93-95)
  • troops (362-364)
src/core/game/UnitImpl.ts (1)
  • troops (164-166)
src/core/game/PlayerImpl.ts (1)
  • troops (789-791)
src/core/game/AttackImpl.ts (1)
  • troops (32-34)
src/core/execution/FakeHumanExecution.ts (2)
src/core/game/Game.ts (2)
  • Player (517-651)
  • PlayerID (21-21)
src/core/execution/UpgradeStructureExecution.ts (1)
  • UpgradeStructureExecution (3-43)
src/client/graphics/layers/BuildMenu.ts (4)
src/core/game/Game.ts (1)
  • BuildableUnit (746-752)
src/core/game/GameView.ts (3)
  • player (583-589)
  • cost (724-726)
  • gold (358-360)
src/client/graphics/layers/UnitDisplay.ts (1)
  • cost (68-75)
src/client/Utils.ts (1)
  • translateText (117-202)
🪛 ast-grep (0.39.6)
src/client/Utils.ts

[warning] 148-148: Regular expression constructed from variable input detected. This can lead to Regular Expression Denial of Service (ReDoS) attacks if the variable contains malicious patterns. Use libraries like 'recheck' to validate regex safety or use static patterns.
Context: new RegExp(\\{${escapeRegex(paramKey)}\\}, "g")
Note: [CWE-1333] Inefficient Regular Expression Complexity [REFERENCES]
- https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS
- https://cwe.mitre.org/data/definitions/1333.html

(regexp-from-variable)

🔇 Additional comments (2)
src/client/graphics/layers/BuildMenu.ts (1)

490-571: Overall BuildMenu wiring looks solid.

Good: availability class, affordability badge, count chip, translateText usage, compact costs via renderNumber.

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

730-756: Good hostiles detection and human‑like heuristics.

The neighbor scan avoids allies/teams; tie‑breakers are randomized. Clear and idiomatic.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 14, 2025

@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: 0

🧹 Nitpick comments (3)
src/core/execution/nation/structureSpawnTileValue.ts (1)

96-144: Consider extracting complementary preferences to constants.

The nested arrays of ClusterPreference objects for City and Factory are quite verbose and make the code harder to scan. Consider extracting these as named constants at module level to improve readability and make future tuning easier.

Example refactor:

const CITY_COMPLEMENTARY_PREFS: Array<[Set<TileRef>, ClusterPreference]> = [
  // Can be initialized in the function where sets are available
];

However, since these reference the sets created in the function scope, you'd need to keep them as-is or restructure. Given the complexity, this is an optional improvement.

tests/core/execution/structureSpawnTileValue.test.ts (1)

70-90: Consider expanding test coverage.

While this test validates that ports influence city placement positively, consider adding tests for:

  • Edge cases with empty unit sets
  • Different structure types (Factory, MissileSilo, SAMLauncher, DefensePost)
  • Boundary conditions (very close vs very far structures)
  • Negative cases (e.g., structures too close should reduce score)

These additional tests would increase confidence in the clustering logic, especially given the complexity of the scoring algorithm.

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

506-558: Conditional rendering could be simplified.

The logic for showing the affordability badge and determining button classes involves multiple ternary operators and variable assignments. Consider extracting this into a separate method to improve readability.

Example:

private renderBuildButton(item: BuildItemDisplay, buildableUnit: BuildableUnit) {
  const enabled = buildableUnit.canBuild !== false || buildableUnit.canUpgrade !== false;
  const affordability = this.affordableCountLabel(item, buildableUnit);
  const buttonClass = `build-button${affordability ? " build-button--available" : ""}`;
  const showMoneyWarning = !enabled && buildableUnit.canBuild !== false;
  
  // ... rest of render logic
}

This would make the main render function more readable, though it's not critical.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5aaf34e and 410c10a.

📒 Files selected for processing (7)
  • resources/lang/en.json (1 hunks)
  • src/client/Utils.ts (11 hunks)
  • src/client/graphics/layers/BuildMenu.ts (15 hunks)
  • src/core/execution/FakeHumanExecution.ts (4 hunks)
  • src/core/execution/nation/structureSpawnTileValue.ts (6 hunks)
  • tests/client/Utils.translate.test.ts (1 hunks)
  • tests/core/execution/structureSpawnTileValue.test.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-08-23T08:03:44.914Z
Learnt from: ElMelchizedek
PR: openfrontio/OpenFrontIO#1876
File: src/core/execution/FakeHumanExecution.ts:547-592
Timestamp: 2025-08-23T08:03:44.914Z
Learning: In OpenFrontIO, FakeHumanExecution is used for AI-controlled nations that simulate human behavior, which is distinct from PlayerType.Bot. FakeHumanExecution players are not PlayerType.Bot - they represent more sophisticated AI that mimics human nation behavior, while PlayerType.Bot represents basic AI players.

Applied to files:

  • src/core/execution/FakeHumanExecution.ts
🧬 Code graph analysis (6)
src/core/execution/nation/structureSpawnTileValue.ts (3)
src/core/game/Game.ts (1)
  • Game (653-737)
src/core/game/GameMap.ts (1)
  • TileRef (3-3)
src/core/execution/Util.ts (1)
  • closestTile (9-24)
src/client/graphics/layers/BuildMenu.ts (6)
src/core/game/Game.ts (1)
  • BuildableUnit (746-752)
src/core/game/GameView.ts (3)
  • player (589-595)
  • cost (730-732)
  • gold (358-360)
src/client/graphics/layers/UnitDisplay.ts (1)
  • cost (68-75)
src/core/game/GameMap.ts (2)
  • cost (248-250)
  • TileRef (3-3)
src/core/game/PlayerImpl.ts (1)
  • gold (764-766)
src/client/Utils.ts (1)
  • translateText (171-267)
src/core/execution/FakeHumanExecution.ts (3)
src/core/game/PlayerImpl.ts (4)
  • type (200-202)
  • gold (764-766)
  • relation (448-454)
  • borderTiles (282-284)
src/core/game/Game.ts (2)
  • Player (517-651)
  • PlayerID (21-21)
src/core/execution/UpgradeStructureExecution.ts (1)
  • UpgradeStructureExecution (3-43)
tests/client/Utils.translate.test.ts (1)
src/client/Utils.ts (2)
  • __resetTranslationCacheForTesting (391-400)
  • translateText (171-267)
src/client/Utils.ts (6)
src/core/game/GameView.ts (4)
  • troops (93-95)
  • troops (362-364)
  • width (673-675)
  • height (676-678)
src/core/game/PlayerImpl.ts (1)
  • troops (790-792)
src/core/game/UnitImpl.ts (1)
  • troops (164-166)
src/core/game/AttackImpl.ts (1)
  • troops (32-34)
src/client/graphics/GameRenderer.ts (1)
  • resize (386-389)
src/client/LangSelector.ts (1)
  • translateText (254-274)
tests/core/execution/structureSpawnTileValue.test.ts (3)
src/core/game/GameMap.ts (1)
  • TileRef (3-3)
src/core/game/Game.ts (1)
  • Unit (427-502)
src/core/execution/nation/structureSpawnTileValue.ts (1)
  • structureSpawnTileValue (45-361)
🔇 Additional comments (23)
resources/lang/en.json (1)

499-500: LGTM! Translation entry looks good.

The new "unavailable" translation is clear and will properly support the BuildMenu UI states. The trailing comma is valid JSON and keeps the format consistent for future additions.

src/core/execution/nation/structureSpawnTileValue.ts (4)

19-43: Verify mathematical correctness of penalty calculation.

On line 30, when distance < pref.near, the penalty calculation is:

const penalty = (pref.near - distance) / Math.max(pref.near, 1);
return -penalty * pref.weight * 0.5;

If pref.near is 0, the Math.max(pref.near, 1) becomes 1, but then penalty = (0 - distance) / 1 = -distance, which is negative. The return multiplies this negative by a negative (due to the - sign), resulting in a positive penalty, which seems incorrect. Review whether this case is properly handled by the assertion or if distances can be negative.


309-331: SAM placement logic looks solid.

The use of two separate ClusterPreference objects (samPreference and missileGuardPreference) to handle economic clusters and missile silos separately is a clean approach. The dynamic ideal calculation based on SAM range shows good attention to gameplay balance.


334-353: Verify penalty logic doesn't over-penalize valid placements.

Lines 348-353 apply penalties when clusters exist but aren't covered. However, this could over-penalize SAMs that cover other valuable structures but happen to miss one cluster type. Consider whether the penalty should be proportional to the number/importance of uncovered structures rather than a flat penalty.


12-17: All ClusterPreference ranges are non-degenerate
Verified that every assertPreference call uses near < ideal < far; no case of near === ideal === far occurs.

tests/core/execution/structureSpawnTileValue.test.ts (1)

6-14: Mock implementation looks good.

The makeUnit helper creates a minimal mock that satisfies the required interface. Using satisfies is a good TypeScript practice here to ensure type safety while keeping the mock minimal.

src/client/graphics/layers/BuildMenu.ts (2)

142-168: Good event-driven architecture.

The init() method properly subscribes to relevant events and manages menu visibility. The check for _hidden on line 147 prevents duplicate menu opens when the user holds a key, which is a thoughtful detail.


454-485: bigint division guard verified
The if (cost <= 0n) guard prevents zero or negative cost before division, and this.cost(item) always returns a valid bigint. No changes required.

src/core/execution/FakeHumanExecution.ts (7)

30-33: Clear documentation of AI behavior.

The new class-level docstring provides a helpful summary of what FakeHumanExecution does. This is especially useful given the complexity of the decision-making logic below.


453-468: Potential infinite loop risk in action execution.

The do-while loop (lines 454-468) continues until either:

  1. performed >= maxActions, or
  2. No action executes in a pass

However, if an action consistently returns false without changing any state, and other actions keep succeeding, the loop might run longer than expected. The executedThisPass flag breaks the loop correctly, but verify that actions can't get stuck in a state where they always fail but other actions keep succeeding.

Consider adding a maximum iteration count as a safety measure:

const maxIterations = maxActions * 2; // Safety margin
let iterations = 0;
do {
  if (++iterations > maxIterations) {
    console.warn("Action loop exceeded max iterations");
    break;
  }
  // ... existing logic
} while (performed < maxActions);

563-587: Defense urgency logic looks solid.

The graduated scoring (1-3) based on incoming attacks and troop comparisons is well thought out. The use of hostileBorderPlayers() to focus on relevant threats is a good design choice.


761-793: Upgrade prioritization is well-designed.

The maybeUpgradeStructure() method intelligently prioritizes border structures (lines 772-776) and lower-level units (lines 777-779). This creates a logical upgrade path that reinforces defensive positions first.


730-755: The review comment is incorrect. The code handles Neutral relations correctly.

The Relation enum orders values numerically: Hostile=0, Distrustful=1, Neutral=2, Friendly=3. The check relation >= Relation.Friendly (i.e., relation >= 3) skips only when relation is Friendly or higher. Neutral (2) does not meet this condition, so Neutral players are correctly included in the hostile neighbors list—which is the intended behavior.

Likely an incorrect or invalid review comment.


544-561: Defense urgency doesn’t bypass cost multiplier
defenseUrgency() only influences build priority—it never alters the (owned+2)² perceivedCost in maybeSpawnStructure. As a result, even with high urgency, steep multipliers can still block late-game Defense Posts. To ensure urgent builds aren’t unaffordable, add logic in maybeSpawnStructure (e.g. when defenseUrgency() ≥ 2) to cap or skip the multiplier.

⛔ Skipped due to learnings
Learnt from: scottanderson
PR: openfrontio/OpenFrontIO#1851
File: src/core/execution/FakeHumanExecution.ts:433-441
Timestamp: 2025-08-18T03:11:18.617Z
Learning: In FakeHumanExecution.maybeSpawnStructure, the perceived cost multiplier (owned + 1, capped at 5) applied to structure costs is intentional. This makes AI nations build fewer structures than players could, saving gold for bombs/nukes rather than maxing out structures.

473-500: Disabled units don’t affect cost(): baselineCosts is never empty so the baseline === 0n branch is unreachable.

Likely an incorrect or invalid review comment.

tests/client/Utils.translate.test.ts (2)

1-8: Good mock data for edge case testing.

The mock includes two specific test cases:

  1. Repeated placeholders ({value} appears 3 times)
  2. Regex metacharacters in placeholder names ({value$})

These are exactly the edge cases that could break naive string replacement implementations.


18-31: Proper test isolation.

The test correctly saves and restores the global.document state, and calls __resetTranslationCacheForTesting() in both setup and teardown. This ensures tests don't interfere with each other.

src/client/Utils.ts (6)

37-60: Verify bigint division accuracy for large numbers.

The bigint handling for renderNumber() uses division to scale values. For example:

  • Line 41: Number(num / 100_000n) / 10 for values ≥ 10M
  • Line 52: Number(num / 100n) / 10 for values ≥ 10K

This approach can lose precision. For instance:

  • 10_000_001n / 100_000n = 100n, then Number(100n) / 10 = 10.0
  • But the actual value should be 10.00000001M, not 10.0M

Consider if this precision loss is acceptable for the UI, or if you need to use more precise division:

const scaled = Number(num) / 100_000 / 10;

However, converting bigint to number might overflow for very large values. The current approach is likely a reasonable trade-off for game UI purposes.


101-129: Good canvas resize handling.

The resize logic properly handles:

  • Non-browser environments (lines 102-106)
  • Device pixel ratio for high-DPI displays (line 107)
  • Minimum dimensions of 1 (lines 111-112)
  • Cleanup via __disposeResize__ property (lines 126-127)

The passive event listener flag (line 125) is a nice touch for performance.


179-207: Translation fallback implementation is sound.

The non-browser fallback correctly:

  • Navigates nested keys (lines 185-194)
  • Falls back to the key itself if not found (lines 197-199)
  • Uses split().join() for substitution instead of regex (lines 202-205)

The split().join() approach (line 204) is excellent for handling regex metacharacters, which aligns with the test case for {value$}.


351-369: Excellent localStorage error handling.

Both getGamesPlayed() and incrementGamesPlayed() properly wrap localStorage access in try-catch blocks. This prevents crashes when:

  • localStorage is disabled
  • Storage quota is exceeded
  • The browser is in private mode

The warning logs (lines 355, 367) will help debug issues without breaking the user experience.


375-386: Safe iframe detection.

The isInIframe() function correctly handles:

  • Non-browser environments (lines 376-378)
  • Cross-origin restrictions (try-catch, lines 379-385)

The comment on lines 382-383 helpfully explains why the catch block returns true.


227-243: Ignore deepGet edge case concerns deepGet is only used with verified non-null translation objects, and JSON keys are nested without embedded dots.

Likely an incorrect or invalid review comment.

coderabbitai[bot]
coderabbitai Bot previously approved these changes Oct 15, 2025
@Hiphex
Hiphex marked this pull request as ready for review October 15, 2025 20:32
@Hiphex
Hiphex requested a review from a team as a code owner October 15, 2025 20:32

@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: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/client/Utils.ts (1)

86-131: Potential memory leak: resize listener is never cleaned up.

The resize event listener is attached (line 125) and a disposal function is stored on the canvas (line 126), but this disposal hook is never invoked. If canvases are created and destroyed dynamically, the listeners will accumulate.

Consider returning an object with an explicit dispose method:

export function createCanvas(): { canvas: HTMLCanvasElement; dispose: () => void } {
  const canvas = document.createElement("canvas");
  // ... canvas setup ...
  
  let disposeResize: (() => void) | undefined;
  if (typeof window !== "undefined") {
    const listener = () => resize();
    window.addEventListener("resize", listener, { passive: true });
    disposeResize = () => window.removeEventListener("resize", listener);
  }
  
  return {
    canvas,
    dispose: () => disposeResize?.(),
  };
}

This removes the unsafe any cast and makes cleanup explicit.

🧹 Nitpick comments (1)
src/client/Utils.ts (1)

37-84: Consider reducing duplication between bigint and number paths.

The bigint and number formatting logic follows nearly identical patterns with thresholds and scaling. A helper function could handle the shared logic:

function formatWithSuffix(
  value: number,
  suffix: string,
  precision?: number
): string {
  return value.toFixed(precision ?? 1) + suffix;
}

Then both paths could call this helper, reducing maintenance burden.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 410c10a and 2ad986a.

📒 Files selected for processing (2)
  • src/client/Utils.ts (11 hunks)
  • tests/client/Utils.translate.test.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
tests/client/Utils.translate.test.ts (1)
src/client/Utils.ts (2)
  • __resetTranslationCacheForTesting (404-413)
  • translateText (171-280)
src/client/Utils.ts (6)
src/core/game/GameView.ts (4)
  • troops (93-95)
  • troops (362-364)
  • width (673-675)
  • height (676-678)
src/core/game/PlayerImpl.ts (1)
  • troops (790-792)
src/core/game/UnitImpl.ts (1)
  • troops (164-166)
src/core/game/AttackImpl.ts (1)
  • troops (32-34)
src/client/graphics/GameRenderer.ts (1)
  • resize (386-389)
src/client/LangSelector.ts (1)
  • translateText (254-274)
🔇 Additional comments (11)
tests/client/Utils.translate.test.ts (1)

1-59: Well-structured test coverage for translation fallback.

The test suite correctly validates the non-browser fallback behavior, including the important edge case of placeholder names containing regex metacharacters (line 40). The setup/teardown properly isolates the global document state between tests.

src/client/Utils.ts (10)

6-18: LGTM!

The duration formatting logic is clear and handles edge cases appropriately.


20-26: LGTM!

Correctly converts server-stored tenths to human-readable format.


137-157: LGTM!

Using globalThis instead of window improves compatibility with non-browser environments like Node.js.


179-207: LGTM!

The non-browser fallback uses split(token).join(...) for placeholder substitution (lines 203-204), which correctly handles parameter names containing regex metacharacters like $. This aligns with the test coverage in Utils.translate.test.ts.


227-260: LGTM!

The deepGet helper and multi-tier fallback logic (direct → nested → default direct → nested default) provide robust translation resolution.


282-291: LGTM!

Adding an explicit Severity type improves type safety and makes the allowed values clear.


334-358: LGTM!

The typeof navigator !== "undefined" guards make these functions safe to call in non-browser contexts like server-side rendering or tests.


360-382: LGTM!

The try-catch blocks provide resilience against localStorage failures (quota exceeded, private browsing mode, etc.). Defaulting to 0 and warning on failure is appropriate.


384-399: LGTM!

The defensive implementation correctly handles both non-browser environments and cross-origin iframe restrictions.


401-413: LGTM!

This test helper correctly resets all memoized translation state between test runs, preventing cross-test pollution.

@DevelopingTom DevelopingTom 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.

This PR includes a number of different changes and features that aren’t related. It makes it a bit difficult to review thoroughly, increases the risk of introducing issues, and would make it harder for us to maintain a good git hygiene.

Could you please break this work into smaller, more focused pull requests? Thanks :)

@github-actions

Copy link
Copy Markdown
Contributor

This pull request is stale because it has been open for fourteen days with no activity. If you want to keep this pull request open, add a comment or update the branch.

@github-actions github-actions Bot added the Stale PRs that haven't been touched for over two weeks. label Nov 13, 2025
@github-actions

Copy link
Copy Markdown
Contributor

This pull request has been closed because fourteen days have passed without activity. If you want to continue work on the code, comment or create a new PR.

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

Labels

Stale PRs that haven't been touched for over two weeks.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants