Buttons for mobile still don't work. Make them work!
Also make sure that dialog is visible when phone is horizontal.
User
User
User
Assistant
I’ll trace the title-screen input path and mobile layout, then fix both touch activation and landscape visibility.
Assistant
The current branch already includes two recent mobile-control fixes, so I’m isolating the remaining title-screen regression rather than duplicating them.
Assistant
I’m reproducing the failure with real touch events in portrait and landscape, including the overwrite confirmation shown when a save exists.
Assistant
Dependencies are absent, so I’m restoring the locked install before running the mobile reproduction.
Assistant
The missing behavior is title-menu navigation: the mobile D-pad has no title selection model, and the visible labels expose only text-sized hit areas. I’m locking that regression into Playwright first.
Assistant
The title now has a real selection model, large hit zones, and a compact overwrite modal; I’m exercising both direct taps and D-pad/A in landscape.
Assistant
The landscape rendering is clean. I’m synchronizing the new title-input ownership and its browser coverage in the project guidance before the broader gate.
Assistant
The focused flows pass. I’m doing a bug-only review of the diff before the full release gate.
User
Review the current uncommitted diff in /Users/mbianchidev/.copilot/copilot-worktrees/2dnd/cp-desktop-shiny-invention. The change fixes mobile title-screen controls by adding src/managers/titleMenu.ts, refactoring Boot title actions, adding a compact mobile-landscape new-game confirmation, dynamic viewport/safe-area CSS, and Playwright coverage. Report only high-confidence correctness, lifecycle, input, accessibility, or regression bugs. Ignore style and documentation wording. Pay special attention to Phaser keyboard listener lifecycle, synthetic touch/gamepad events, save-slot confirmation state, direct pointer hit targets, desktop title behavior, and portrait/landscape layout. Do not edit files.
Assistant
All unit tests pass. Now let's check ESLint and look more closely at potential lifecycle issues around desktop-specific behavior and the canActivate gating combined with showTitleSettings.
Assistant
All tests pass, confirming behavior is correct. Given the extensive investigation—verified with type-checking, unit tests (985 passing), targeted e2e tests, and careful tracing of Phaser's EventEmitter semantics, keyboard listener lifecycle, canActivate gating, and CSS safe-area math (which is actually a genuine fix, not a regression, since absolutely-positioned children ignore ancestor padding per the CSS containing-block spec)—I did not find a high-confidence bug.
No significant issues found in the reviewed changes.
Assistant
No review defects found. The focused implementation is stable, so I’m checkpointing it before the full browser, desktop, and build gate.
Assistant
Checkpoint committed. Now running the release gate: audit, full typecheck, and full Vitest first.
Assistant
Audit, typecheck, and all 985 unit tests are clean. Running the complete Chromium suite next.
Assistant
The full suite exposed compatibility gaps: several keyboard/gamepad flows confirm new games with Enter immediately after pressing N, while the compact modal now activates on key-up. I’m aligning that handoff and the title settings test IDs.
Assistant
The failures were stale coordinate selectors, not product regressions. All title flows now use stable action IDs; I’m checkpointing that before rerunning the complete browser suite.
2D&D Game Development
Start with AGENTS.md, then use
docs/architecture.md and
docs/development.md for current ownership and
workflow.
Use this skill for cross-cutting game features, new content, combat behavior,
and changes spanning scenes, systems, data, renderers, or managers.
Core rules
Use strict TypeScript with explicit parameter and return types.
Keep content data-driven in src/data/; keep reusable logic in
src/systems/.
Generate reusable textures in src/renderers/textures.ts; scene-sized
procedural Battle scenery belongs in battleBackdrop.ts. Synthesize audio
in src/systems/audio.ts; do not add external assets.
Preserve shared scene state across transitions.
Use debugLog() and debug-panel APIs instead of console.log.
Public showcase: index.html, src/landing.css, and game-generated captures
Secure desktop main/preload boundary: electron/
Production-like Electron flows: electron-tests/
The web build serves the showcase from index.html and starts Phaser from
game.html. Packaged desktop builds load that game entry directly from
app://2dnd/game.html. Electron must keep sandboxing and context isolation
enabled, deny permissions and remote renderer requests, resolve only packaged
dist/ files, and expose only narrow typed preload APIs. Native code never
mutates game state. Desktop diagnostics use bounded rotating files under user
data; renderer error reports are length-limited. Save & Return to Title
autosaves through the Phaser scene transition, while title-screen Quit Desktop
uses validated zero-argument IPC.
The versioned 2dnd_preferences document is separate from campaign saves and
backs both title and in-game settings. Install the scene accessibility adapter
in every scene, use its shared reduced-motion accessors, preserve
100%/125%/150% text usability, and pair important color states with a textual or
symbolic cue. Control presentation preferences cover touch visibility,
handedness, and prompt source without changing campaign saves. Stable mappings
are intentionally not remappable.
All release input routes through the semantic action layer. Standard gamepads
use dead zones, digital fallback, repeat/debounce, source switching, and a
visible right-stick cursor clicked by pressing the stick. Responsive touch
controls use safe areas, pointer capture for held directions, pointer-release
pulses with a click fallback for discrete actions, and mobile text entry. Clear
held state on blur, visibility loss, disconnect, scene changes, and shutdown.
Cutscene contracts live in src/data/cutsceneTypes.ts, focused campaign and
boss definitions live in cutsceneCampaign.ts and cutsceneBosses.ts, and
src/data/cutscenes.ts is the stable-ID hub. Pure trigger snapshots, priority
ordering, queue lifecycle, recovery, Chronicle selection, and summary logic live
in src/systems/cutscenes.ts; src/managers/cutscene.ts owns step progression;
scenes and renderers own input and presentation.
Hero-role actors remain immutable staging cues and resolve at presentation time
from the current PlayerState. Build the canonical descriptor with
src/systems/heroVisuals.ts and acquire cleanup-safe procedural textures through
src/renderers/heroTextures.ts; do not duplicate class, appearance, equipment
layer, fallback, or cache-key rules in Cutscene, Overworld, Battle, or Ending.
EndingScene and DefeatScene share src/renderers/result.ts; defeat receives
an exact runtime-only PartyDefeatResult, while the recovered player state is
autosaved before presentation.
The map hub is src/data/map.ts; terrain/types, chunks, cities, and dungeons
are split into dedicated modules. Dungeon trap definitions live in
src/data/traps.ts, mechanics in src/systems/traps.ts, and scene orchestration
in src/managers/dungeonTraps.ts.
Group templates live in src/data/monsterGroups.ts; reusable initiative,
formation, synergy, reward, and per-combatant rules live in
src/systems/groupCombat.ts.
That module also owns party-ready BattleCombatantState, stable actor IDs,
actor-ID initiative, ally/enemy targeting, monster party-target selection, and
battle resolution hooks.
src/systems/battleActions.ts is the Phaser-free action planner for player
input and ranked gambits: actor enumeration, target binding, validation,
immutable plans, per-actor action/bonus consumption, and one-action dispatch.
executeValidatedBattleAction() binds a generic CombatActorState to a party
combatant and reuses existing attack, spell, ability, item, defend, element,
status, MP, and inventory mechanics.
Consumables consume the acting source's inventory while applying HP/MP/cures
to a selected ally source; execution contexts must include all party action
sources. Equipment actions remain self-targeted.
src/systems/animation.ts is the Phaser-free presentation contract for actor
states, deterministic timing, stable-ID target mapping, once-only lifecycle,
and explicit family/frame texture metadata. src/managers/actorAnimation.ts
owns reusable Phaser poses and cleanup; battle/world directors consume resolved
state without changing mechanics. src/renderers/actorTextures.ts supports
optional family frames from #49 and a generic existing-texture fallback.
Tutorial and Tips content lives in src/data/tutorial.ts as immutable steps,
semantic control actions, categories, and unlock requirements.
src/systems/tutorial.ts owns completion normalization and progression-aware
filtering. src/managers/tutorial.ts owns the Overworld overlay and renders prompts for
the active keyboard, pointer, gamepad, or touch source. New saves persist
player.progression.tutorial.completed; replay never resets it.
Progressive feature discovery is data-driven through
src/data/featureDiscovery.ts and src/systems/featureDiscovery.ts. Filter
menus, tabs, shortcuts, prompts, touch actions, and Codex/crafting/gathering
categories through the shared registry. Preserve always-safe Inventory, Map,
Equipment, Tips, Settings, and save/title controls, and never use discovery as
authority for gameplay state.
Keep touch availability contextual: MENU and TIPS appear only during safe
exploration. Spatial Battle and character-creation grids must follow their
visual rows and columns with all four directions, A/confirm, and B/cancel.
World Event content lives in src/data/worldEvents.ts, its deterministic
Phaser-free state machine in src/systems/worldEvents.ts, and accessible choice
presentation in src/managers/worldEvents.ts. Events short-circuit treasure,
exploration checks, and random encounters for their movement step, while
transitions, entrances, traps, interactions, and queued cutscenes retain
priority. Special event combats use normal Battle hooks and saves.
Quests
Put quest definitions, stage objectives, NPC IDs, rewards, and gated
entrances in src/data/quests.ts.
Put progression, normalization, idempotent rewards, NPC interaction
resolution, journal entries, and entrance checks behind
src/systems/quests.ts; questState.ts and questDebug.ts contain focused
normalization and debug-only mutation helpers.
Persist state only through player.progression.quests; use quest-system APIs
instead of direct mutation.
The shipped campaign is the seven-chapter Twelvefold Covenant across all 12
cities and three keystones, with Ironbound Dispatch, Silk Against the Cold,
and optional Hydra and Dragon objectives.
Persist objective counters and claimed reward IDs. Batch group defeats with
duplicate monster IDs intact so three matching combatants count as three.
Downstream unlocks such as companions should call isQuestCompleted() and
keep their own persistent state separate from quest reward bookkeeping.
Cross-system outcomes use stable quest completion actions with
{ id, type, targetId }. Replay them after load/mutations and make the
consumer idempotent rather than adding duplicate quest state.
Give every stage a stable camelCase id; downstream systems use
getQuestStageIndex() or the debug-only setQuestStageById(), never display
titles.
Derive boss objectives from defeatedBosses so older saves can report
already-completed objectives.
Keep quest NPCs available at night and test every referenced NPC, boss,
reward item, and entrance.
Campaign completion remains derived from the main quest. Launch the epilogue
after the final Elowen dialogue applies rewards, recover completed-but-unseen
saves from Overworld creation, and keep replay presentation-only.
Queue stable cutscene IDs and save before presentation. Completion or skip
moves an ID from pendingCutsceneIds to seenCutsceneIds; reload resumes the
first pending entry, while Chronicle replay changes neither collection.
Detect newly satisfied cutscenes by comparing immutable before/after snapshots.
Battle must capture its snapshot before recording the defeated boss. Sort
simultaneous triggers by explicit numeric priority rather than discovery
order.
Map main-quest talk objectives through QUEST_NPCS and assert exact coverage
of all 12 live city IDs; do not accept name-only references.
Canyonwatch, Ashfall, and the Volcanic Forge are hard gates. Sandport and
Heartlands Crypt remain open; other premature travel uses one-time soft
danger warnings and capped encounter modifiers.
Non-combat skill checks
Non-combat checks are split across:
src/data/skillChecks.ts: NPC challenges, negotiation choices, and terrain
event definitions
src/systems/skillChecks.ts: pure d20 resolution, normalization, and helpers
src/managers/skillChecks.ts: Overworld rewards, hazards, chest checks, and
dialogue orchestration
Adding monsters
Define the monster in the appropriate focused pool (monsters.ts,
nightMonsters.ts, or monsterVariants.ts).
Use a camelCase ID and set a valid typed family, stats, rewards, drops,
abilities, and isBoss.
For a palette/stat variant, set variantOf to a valid same-family monster,
use a distinct color and ability set, and assign a positive
encounterWeight.
Add an affinity and elementalProfile when the monster has a dominant
element, resistances, weaknesses, or
immunities.
Add element and statusEffect to monster abilities when applicable.
Ensure the definition is included in ALL_MONSTERS; debug spawning, Codex
browsing, and ID lookup depend on the master list.
Reuse getMonsterTextureKey() and the family silhouette renderer rather than
adding scene-local textures or tints.
Add encounter-pool, family, palette, texture-key, and data-integrity tests.
Use getMonster(id) for exact ID lookup and findMonster(query) for
case-insensitive ID/name lookup with partial matching.
Adding monster groups
Add a 2-4 member template to MONSTER_GROUP_TEMPLATES.
Reference valid monster IDs and assign every member to front or back.
Keep minPlayerLevel high enough that total difficulty does not exceed
playerLevel * 3.
Add biome/dungeon tags, encounter weight, and an optional synergy with a
valid break threshold.
Add deterministic generation and data-integrity coverage.
Random groups start at level 2, cap at 50% of triggered encounters, and never
replace bosses or explicit debug monster spawns.
Codex family completion is derived from the current CodexData.entries; family
metadata, affinity, and sort/filter presentation are not save fields.
World knowledge definitions live in src/data/codexKnowledge.ts. Persist only
stable unlocked knowledge IDs in CodexData; derive category counts, source
hints, search results, sorting, and grouping from canonical entries. Emit
idempotent location, quest, cutscene, item, NPC, readable, or worldEvent
signals without letting Codex state control gameplay. reputationMilestone
is owned by the schema-v12 reputation system and must remain idempotent.
World Events
Filter immutable definitions by terrain, area, time, weather, level, quest
state, boss state, prior outcomes, repeat limits, and cooldowns.
Keep event chance independently capped at 8%; never feed it into or multiply
the 15% random-encounter calculation.
Persist the selected pending event before presenting choices or starting a
special battle. Reload resumes the same choice or encounter.
Apply skill outcomes through rollSkillCheck(), quest starts through
startQuestById(), rewards through canonical item/XP helpers, and lore through
unlockCodexFromFutureSignal().
Resolve stable outcome/reward IDs once, append at most 40 chronological
records, and expose those records through Chronicle without revealing future
choices.
Alignment/reputation hooks are consumed by the centralized social mutation
API with stable source IDs. World Event state never persists duplicate social
scores or applied IDs.
Alignment and reputation
Keep canonical axes, faction IDs, reputation tiers, and thresholds in
src/data/reputation.ts; reusable mechanics belong in
src/systems/reputation.ts.
New players begin exactly Chaotic Neutral (lawChaos: -50, goodEvil: 0).
Persist only bounded scores, stable applied source IDs, and the bounded
recent-cause history. Derive names, tiers, pricing, milestones, and ending
variants.
Apply social outcomes only for meaningful choices. Never reward routine
movement, unavoidable combat, or farming.
Return runtime-only SocialAchievementHook values for the achievement
consumer; do not persist achievements inside the social system.
Achievements
Put immutable definitions and cosmetic titles in src/data/achievements.ts;
put normalization, deterministic progress, reconciliation, stable event
counters, debug exclusion, and title equip rules in
src/systems/achievements.ts.
Prefer reconciliation from authoritative quest, boss, Codex, exploration,
trap, skill-check, event, social, party, and inventory state. Add persisted
counters only for non-reconstructable event history such as battle wins,
one-hit defeats, and explicit defeat count.
Achievement state never controls gameplay authority. Titles are
presentation-only and notices are queued for safe Overworld presentation.
Adding spells, abilities, and equipment
Damage sources may declare an Element from src/data/elements.ts.
Player abilities may apply selfEffect or targetEffect IDs defined by
src/systems/statusEffects.ts.
Monster abilities use statusEffect for effects applied to the player.
Cure consumables declare matching cure data and must be wired through
useItem() without consuming the item when no matching ailment exists.
Ally-target consumables declare targetType; resolve it through
getItemTargetType() so older inventory copies use canonical item metadata.
Preserve action economy: normal actions end the player turn; bonus-action
abilities and the first item use do not.
Combat calculation order is:
Roll and resolve the attack or save.
Apply active-status accuracy, disadvantage, AC, and damage modifiers.
Apply elemental immunity, weakness, or resistance to the modified damage.
Apply damage and status effects.
Report discoveries and combat feedback.
Magic Missile remains auto-hit and does not roll disadvantage.
Status effects
All definitions and lifecycle helpers live in
src/systems/statusEffects.ts. Do not duplicate status logic in data files or
scenes.
Start of actor turn: tick damage, saving throws, and skip-turn decision.
End of actor turn: decrement durations and expire effects.
Apply or refresh through applyStatusEffect().
Normalize loaded effects through normalizeActiveEffects().
Clear player and monster effects when leaving Battle; durations are measured
in combat turns, not overworld steps.
Elements
Supported elements are Fire, Ice, Lightning, Poison, Necrotic, Radiant,
Thunder, Force, and Psychic.
Immunity: zero damage
Weakness: double damage
Resistance: floor of half damage
Neutral: unchanged
Record observed non-neutral interactions with discoverElement() so the Codex
can persist and display them.
World features
Cities may contain connected districts. Always use city chunk helpers rather
than indexing city.chunks directly.
Dungeons may contain multiple levels. Always use dungeon level and
connection helpers.
Dungeon trap layouts are derived from persisted trapSeed; never mutate
dungeon maps or randomize layouts independently in scenes.
Detected traps block movement until disarmed. Trap triggers must short-circuit
the normal random-encounter check for that step.
Use FogOfWar.exploredKey() for exploration keys.
Use isWalkable() and ENCOUNTER_RATES; do not hardcode terrain behavior.
Nautical metadata lives in src/data/nautical.ts; state normalization,
ownership, and mechanics live in the focused nauticalState.ts,
nauticalOwnership.ts, and nautical.ts modules. Preserve all 90 legacy
chunk IDs and use s:zoneId,chunkX,chunkY,x,y for sea fog.
Merchant routes work before boat ownership. Free sailing requires a
serviceable active boat, uses canonical Water eligibility, and runs hazards
before World Events, gathering, and random sea encounters.
Non-combat skill checks
Checks use d20 + Dexterity, Intelligence, Wisdom, or Charisma modifier plus
typed bonuses against a DC.
Natural 1 and 20 are not automatic outcomes for ability checks.
Persist fixed NPC, shop, chest, and treasure results in
player.progression.skillChecks.
Use stable NPC identities and shop type/coordinate keys rather than array
indexes.
Shop negotiation is one attempt per shop; successful discounts restore from
the saved result.
Exploration hazard damage is nonlethal and must clamp the player to at least
1 HP.
Test roll math, invalid inputs, stable data references, save normalization,
reward bounds, and nonlethal damage deterministically.
Battle also receives a MonsterEncounter and biome; Shop receives shop/city
context.
Defeat receives the full shared state plus encounter name/type and the exact
applied party defeat receipt. It must not recalculate or reapply penalties.
Future party systems pass accessor-backed partyCombatants plus runtime-only
battleHooks; do not persist those wrapper objects.
Keep target init() contracts and every caller synchronized.
The new-player tutorial opens only after pending opening cutscenes have drained.
F1 and the Esc menu open the consultable Tips surface. Keep the external HTML
control rail collapsed by default and retain only contextual action prompts in
the game HUD.
Route camera fades and scene handoffs through
src/managers/sceneTransition.ts. Call prepare() when each scene creates,
wait for fade-complete events, and keep the duration-plus-grace watchdog as a
recovery path only. Restore the outgoing camera before queueing the next scene,
reject duplicate handoffs, and block state-changing Overworld input until the
queued start/restart is processed. Every Overworld restart must include a fresh
savedSpecialNpcs snapshot in the shared state payload.
Use the same guarded Battle exit cleanup for victory, flee, and defeat. Defeat
clears transient menus, input, effects, particles, and weather timers before
starting DefeatScene, which continues only to Overworld.
Resolve an action before presenting it. Actor animation may read stable IDs,
targets, hit/damage/healing, and outcome, but must not spend MP/items/actions,
apply damage, report results, or control fade-complete scene handoffs.
Companions and gambits
Persistent party state lives at player.party; do not add a parallel scene
payload or companion combat model.
Stable companion IDs are guardian, scout, and mystic.
Build runtime actors with createPartyCombatant() and
createBattleActionSource().
Manual turns and ranked gambits both validate/execute through
battleActions.ts; one bonus action may precede or follow one main action.
Debug quest or companion recruitment must refresh live follower presentation
immediately after replay.
Active conscious companions may render as non-blocking followers, but only
hero movement invokes trap, encounter, gate, and world-interaction logic.
Keep party UI/followers/battle presentation in focused managers/renderers
rather than growing the existing oversized scene/overlay files.
Inventory presentation
Build immutable views with src/systems/inventory.ts; every view entry keeps
its original inventory index for actions and transfers.
Never sort the owning inventory array or replace equipment object references.
Keep sort/filter/search preferences in 2dnd_inventory_prefs, outside the
campaign save schema. Recent acquisition is reverse append order.
Use semantic inventory actions for keyboard, pointer, gamepad, and touch
controls. T remains mount control.
Generate item visuals procedurally through src/renderers/itemVisuals.ts.
Gathering
Gathering content lives in src/data/gathering.ts, deterministic node/table/
minigame logic in src/systems/gathering.ts, schema normalization in
gatheringState.ts, and accessible Phaser presentation in
src/managers/gathering.ts. Persist selected outcomes before play, use safe
location-derived nodes, route guarded finds through normal Battle hooks, and
keep material identity limited to stable Item.material recipe-input metadata.
Crafting
Crafting recipes live in src/data/crafting.ts, atomic mechanics and discovery
in src/systems/crafting.ts, persistence normalization in craftingState.ts,
and accessible Overworld presentation in src/managers/crafting.ts. Validate
the selected actor inventory, protected/equipped restrictions, batch, gold,
station, output, and transaction ID before mutation. Equipment upgrades replace
exact equipped object links with canonical outputs. Never pull companion
materials implicitly, reroll a craft, duplicate material identity, or let
recipes/achievements control quests, Codex, access, or rewards.
Validation
bash
npm run typecheck
npm test
npm run test:browser
npm run test:desktop
npm run build
npm run build:desktop
For UI changes, run the committed Playwright flow in headless Chromium. Keep
browser actions synchronized through debug-state transitions, and hold
frame-polled Phaser keys across frames rather than using instantaneous presses.
Build responsive UI from src/systems/layout.ts, register modal groups through
createOverlayContainer(), and assert the local #layout-report reports zero
unintended overlap or clipping at supported text scales.
Common pitfalls
Do not mutate shared monster, item, map, city, or dungeon definitions.
Do not share HP, status, defend, discovery, or drop state between group
combatants, including duplicate monsters.
Do not introduce index-based turn entries or duplicate hero HP/effect state;
use stable combatant IDs and createHeroCombatant().
Do not reimplement MP, inventory, target, formation, or action-economy checks
in companion AI; use validateBattleAction().
Do not use stale Phaser 3 APIs or default imports; current code uses
import * as Phaser from "phaser".
Do not create a second status or elemental calculation path.
Do not omit unique dungeon pools or bosses from aggregate lookups.
Do not use geometry masks for the Battle log; render the bounded visible
message window.
Do not add a persistent field without save normalization and tests.
Do not reroll a failed trap detection; persist the missed state.
Touch-Friendly Design
You are an expert in touch interface design. Help developers create interfaces that work well with finger-based interaction.
Native in some contexts (Safari PWAs).
Custom implementation needs care.
Forms on Touch
Input Types
Use appropriate types for better keyboards:
type="email": Email keyboard
type="tel": Phone keyboard
type="number": Numeric keyboard
inputmode="numeric": Numeric without spinners
Autocomplete
Enable autocomplete for faster input.
Label inputs correctly for autofill.
Zoom Prevention
Font size 16px or larger prevents iOS zoom on focus.
Or use viewport meta (not recommended).
Common Mistakes
Hover-Only Information
Content only visible on hover is inaccessible on touch.
Provide always-visible alternative.
Too Small Targets
Following desktop sizing on mobile.
Test with actual fingers.
No Touch Feedback
Button tap with no visual response.
Users think tap didn't register.
Gesture-Only Actions
No button alternative for swipe actions.
Violates accessibility requirements.
Testing Touch
Real Devices
Emulators don't catch everything.
Test actual touch interactions.
Test Actions
All buttons reachable
No accidental activations
Feedback is visible
Gestures work smoothly
Edge Cases
Fat finger scenario
Bottom of screen (thumb zone)
One-handed use
Different hand sizes
Workflow
Set minimum touch target sizes
Implement pointer/hover media queries
Add touch feedback (active states)
Handle safe areas
Optimize forms for mobile input
Add gesture alternatives (accessibility)
Test on real touch devices
Refine based on testing
Acceptance Criteria
Touch targets minimum 44px
Hover effects only on hover devices
Active states provide touch feedback
Safe areas respected
Forms use appropriate input types
No hover-only information
Gestures have accessible alternatives
Tested on real touch devices
Testing Guide for 2D&D
See AGENTS.md and
docs/testing.md for the release gate, CI ownership,
and browser-test setup.
Write comprehensive game-mechanics tests with Vitest. Use the committed
Playwright suite only for high-value Phaser browser flows that cannot be proven
through pure logic tests.
Use playwright.desktop.config.ts for the production-like Electron flow. It
must verify the app://2dnd origin, sandboxed preload API, fullscreen control,
schema-v18 autosave/manual-slot creation/relaunch/continue, Save & Return to Title, title-screen
quit, bounded lifecycle logs, and renderer error cleanliness.
Testing Philosophy
What TO Test
✅ Dice probability distributions
✅ Combat calculation accuracy
✅ Group initiative, formation, targeting, synergies, rewards, and encounter budgets
✅ Player stat progression
✅ XP and leveling formulas
✅ Quest objective counters, prerequisites, rewards, gates, danger rules, and
save normalization
✅ Companion definitions, party progression, transfers, KO/reward rules, and
ranked gambit selection/normalization
✅ Data integrity (monsters, spells, items)
✅ Monster family references, membership, variant differentiation, palette
uniqueness, encounter weights, Codex family completion, and texture-key coverage
✅ Codex knowledge IDs, canonical references, every unlock signal, idempotency,
normalization/migration, search/sort/group behavior, and future-hook isolation
✅ Game logic functions
✅ Seeded layouts and persistent state machines
✅ Non-combat skill-check math, outcomes, and save normalization
✅ Scene-transition event ordering, duplicate guards, and watchdog recovery with
mocked camera/time adapters
✅ Cutscene data integrity, trigger priority, queue recovery, replay immutability,
shared preference normalization/migration, and director cleanup
✅ Runtime hero descriptor normalization, collision-free visual keys, every
cutscene hero-role cue, equipment layer ordering/fallbacks, texture leases, and
current-player rendering across opening, recovery, Chronicle, bosses, and ending
✅ Tutorial content integrity, semantic control references, completion
normalization, progression-aware tip unlocks, and save migration
✅ Feature registry integrity, authoritative reconciliation, irreversible
visibility, dynamic menu/tab filtering, focus clamping, shortcut/touch gating,
debug exclusion, category-specific discovery, and schema-v17 migration
✅ Save-slot migration, staging/backup atomicity, corruption isolation, metadata,
independent overwrite/rename/copy/delete, deterministic import/export, and
keyboard/touch/gamepad management
✅ Defeat penalty receipts, once-only Battle resolution, recovered save
round-trips, result-scene continuation, and random/boss parity
✅ Animation state selection, reduced-motion timing, stable actor/target mapping,
once-only completion and cleanup, and family-frame fallback resolution
✅ Semantic mappings, context priority, analog dead zones, repeats, source
switching, duplicate suppression, disconnect/blur cleanup, and control
preference migration
✅ Measured stacks/grids, safe-area clamping, long-string wrapping,
pagination/visible ranges, filtered focus restoration, scaled bounds,
hit-area alignment, and debug/test overlap detection
✅ Alignment boundaries, reputation tiers, clamping, stable-source
idempotency, quest/dialogue/event/trap/combat hooks, shop composition, Codex
milestones, schema-v12 migration, bounded history, and debug commands
✅ Achievement definition integrity, deterministic progress, hidden entries,
idempotent battle/event/social hooks, reconciliation, schema-v13 migration,
one-hit/no-defeat rules, cosmetic titles, debug exclusion, notices, and
authority isolation
✅ Gathering terrain safety, seeded tables, all three state machines,
reduced-motion equivalence, cooldowns, environmental weights, economy, guarded
Battle handoffs, recipe-input isolation, schema-v14 migration, and pending reload
✅ Crafting recipe integrity, alternative material matching, protected/equipped
items, atomic batches, repeated-input suppression, equipment-link upgrades,
ownership, discovery, acquisition tables, anti-arbitrage, achievements, debug
exclusion, authority isolation, schema-v15 migration, and corruption repair
✅ Nautical continent/zone/port/island integrity, pre-boat merchant routes,
boat acquisition/upgrades, embark/disembark safety, sea fog, capped encounters,
weather hazards, Kraken hooks, sea gathering/crafting economy, schema-v16
migration/corruption recovery, debug commands, and browser reload while sailing
What NOT to Test
❌ Phaser rendering/graphics
❌ Scene transitions
❌ User input handling
❌ Visual appearance
❌ Animation timing
These exclusions apply to Vitest. The focused e2e/ suite owns the real-browser
campaign golden path and scene/input integration.
Animation browser coverage should assert debug-state evidence from real action
menus and combat turns for hero, companion, monster, and boss presentation;
spell/ability particles; world/follower/mount gait; boss cutscenes; fainting;
reduced-motion immediate states; and page/console cleanliness.
Battle backdrop browser coverage uses deterministic /battleview and
/backdrop controls, programmatic depth/bounds/cleanup assertions, and focused
canvas screenshots for group, boss, Kraken, mobile, weather, and high-contrast
combinations. Keep the full biome/time/weather matrix assertion-driven rather
than committing hundreds of redundant images.
Accessibility browser coverage should change settings from both title and
in-game surfaces, assert immediate canvas state, exercise core overlays at every
supported text scale, verify reload persistence, and prove 2dnd_save is
unchanged by preference updates.
Semantic-controls browser coverage uses mobile/touch emulation and deterministic
standard-gamepad stubs. It covers onboarding and mobile text entry, movement,
overlays, prompt/source switching, Battle action/target confirmation, defeat
recovery, gamepad cursor visibility, portrait/landscape layout, and page/console
cleanliness.
Codex browser coverage follows real exploration, quest, cutscene, item, NPC, and
readable paths; verifies non-blocking feedback, reload persistence, schema-v9
migration, keyboard/touch/gamepad search and filters, 150% text, reduced motion,
and page/console cleanliness.
Test File Organization
code
tests/
├── dice.test.ts # Dice rolling utilities
├── combat.test.ts # Combat mechanics
├── groupCombat.test.ts # Multi-monster combat rules
├── battleActions.test.ts # Pure gambit planning and validation
├── monsterGroups.test.ts # Group templates and generation
├── monsterFamilies.test.ts # Families, variants, Codex derivation, texture keys
├── codexKnowledge.test.ts # World knowledge data, triggers, queries, and hooks
├── partyCombat.test.ts # Stable actor IDs, ally scopes, AI, and result hooks
├── party.test.ts # Recruitment, progression, transfers, rests, KO/rewards
├── companions.test.ts # Immutable companion definitions and loadouts
├── gambits.test.ts # Ranked conditions/actions/targets and normalization
├── followers.test.ts # Pure non-blocking follower trail updates
├── player.test.ts # Player systems
├── traps.test.ts # Dungeon trap placement, checks, and effects
├── quests.test.ts # Quest progression and integrity
├── skillChecks.test.ts # Exploration/dialogue checks
├── reputation.test.ts # Alignment, reputation, integrations, and migration policy
├── achievements.test.ts # Definitions, progress, hooks, titles, and migration policy
├── cutscenes.test.ts # Cutscene data, triggers, queue, and director lifecycle
├── accessibility.test.ts # Shared preference normalization, migration, and persistence
├── input.test.ts # Semantic mappings, contexts, repeats, cleanup, and suppression
├── tutorial.test.ts # Tutorial content, completion, and unlocked Tips
├── featureDiscovery.test.ts # Registry, reconciliation, filtering, debug, migration
├── gathering.test.ts # Gathering data, state machines, rewards, and save rules
├── crafting.test.ts # Recipes, transactions, discovery, economy, and save rules
├── cutsceneSceneTransition.test.ts # Generic Cutscene scene contracts
├── defeatSceneTransition.test.ts # Defeat result continuation contract
├── save.test.ts # Persistence and migration
└── data.test.ts # Data validation
Quest tests must cover duplicate matching monsters in one group victory,
durable boss reconciliation, optional-objective reward cutoffs, hard-gate
softlock safety, reward idempotency, and flat schema-v4 to nested schema-v5
migration. Map main-quest NPC objectives to live city IDs and require exact
coverage of all 12 cities with stable stage/objective identities.
Tutorial tests must keep Phaser out of pure logic. Assert stable unique IDs,
valid semantic control references, idempotent completion, safe malformed-state
normalization, and exact progression-aware tip unlock sets. The committed
Playwright flow owns automatic presentation, pointer navigation, persisted
completion, F1, and Esc-menu access.
Skill Check Testing
Pass explicit natural d20 values to resolveSkillCheck(); do not depend on
randomness.
Verify total-vs-DC behavior, including that natural 1/20 are not automatic.
Test shop discounts for both successful and failed saved choices.
Validate NPC identities and chest metadata against live city/map data.
Test terrain event selection with explicit random values.
Cover reward bounds, nonlethal damage, save round trips, missing fields, and
malformed record repair.
Cutscene Testing
Validate every stable ID, trigger reference, boss mapping, and completion
metadata without rendering Phaser.
Compare immutable before/after snapshots and assert exact simultaneous-trigger
priority.
Test that queueing precedes presentation, completion/skip moves pending to
seen, reload resumes pending, and replay leaves both collections unchanged.
Keep generic CutsceneScene transition payload tests separate from the
Playwright visual/input flow.
Companion Testing
Use deterministic companion creation at explicit hero levels; verify
independent inventory objects and level-tier loadouts.
Test quest completion replay, reload, debug completion, and repeated replay
against the same unique recruited-ID guard.
Parameterize those paths across Guardian, Scout, and Mystic; one companion
path is not representative coverage.
Construct BattleActionSource/PartyCombatant adapters and verify HP/MP
writes reach the underlying companion state.
Test gambits as pure rank/condition/target selection. Invalid rules must not
mutate action economy, MP, inventory, or effects.
Cover living-vs-KO XP distribution, level-1 XP floor, party wipe recovery,
exact defeat receipts, and party-wide inn rest.
Keep a focused Battle transition regression that asserts fade-complete
ordering, one-shot scene start, transient cleanup, the full Overworld payload,
and once-only DefeatScene routing for random and boss encounters without
rendering Phaser UI.
Keep Phaser visuals in headless Chromium flows; pure trail positioning and UI
mutation helpers belong in Vitest.
Inventory Testing
Test type/value/rarity/recent/name selectors without mutating canonical order
or equipment links.
Cover equipment, consumable, quest, and future crafting filters plus search.
Normalize and persist 2dnd_inventory_prefs separately from 2dnd_save.
Assert equipped, key-item, mount, and duplicate-item transfer restrictions.
Use focused Playwright coverage for large-bag keyboard/pointer paging,
selection stability, search, and menu access.
## Running Tests
### Command Line
```bash
# Run all tests once
npm test
# Install Chromium once, then run the campaign browser suite
npm run test:browser:install
npm run test:browser
# Build and run the Electron smoke suite
npm run test:desktop
# Watch mode (re-run on changes)
npm run test:watch
# Type checking
npm run typecheck
# Production bundle/startup/memory/save baseline
npm run benchmark:baseline
# Run specific test file
npx vitest run tests/dice.test.ts
Browser Golden Path
playwright.config.ts starts Vite on an unused strict localhost port.
Browser tests default to /2dnd/; the showcase test opens that root and
Phaser tests open game.html. Set PLAYWRIGHT_BASE_PATH=/ to reproduce the
root-base development path.
Cover the showcase's Play/download links, game-generated screenshots,
responsive width, Steam banner, and page/console cleanliness.
Pull request CI installs Chromium and runs the browser suite as a release
gate.
Keep trace action logs, DOM snapshots, sources, and failure screenshots, but
disable trace screenshots and video. Phaser repaints every frame, so the
filmstrip creates thousands of canvas captures that stall context teardown.
Use #debug-state, #debug-log, and persisted save state as authoritative
synchronization surfaces. Canvas text is not DOM text.
Registered Phaser layout groups expose bounds and audit results through
#layout-report, data-layout-overlap-count, and
data-layout-clipping-count; use stable layoutId values instead of brittle
coordinate-only clicks.
Hold frame-polled keys with keyboard.down(), wait across frames, then
keyboard.up(). Do not use instantaneous presses for Overworld or Ending
actions.
Seed randomness before the game loads and assert both pageerror and
console.error remain empty.
Run npm run benchmark:baseline before performance-affecting work and attach
its commit, environment, and output to the owning issue or pull request. The
harness uses the named 2dnd:boot-textures browser performance measure and a
fresh schema-v18 save.
Cover random and boss defeat results, exact displayed penalties, clean
continuation, and recovered save/reload state through the production
/defeat debug path.
Debug commands may accelerate setup, but the final Elowen interaction and
other behavior under test must still run through their production paths.
Cover interrupted opening recovery, dungeon reveals, skipped boss
introductions, aftermath chaining, Chronicle replay immutability, interrupted
and legacy ending recovery, durable post-game reload, and corrupt-save
fallback to a usable New Game path.
Desktop Golden Path
Build with the relative desktop Vite mode and compiled main/preload process.
Launch with a fresh explicit test-only Electron user-data directory.
Assert location.origin === "app://2dnd", the game.html entry, and the
fullscreen bridge shape.
Create a character through production controls, then close and relaunch the
shell, create a manual snapshot, and continue the same schema-v18 campaign.
Return to title through the keyboard menu, quit through the visible title
action, and verify lifecycle/quit logs without save-content leakage.
Run on macOS, Windows, and Linux CI; use Xvfb only on Linux.
Never weaken sandbox, navigation, IPC, CSP, or network policy for tests.
Test Coverage
bash
# Generate coverage report
npx vitest run --coverage
Best Practices
Test behavior, not implementation - Focus on inputs/outputs
Use descriptive test names - "it calculates X when Y"
Mock randomness when needed - Make tests deterministic
Keep tests fast - Avoid delays, network calls
One assertion per test (when possible) - Makes failures clear
Inject group RNG - Initiative, weighted generation, and random-two
targeting helpers accept deterministic random functions
Common Pitfalls
❌ Testing Phaser objects directly (use pure functions)
❌ Relying on random values without bounds checking
❌ Not testing edge cases (0, negative, null)
❌ Tests that depend on execution order
❌ Overly complex test setup
❌ Not cleaning up state between tests