block
Explorer
pokerstudy.ai's Explorer: walk every solved preflop tree (hold'em, PLO, PLO5, PLO6 heads-up, PLO 9-max, tournament and ICM) seat by seat, with the strategy grid or PLO hand lists, hand search, bucket mixes and the solution picker, and, where the host serves a solver, inline postflop solves. Point it at your feeds and switch features with setExplorerHost (lib/explorer/host.ts).
The full Explorer, shared with pokerdata.io's Explorer page. It reads this site's feeds by default; call setExplorerHost before it mounts to use your own and switch off solving, saving or downloads.
Live
The Explorer needs a signed-in session, so open /explorer to try it.
Installation
$ npx shadcn@latest add https://www.pokerstudy.ai/r/explorer-app.jsonProps
Generated from the component source with react-docgen-typescript.
FacetGroup
| Prop | Type | Default | Description |
|---|---|---|---|
| label * | string | – | – |
FacetRadioList
| Prop | Type | Default | Description |
|---|---|---|---|
| name * | string | – | – |
| onChange * | (value: T) => void | – | – |
| options * | FacetOption<T>[] | – | – |
| value * | string | – | – |
ActiveFilterChips
| Prop | Type | Default | Description |
|---|---|---|---|
| chips * | { key: string; label: string; onRemove: () => void; }[] | – | – |
| onClearAll * | () => void | – | – |
FilterToggleButton
| Prop | Type | Default | Description |
|---|---|---|---|
| className | string | – | – |
| count * | number | – | – |
| onClick * | () => void | – | – |
| open * | boolean | – | – |
ResultFrame
| Prop | Type | Default | Description |
|---|---|---|---|
| aside | ReactNode | – | Right-hand note in the header, e.g. "Not browsable yet". |
| meta | ReactNode | – | – |
| muted | boolean | false | – |
| tags | string[] | – | – |
| title * | ReactNode | – | – |
ResultChoice
| Prop | Type | Default | Description |
|---|---|---|---|
| current | boolean | false | – |
| disabled | boolean | false | – |
| label * | string | – | – |
| onClick * | () => void | – | – |
| title | string | – | – |
EmptyResults
| Prop | Type | Default | Description |
|---|---|---|---|
| description * | string | – | – |
| onClear * | () => void | – | – |
| title * | string | – | – |
BottomSheet
| Prop | Type | Default | Description |
|---|---|---|---|
| footer | ReactNode | – | Pinned action row under the scrollable body. |
| icon | ReactNode | – | – |
| onClose * | () => void | – | – |
| title * | string | – | – |
Builder
| Prop | Type | Default | Description |
|---|---|---|---|
| autoSolve | boolean | false | Kick the solve off on mount when the seeded board is complete. Held while a previous session's solve is pending (Resume / Discard decides first). |
| layout | "page" | "drawer" | "inline" | page | "drawer"/"inline" stack inputs over output in a single column; "inline" also collapses the advanced solve settings so the seeded flow stays lean. |
| onRunningChange | ((running: boolean) => void) | – | Mirrors the base solve's running state, so the parent can render the acting card as a loading placeholder in its own strip. |
| onSaved * | (s: CustomSolutionSummary, bundle: CustomSolutionBundle) => void | – | Called after a successful save with the summary + the full bundle, so the caller can open it straight in the SolutionViewer. |
| onSetupError | ((message: string) => void) | – | The solve was refused before it was sent (empty range, bad input). The running mirror never flips for these, so without this the parent's loading card would spin forever. |
| onSolvedChange | ((solved: boolean) => void) | – | (inline) Fired when a result appears (true) or a solve (re)starts (false), so the parent can hide its own seat strip while the navigator is up. |
| seed | BuilderSeed | – | – |
| setupless | boolean | false | (inline) Never show the setup form up front — the Explorer's picker-drawer flow already fixed the board, and the solve starts on its own. The full form stays reachable post-solve via "Edit spot · re-solve". |
| stripLead | ReactNode | – | (inline) The game card, pinned left of the navigator's strip. |
| stripPrefix | ReactNode | – | (inline) Leading cards for the postflop navigator's strip — the preflop seat cards, so preflop + postflop form one continuous action bar. |
CardGridPicker
| Prop | Type | Default | Description |
|---|---|---|---|
| dead | string[] | [] | Cards already on the board, shown but not pickable. |
| max | number | 5 | – |
| onChange * | (next: string[]) => void | – | – |
| value * | string[] | – | – |
ExplorerApp
| Prop | Type | Default | Description |
|---|---|---|---|
| initial | Partial<Record<ExplorerUrlKey, string>> | {} | – |
ExplorerTabs
| Prop | Type | Default | Description |
|---|---|---|---|
| buckets | ReactNode | – | Stored bucket tree. Omitted games get the coming-soon placeholder. |
| explorer * | ReactNode | – | – |
ExplorerUrlProvider
| Prop | Type | Default | Description |
|---|---|---|---|
| initial * | Partial<Record<ExplorerUrlKey, string>> | – | – |
HandSearchBar
| Prop | Type | Default | Description |
|---|---|---|---|
| error * | string | null | – | – |
| note * | string | null | – | – |
| onChange * | (next: string) => void | – | – |
| value * | string | – | – |
PreflopHandSummary
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | NodeAction[] | – | – |
| evUnit | "sb" | "usd" | sb | Unit of the actions' `evs`: small blinds (shown as bb), or tournament dollars on the ICM sets (shown as $). |
LockEditor
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | SolverActionInfo[] | – | – |
| hasLock * | boolean | – | True when this node already has a pending lock (shows Remove). |
| initial * | number[] | – | Starting frequencies — the existing lock, or the node's current aggregate strategy (so "apply" with no edits locks the solver line). |
| onApply * | (freqs: number[]) => void | – | Called with the normalized frequency vector (one per action, sum 1). |
| onCancel * | () => void | – | – |
| onRemove * | () => void | – | – |
| pot * | number | – | Pot before the player acts, for the %-pot hint on bets/raises. |
NodeEditModal
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | SolverActionInfo[] | – | The node's current actions (engine dump order). |
| actorLabel * | string | – | – |
| busy * | boolean | – | A re-solve is already running. |
| hasEdits * | boolean | – | Any node edits are active anywhere in the tree. |
| onClearAll | (() => void) | – | Remove every node edit in the tree (then re-solve). |
| onClose * | () => void | – | – |
| onConfirm * | (sizes: number[], allin: boolean) => void | – | Lowered rows: pot fractions (sorted asc) + whether to keep the shove. |
| pot * | number | – | Pot before this player acts (bb). |
PloRangeList
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | NodeAction[] | – | – |
| stack * | number | – | – |
PloActionBreakdown
| Prop | Type | Default | Description |
|---|---|---|---|
| board | string[] | – | – |
| sampleOf | number | – | Set when the rows are a sample of the range: the sample's size. |
| sections * | BreakdownSection[] | – | – |
Plo4HuPostflop
| Prop | Type | Default | Description |
|---|---|---|---|
| effStack * | number | – | – |
| flop * | string[] | – | – |
| line * | string | – | The closed preflop line, e.g. "SB_Limp_BB_Check". |
| onRepickFlop * | () => void | – | – |
| pot * | number | – | – |
| stack * | number | – | – |
| stripLead | ReactNode | – | The game card, pinned left of the rail (above it on phones). |
| stripPrefix | ReactNode | – | The preflop seat cards, so the rail reads as one continuous line. |
HandCards
| Prop | Type | Default | Description |
|---|---|---|---|
| hand * | string | – | – |
PloExplorer
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | NodeAction[] | – | – |
| game * | "plo" | "plo5" | "plo6hu" | – | – |
| history * | string | – | – |
| stack * | number | – | – |
HdvActionSection
| Prop | Type | Default | Description |
|---|---|---|---|
| busy * | boolean | – | – |
| color * | string | – | – |
| label * | string | – | – |
| maxHeight | string | max-h-[560px] | Height cap on the hand list (Tailwind class). |
| onMore | (() => void) | – | – |
| pct * | number | – | Pool share of this action, 0–100. |
| rows * | Plo5ListedHand[] | – | – |
| total * | number | – | Hands that take this action at all (rows is the top slice). |
Plo6BucketBars
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | { action: NodeAction; color: string; }[] | – | – |
| history * | string | – | – |
| stack * | number | – | – |
PostflopHandSummary
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | SolverActionInfo[] | – | – |
| evByCombo | Map<string, number> | null | – | Per-combo EV in bb, when this node is a solve root with `dump_ev`. |
| hands * | SolverHandStrategy[] | – | – |
| reach * | ComboWeights | null | – | Reach-weighted range of the acting player (drops folded-out combos). |
PreflopBrowser
| Prop | Type | Default | Description |
|---|---|---|---|
| game | "plo" | "plo5" | "plo6hu" | "nl" | "plo4hu" | "plo9" | "nlmtt8" | "icmft" | "icmbubble" | "icmbubble35" | – | Keep the walk on this dataset. Stack changes inside it still apply. |
| onSaved | ((bundle: CustomSolutionBundle) => void) | – | Fired after a custom solution is saved from the inline solve panel, so the page can refresh its saved-solutions library. |
PreflopStrategyGrid
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | NodeAction[] | – | – |
| raiseContext | RaiseContext | – | Where the actor stands; when given, sized raises read as pot percentages. |
| stack * | number | – | Effective stack in bb — only used for the legend's all-in label. |
RailRow
| Prop | Type | Default | Description |
|---|---|---|---|
| lead | ReactNode | – | – |
| scrollerRef | Ref<HTMLDivElement> | – | – |
RangeGridEditor
| Prop | Type | Default | Description |
|---|---|---|---|
| onChange * | (next: RangeWeights) => void | – | – |
| pos * | string | – | – |
| role * | "oop" | "ip" | – | – |
| seed | RangeWeights | – | The range as it came off the preflop line, for "reset to line". |
| weights * | RangeWeights | – | – |
SolutionSelectorCard
| Prop | Type | Default | Description |
|---|---|---|---|
| availableStacks * | number[] | – | Stacks present in the ranges manifest (browsable rows gate on this). |
| group * | SolutionGroup | – | – |
| onlyGroupId | string | – | When set, the drawer only lists stacks in this catalog group. |
| onOpenChange * | (open: boolean) => void | – | – |
| onSelect * | (groupId: string, stack: number, table?: string | null | undefined) => void | – | – |
| open * | boolean | – | – |
| shareable | boolean | false | Show a "Copy link" button for the current address (the explorer keeps its view in the URL, so the address is a link to this exact spot). |
| stack * | number | – | – |
| table | string | null | null | ICM sets: the stack table on screen (a scenario id). |
SolutionViewer
| Prop | Type | Default | Description |
|---|---|---|---|
| bundle * | CustomSolutionBundle | – | – |
| drillHref | string | – | Link to drill this solution in the trainer. Set only for the user's own saved solves — they're the ones that become `custom:` drill packs. |
| embedded | boolean | false | Rendered as a continuation of another navigator (the Explorer's preflop strip): drops the redundant title header, keeps the breadcrumb + action selector so it reads as one continuous walk rather than a nested viewer. |
| locking | ViewerLocking | – | Enables "Edit strategy" node locking (#268) — see `ViewerLocking`. |
| nodeEditing | ViewerNodeEditing | – | Enables structural node edits (#390) — see `ViewerNodeEditing`. |
| onBack | (() => void) | – | – |
| stripLead | ReactNode | – | (embedded) The game card, pinned left of the strip (above it on phones). |
| stripPrefix | ReactNode | – | (embedded) Leading cards for the decision strip — the preflop seat cards, so the preflop line + postflop tree render as one continuous action bar. |
TreeFlow
| Prop | Type | Default | Description |
|---|---|---|---|
| base * | SizingBase | – | – |
| boardCards * | number | – | – |
| grid * | SizingGrid | – | – |
| maxNodes | number | 4000 | Node budget for the expansion. |
| nodeEdits * | NodeEdit[] | – | – |
| onNodeEditsChange * | (edits: NodeEdit[]) => void | – | – |
| onStats | ((t: FullTree) => void) | – | Called with tree stats whenever the tree rebuilds. |
| result | SolverResult | null | – | Solve result (dump_nodes) — enables the frequency overlay. |
TreeSizingEditor
| Prop | Type | Default | Description |
|---|---|---|---|
| base * | SizingBase | – | – |
| boardCards * | number | – | 3/4/5 → flop/turn/river start; earlier streets are hidden (never built). |
| grid * | SizingGrid | – | – |
| nodeEdits * | NodeEdit[] | – | – |
| onChange * | (g: SizingGrid) => void | – | – |
| onNodeEditsChange * | (edits: NodeEdit[]) => void | – | – |
TreeVisualizationModal
| Prop | Type | Default | Description |
|---|---|---|---|
| base * | SizingBase | – | – |
| boardCards * | number | – | – |
| grid * | SizingGrid | – | – |
| isSolving | boolean | false | – |
| nodeEdits * | NodeEdit[] | – | – |
| onNodeEditsChange * | (edits: NodeEdit[]) => void | – | – |
| onOpenChange * | (open: boolean) => void | – | – |
| onSolve * | () => void | – | – |
| open * | boolean | – | – |
| result | SolverResult | null | – | – |
ScenarioStrip
| Prop | Type | Default | Description |
|---|---|---|---|
| onResolved * | (r: ResolvedScenario | null) => void | – | Emitted when the pot closes heads-up (ranges + seats) or the walk resets (null). |
StrategyGrid
| Prop | Type | Default | Description |
|---|---|---|---|
| actions * | SolverActionInfo[] | – | – |
| hands * | SolverHandStrategy[] | – | – |
| reach | ReadonlyMap<string, number> | null | – | Per-combo reach at this node. Omit at a solve root, where the dumped combos ARE the range; pass it anywhere the line has narrowed the range, so the grid agrees with the reach-weighted action summary. |
HandMatrix
| Prop | Type | Default | Description |
|---|---|---|---|
| aggressiveFirst | boolean | false | Draw the last action (the biggest raise) on the left of each cell and first in the legend. |
| cells * | (MatrixCell | null)[] | – | 169 cells, row-major A→2 by A→2 (suited above the diagonal). |
| colors * | string[] | – | Per-action colors, parallel to each cell's `freqs`. |
| foldIndex | number | – | Index of the fold action in `colors`; a cell that always folds gets a softer label. |
| legend * | { label: string; color: string; }[] | – | Legend entries under the grid, one per action. |
| onHover | ((label: string | null) => void) | – | Pointer over a cell, null when it leaves the grid. |
| onSelect | ((label: string) => void) | – | – |
| selected | string | null | – | Label of the highlighted cell, e.g. "AKs". |
Source
components/explorer/bottom-sheet.tsx
"use client";
// Shared bottom-sheet chrome for the viewer's node editors (Edit Node, lock
// strategy): backdrop + slide-up panel + header/body/footer scaffolding, so
// every editor opened from a node card presents identically.
import { useEffect, type ReactNode } from "react";
import { X } from "lucide-react";
export function BottomSheet({
title,
icon,
onClose,
children,
footer,
}: {
title: string;
icon?: ReactNode;
onClose: () => void;
children: ReactNode;
/** Pinned action row under the scrollable body. */
footer?: ReactNode;
}) {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
return (
<div
className="fixed inset-0 z-50 flex flex-col justify-end bg-black/60"
role="dialog"
aria-modal="true"
aria-label={title}
onClick={onClose}
>
<div
className="animate-in fade-in slide-in-from-bottom-8 mx-auto flex w-full max-w-2xl flex-col rounded-t-2xl border border-b-0 border-border bg-card shadow-2xl duration-200"
onClick={(e) => e.stopPropagation()}
>
<div className="mx-auto mt-2 h-1 w-10 shrink-0 rounded-full bg-border" aria-hidden />
<div className="flex items-center justify-between px-4 py-3">
<span className="flex items-center gap-2 text-base font-semibold text-foreground">
{icon}
{title}
</span>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
<div className="flex max-h-[55vh] flex-col gap-2 overflow-y-auto px-4 pb-3">
{children}
</div>
{footer ? (
<div className="flex items-center justify-between gap-2 border-t border-border px-4 py-3">
{footer}
</div>
) : null}
</div>
</div>
);
}
/** Uniform row style for sheet content (action rows, size rows). */
export const SHEET_ROW = "flex items-center gap-3 rounded-lg bg-accent/40 px-3 py-2";
components/explorer/builder.tsx
"use client";
// The custom-solution builder. A focused NLHE postflop setup form (board,
// ranges via the preflop scenario picker, bet tree) that solves with the engine
// in `dump_nodes` mode so the whole strategy tree comes back — flop solves are
// first-class: the defaults mirror the sample fixtures (0.75 sizing + all-in,
// #220 river action abstraction) and a product-quality flop solve runs
// ~10-15 min on the worker. The job lives server-side, so the builder records
// the job id in localStorage and can re-attach after a tab reload ("Resume").
// Results preview in the full SolutionViewer, then save (title + tags) to the
// Explorer catalog and open in the viewer proper.
import { explorerHost } from "@/lib/explorer/host";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Loader2, Lock, Play, Save, Sparkles, X, Eye } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ScenarioStrip, type ResolvedScenario } from "@/components/solver/scenario-strip";
import { resumeSolve, startSolve, type SolveHandle } from "@/lib/solver/client";
import {
fullRange,
isEmptyRange,
weightsToEngineString,
type RangeWeights,
} from "@/lib/solver/range-model";
import type {
LockedNode,
SolveRequest,
SolverProgress,
SolverResult,
} from "@/lib/solver/types";
import { buildLockedResolveRequest, isWarmStartFailure } from "@/lib/explorer/locks";
import {
betSizingLabel,
streetForBoard,
type CustomSolutionBundle,
type CustomSolutionMeta,
type CustomSolutionSummary,
} from "@/lib/explorer/types";
import {
buildPostflopSolveRequest,
sameSolveGeometry,
clearPendingSolve,
CUSTOM_SOLVE_DEFAULTS,
describeSolveError,
readPendingSolve,
solveEtaHint,
writePendingSolve,
type PendingSolve,
} from "@/lib/explorer/custom-solve";
import { SolutionViewer } from "./solution-viewer";
import { CardGridPicker } from "./card-picker";
import { RangeGridEditor } from "./range-grid-editor";
import {
emptySizingGrid,
sizingFromEditor,
TreeSizingEditor,
type NodeEdit,
type SizingBase,
type SizingGrid,
} from "./tree-sizing-editor";
import { TreeVisualizationModal } from "./tree-visualization-modal";
import { MiniCard } from "@/components/trainer/cards";
/** AI solve is disabled pending a solve path that's correct at all stack
* depths (#234: one-shot depth-limited solves produce phantom aggression at
* high SPR). Internal testing can re-enable with NEXT_PUBLIC_AI_SOLVE=1. */
const AI_SOLVE_ENABLED = process.env.NEXT_PUBLIC_AI_SOLVE === "1";
const DEFAULTS = {
board: "Qs Jh 2h",
pot: "5.5",
effective_stack: "97",
bet_sizes: CUSTOM_SOLVE_DEFAULTS.betSizes.join(", "),
max_aggressions: String(CUSTOM_SOLVE_DEFAULTS.maxAggressions),
river_bet_sizes: CUSTOM_SOLVE_DEFAULTS.riverBetSizes.join(", "),
river_max_aggressions: String(CUSTOM_SOLVE_DEFAULTS.riverMaxAggressions),
iterations: String(CUSTOM_SOLVE_DEFAULTS.iterations),
target_exploitability: String(CUSTOM_SOLVE_DEFAULTS.targetExploitability),
};
function parseNum(s: string, label: string): number {
const n = Number(s.trim());
if (!Number.isFinite(n)) throw new Error(`${label} must be a number`);
return n;
}
function parseSizes(s: string, label: string): number[] {
return s
.split(",")
.map((t) => t.trim())
.filter(Boolean)
.map((t, i) => parseNum(t, `${label} #${i + 1}`));
}
function Field({
label,
value,
onChange,
placeholder,
hint,
}: {
label: string;
value: string;
onChange: (v: string) => void;
placeholder?: string;
hint?: string;
}) {
return (
<label className="flex flex-col gap-1.5">
<span className="text-xs font-medium text-muted-foreground">{label}</span>
<input
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
spellCheck={false}
autoCapitalize="none"
className="h-9 rounded-lg border border-input bg-card px-3 text-sm text-foreground outline-none transition-colors placeholder:text-muted-foreground/60 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40"
/>
{hint ? <span className="text-[11px] text-muted-foreground/70">{hint}</span> : null}
</label>
);
}
/** The bet-tree / iteration knobs. Shown plainly in the full builder; tucked
* behind a disclosure in the inline (seeded) flow so the defaults just work. */
function Advanced({
collapsible,
children,
}: {
collapsible: boolean;
children: React.ReactNode;
}) {
if (!collapsible) return <>{children}</>;
return (
<details className="group rounded-lg border border-border bg-card/40 p-3">
<summary className="flex cursor-pointer list-none items-center justify-between text-xs font-medium text-muted-foreground">
Solve settings
<span className="text-muted-foreground/60 transition-transform group-open:rotate-180">▾</span>
</summary>
<div className="flex flex-col gap-4 pt-3">{children}</div>
</details>
);
}
/** The slim summary the solve setup collapses into once solved — keeps the flop
* visible while the postflop navigator takes the stage, with a way back in. */
function CollapsedSpot({
board,
sizing,
onEdit,
}: {
board: string;
sizing: string;
onEdit: () => void;
}) {
const cards = board.trim().split(/\s+/).filter(Boolean);
return (
<div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-border bg-card/40 px-4 py-2.5">
<div className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
<span className="text-[10px] uppercase tracking-wide text-muted-foreground/70">Flop</span>
<span className="inline-flex items-center gap-1 text-sm font-semibold tabular-nums">
{cards.map((c, i) => (
<MiniCard key={i} card={c} className="h-6 w-[18px] text-[15px]" />
))}
</span>
{sizing ? (
<>
<span className="text-muted-foreground/70">·</span>
<span>{sizing}</span>
</>
) : null}
</div>
<button
type="button"
onClick={onEdit}
className="shrink-0 rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-foreground transition-colors hover:bg-accent"
>
Edit spot · re-solve
</button>
</div>
);
}
/** A preflop spot handed in from the Explorer: ranges, geometry, and the chosen
* board already fixed, so the builder can solve immediately. */
export interface BuilderSeed {
oopWeights: RangeWeights;
ipWeights: RangeWeights;
potBb: number;
effStackBb: number;
oopLabel: string;
ipLabel: string;
/** Flop (or turn/river) chosen in the picker, space-separated. */
board: string;
/** OOP called the last preflop raise instead of making it. Such a player has
* effectively no donk range (our own solves put them at ~99% check), so the
* flop lead is pruned by default — see `NO_FLOP_DONK_EDIT`. */
oopIsPreflopCaller?: boolean;
}
const round1 = (n: number) => String(Math.round(n * 10) / 10);
/**
* The "no flop donk" preset: a node edit on the ROOT (OOP's first flop
* decision) that offers neither a bet nor a shove, leaving Check as the only
* action. Deliberately a node edit and not a street rule — a street-level
* `oop_bet_sizes: []` also erases OOP's check-raise, because raise sizes
* mirror the player's street bet sizes once those are set (see tree.rs
* `root_override_removes_the_flop_donk_only`). Only meaningful on a 3-card
* board, where the root IS the flop lead node.
*/
const NO_FLOP_DONK_EDIT: NodeEdit = { path: [], sizes: "none", allin: "off" };
/** Stable empty grid for when the custom-tree toggle is off — a fresh object
* per render would loop the tree-preview's rebuild memo. */
const EMPTY_GRID = emptySizingGrid();
const isNoFlopDonkEdit = (e: NodeEdit) => e.path.length === 0 && e.sizes.trim() === "none";
function formatElapsed(ms: number): string {
const s = Math.max(0, Math.floor(ms / 1000));
const m = Math.floor(s / 60);
return m > 0 ? `${m}m ${String(s % 60).padStart(2, "0")}s` : `${s}s`;
}
export function Builder({
onSaved,
seed,
layout = "page",
stripPrefix,
stripLead,
onSolvedChange,
setupless = false,
autoSolve = false,
onRunningChange,
onSetupError,
}: {
/** Called after a successful save with the summary + the full bundle, so the
* caller can open it straight in the SolutionViewer. */
onSaved: (s: CustomSolutionSummary, bundle: CustomSolutionBundle) => void;
seed?: BuilderSeed;
/** "drawer"/"inline" stack inputs over output in a single column; "inline"
* also collapses the advanced solve settings so the seeded flow stays lean. */
layout?: "page" | "drawer" | "inline";
/** (inline) Leading cards for the postflop navigator's strip — the preflop
* seat cards, so preflop + postflop form one continuous action bar. */
stripPrefix?: ReactNode;
/** (inline) The game card, pinned left of the navigator's strip. */
stripLead?: ReactNode;
/** (inline) Fired when a result appears (true) or a solve (re)starts (false),
* so the parent can hide its own seat strip while the navigator is up. */
onSolvedChange?: (solved: boolean) => void;
/** (inline) Never show the setup form up front — the Explorer's picker-drawer
* flow already fixed the board, and the solve starts on its own. The full
* form stays reachable post-solve via "Edit spot · re-solve". */
setupless?: boolean;
/** Kick the solve off on mount when the seeded board is complete. Held while
* a previous session's solve is pending (Resume / Discard decides first). */
autoSolve?: boolean;
/** Mirrors the base solve's running state, so the parent can render the
* acting card as a loading placeholder in its own strip. */
onRunningChange?: (running: boolean) => void;
/** The solve was refused before it was sent (empty range, bad input). The
* running mirror never flips for these, so without this the parent's
* loading card would spin forever. */
onSetupError?: (message: string) => void;
}) {
const inline = layout === "inline";
const stacked = layout === "drawer" || inline;
// When seeded from a closed preflop spot, the board is the only thing left to
// choose, and the ranges/pot/stack come pre-filled.
const [board, setBoard] = useState(() => seed?.board ?? (seed ? "" : DEFAULTS.board));
const [pot, setPot] = useState(() => (seed ? round1(seed.potBb) : DEFAULTS.pot));
const [stack, setStack] = useState(() => (seed ? round1(seed.effStackBb) : DEFAULTS.effective_stack));
const [betSizes, setBetSizes] = useState(DEFAULTS.bet_sizes);
// All-in is off by default: the default tree (0.75 pot) rarely uses it at a
// meaningful frequency and it clutters every acting card with an "AllIn 0%"
// row. "Always offer all-in" in the solve settings turns it back on.
const [addAllin, setAddAllin] = useState(false);
const [maxAggr, setMaxAggr] = useState(DEFAULTS.max_aggressions);
const [riverBetSizes, setRiverBetSizes] = useState(DEFAULTS.river_bet_sizes);
const [riverMaxAggr, setRiverMaxAggr] = useState(DEFAULTS.river_max_aggressions);
// Per-street/per-player tree overrides (GTO-Wizard-style). The grid only
// ships with the request while the toggle is on, so switching it off
// restores the exact legacy geometry (and its warm-start compatibility).
const [customTree, setCustomTree] = useState(false);
const [sizingGrid, setSizingGrid] = useState<SizingGrid>(emptySizingGrid);
// Seeded with the no-flop-donk preset when the preflop line handed us an OOP
// caller: the donk is ~0% of a real solution, and pruning it off the root
// cuts the widest branch of the flop tree.
const [nodeEdits, setNodeEdits] = useState<NodeEdit[]>(() =>
seed?.oopIsPreflopCaller ? [NO_FLOP_DONK_EDIT] : [],
);
const [iterations, setIterations] = useState(DEFAULTS.iterations);
const [targetExp, setTargetExp] = useState(DEFAULTS.target_exploitability);
const [oopWeights, setOopWeights] = useState<RangeWeights>(() => (seed ? seed.oopWeights : fullRange()));
const [ipWeights, setIpWeights] = useState<RangeWeights>(() => (seed ? seed.ipWeights : fullRange()));
const [scenario, setScenario] = useState<ResolvedScenario | null>(null);
const [running, setRunning] = useState(false);
const [runningAi, setRunningAi] = useState(false);
const [queued, setQueued] = useState(false);
const [progress, setProgress] = useState<SolverProgress | null>(null);
const [startedAt, setStartedAt] = useState<number | null>(null);
const [elapsedMs, setElapsedMs] = useState(0);
const [result, setResult] = useState<SolverResult | null>(null);
const [solvedConfig, setSolvedConfig] = useState<SolveRequest | null>(null);
/** Last COMPLETED solve (job id + request) — the warm-start source (#262).
* Locked what-if re-solves (#268) read it but NEVER update it: the
* unlocked base stays the one warm-start source.
*
* `cached` marks a solve the shared cache answered: correct strategy, but no
* worker job behind it and therefore no snapshot, so a locked re-solve has to
* re-run the base for real first. */
const lastSolveRef = useRef<{ jobId: string; request: SolveRequest; cached: boolean } | null>(
null,
);
const [labels, setLabels] = useState<{ oop: string; ip: string }>({ oop: "OOP", ip: "IP" });
const [error, setError] = useState<string | null>(null);
const handleRef = useRef<SolveHandle | null>(null);
// Locked what-if re-solve (#268) — kept fully apart from the base solve
// state so a what-if never contaminates the base result, the save panel, or
// the warm-start ref.
const [whatIf, setWhatIf] = useState<{ config: SolveRequest; result: SolverResult } | null>(
null,
);
const [lockBusy, setLockBusy] = useState(false);
const [lockProgress, setLockProgress] = useState<SolverProgress | null>(null);
const [lockError, setLockError] = useState<string | null>(null);
const lockHandleRef = useRef<SolveHandle | null>(null);
// A solve left running on the worker by an earlier session (tab reload).
// Lazy-read: the builder only mounts client-side (the drawer opens on user
// interaction), so localStorage is available and there's no hydration skew.
const [pending, setPending] = useState<PendingSolve | null>(() =>
typeof window === "undefined" ? null : readPendingSolve(),
);
// Save panel
const [title, setTitle] = useState("");
const [tagsInput, setTagsInput] = useState("");
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState<string | null>(null);
// Once solved, the inline flow collapses the setup form so the postflop
// navigator becomes the continuation; "Edit spot" reopens it.
const [editing, setEditing] = useState(false);
// Tree visualization + pruning modal (React Flow), opened before a solve.
const [treePreviewOpen, setTreePreviewOpen] = useState(false);
// Elapsed ticker while a solve runs.
useEffect(() => {
if (!running || startedAt === null) return;
const t = setInterval(() => setElapsedMs(Date.now() - startedAt), 1000);
return () => clearInterval(t);
}, [running, startedAt]);
const onScenarioResolved = (r: ResolvedScenario | null) => {
setScenario(r);
setOopWeights(r ? r.oop : fullRange());
setIpWeights(r ? r.ip : fullRange());
};
const boardCards = board.trim().split(/\s+/).filter(Boolean).length;
// The root preset prunes a FLOP lead. On a turn/river start the root is that
// street's lead node instead, which we leave alone — so drop it there.
const forBoard = (edits: NodeEdit[]) =>
boardCards === 3 ? edits : edits.filter((e) => !isNoFlopDonkEdit(e));
const effectiveNodeEdits = useMemo(
() => (boardCards === 3 ? nodeEdits : nodeEdits.filter((e) => !isNoFlopDonkEdit(e))),
[nodeEdits, boardCards],
);
const noFlopDonk = nodeEdits.some(isNoFlopDonkEdit);
const setNoFlopDonk = (on: boolean) =>
setNodeEdits((prev) => {
const rest = prev.filter((e) => !isNoFlopDonkEdit(e));
// Appended last so an explicit root edit of the user's own still wins:
// the engine applies the FIRST override whose path matches.
return on ? [...rest, NO_FLOP_DONK_EDIT] : rest;
});
// Lenient view of the base fields for the tree-edit node preview (invalid
// text falls back to defaults; the strict parse happens on Solve).
const sizingBase = useMemo<SizingBase>(() => {
const nums = (s: string) =>
s
.split(",")
.map((t) => Number(t.trim()))
.filter((n) => Number.isFinite(n) && n > 0);
const bets = nums(betSizes);
const aggr = Math.floor(Number(maxAggr));
const riverAggr = Math.floor(Number(riverMaxAggr));
return {
betSizes: bets.length > 0 ? bets : [0.75],
riverBetSizes: nums(riverBetSizes),
addAllin,
maxAggressions: Number.isFinite(aggr) && aggr >= 0 ? aggr : 2,
riverMaxAggressions: Number.isFinite(riverAggr) && riverAggr >= 0 ? riverAggr : undefined,
potBb: Number(pot) > 0 ? Number(pot) : 1,
effStackBb: Number(stack) > 0 ? Number(stack) : 100,
};
}, [betSizes, riverBetSizes, addAllin, maxAggr, riverMaxAggr, pot, stack]);
/** Drive a handle (fresh or resumed) to completion and adopt its outcome. */
const drive = async (
handle: SolveHandle,
request: SolveRequest,
ctx: { oop: string; ip: string; title: string },
): Promise<string | null> => {
handleRef.current = handle;
setRunning(true);
setQueued(true);
onSolvedChange?.(false);
try {
const outcome = await handle.promise;
setResult(outcome.result);
setSolvedConfig(request);
setLabels({ oop: ctx.oop, ip: ctx.ip });
setTitle(ctx.title);
clearPendingSolve();
setPending(null);
onSolvedChange?.(true);
// Remember the completed job for warm re-solves (#262): the worker kept
// its snapshot, so a same-geometry follow-up starts from this solution.
// A cache-served solve has no snapshot — recorded here so the locked
// re-solve path knows it must run the base for real first.
Promise.all([handle.jobId, handle.cached])
.then(([jobId, cached]) => {
lastSolveRef.current = { jobId, request, cached };
})
.catch(() => {});
return null;
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
setError(describeSolveError(msg));
// A job the worker no longer knows (restarted) can't be resumed — drop it.
if (/no such job/i.test(msg)) {
clearPendingSolve();
setPending(null);
}
return msg;
} finally {
setRunning(false);
setQueued(false);
handleRef.current = null;
}
};
const onSolve = async (ai: boolean, treeOverride?: { nodeEdits: NodeEdit[] }) => {
setError(null);
setResult(null);
setSolvedConfig(null);
setProgress(null);
setSaveError(null);
// A new base solve invalidates any locked what-if built on the old one.
lockHandleRef.current?.cancel().catch(() => {});
setWhatIf(null);
setLockError(null);
// Collapse the setup back down as the (re-)solve kicks off.
setEditing(false);
let request: SolveRequest;
try {
if (isEmptyRange(oopWeights)) throw new Error("OOP range is empty — pick a scenario or reset.");
if (isEmptyRange(ipWeights)) throw new Error("IP range is empty — pick a scenario or reset.");
const target = targetExp.trim() ? parseNum(targetExp, "target exploitability") : undefined;
const riverSizes = parseSizes(riverBetSizes, "river bet size");
request = buildPostflopSolveRequest({
board: board.trim(),
potBb: parseNum(pot, "pot"),
effStackBb: parseNum(stack, "effective stack"),
betSizes: parseSizes(betSizes, "bet size"),
addAllin,
maxAggressions: parseNum(maxAggr, "max aggressions"),
riverBetSizes: riverSizes.length > 0 ? riverSizes : undefined,
riverMaxAggressions: riverMaxAggr.trim()
? parseNum(riverMaxAggr, "river max aggressions")
: undefined,
// Node edits always ship — an Edit Node from the viewer (#390) and the
// no-flop-donk preset are both explicit tree intent, independent of
// the "customize tree" toggle. The grid stays gated by that toggle, so
// switching it off still restores the legacy geometry. With neither,
// `sizingFromEditor` returns undefined and the request is unchanged.
sizing: sizingFromEditor(
customTree || treeOverride ? sizingGrid : EMPTY_GRID,
forBoard(treeOverride ? treeOverride.nodeEdits : nodeEdits),
),
// AI solves converge on iteration budget alone — no target field.
iterations: ai ? CUSTOM_SOLVE_DEFAULTS.aiIterations : parseNum(iterations, "iterations"),
targetExploitability: ai ? undefined : target,
// Plateau stop only at study-grade targets. Deep spots decay
// ~1/iterations, so the default 1% target can be unreachable — the
// plateau ends the solve once converged instead of grinding to the
// cap. But a user who TYPES a tighter target (< 1%) is explicitly
// buying precision; the plateau would silently cap them near ~1.2%
// regardless, so high-precision runs let the target/cap govern.
convergencePlateau:
ai || (target !== undefined && target < CUSTOM_SOLVE_DEFAULTS.targetExploitability)
? undefined
: CUSTOM_SOLVE_DEFAULTS.convergencePlateau,
oopRange: weightsToEngineString(oopWeights),
ipRange: weightsToEngineString(ipWeights),
aiSolve: ai,
});
} catch (e) {
const msg = e instanceof Error ? e.message : "invalid input";
setError(msg);
onSetupError?.(msg);
return;
}
// Warm re-solve (#262): if the tree geometry is unchanged since the last
// completed solve (only convergence knobs tweaked), start from its
// snapshot — seconds instead of minutes. The engine fingerprint verifies
// server-side; the client-side check just avoids sending doomed requests.
const last = lastSolveRef.current;
if (!ai && last && sameSolveGeometry(request, last.request)) {
request.warm_start_from = last.jobId;
}
const oop = seed ? seed.oopLabel : scenario ? scenario.oopPos : "OOP";
const ip = seed ? seed.ipLabel : scenario ? scenario.ipPos : "IP";
const suggestedTitle = `${oop} vs ${ip} · ${request.board}`;
const launch = async (req: SolveRequest): Promise<string | null> => {
const t0 = Date.now();
setStartedAt(t0);
setElapsedMs(0);
setRunningAi(ai);
const handle = startSolve(req, (p) => {
setQueued(false);
setProgress(p);
});
// Record the job for resume as soon as the worker accepts it — the solve
// runs server-side, so a closed tab doesn't lose it.
handle.jobId
.then((jobId) =>
writePendingSolve({
jobId,
request: req,
startedAt: t0,
oopLabel: oop,
ipLabel: ip,
title: suggestedTitle,
ai,
}),
)
.catch(() => {});
return drive(handle, req, { oop, ip, title: suggestedTitle });
};
const err = await launch(request);
// Snapshot evicted / worker restarted / fingerprint mismatch: fall back
// to a cold solve automatically rather than surfacing a warm-start error.
if (err && request.warm_start_from && /snapshot|warm/i.test(err)) {
lastSolveRef.current = null;
const { warm_start_from: _dropped, ...cold } = request;
setError(null);
await launch(cold as SolveRequest);
}
};
// Mirror the running flag out to the parent (strip loading card).
useEffect(() => {
onRunningChange?.(running);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [running]);
// Auto-solve (Explorer picker flow): the drawer fixed the board, so the
// solve starts the moment this mounts. Deferred while a previous session's
// job is pending — Resume/Discard decides — and never re-fired after a
// cancel or failure (the parent's retry card remounts us with a fresh key).
const autoStarted = useRef(false);
useEffect(() => {
if (!autoSolve || autoStarted.current) return;
if (pending || running || result) return;
if (boardCards < 3) return;
autoStarted.current = true;
void onSolve(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [autoSolve, pending]);
const onResume = async (p: PendingSolve) => {
setError(null);
setResult(null);
setSolvedConfig(null);
setProgress(null);
setSaveError(null);
setStartedAt(p.startedAt);
setElapsedMs(Date.now() - p.startedAt);
setRunningAi(Boolean(p.ai));
const handle = resumeSolve(p.jobId, (tick) => {
setQueued(false);
setProgress(tick);
});
await drive(handle, p.request, { oop: p.oopLabel, ip: p.ipLabel, title: p.title });
};
const onDiscardPending = () => {
// Best-effort cancel so an abandoned flop solve frees its worker slot.
if (pending) resumeSolve(pending.jobId).cancel().catch(() => {});
clearPendingSolve();
setPending(null);
};
const onCancel = () => {
handleRef.current?.cancel().catch(() => {});
};
/**
* "Re-solve with edits" (#268): the base config + `locked_nodes` +
* `warm_start_from` the base job. The warm start is REQUIRED, not an
* optimization — a cold locked solve can never train the response behind a
* zeroed action (PR #269), so when no base snapshot exists we error out
* instead of falling back to cold (unlike the base solve's fallback).
*
* When the base was served from the shared solve cache there is no worker job
* to warm-start from, so the base is re-run on the worker (`noCache`) first.
* That's slow — it's the solve the cache just saved — but it's the only honest
* way to edit nodes, and it happens once per cached spot the user edits.
*/
const onLockedResolve = async (locks: LockedNode[]) => {
if (!solvedConfig || lockBusy) return;
setLockError(null);
let last = lastSolveRef.current;
if (!last || !sameSolveGeometry(solvedConfig, last.request)) {
setLockError(
"No warm-start snapshot for this spot — run the base solve first. Locked re-solves always start from the unlocked solution (a cold locked solve reads wrong wherever an action is locked to 0%).",
);
return;
}
if (last.cached) {
setLockBusy(true);
setLockProgress(null);
const baseRequest: SolveRequest = { ...last.request, noCache: true };
const baseHandle = startSolve(baseRequest, (p) => setLockProgress(p));
lockHandleRef.current = baseHandle;
try {
await baseHandle.promise;
const jobId = await baseHandle.jobId;
last = { jobId, request: baseRequest, cached: false };
lastSolveRef.current = last;
} catch (e) {
setLockError(
`Couldn't re-run the base solve needed to edit nodes: ${describeSolveError(
e instanceof Error ? e.message : String(e),
)}`,
);
setLockBusy(false);
setLockProgress(null);
lockHandleRef.current = null;
return;
}
}
let request: SolveRequest;
try {
request = buildLockedResolveRequest(solvedConfig, locks, last.jobId);
} catch (e) {
setLockError(e instanceof Error ? e.message : String(e));
setLockBusy(false);
setLockProgress(null);
lockHandleRef.current = null;
return;
}
setLockBusy(true);
setLockProgress(null);
const handle = startSolve(request, (p) => setLockProgress(p));
lockHandleRef.current = handle;
try {
const outcome = await handle.promise;
// A cancelled what-if is abandoned (unlike base solves, where the
// partial strategy is worth keeping — a what-if is cheap to redo warm).
if (!outcome.cancelled) setWhatIf({ config: request, result: outcome.result });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
setLockError(
isWarmStartFailure(msg)
? "The base solve's snapshot is no longer on the worker — run the base solve again, then re-apply your edits. (Locked re-solves never run cold: the response behind a zeroed action would stay untrained and silently wrong.)"
: describeSolveError(msg),
);
} finally {
setLockBusy(false);
setLockProgress(null);
lockHandleRef.current = null;
}
};
/**
* Structural "Edit Node" from the viewer (#390): merge the node's new action
* set into `nodeEdits` and re-solve the whole tree. Always a cold solve — a
* changed action set is a different geometry, so no warm start.
*/
const onNodeEditApply = (path: string[], sizes: number[], allin: boolean) => {
const sizesText =
sizes.length === 0
? "none"
: sizes.map((f) => String(Math.round(f * 1000) / 1000)).join(", ");
const next: NodeEdit = { path, sizes: sizesText, allin: allin ? "on" : "off" };
const merged = [...nodeEdits.filter((e) => e.path.join(" ") !== path.join(" ")), next];
setNodeEdits(merged);
setCustomTree(true);
void onSolve(false, { nodeEdits: merged });
};
const onNodeEditsClearAll = () => {
setNodeEdits([]);
void onSolve(false, { nodeEdits: [] });
};
const onCancelLockedResolve = () => {
lockHandleRef.current?.cancel().catch(() => {});
};
const onSave = async () => {
if (!result || !solvedConfig) return;
setSaving(true);
setSaveError(null);
try {
const meta: CustomSolutionMeta = {
potBb: solvedConfig.pot,
effStackBb: solvedConfig.effective_stack,
betSizing: betSizingLabel(solvedConfig),
oopLabel: labels.oop,
ipLabel: labels.ip,
startStreet: streetForBoard(solvedConfig.board),
ai: solvedConfig.aiSolve === true,
};
const tags = tagsInput
.split(",")
.map((t) => t.trim())
.filter(Boolean);
const solutionsApi = explorerHost().solutions;
if (!solutionsApi) throw new Error("Saving solutions isn't available here.");
const res = await fetch(solutionsApi, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title: title.trim(), tags, config: solvedConfig, result, meta }),
});
if (!res.ok) {
const body = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(body.error ?? `save failed (${res.status})`);
}
const { solution } = (await res.json()) as { solution: CustomSolutionSummary };
onSaved(solution, {
id: solution.id,
title: solution.title,
tags: solution.tags,
board: solvedConfig.board,
meta,
config: solvedConfig,
result,
generatedAt: solution.createdAt,
});
} catch (e) {
setSaveError(e instanceof Error ? e.message : String(e));
} finally {
setSaving(false);
}
};
// Ephemeral bundle so the fresh result previews in the real viewer (the same
// component saved solutions open in), on-demand river solves included.
const previewBundle = useMemo<CustomSolutionBundle | null>(() => {
if (!result || !solvedConfig) return null;
return {
id: "preview",
title: title.trim() || "Custom solve",
tags: [],
board: solvedConfig.board,
meta: {
potBb: solvedConfig.pot,
effStackBb: solvedConfig.effective_stack,
betSizing: betSizingLabel(solvedConfig),
oopLabel: labels.oop,
ipLabel: labels.ip,
startStreet: streetForBoard(solvedConfig.board),
ai: solvedConfig.aiSolve === true,
},
config: solvedConfig,
result,
generatedAt: new Date().toISOString(),
};
// Title is intentionally omitted: retyping the save title shouldn't remount
// the viewer (and reset its navigation) on every keystroke.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [result, solvedConfig, labels]);
// The locked what-if bundle (#268): same viewer, clearly labelled, NOT
// saveable in v1 (the save panel is hidden while it's shown).
const whatIfBundle = useMemo<CustomSolutionBundle | null>(() => {
if (!whatIf) return null;
return {
id: "locked-what-if",
title: `${title.trim() || "Custom solve"} · locked what-if`,
tags: [],
board: whatIf.config.board,
meta: {
potBb: whatIf.config.pot,
effStackBb: whatIf.config.effective_stack,
betSizing: betSizingLabel(whatIf.config),
oopLabel: labels.oop,
ipLabel: labels.ip,
startStreet: streetForBoard(whatIf.config.board),
},
config: whatIf.config,
result: whatIf.result,
generatedAt: new Date().toISOString(),
};
// Title omitted for the same reason as previewBundle.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [whatIf, labels]);
const solved = Boolean(result && solvedConfig);
// Inline: hide the setup form once solved so the navigator is the continuation.
// Setupless (Explorer picker flow): the form only ever appears via "Edit spot".
const showSetup = setupless ? editing : !inline || !solved || editing;
// A leftover job from a previous session. Normally shown inside the setup
// form; with the form hidden it renders standalone so Resume/Discard stays
// reachable (auto-solve waits on this decision).
const pendingBanner =
pending && !running && !result ? (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-card/60 p-3">
<span className="text-xs font-medium text-foreground">
A solve from a previous session is still on the server
</span>
<span className="text-[11px] text-muted-foreground">
{pending.title} · started {formatElapsed(Date.now() - pending.startedAt)} ago.
Jobs keep running server-side — re-attach to see progress and the result.
</span>
<div className="flex gap-2">
<Button size="sm" onClick={() => onResume(pending)}>
<Play className="size-3.5" /> Resume
</Button>
<Button size="sm" variant="outline" onClick={onDiscardPending}>
Discard
</Button>
</div>
</div>
) : null;
// The two post-solve blocks, ordered differently inline (viewer flows first,
// straight off the preflop strip) vs. standalone (save panel on top).
const resultBlocks =
result && solvedConfig ? (
{
// Locked what-ifs are not saveable in v1 — the save panel yields to
// the what-if banner while one is on screen.
save: whatIf ? null : (
<div className="flex flex-col gap-3 rounded-xl border border-border bg-card/40 p-4">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium text-foreground">Save this solution</span>
<span className="text-xs text-muted-foreground">
{solvedConfig.aiSolve
? "AI solve (exploitability not measurable)"
: `Exploitability ${result.exploitability.percent.toFixed(3)}%`}{" "}
· {result.iterations_run} iters · {result.elapsed_seconds.toFixed(1)}s
</span>
</div>
<Field label="Title" value={title} onChange={setTitle} placeholder="e.g. BTN vs CO 3-bet · QJ2" />
<Field
label="Tags (comma-separated)"
value={tagsInput}
onChange={setTagsInput}
placeholder="3bet-pot, BTN-vs-CO, two-tone"
/>
{saveError ? <p className="text-xs text-destructive">{saveError}</p> : null}
<Button onClick={onSave} disabled={saving || !title.trim()} className="self-start">
{saving ? (
<>
<Loader2 className="size-4 animate-spin" /> Saving…
</>
) : (
<>
<Save className="size-4" /> Save & open in viewer
</>
)}
</Button>
</div>
),
viewer: (
<div
className={
inline
? "flex flex-col gap-3"
: "flex flex-col gap-3 rounded-xl border border-border bg-card/20 p-4"
}
>
{lockError ? (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2.5 text-sm text-destructive">
{lockError}
</div>
) : null}
{lockBusy ? (
<div className="flex items-center gap-3 rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-2.5 text-sm text-muted-foreground">
<Loader2 className="size-4 shrink-0 animate-spin" />
<span className="tabular-nums">
Re-solving with your locked edits (warm start — usually seconds)…{" "}
{lockProgress
? `iter ${lockProgress.iter} · expl ${lockProgress.percent.toFixed(2)}%`
: "starting"}
</span>
<button
type="button"
onClick={onCancelLockedResolve}
aria-label="Cancel locked re-solve"
className="ml-auto rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
) : null}
{whatIf && whatIfBundle ? (
<>
<div className="flex flex-wrap items-center gap-2 rounded-lg border border-amber-500/40 bg-amber-500/[0.06] px-4 py-2.5 text-sm">
<Lock className="size-4 shrink-0 text-amber-400" />
<span className="text-foreground">
Locked what-if — {whatIf.config.locked_nodes?.length ?? 0} node
{(whatIf.config.locked_nodes?.length ?? 0) === 1 ? "" : "s"} play your
edits verbatim; the rest of the tree re-equilibrated against them.
</span>
<span className="text-xs text-muted-foreground tabular-nums">
composed expl {whatIf.result.exploitability.percent.toFixed(2)}% (the lock
sets the floor)
</span>
<button
type="button"
onClick={() => setWhatIf(null)}
className="ml-auto shrink-0 rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-foreground transition-colors hover:bg-accent"
>
Back to base solution
</button>
</div>
<SolutionViewer key="what-if" bundle={whatIfBundle} embedded={inline} stripPrefix={stripPrefix} stripLead={stripLead} />
</>
) : previewBundle && result.nodes && result.nodes.length > 0 ? (
<SolutionViewer
key="base"
bundle={previewBundle}
embedded={inline}
stripPrefix={stripPrefix}
stripLead={stripLead}
// Node locking (#268) needs the base job's snapshot to warm-start
// from; AI solves never snapshot, so they can't be edited.
locking={
!solvedConfig.aiSolve
? { onResolve: onLockedResolve, busy: lockBusy }
: undefined
}
// Structural Edit Node (#390) — full cold re-solve on confirm.
nodeEditing={
!solvedConfig.aiSolve
? {
onApply: onNodeEditApply,
onClearAll: onNodeEditsClearAll,
editedKeys: nodeEdits.map((e) => e.path.join(" ")),
busy: running,
}
: undefined
}
/>
) : (
<p className="text-sm text-muted-foreground">
The solve returned no node tree to walk — try a smaller spot.
</p>
)}
</div>
),
}
) : null;
return (
<div
className={
stacked
? "flex flex-col gap-6"
: "grid gap-6 lg:grid-cols-[minmax(0,360px)_minmax(0,1fr)]"
}
>
{/* ---- Inputs ---- */}
{showSetup ? (
<div className="flex flex-col gap-4 rounded-xl border border-border bg-card/40 p-4">
{pendingBanner}
{seed ? (
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-muted-foreground">Flop / board</span>
<CardGridPicker
value={board.trim().split(/\s+/).filter(Boolean)}
onChange={(next) => setBoard(next.join(" "))}
/>
<span className="text-[11px] text-muted-foreground/70">
3 / 4 / 5 cards → flop / turn / river
</span>
</div>
) : (
<Field
label="Board"
value={board}
onChange={setBoard}
placeholder="Qs Jh 2h"
hint="3 / 4 / 5 cards → flop / turn / river"
/>
)}
<div className="grid grid-cols-2 gap-3">
<Field label="Pot (bb)" value={pot} onChange={setPot} />
<Field label="Eff. stack (bb)" value={stack} onChange={setStack} />
</div>
<Advanced collapsible={inline}>
<Field
label="Bet sizes (× pot)"
value={betSizes}
onChange={setBetSizes}
placeholder="0.5, 0.75, 1"
/>
<label className="flex items-center justify-between gap-2">
<span className="text-xs font-medium text-muted-foreground">Always offer all-in</span>
<input
type="checkbox"
checked={addAllin}
onChange={(e) => setAddAllin(e.target.checked)}
className="size-4 accent-primary"
/>
</label>
<div className="grid grid-cols-2 gap-3">
<Field label="Max aggressions" value={maxAggr} onChange={setMaxAggr} />
<Field label="Iterations" value={iterations} onChange={setIterations} />
</div>
<div className="grid grid-cols-2 gap-3">
<Field
label="River bet sizes (× pot)"
value={riverBetSizes}
onChange={setRiverBetSizes}
placeholder="0.75"
/>
<Field label="River max aggr." value={riverMaxAggr} onChange={setRiverMaxAggr} />
</div>
<span className="-mt-2 text-[11px] text-muted-foreground/70">
A coarser river-only abstraction keeps full flop trees solvable. Leave river
sizes empty to reuse the main sizes.
</span>
<label className="flex items-center justify-between gap-2">
<span className="flex flex-col">
<span className="text-xs font-medium text-foreground">No flop donk</span>
<span className="text-[11px] text-muted-foreground/70">
OOP can only check the flop. The preflop caller donks at ~0% anyway,
so dropping the lead narrows the tree and speeds the solve up. Their
check-raise and later-street leads are untouched.
</span>
</span>
<input
type="checkbox"
checked={noFlopDonk}
disabled={boardCards !== 3}
onChange={(e) => setNoFlopDonk(e.target.checked)}
className="size-4 accent-primary disabled:opacity-40"
/>
</label>
<div className="flex flex-col gap-3 rounded-lg border border-border bg-card/60 p-3">
<label className="flex items-center justify-between gap-2">
<span className="flex flex-col">
<span className="text-xs font-medium text-foreground">Tree edit</span>
<span className="text-[11px] text-muted-foreground/70">
See every betting node the solve will offer and edit OOP / IP sizes per
street, GTO-Wizard style.
</span>
</span>
<input
type="checkbox"
checked={customTree}
onChange={(e) => setCustomTree(e.target.checked)}
className="size-4 accent-primary"
/>
</label>
{customTree ? (
<TreeSizingEditor
grid={sizingGrid}
onChange={setSizingGrid}
nodeEdits={effectiveNodeEdits}
onNodeEditsChange={setNodeEdits}
boardCards={boardCards}
base={sizingBase}
/>
) : null}
</div>
<Field
label="Target expl. % (optional)"
value={targetExp}
onChange={setTargetExp}
placeholder="e.g. 0.5"
hint="Stop early once exploitability drops below this. 1% is study grade (charts are visually converged); type 0.5 for high precision — slower, and deep spots may run to the iteration cap. Solves also end on their own when improvement stalls."
/>
</Advanced>
<div className="border-t border-border pt-4">
{seed ? (
<div className="flex flex-col gap-2">
<span className="text-xs font-medium text-muted-foreground">
Ranges — seeded from the preflop line, click or drag to edit
</span>
<div className="grid gap-2 sm:grid-cols-2">
<RangeGridEditor
pos={seed.oopLabel}
role="oop"
weights={oopWeights}
onChange={setOopWeights}
seed={seed.oopWeights}
/>
<RangeGridEditor
pos={seed.ipLabel}
role="ip"
weights={ipWeights}
onChange={setIpWeights}
seed={seed.ipWeights}
/>
</div>
</div>
) : (
<ScenarioStrip onResolved={onScenarioResolved} />
)}
</div>
{boardCards === 3 ? (
<div className="rounded-lg border border-border bg-card/60 px-3 py-2 text-[11px] text-muted-foreground">
Full flop solution: every turn subtree is solved and dumped; river runouts
open on demand in the viewer. Expect ~3–8 minutes (deep stacks trend higher;
the solve ends early once it converges) — it runs on the server, so you can
close this tab and resume from here later.
{Number(maxAggr) > 2 || betSizes.split(",").filter((s) => s.trim()).length > 1 ? (
<span className="mt-1 block">
Heads-up: extra sizes or more than 2 aggressions on a flop start can make
the strategy dump too large to load back — keep the tree small.
</span>
) : null}
</div>
) : null}
<div className="flex flex-col gap-2">
<div className="flex gap-2">
{/* AI solve is gated off (#234): the one-shot depth-limited path
produces distorted flop strategies at high SPR (e.g. phantom
donk ranges vs a ~100% exact check). Re-enable via the env flag
only for internal testing until the solve path is corrected. */}
{boardCards === 3 && AI_SOLVE_ENABLED ? (
<>
<Button onClick={() => onSolve(true)} disabled={running} className="flex-1">
{running && runningAi ? (
<>
<Loader2 className="size-4 animate-spin" /> Solving…
</>
) : (
<>
<Sparkles className="size-4" /> AI solve
</>
)}
</Button>
<Button
variant="outline"
onClick={() => onSolve(false)}
disabled={running}
className="flex-1"
>
{running && !runningAi ? (
<>
<Loader2 className="size-4 animate-spin" /> Solving…
</>
) : (
"Exact solve"
)}
</Button>
</>
) : (
<Button onClick={() => onSolve(false)} disabled={running || boardCards < 3} className="flex-1">
{running ? (
<>
<Loader2 className="size-4 animate-spin" /> Solving…
</>
) : boardCards < 3 ? (
"Pick a flop to solve"
) : (
"Solve"
)}
</Button>
)}
{boardCards === 3 && !running ? (
<Button
variant="outline"
onClick={() => setTreePreviewOpen(true)}
title="Visualize game tree and prune branches before solving"
>
<Eye className="size-4" /> Preview tree
</Button>
) : null}
{running ? (
<Button variant="outline" onClick={onCancel}>
Cancel
</Button>
) : null}
</div>
{boardCards === 3 && AI_SOLVE_ENABLED ? (
<span className="text-[11px] text-muted-foreground/70">
AI solve: seconds–minutes (beta), AI-assisted accuracy ~1–2% of pot vs 0.5%
exact. Turn cards open via fast exact re-solves in the viewer.
</span>
) : null}
</div>
</div>
) : null}
{/* ---- Output ---- */}
<div className="flex flex-col gap-4">
{!showSetup ? pendingBanner : null}
{error ? (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
{error}
</div>
) : null}
{running ? (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-card/40 px-4 py-3">
<div className="flex items-center justify-between gap-3 text-sm text-muted-foreground tabular-nums">
{queued && !progress ? (
<span className="flex items-center gap-2">
<Loader2 className="size-4 animate-spin" />
Waiting for a solver slot (the worker runs 2 solves at a time)…
</span>
) : progress ? (
<span>
{/* AI solves run a fixed iteration budget, and exploitability
isn't computable in the depth-limited game — show honest
progress instead of a meaningless 0.000%. */}
{runningAi
? `iter ${progress.iter} / ${CUSTOM_SOLVE_DEFAULTS.aiIterations}`
: `iter ${progress.iter} · expl ${progress.percent.toFixed(3)}%`}{" "}
· {formatElapsed(elapsedMs)} elapsed
</span>
) : (
<span>Starting solve…</span>
)}
<span className="flex shrink-0 items-center gap-2">
<span className="text-[11px] text-muted-foreground/70">
{solveEtaHint(boardCards, runningAi)}
</span>
{/* With the setup form hidden (picker flow) this is the only
cancel affordance. */}
{!showSetup ? (
<button
type="button"
onClick={onCancel}
aria-label="Cancel solve"
className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
) : null}
</span>
</div>
<span className="text-[11px] text-muted-foreground/70">
Runs server-side — closing this tab won't stop it; reopen the builder to
resume.
</span>
</div>
) : null}
{resultBlocks ? (
inline ? (
// Inline: the postflop navigator flows straight off the preflop
// strip; the collapsed spot + save panel sit below it.
<>
{resultBlocks.viewer}
{!editing ? (
<CollapsedSpot
board={solvedConfig?.board ?? board}
sizing={solvedConfig ? betSizingLabel(solvedConfig) : ""}
onEdit={() => setEditing(true)}
/>
) : null}
{resultBlocks.save}
</>
) : (
<>
{resultBlocks.save}
{resultBlocks.viewer}
</>
)
) : !running ? (
<div className="flex min-h-[200px] items-center justify-center rounded-xl border border-dashed border-border text-sm text-muted-foreground">
Set up a postflop spot and hit Solve. The full strategy tree is solved,
then you can name, tag, and save it.
</div>
) : null}
</div>
{/* Tree visualization + pruning modal (React Flow, editable nodes).
Node edits made in the flow land in the SAME nodeEdits state the
Tree-edit strip uses, and node edits always ship with the solve. */}
{treePreviewOpen ? (
<TreeVisualizationModal
open={treePreviewOpen}
onOpenChange={setTreePreviewOpen}
grid={customTree ? sizingGrid : EMPTY_GRID}
base={sizingBase}
boardCards={boardCards}
nodeEdits={effectiveNodeEdits}
onNodeEditsChange={setNodeEdits}
result={result}
onSolve={() => {
setTreePreviewOpen(false);
onSolve(false);
}}
isSolving={running}
/>
) : null}
</div>
);
}
components/explorer/card-picker.tsx
"use client";
// A GTO-Wizard-style card grid for choosing a board: four suit rows × thirteen
// ranks. Click to add a card; click a used (highlighted) card to remove it.
// Used to select a flop (and optionally a turn/river) when a closed preflop
// line goes postflop.
import { Trash2 } from "lucide-react";
import { MiniCard } from "@/components/trainer/cards";
import { suitTile } from "@/components/trainer/theme";
const RANKS = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"];
const SUITS = ["s", "h", "d", "c"] as const;
// Suit rows use the table's four-color deck (`suitTile`), like every other card.
const SUIT_GLYPH: Record<string, string> = { s: "♠", h: "♥", d: "♦", c: "♣" };
export function CardGridPicker({
value,
onChange,
max = 5,
dead = [],
}: {
value: string[];
onChange: (next: string[]) => void;
max?: number;
/** Cards already on the board, shown but not pickable. */
dead?: string[];
}) {
const toggle = (card: string) => {
if (value.includes(card)) onChange(value.filter((c) => c !== card));
else if (value.length < max) onChange([...value, card]);
};
return (
<div className="flex w-full max-w-[460px] flex-col gap-3">
{/* Selected board */}
<div className="flex items-center gap-2">
<div className="flex min-h-[30px] flex-1 flex-wrap items-center gap-1">
{value.length === 0 ? (
<span className="text-xs text-muted-foreground">Pick a flop (3 cards)…</span>
) : (
value.map((c, i) => (
<MiniCard key={i} card={c} className="h-8 w-6 text-xl" />
))
)}
</div>
{value.length > 0 ? (
<button
type="button"
onClick={() => onChange([])}
aria-label="Clear board"
className="rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<Trash2 className="size-4" />
</button>
) : null}
</div>
{/* Suit rows */}
<div className="flex flex-col gap-1">
{SUITS.map((suit) => (
<div
key={suit}
className="grid grid-cols-[repeat(13,minmax(0,1fr))] gap-1"
>
{RANKS.map((rank) => {
const card = `${rank}${suit}`;
const used = value.includes(card);
const disabled = dead.includes(card) || (!used && value.length >= max);
return (
<button
key={card}
type="button"
disabled={disabled}
onClick={() => toggle(card)}
style={{ backgroundColor: suitTile(suit).bg, opacity: used ? 0.35 : disabled ? 0.25 : 1 }}
className={`flex h-8 items-center justify-center rounded border border-white/25 text-sm font-bold text-white transition ${
used ? "ring-2 ring-white/80" : disabled ? "cursor-not-allowed" : "hover:brightness-110"
}`}
title={`${rank}${SUIT_GLYPH[suit]}`}
>
{rank}
</button>
);
})}
</div>
))}
</div>
</div>
);
}
components/explorer/explorer-app.tsx
"use client";
// The Explorer — one continuous screen, modeled on GTO Wizard's Study mode.
//
// You walk the precomputed multiway NLHE tree one seat at a time. The moment a
// line closes heads-up, the postflop solve panel appears inline right below the
// seat strip — pick a flop, tweak the seeded continue ranges, and solve, all in
// the same scroll (no drawer, no separate "postflop" screen). Results preview in
// the full SolutionViewer and save with one button.
//
// Saved and sample solutions live on their own page, /library — this screen is
// only the walk.
import { PreflopBrowser } from "./preflop-browser";
import { ExplorerUrlProvider } from "./explorer-url";
import type { ExplorerUrlState } from "@/lib/explorer/share-url";
export function ExplorerApp({ initial = {} }: { initial?: ExplorerUrlState }) {
return (
<ExplorerUrlProvider initial={initial}>
<PreflopBrowser />
</ExplorerUrlProvider>
);
}
components/explorer/explorer-tabs.tsx
"use client";
// One panel, two views: stored suit-bucket mixes, and the range explorer.
// Games without a stored bucket tree show a placeholder on the Buckets tab.
import { useState, type ReactNode } from "react";
import { useExplorerUrl } from "./explorer-url";
export function BucketsComingSoon() {
return (
<p className="px-3 py-12 text-center text-sm text-muted-foreground">Coming soon</p>
);
}
export function ExplorerTabs({
buckets,
explorer,
}: {
/** Stored bucket tree. Omitted games get the coming-soon placeholder. */
buckets?: ReactNode;
explorer: ReactNode;
}) {
// The open tab is part of the shareable URL (?tab=buckets; Explorer is the default).
const url = useExplorerUrl();
const [tab, setTabState] = useState<"buckets" | "explorer">(() =>
url.get("tab") === "buckets" ? "buckets" : "explorer",
);
const setTab = (next: "buckets" | "explorer") => {
setTabState(next);
url.set({ tab: next === "buckets" ? "buckets" : null });
};
const tabs = [
{ id: "buckets" as const, label: "Buckets" },
{ id: "explorer" as const, label: "Explorer" },
];
return (
<div className="overflow-hidden rounded-xl border border-border bg-card/40">
<div
role="tablist"
aria-label="Range view"
className="flex gap-1 border-b border-border px-2 pt-2"
>
{tabs.map((item) => {
const selected = tab === item.id;
return (
<button
key={item.id}
type="button"
role="tab"
id={`range-tab-${item.id}`}
aria-selected={selected}
aria-controls={`range-panel-${item.id}`}
onClick={() => setTab(item.id)}
className={
selected
? "-mb-px border-b-2 border-foreground px-3 py-1.5 text-xs font-medium text-foreground"
: "-mb-px border-b-2 border-transparent px-3 py-1.5 text-xs font-medium text-muted-foreground hover:text-foreground"
}
>
{item.label}
</button>
);
})}
</div>
<div
role="tabpanel"
id="range-panel-buckets"
aria-labelledby="range-tab-buckets"
className={tab === "buckets" ? "px-2 py-2" : "hidden"}
>
{buckets ?? <BucketsComingSoon />}
</div>
<div
role="tabpanel"
id="range-panel-explorer"
aria-labelledby="range-tab-explorer"
className={tab === "explorer" ? "p-3" : "hidden"}
>
{explorer}
</div>
</div>
);
}
components/explorer/explorer-url.tsx
"use client";
// Keeps the Explorer's view in the address bar so any view is a shareable
// link. The page reads the query on the server and hands it down as `initial`
// (no useSearchParams, so nothing needs its own Suspense boundary); components
// read their starting value from here and write changes back with
// history.replaceState, which updates the URL without a navigation or a new
// history entry per click.
//
// Without a provider (the explorer pieces rendered elsewhere) reads return
// nothing and writes are dropped, so the components behave as before.
import { createContext, useContext, useMemo, useRef, type ReactNode } from "react";
import { mergeSearch, type ExplorerUrlKey, type ExplorerUrlState } from "@/lib/explorer/share-url";
interface ExplorerUrlApi {
get: (key: ExplorerUrlKey) => string | undefined;
set: (patch: Partial<Record<ExplorerUrlKey, string | null>>) => void;
}
const NOOP: ExplorerUrlApi = { get: () => undefined, set: () => {} };
const Ctx = createContext<ExplorerUrlApi>(NOOP);
export function ExplorerUrlProvider({
initial,
children,
}: {
initial: ExplorerUrlState;
children: ReactNode;
}) {
// The current values, so a component that mounts later (a tab panel after a
// game switch) starts from what the URL says now, not what it said on load.
const state = useRef<ExplorerUrlState>({ ...initial });
const api = useMemo<ExplorerUrlApi>(
() => ({
get: (key) => state.current[key],
set: (patch) => {
let changed = false;
for (const [k, v] of Object.entries(patch) as [ExplorerUrlKey, string | null][]) {
const next = v == null || v === "" ? undefined : v;
if (state.current[k] !== next) {
changed = true;
if (next === undefined) delete state.current[k];
else state.current[k] = next;
}
}
if (!changed || typeof window === "undefined") return;
// `download` is a one-off error flag from a failed pack download; a
// shared link shouldn't carry it.
const search = mergeSearch(window.location.search, { ...patch, download: null });
const url = `${window.location.pathname}${search}${window.location.hash}`;
window.history.replaceState(null, "", url);
},
}),
[],
);
return <Ctx.Provider value={api}>{children}</Ctx.Provider>;
}
export function useExplorerUrl(): ExplorerUrlApi {
return useContext(Ctx);
}
components/explorer/hand-search-bar.tsx
"use client";
// Hand search for the PLO Explorer, in GTO Wizard's syntax (parser and
// definitions in lib/hand-search). The field is the shared SearchField block;
// this file only supplies the syntax reference shown in its ? popover.
import type { ReactNode } from "react";
import { SearchField } from "@/components/blocks/search-field";
import {
DRAW_MACROS,
POSTFLOP_MACROS,
PREFLOP_MACROS,
} from "@/lib/hand-search";
const GENERAL: [string, string][] = [
["*", "Any single rank"],
["AKQJT98765432", "Ranks, ace down to two"],
[
"R O N",
"Rank variables: R (or P) and O bind a rank, so RR is a pair; N is a rank held once",
],
[
"[ ]",
"A list of ranks, suits or cards for one position: [AK], [T-A], A[sh], [As,Kd]",
],
["s h d c", "Suits: spades, hearts, diamonds, clubs"],
[
"w x y z",
"Suit variables: same letter same suit, different letters different suits",
],
];
const OPERATORS: [string, string][] = [
[",", "Union: either side"],
[":", "Intersection: both sides"],
[
"!",
"Difference: left side without the right (!AA alone = every hand but AA)",
],
["( )", "Group to set the order"],
[">", "Equal or better than a made-hand category (needs a board)"],
["<", "Worse than a made-hand category (needs a board)"],
];
const EXAMPLES = [
["AA**:$ds", "Double-suited aces"],
["AxKx**", "A and K of one suit"],
["RROO", "Two pair"],
["$0g!$rb", "Rundowns that aren't rainbow"],
["[T-A][T-A][T-A][T-A]", "Four Broadway cards"],
["(KK,QQ):$dsn", "KK or QQ, double-suited with a nut suit"],
].map(([code, text]) => ({ code, text }));
export function HandSearchBar({
value,
onChange,
error,
note,
}: {
value: string;
onChange: (next: string) => void;
error: string | null;
note: string | null;
}) {
return (
<SearchField
value={value}
onChange={onChange}
label="Search hands"
placeholder="Search hands, e.g. AA**:$ds"
error={error}
note={note}
helpLabel="Hand search syntax"
examples={EXAMPLES}
help={
<>
<HelpSection title="General">
<Rows rows={GENERAL} />
</HelpSection>
<HelpSection title="Operators">
<Rows rows={OPERATORS} />
</HelpSection>
<HelpSection title="Preflop macros">
<Rows rows={PREFLOP_MACROS.map((m) => [m.name, m.help])} />
</HelpSection>
<HelpSection
title="Postflop macros"
hint="Need a board, so they don't filter preflop ranges."
>
<Rows rows={POSTFLOP_MACROS.map((m) => [m.name, m.help])} />
</HelpSection>
<HelpSection title="Draws and blockers" hint="Need a board too.">
<Rows rows={DRAW_MACROS.map((m) => [m.name, m.help])} />
</HelpSection>
</>
}
/>
);
}
function HelpSection({
title,
hint,
children,
}: {
title: string;
hint?: string;
children: ReactNode;
}) {
return (
<section className="flex flex-col gap-1.5">
<h3 className="text-[12px] font-medium uppercase tracking-wide text-muted-foreground">
{title}
</h3>
{hint ? (
<p className="text-[12px] text-muted-foreground">{hint}</p>
) : null}
{children}
</section>
);
}
function Rows({ rows }: { rows: [string, string][] }) {
return (
<dl className="grid grid-cols-[minmax(0,9.5rem)_1fr] gap-x-3 gap-y-1 px-1">
{rows.map(([k, v]) => (
<div key={k} className="contents">
<dt className="font-mono text-[12px] text-foreground">{k}</dt>
<dd className="text-[12px] text-muted-foreground">{v}</dd>
</div>
))}
</dl>
);
}
components/explorer/hand-summary.tsx
"use client";
// GTO-Wizard-style hand summary for the preflop browser. One row per in-range
// hand class: the class label, a mini strategy bar (the action split), the
// hand's EV, and the share of the range it represents. Sorted so the hands that
// keep going (raise/all-in) sit on top, like GTO Wizard's Summary tab.
//
// EV comes from the v2 ranges dataset (`/api/ranges/nl/v2/node`), which carries
// per-action EV in small blinds. The hand's EV is the strategy-frequency-
// weighted average of the EVs of the actions it takes (at equilibrium those are
// indifferent), shown in big blinds. When a node has no EV (legacy data), the
// column is hidden rather than faked.
import { useMemo } from "react";
import { ALL_HANDS, comboCountOf } from "@/lib/solver/range-model";
import { colorActions } from "./preflop-strategy-grid";
import type { NodeAction } from "@/lib/solver/preflop";
interface Row {
hand: string;
/** Per-action frequency for this class, parallel to the colored actions. */
freqs: number[];
/** In-range fraction (Σ freqs). */
total: number;
/** Weighted concrete combos (total × comboCount). */
combos: number;
/** Raise + all-in frequency (the EV tiebreak: how much the hand raises). */
raiseFreq: number;
/** Strategy-weighted EV in big blinds, when the dataset carries EV. */
evBb?: number;
}
export function PreflopHandSummary({
actions,
evUnit = "sb",
}: {
actions: NodeAction[];
/** Unit of the actions' `evs`: small blinds (shown as bb), or tournament
* dollars on the ICM sets (shown as $). */
evUnit?: "sb" | "usd";
}) {
const usd = evUnit === "usd";
const colored = useMemo(() => colorActions(actions), [actions]);
const { rows, rangeCombos, hasEv } = useMemo(() => {
const out: Row[] = [];
let rangeCombos = 0;
let hasEv = false;
for (const hand of ALL_HANDS) {
const freqs = colored.map(({ action }) => action.weights[hand] ?? 0);
const total = freqs.reduce((s, f) => s + f, 0);
if (total <= 0.0005) continue;
const combos = total * comboCountOf(hand);
rangeCombos += combos;
// How much the hand raises (raise + all-in share) — the EV tiebreak.
let raiseW = 0;
colored.forEach(({ action }, a) => {
if (action.kind === "raise" || action.kind === "allin") raiseW += freqs[a];
});
const raiseFreq = raiseW / (total || 1);
// Hand EV = strategy-weighted mean of the EVs of the actions it takes
// (small blinds → bb). Only counts actions that carry an EV for this hand.
let evWeighted = 0;
let evDenom = 0;
colored.forEach(({ action }, a) => {
const e = action.evs?.[hand];
if (e === undefined) return;
const f = freqs[a];
if (f > 0) {
evWeighted += f * e;
evDenom += f;
}
});
const evBb = evDenom > 0 ? evWeighted / evDenom / (usd ? 1 : 2) : undefined;
if (evBb !== undefined) hasEv = true;
out.push({ hand, freqs, total, combos, raiseFreq, evBb });
}
// Highest EV on top. Hands that show the same EV (rounded to the displayed
// 0.01bb — the indifferent "zero-EV mixed" cluster) are ordered by how much
// they raise. Hands without EV fall to the bottom, also by raise frequency.
const r2 = (x: number) => Math.round(x * 100) / 100;
out.sort((a, b) => {
if (a.evBb !== undefined && b.evBb !== undefined) {
const d = r2(b.evBb) - r2(a.evBb);
if (d !== 0) return d;
return b.raiseFreq - a.raiseFreq || b.combos - a.combos;
}
if (a.evBb !== undefined) return -1;
if (b.evBb !== undefined) return 1;
return b.raiseFreq - a.raiseFreq || b.combos - a.combos;
});
return { rows: out, rangeCombos, hasEv };
}, [colored, usd]);
const cols = hasEv ? "52px minmax(0,1fr) 58px 56px" : "52px minmax(0,1fr) 62px";
return (
<div className="flex flex-col gap-2">
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">Hand summary</span>
<div
className="grid gap-2 px-1 text-[10px] uppercase tracking-wide text-muted-foreground/70"
style={{ gridTemplateColumns: cols }}
>
<span>Hand</span>
<span>Strategy</span>
{hasEv ? <span className="text-right">{usd ? "EV $" : "EV bb"}</span> : null}
<span className="text-right">Range</span>
</div>
<div className="flex max-h-[460px] flex-col overflow-y-auto pr-0.5">
{rows.map((r) => {
const rangePct = rangeCombos > 0 ? (r.combos / rangeCombos) * 100 : 0;
return (
<div
key={r.hand}
className="grid items-center gap-2 rounded px-1 py-1 hover:bg-accent/30"
style={{ gridTemplateColumns: cols }}
>
<span className="text-xs font-semibold text-foreground tabular-nums">{r.hand}</span>
<div className="flex h-2 overflow-hidden rounded-full bg-white/[0.06]">
{r.freqs.map((f, a) =>
f <= 0.001 ? null : (
<div key={a} style={{ flexGrow: f, backgroundColor: colored[a].color }} />
),
)}
</div>
{hasEv ? (
<span
className={`text-right text-[11px] tabular-nums ${
r.evBb === undefined
? "text-muted-foreground/40"
: r.evBb >= 0
? "text-emerald-400"
: "text-rose-400"
}`}
>
{r.evBb === undefined ? "—" : `${r.evBb >= 0 ? "+" : ""}${r.evBb.toFixed(2)}`}
</span>
) : null}
<span className="text-right text-[11px] text-muted-foreground tabular-nums">
{rangePct.toFixed(1)}%
</span>
</div>
);
})}
</div>
</div>
);
}
components/explorer/lock-editor.tsx
"use client";
// The node strategy editor (#268): opened from the solution viewer at an
// action node, one slider + number input per action. Values are free-form
// weights, displayed and applied as the normalized percentage split (so
// dragging one slider never has to fight the others to stay at 100%). Applying
// produces an aggregate (`all_hands`) lock — every combo of the acting
// player's range plays the same frequencies verbatim in the re-solve.
// Presented in the shared BottomSheet chrome so it matches the Edit Node sheet.
import { useMemo, useState } from "react";
import { Lock, Trash2 } from "lucide-react";
import { Button } from "@/components/ui/button";
import { ACTION_COLORS } from "@/components/solver/strategy-grid";
import type { SolverActionInfo } from "@/lib/solver/types";
import { normalizeLockFreqs } from "@/lib/explorer/locks";
import { BottomSheet, SHEET_ROW } from "./bottom-sheet";
export function LockEditor({
actions,
pot,
initial,
hasLock,
onApply,
onRemove,
onCancel,
}: {
actions: SolverActionInfo[];
/** Pot before the player acts, for the %-pot hint on bets/raises. */
pot: number;
/** Starting frequencies — the existing lock, or the node's current
* aggregate strategy (so "apply" with no edits locks the solver line). */
initial: number[];
/** True when this node already has a pending lock (shows Remove). */
hasLock: boolean;
/** Called with the normalized frequency vector (one per action, sum 1). */
onApply: (freqs: number[]) => void;
onRemove: () => void;
onCancel: () => void;
}) {
const [weights, setWeights] = useState<number[]>(() =>
actions.map((_, i) => Math.max(0, (initial[i] ?? 0) * 100)),
);
const normalized = useMemo(() => normalizeLockFreqs(weights), [weights]);
const setWeight = (i: number, v: number) => {
setWeights((w) => w.map((x, j) => (j === i ? Math.min(100, Math.max(0, v)) : x)));
};
return (
<BottomSheet
title="Lock strategy — this node"
icon={<Lock className="size-4 text-amber-400" />}
onClose={onCancel}
footer={
<>
<span className="flex items-center gap-2">
{hasLock ? (
<Button size="sm" variant="outline" onClick={onRemove}>
<Trash2 className="size-3.5" /> Remove lock
</Button>
) : null}
{!normalized ? (
<span className="text-xs text-destructive">
At least one action needs a positive weight.
</span>
) : null}
</span>
<Button size="sm" onClick={() => normalized && onApply(normalized)} disabled={!normalized}>
<Lock className="size-3.5" /> {hasLock ? "Update lock" : "Apply lock"}
</Button>
</>
}
>
<p className="text-[11px] text-muted-foreground/70">
Every hand in range will play this exact split (an aggregate lock). Frequencies
normalize to 100% automatically. Re-solving makes the rest of the tree adjust
against it.
</p>
{actions.map((action, i) => {
const pct = normalized ? normalized[i] * 100 : 0;
return (
<div key={i} className={SHEET_ROW}>
<span className="flex w-32 shrink-0 items-center gap-2 text-sm text-foreground">
<span
className="size-3 shrink-0 rounded-[3px]"
style={{ backgroundColor: ACTION_COLORS[action.label] }}
/>
<span className="truncate">
{action.label}
{action.add > 0 ? (
<span className="ml-1 text-xs text-muted-foreground tabular-nums">
{Math.round(action.add * 10) / 10}bb
{pot > 0 && (action.label === "Bet" || action.label === "Raise")
? ` · ${Math.round((action.add / pot) * 100)}%`
: ""}
</span>
) : null}
</span>
</span>
<input
type="range"
min={0}
max={100}
step={1}
value={weights[i]}
onChange={(e) => setWeight(i, Number(e.target.value))}
aria-label={`${action.label} weight`}
className="min-w-0 flex-1 accent-amber-400"
/>
<span className="flex items-center rounded-md border border-input bg-card">
<input
type="number"
min={0}
max={100}
step={1}
value={Math.round(weights[i] * 10) / 10}
onChange={(e) => setWeight(i, Number(e.target.value))}
aria-label={`${action.label} percent`}
className="h-8 w-14 bg-transparent px-2 text-right text-sm text-foreground tabular-nums outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
/>
<span className="pr-2 text-xs text-muted-foreground">%</span>
</span>
<span className="w-14 shrink-0 text-right text-xs text-muted-foreground tabular-nums">
→ {pct.toFixed(1)}%
</span>
</div>
);
})}
{/* Normalized split preview bar */}
<div className="flex h-2 w-full overflow-hidden rounded-full bg-white/[0.06]">
{normalized
? actions.map((action, i) =>
normalized[i] > 0 ? (
<div
key={i}
style={{
flexGrow: normalized[i],
backgroundColor: ACTION_COLORS[action.label],
}}
/>
) : null,
)
: null}
</div>
</BottomSheet>
);
}
components/explorer/node-edit-modal.tsx
"use client";
// GTO-Wizard-style "Edit node" sheet (#390 + node cards): edit the ACTION SET
// at one decision point — bet/raise sizes as % of pot, plus the all-in shove.
// Confirming lowers the rows to a `sizing.nodes` entry (engine NodeSizingConfig)
// and re-solves the tree; this is a structural edit, so unlike a frequency
// lock it can never warm-start. Presented in the shared BottomSheet chrome so
// it matches the lock editor.
import { useMemo, useState } from "react";
import { Pencil, Plus, X } from "lucide-react";
import type { SolverActionInfo } from "@/lib/solver/types";
import { BottomSheet, SHEET_ROW } from "./bottom-sheet";
/** Engine formula inverted: add = toCall + f·(pot + toCall). */
function fracOf(add: number, pot: number, toCall: number): number {
return (add - toCall) / (pot + toCall);
}
export function NodeEditModal({
actorLabel,
pot,
actions,
hasEdits,
busy,
onConfirm,
onClearAll,
onClose,
}: {
actorLabel: string;
/** Pot before this player acts (bb). */
pot: number;
/** The node's current actions (engine dump order). */
actions: SolverActionInfo[];
/** Any node edits are active anywhere in the tree. */
hasEdits: boolean;
/** A re-solve is already running. */
busy: boolean;
/** Lowered rows: pot fractions (sorted asc) + whether to keep the shove. */
onConfirm: (sizes: number[], allin: boolean) => void;
/** Remove every node edit in the tree (then re-solve). */
onClearAll?: () => void;
onClose: () => void;
}) {
const toCall = actions.find((a) => a.label === "Call")?.add ?? 0;
const passive = useMemo(
() => actions.filter((a) => a.label === "Check" || a.label === "Fold" || a.label === "Call"),
[actions],
);
const aggressive = actions.filter((a) => a.label === "Bet" || a.label === "Raise");
const betWord = toCall > 0 ? "Raise" : "Bet";
// Rows are % of pot (integers in the UI, fractions on confirm).
const [rows, setRows] = useState<number[]>(() =>
aggressive.map((a) => Math.round(fracOf(a.add, pot, toCall) * 100)),
);
const [allin, setAllin] = useState(() => actions.some((a) => a.label === "AllIn"));
const setRow = (i: number, pct: number) =>
setRows((r) => r.map((v, j) => (j === i ? pct : v)));
const removeRow = (i: number) => setRows((r) => r.filter((_, j) => j !== i));
const addRow = () => setRows((r) => [...r, 50]);
const valid = rows.every((p) => Number.isFinite(p) && p > 0);
const confirm = () => {
if (!valid || busy) return;
const sizes = [...new Set(rows.map((p) => p / 100))].sort((a, b) => a - b);
onConfirm(sizes, allin);
};
return (
<BottomSheet
title={`Edit node · ${actorLabel}`}
icon={<Pencil className="size-4 text-muted-foreground" />}
onClose={onClose}
footer={
<>
{hasEdits && onClearAll ? (
<button
type="button"
onClick={onClearAll}
disabled={busy}
className="text-sm font-medium text-muted-foreground transition-colors hover:text-foreground disabled:opacity-50"
>
Delete All Node Edits
</button>
) : (
<span />
)}
<button
type="button"
onClick={confirm}
disabled={!valid || busy}
className="rounded-lg bg-foreground px-4 py-2 text-sm font-semibold text-background transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
Confirm
</button>
</>
}
>
{passive.map((a) => (
<div key={a.label} className={SHEET_ROW}>
<span className="flex-1 text-sm text-foreground">
{a.label}
{a.add > 0 ? (
<span className="ml-2 text-xs text-muted-foreground tabular-nums">
{Math.round(a.add * 10) / 10}bb
</span>
) : null}
</span>
<span className="text-[10px] text-muted-foreground/60">always kept</span>
</div>
))}
{rows.map((pct, i) => (
<div key={i} className={SHEET_ROW}>
<span className="w-11 text-sm text-foreground">{betWord}</span>
<span className="flex items-center rounded-md border border-input bg-card">
<input
value={Number.isFinite(pct) ? String(pct) : ""}
onChange={(e) => setRow(i, Number(e.target.value))}
inputMode="numeric"
aria-label={`${betWord} size ${i + 1} (% of pot)`}
className="h-8 w-14 bg-transparent px-2 text-right text-sm text-foreground tabular-nums outline-none"
/>
<span className="pr-2 text-xs text-muted-foreground">%</span>
</span>
<input
type="range"
min={5}
max={200}
step={1}
value={Math.min(Math.max(Number.isFinite(pct) ? pct : 5, 5), 200)}
onChange={(e) => setRow(i, Number(e.target.value))}
aria-label={`${betWord} size ${i + 1} slider`}
className="min-w-0 flex-1 accent-foreground"
/>
<button
type="button"
onClick={() => removeRow(i)}
aria-label={`Remove ${betWord.toLowerCase()} size`}
className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
))}
<div className={SHEET_ROW}>
<span className="flex-1 text-sm text-foreground">All-in</span>
<input
type="checkbox"
checked={allin}
onChange={(e) => setAllin(e.target.checked)}
aria-label="Include all-in"
className="size-4 accent-foreground"
/>
</div>
<button
type="button"
onClick={addRow}
className="flex items-center justify-between rounded-lg border border-dashed border-border px-3 py-2 text-left text-sm text-muted-foreground transition-colors hover:border-foreground/40 hover:text-foreground"
>
{betWord}
<Plus className="size-4" />
</button>
<p className="text-[11px] text-muted-foreground/70">
Confirm rebuilds the game tree with these actions and re-solves the spot from
scratch (a structural edit can't warm-start).
</p>
</BottomSheet>
);
}
components/explorer/plo-range-list.tsx
"use client";
// PLO hand-class viewer for the Explorer: one section per action (Fold / Call /
// Raise pot …), each listing every hand that takes it, sorted by EV. Omaha has
// no 13×13 grid — 16,432 suit-isomorphism classes — so hands render as compact
// card tiles and the filter chips (suitedness / connectedness / pairing /
// height) slice every section at once.
//
// Ported from pokerdata.io's explorer, restyled onto this app's tokens: the
// action palette is the solver grid's (`colorActions`), and the cards are the
// same white faces with four-color suits the trainer and hand replayer use,
// rather than pokerdata's solid suit-tinted tiles.
import { useDeferredValue, useMemo, useState } from "react";
import { useExplorerUrl } from "./explorer-url";
import { HandSearchBar } from "./hand-search-bar";
import { matchesHandClass, parseHandQuery } from "@/lib/hand-search";
import {
FILTER_GROUPS,
handProps,
matchesFilters,
type FilterId,
type HandProps,
} from "@/lib/explorer/plo-filter";
import { ploLabelForAction, sortActionsForDisplay, type NodeAction } from "@/lib/solver/preflop";
import { MiniCard } from "@/components/trainer/cards";
import { ploStringToCards } from "@/lib/trainer/plo-hand";
import { classComboCount } from "@/lib/plo-ranges/combos";
import { colorActions, type PreflopActionItem } from "./preflop-strategy-grid";
const comboMemo = new Map<string, number>();
/** Concrete combos a Monker hand class stands for ("(2A)AA" → 12), memoized. */
function combosOf(hand: string): number {
let n = comboMemo.get(hand);
if (n === undefined) {
n = classComboCount(hand);
comboMemo.set(hand, n);
}
return n;
}
/** Σ weight × combos: the share of the 270,725 starting hands, as solvers report it. */
function comboMass(weights: Record<string, number>): number {
let s = 0;
for (const [hand, w] of Object.entries(weights)) if (w > 0) s += w * combosOf(hand);
return s;
}
/**
* Aggregate action shares for the seat cards, weighted by concrete combos.
*
* A class like "AAAA" is 1 combo and "AKQJ" rainbow is 24, so counting classes
* misstates the split (heads-up PLO4 SB root: 6.8/27.5/65.7 by class against
* 6.4/25.7/68.0 by combo). Solvers and GTO Wizard report combo shares.
*/
export function ploActionItems(actions: NodeAction[], stack: number): PreflopActionItem[] {
const colored = colorActions(sortActionsForDisplay(actions));
const mass = colored.map(({ action }) => comboMass(action.weights));
const denom = mass.reduce((s, m) => s + m, 0) || 1;
return colored.map(({ action, color }, i) => ({
action,
label: ploLabelForAction(action, stack),
color,
freq: mass[i] / denom,
combos: mass[i],
}));
}
/** One hand's line in an action column. */
export interface BreakdownRow {
/** Stable key: a Monker class string preflop, a concrete combo postflop. */
key: string;
/** The hand's cards, any order (they render high first). */
cards: string[];
/** Frequency of taking THIS action, in [0, 1]. */
freq: number;
/** EV (bb) of this action, when the dataset carries EV. */
evBb: number | null;
/** EV edge (bb) over the hand's best alternative action; null if unknown. */
evDiffBb: number | null;
props: HandProps;
/** This row's share of the range: freq × combos preflop, freq × reach postflop.
* Filters recompute each column's percent from these. */
weight: number;
}
/** One action column: its header share and every hand that takes it. */
export interface BreakdownSection {
key: string;
label: string;
color: string;
/** The action's share of the whole range, in percent (unfiltered). */
pct: number;
/** Sorted rows, best EV first. */
rows: BreakdownRow[];
}
/** Rows rendered per section before "show all" — the 13k-hand fold list would
* otherwise lock the tab on first paint. */
const SECTION_PREVIEW = 150;
export function PloRangeList({ actions, stack }: { actions: NodeAction[]; stack: number }) {
const colored = useMemo(() => colorActions(sortActionsForDisplay(actions)), [actions]);
const sections = useMemo<BreakdownSection[]>(() => {
// hand → filterable props, computed once across every action's key set.
const propsByHand = new Map<string, HandProps>();
for (const { action } of colored) {
for (const h of Object.keys(action.weights)) if (!propsByHand.has(h)) propsByHand.set(h, handProps(h));
}
const built = colored.map(({ action, color }, idx) => {
const rows: BreakdownRow[] = [];
let mass = 0;
for (const [hand, freq] of Object.entries(action.weights)) {
if (freq <= 0.0005) continue;
const ev = action.evs?.[hand];
// Edge over the best alternative action that carries an EV for this hand.
let bestOther: number | null = null;
colored.forEach(({ action: other }, j) => {
if (j === idx) return;
const e = other.evs?.[hand];
if (e !== undefined && (bestOther === null || e > bestOther)) bestOther = e;
});
const weight = freq * combosOf(hand);
mass += weight;
rows.push({
key: hand,
cards: ploStringToCards(hand),
freq,
// The dataset's EV is in small blinds; the Explorer talks in bb.
evBb: ev === undefined ? null : ev / 2,
evDiffBb: ev === undefined || bestOther === null ? null : (ev - bestOther) / 2,
props: propsByHand.get(hand)!,
weight,
});
}
rows.sort((a, b) => (b.evBb ?? -Infinity) - (a.evBb ?? -Infinity) || b.freq - a.freq);
return { key: action.action, label: ploLabelForAction(action, stack), color, rows, mass };
});
const total = built.reduce((s, sec) => s + sec.mass, 0) || 1;
return built.map(({ mass, ...sec }) => ({ ...sec, pct: (mass / total) * 100 }));
}, [colored, stack]);
return <PloActionBreakdown sections={sections} />;
}
/**
* The per-action range breakdown: hand search, filter chips, then one column
* per action with its share, hand count and hand list (freq, EV, diff). The
* preflop Explorer and the PLO postflop view both render through this.
*
* Without `board` the rows are suit-isomorphism classes (preflop); with it they
* are concrete combos, and board-aware searches (TP, FD, >2P …) apply.
*/
export function PloActionBreakdown({
sections,
board,
sampleOf,
}: {
sections: BreakdownSection[];
board?: string[];
/** Set when the rows are a sample of the range: the sample's size. */
sampleOf?: number;
}) {
// Active chips are part of the shareable URL (?f=ds,rundown).
const url = useExplorerUrl();
const [active, setActiveState] = useState<Set<FilterId>>(() => {
const known = new Set<string>(FILTER_GROUPS.flatMap((g) => g.chips.map((c) => c.id)));
const ids = (url.get("f") ?? "").split(",").filter((id) => known.has(id));
return new Set(ids as FilterId[]);
});
const setActive = (update: (prev: Set<FilterId>) => Set<FilterId>) => {
const next = update(active);
setActiveState(next);
url.set({ f: [...next].join(",") || null });
};
const [expanded, setExpanded] = useState<Set<string>>(() => new Set());
// Hand search (GTO Wizard syntax), also in the URL (?s=AA**:$ds).
const [search, setSearchState] = useState(() => url.get("s") ?? "");
const setSearch = (next: string) => {
setSearchState(next);
url.set({ s: next.trim() || null });
};
const deferredSearch = useDeferredValue(search);
const parsed = useMemo(() => {
const text = deferredSearch.trim();
return text ? parseHandQuery(text) : null;
}, [deferredSearch]);
// A query filters when it parses, and needs no board or has one.
const query = parsed?.ok && (!parsed.query.needsBoard || board) ? parsed.query : null;
const searchError = parsed && !parsed.ok ? `${parsed.error} (at character ${parsed.index + 1})` : null;
const searchNote =
parsed?.ok && parsed.query.needsBoard && !board
? "Postflop and draw macros (TP, FD, >2P …) need a board. These are preflop ranges, so this search isn't applied."
: null;
// Every distinct hand across the columns.
const hands = useMemo(() => {
const map = new Map<string, BreakdownRow>();
for (const sec of sections) for (const r of sec.rows) if (!map.has(r.key)) map.set(r.key, r);
return map;
}, [sections]);
const toggle = (id: FilterId) =>
setActive((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
// Hands passing the chips AND the search; null = no filter at all.
const passing = useMemo(() => {
if (active.size === 0 && !query) return null;
const out = new Set<string>();
for (const [key, r] of hands) {
if (active.size > 0 && !matchesFilters(r.props, active)) continue;
if (query) {
// Concrete combos on a board are tested as dealt; classes try each suit relabelling.
const ok = board ? query.test(r.cards, board) : matchesHandClass(query, r.cards);
if (!ok) continue;
}
out.add(key);
}
return out;
}, [hands, active, query, board]);
// With a filter on, each column's percent is its share of the hands that
// pass, weighted the same way as the unfiltered figure (combos × freq).
const filtered = useMemo(() => {
if (passing === null) return sections;
const kept = sections.map((sec) => {
const rows = sec.rows.filter((r) => passing.has(r.key));
return { ...sec, rows, mass: rows.reduce((s, r) => s + r.weight, 0) };
});
const total = kept.reduce((s, sec) => s + sec.mass, 0);
return kept.map(({ mass, ...sec }) => ({ ...sec, pct: total > 0 ? (mass / total) * 100 : 0 }));
}, [sections, passing]);
const matching = passing === null ? hands.size : passing.size;
const anyFilter = active.size > 0 || search.trim() !== "";
const hasEv = sections.some((s) => s.rows.some((r) => r.evBb !== null));
const cols = hasEv
? "grid-cols-[minmax(0,1fr)_44px_52px_52px]"
: "grid-cols-[minmax(0,1fr)_44px]";
return (
<div className="flex flex-col gap-3">
<HandSearchBar value={search} onChange={setSearch} error={searchError} note={searchNote} />
<div className="flex items-center justify-between gap-3">
<span className="text-xs tabular-nums text-muted-foreground">
{matching.toLocaleString("en-US")} of{" "}
{sampleOf !== undefined
? `a ${sampleOf.toLocaleString("en-US")}-hand sample`
: `${hands.size.toLocaleString("en-US")} hands`}
</span>
{anyFilter ? (
<button
type="button"
onClick={() => {
setActive(() => new Set());
setSearch("");
}}
className="text-xs text-muted-foreground underline underline-offset-2 hover:text-foreground"
>
Clear filters
</button>
) : null}
</div>
{/* OR within a group, AND across groups. */}
<div className="flex flex-wrap items-center gap-1.5">
{FILTER_GROUPS.map((group, gi) => (
<div key={group.key} className="flex items-center gap-1.5">
{gi > 0 ? <span aria-hidden className="h-4 w-px bg-border" /> : null}
{group.chips.map((chip) => {
const on = active.has(chip.id);
return (
<button
key={chip.id}
type="button"
onClick={() => toggle(chip.id)}
aria-pressed={on}
className={`rounded-full px-3 py-1 text-xs font-medium transition-colors ${
on
? "bg-primary text-primary-foreground"
: "bg-secondary text-muted-foreground hover:bg-accent hover:text-foreground"
}`}
>
{chip.label}
</button>
);
})}
</div>
))}
</div>
<div className="grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(280px,1fr))]">
{filtered.map((sec) => {
const isOpen = expanded.has(sec.key);
const shown = isOpen ? sec.rows : sec.rows.slice(0, SECTION_PREVIEW);
const pct = sec.pct;
return (
<section
key={sec.key}
className="flex flex-col overflow-hidden rounded-xl border border-border bg-card/40"
>
{/* Header tinted by the action's own color, as in the grid legend. */}
<div
className="flex flex-col gap-1.5 px-3 py-2.5"
style={{ backgroundColor: `${sec.color}26` }}
>
<div className="flex items-baseline justify-between gap-2">
<span className="text-sm font-medium text-foreground">{sec.label}</span>
<span className="text-[11px] tabular-nums text-muted-foreground">
{sec.rows.length.toLocaleString("en-US")}{" "}
{sec.rows.length === 1 ? "hand" : "hands"}
</span>
</div>
<div className="flex items-center gap-2">
<span className="text-base font-semibold tabular-nums text-foreground">
{pct.toFixed(1)}%
</span>
<div className="flex h-1.5 flex-1 overflow-hidden rounded-full bg-foreground/10">
<div style={{ width: `${pct}%`, backgroundColor: sec.color }} />
</div>
</div>
</div>
<div className="flex max-h-[560px] flex-col overflow-y-auto px-2 pb-2">
<div
className={`sticky top-0 z-10 grid items-center gap-2 bg-card px-1 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70 ${cols}`}
>
<span>Hand</span>
<span className="text-right">Freq %</span>
{hasEv ? (
<>
<span className="text-right">EV bb</span>
<span className="text-right">Diff bb</span>
</>
) : null}
</div>
{shown.length === 0 ? (
<p className="py-6 text-center text-xs text-muted-foreground">
No hands match {query ? "this search" : "these filters"}.
</p>
) : (
shown.map((r) => (
<div
key={r.key}
className={`grid items-center gap-2 rounded px-1 py-[3px] hover:bg-accent/40 ${cols}`}
// Keeps thousands of rows cheap to scroll.
style={{ contentVisibility: "auto", containIntrinsicSize: "auto 30px" }}
>
<HandCards id={r.key} cards={r.cards} />
<span className="text-right text-[11px] tabular-nums text-foreground">
{Math.round(r.freq * 100)}
</span>
{hasEv ? (
<>
<span className="text-right text-[11px] tabular-nums text-foreground">
{r.evBb === null ? "—" : r.evBb.toFixed(2)}
</span>
<span
className={`text-right text-[11px] tabular-nums ${
r.evDiffBb === null
? "text-muted-foreground/60"
: r.evDiffBb >= 0
? "text-emerald-500"
: "text-rose-500"
}`}
>
{r.evDiffBb === null
? "—"
: `${r.evDiffBb >= 0 ? "+" : ""}${r.evDiffBb.toFixed(2)}`}
</span>
</>
) : null}
</div>
))
)}
{!isOpen && sec.rows.length > SECTION_PREVIEW ? (
<button
type="button"
onClick={() => setExpanded((prev) => new Set(prev).add(sec.key))}
className="mx-1 my-1 self-start rounded-full border border-border px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
Show all {sec.rows.length.toLocaleString("en-US")} ↓
</button>
) : null}
</div>
</section>
);
})}
</div>
</div>
);
}
const RANK_ORDER = "23456789TJQKA";
const SUIT_ORDER = "shdc";
/** Highest rank on the left, lowest on the right (GTO Wizard's order), ties
* by suit so paired cards keep a stable colour order. Same rule as the
* PLO5/PLO6 lists (`cardsOf` in plo5-range-panel). */
function highFirst(cards: string[]): string[] {
return [...cards].sort(
(a, b) =>
RANK_ORDER.indexOf(b[0]) - RANK_ORDER.indexOf(a[0]) ||
SUIT_ORDER.indexOf(a[1]) - SUIT_ORDER.indexOf(b[1]),
);
}
/** A hand's cards, high first, as miniature app card faces. */
function HandCards({ id, cards }: { id: string; cards: string[] }) {
return (
<div className="flex items-center gap-[3px]">
{highFirst(cards).map((card, i) => (
<MiniCard key={`${id}-${i}`} card={card} className="h-[26px] w-5 text-base" />
))}
</div>
);
}
components/explorer/plo4hu-postflop.tsx
"use client";
// Heads-up PLO4 postflop in the Explorer. The flop is the MonkerSolver
// postflop blueprint itself (looked up, not solved); every turn card re-solves
// the turn from the ranges the blueprint reaches there, and every river card
// re-solves the river exactly, hand by hand (the engine is solver-engine's
// PLO4 heads-up explorer service, see `@/lib/explorer/plo4hu-postflop`).
//
// The rail continues the preflop seat strip: a street card per board, then one
// decision card per action taken, the acting card last. Below it, the acting
// range's sample in the preflop Explorer's per-action columns (search, chips,
// freq / EV / diff per hand).
//
// ui-exception: the decision rail and the per-hand strategy rows match the
// preflop rail cards this view continues (`preflop-browser.tsx`); no App UI
// block renders a poker action tree.
import { explorerHost } from "@/lib/explorer/host";
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { MiniCard } from "@/components/trainer/cards";
import { actionColor } from "@/lib/pokerstudy/poker";
import { handProps } from "@/lib/explorer/plo-filter";
import { streetBetPotPct } from "@/lib/explorer/bet-size";
import { cardsToPloString } from "@/lib/trainer/plo-hand";
import type { Card } from "@/lib/trainer/hand";
import { PloActionBreakdown, type BreakdownRow, type BreakdownSection } from "./plo-range-list";
import { BottomSheet } from "./bottom-sheet";
import { CardGridPicker } from "./card-picker";
import { RailRow } from "./rail-row";
type Next = "action" | "deal" | "fold" | "allin" | "showdown";
interface NodeSummary {
path: string[];
player: 0 | 1;
actions: { label: string; freq: number; next: Next }[];
combos: number;
}
interface Street {
id: string;
status: "queued" | "running" | "done" | "failed" | "missing" | "lost";
board?: string;
pot?: number;
stack?: number;
nodes?: NodeSummary[];
error?: string;
elapsed?: number;
exploitability_pct?: number;
/** "blueprint" for the flop looked up from the Monker blueprint. */
source?: string;
/** True when the street was solved per hand, without grouping. */
exact?: boolean;
}
interface NodeDetail {
path: string[];
player: 0 | 1;
actions: string[];
range_freqs: number[];
combos: number;
hands: { combo: string; reach: number; freqs: number[]; evs: number[] | null }[];
}
/** The host's heads-up PLO4 postflop routes (the Explorer only mounts this
* panel where the host serves them). */
const api = () => explorerHost().plo4huPostflop ?? "/api/explorer/plo4hu-postflop";
/** Solver player 0 is out of position: the big blind, heads-up. */
const SEAT = ["BB", "SB"] as const;
const STREET_NAME = ["Flop", "Turn", "River"];
function kindOf(label: string): "fold" | "check" | "call" | "raise" | "allin" {
const k = label.split(" ")[0];
if (k === "Fold") return "fold";
if (k === "Check") return "check";
if (k === "Call") return "call";
if (k === "AllIn") return "allin";
return "raise";
}
function colorOf(label: string): string {
return actionColor(kindOf(label), label);
}
/** "Bet 1" → "Bet 1bb"; amounts are the chips the action puts in. */
function display(label: string): string {
const [k, amt] = label.split(" ");
const name = k === "AllIn" ? "All-in" : k;
return amt ? `${name} ${amt}bb` : name;
}
/**
* "Bet 3" with the street's pot 6 → "Bet 50%": bets and raises read as a
* percentage of the pot, GTO Wizard style (`@/lib/explorer/bet-size`). Falls
* back to the chip amount when the pot isn't known yet. `prior` is the
* street's actions before this one.
*/
function sizeLabel(label: string, prior: string[], pot: number | undefined): string {
const pct = pot === undefined ? null : streetBetPotPct(pot, prior, label);
return pct === null ? display(label) : `${label.split(" ")[0]} ${pct}%`;
}
function cardsOf(s: string): string[] {
const out: string[] = [];
for (let i = 0; i + 1 < s.length; i += 2) out.push(s.slice(i, i + 2));
return out;
}
async function json<T>(res: Response): Promise<T> {
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error((body as { error?: string }).error ?? `request failed (${res.status})`);
return body as T;
}
/** Poll a street until it is solved (or fails); solved streets land in `onDone`. */
function useStreet(id: string | null, onDone: (s: Street) => void): Street | null {
const [street, setStreet] = useState<Street | null>(null);
const doneRef = useRef(onDone);
useEffect(() => {
doneRef.current = onDone;
});
useEffect(() => {
if (!id) return;
let cancelled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const tick = async () => {
try {
const s = await json<Street>(await fetch(`${api()}/${id}`, { cache: "no-store" }));
if (cancelled) return;
setStreet(s);
if (s.status === "done") doneRef.current(s);
if (s.status === "queued" || s.status === "running") timer = setTimeout(tick, 2500);
} catch (e) {
if (cancelled) return;
setStreet({ id, status: "failed", error: e instanceof Error ? e.message : "failed" });
}
};
tick();
return () => {
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [id]);
// A street that hasn't answered yet reads as queued.
if (!id) return null;
return street?.id === id ? street : { id, status: "queued" };
}
const RAIL_CARD = "flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2";
export function Plo4HuPostflop({
stack,
line,
flop,
pot,
effStack,
stripPrefix,
stripLead,
onRepickFlop,
}: {
stack: number;
/** The closed preflop line, e.g. "SB_Limp_BB_Check". */
line: string;
flop: string[];
pot: number;
effStack: number;
/** The preflop seat cards, so the rail reads as one continuous line. */
stripPrefix?: ReactNode;
/** The game card, pinned left of the rail (above it on phones). */
stripLead?: ReactNode;
onRepickFlop: () => void;
}) {
// One entry per street: its solve id and the actions taken on it. Keyed by
// the spot, so a different flop or line starts over.
const spotKey = `${stack}|${line}|${flop.join("")}|${pot}|${effStack}`;
const [state, setState] = useState<{ key: string; streets: { id: string; path: string[] }[]; error: string | null }>({
key: "",
streets: [],
error: null,
});
const fresh = state.key === spotKey;
const streets = useMemo(() => (fresh ? state.streets : []), [fresh, state.streets]);
const startError = fresh ? state.error : null;
const setStreets = (f: (ss: { id: string; path: string[] }[]) => { id: string; path: string[] }[]) =>
setState((st) => ({ ...st, streets: f(st.streets) }));
const setStartError = (error: string | null) => setState((st) => ({ ...st, error }));
const [picker, setPicker] = useState(false);
const [dealing, setDealing] = useState(false);
useEffect(() => {
let cancelled = false;
(async () => {
try {
const r = await json<{ id: string }>(
await fetch(api(), {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ stack, line, board: flop.join(""), pot, effStack }),
}),
);
if (!cancelled) setState({ key: spotKey, streets: [{ id: r.id, path: [] }], error: null });
} catch (e) {
if (!cancelled)
setState({ key: spotKey, streets: [], error: e instanceof Error ? e.message : "Could not start the solve." });
}
})();
return () => {
cancelled = true;
};
}, [spotKey, stack, line, flop, pot, effStack]);
const last = streets.length - 1;
// Earlier streets are done by construction; keep their summaries.
const [done, setDone] = useState<Record<string, Street>>({});
const current = useStreet(streets[last]?.id ?? null, (s) => setDone((d) => ({ ...d, [s.id]: s })));
const streetData = (i: number): Street | null =>
done[streets[i]?.id] ?? (i === last ? current : null);
const choose = (si: number, depth: number, label: string) => {
setStreets((ss) => {
const next = ss.slice(0, si + 1);
next[si] = { ...next[si], path: [...next[si].path.slice(0, depth), label] };
return next;
});
};
const rewind = (si: number, depth: number) => {
setStreets((ss) => {
const next = ss.slice(0, si + 1);
next[si] = { ...next[si], path: next[si].path.slice(0, depth) };
return next;
});
};
// Where the line stands: the live node, or what the last action led to.
const lastStreet = streetData(last);
const lastPath = streets[last]?.path ?? [];
const nodeMap = useMemo(() => {
const m = new Map<string, NodeSummary>();
for (const n of lastStreet?.nodes ?? []) m.set(n.path.join("|"), n);
return m;
}, [lastStreet]);
const liveNode = lastStreet?.status === "done" ? nodeMap.get(lastPath.join("|")) : undefined;
const parentNode =
lastPath.length > 0 ? nodeMap.get(lastPath.slice(0, -1).join("|")) : undefined;
const lastNext = parentNode?.actions.find((a) => a.label === lastPath[lastPath.length - 1])?.next;
const boardNow = lastStreet?.board ? cardsOf(lastStreet.board) : flop;
const deal = async (card: string) => {
const s = streets[last];
setPicker(false);
setDealing(true);
try {
const r = await json<{ id: string }>(
await fetch(`${api()}/${s.id}/deal`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ path: s.path, card }),
}),
);
setStreets((ss) => [...ss, { id: r.id, path: [] }]);
} catch (e) {
setStartError(e instanceof Error ? e.message : "Could not deal that card.");
} finally {
setDealing(false);
}
};
const railRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = railRef.current;
if (el) el.scrollLeft = el.scrollWidth;
}, [streets, current?.status]);
const rail: ReactNode[] = [];
streets.forEach((s, si) => {
const data = streetData(si);
const board = data?.board ? cardsOf(data.board) : si === 0 ? flop : [];
rail.push(
<StreetCard
key={`street-${si}`}
name={STREET_NAME[si] ?? "Street"}
cards={si === 0 ? board : board.slice(-1)}
pot={data?.pot}
onClick={si === 0 ? onRepickFlop : () => rewind(si - 1, streets[si - 1].path.length)}
title={si === 0 ? "Re-pick the flop" : "Re-pick this card"}
/>,
);
if (!data || data.status !== "done") return;
const map = new Map((data.nodes ?? []).map((n) => [n.path.join("|"), n]));
for (let d = 0; d <= s.path.length; d++) {
const n = map.get(s.path.slice(0, d).join("|"));
if (!n) break;
const chosen = s.path[d];
rail.push(
<DecisionCard
key={`n-${si}-${d}`}
node={n}
pot={data.pot}
chosen={chosen}
live={chosen === undefined && si === last}
onPick={(label) => choose(si, d, label)}
onRewind={() => rewind(si, d)}
/>,
);
}
});
const solving =
dealing || (current && (current.status === "queued" || current.status === "running"));
if (solving) {
rail.push(
<div key="solving" className={`${RAIL_CARD} items-center justify-center border-border bg-card/40 text-center`}>
<Loader2 className="size-4 animate-spin text-muted-foreground" />
<span className="text-[11px] text-muted-foreground">
{current?.status === "running" ? `Solving… ${Math.round(current.elapsed ?? 0)}s` : "Queued…"}
</span>
</div>,
);
} else if (lastNext === "deal" && boardNow.length < 5) {
rail.push(
// ui-exception: the next-street card is a rail card like the preflop strip's FLOP card
<button
key="pick"
type="button"
onClick={() => setPicker(true)}
className={`${RAIL_CARD} items-center justify-center border-dashed border-foreground/40 bg-accent/30 text-center`}
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">
{STREET_NAME[streets.length] ?? "Card"}
</span>
<span className="text-xs text-muted-foreground">pick a card ↓</span>
</button>,
);
}
const endText =
lastNext === "fold"
? "Hand over: a fold ends it."
: lastNext === "allin"
? "All-in and called: no more decisions."
: lastNext === "showdown"
? "River closed: showdown."
: null;
return (
<div className="flex flex-col gap-4">
<RailRow lead={stripLead} scrollerRef={railRef}>
{stripPrefix}
{rail}
</RailRow>
{startError ? <p className="text-xs text-destructive">{startError}</p> : null}
{current?.status === "failed" || current?.status === "lost" ? (
<p className="text-xs text-destructive">
{current.error ?? "The solve stopped. Pick the card again to retry."}
</p>
) : null}
{endText ? (
<div className="rounded-xl border border-border bg-card/40 px-4 py-3 text-sm text-muted-foreground">
{endText}
</div>
) : null}
{solving && streets.length <= 1 ? (
<p className="text-xs text-muted-foreground">
Loading the blueprint's flop strategy for this line.
</p>
) : null}
{liveNode && streets[last] ? (
<NodePanel
key={`${streets[last].id}:${lastPath.join("|")}`}
id={streets[last].id}
path={lastPath}
summary={liveNode}
street={lastStreet}
streetName={STREET_NAME[last] ?? ""}
board={boardNow}
/>
) : null}
{picker ? (
<BottomSheet title={`Pick the ${(STREET_NAME[streets.length] ?? "card").toLowerCase()}`} onClose={() => setPicker(false)}>
<CardGridPicker value={[]} max={1} dead={boardNow} onChange={(next) => next[0] && deal(next[0])} />
<span className="pb-2 text-[11px] text-muted-foreground/70">
{streets.length >= 2
? "The river is solved exactly, hand by hand, from the ranges the turn reaches here. It takes about half a minute."
: "The turn is re-solved from the ranges the blueprint reaches here. It takes about half a minute."}
</span>
</BottomSheet>
) : null}
</div>
);
}
function StreetCard({
name,
cards,
pot,
onClick,
title,
}: {
name: string;
cards: string[];
pot?: number;
onClick: () => void;
title: string;
}) {
return (
// ui-exception: street card in the decision rail, matching the preflop strip's FLOP card
<button
type="button"
onClick={onClick}
title={title}
className={`${RAIL_CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">{name}</span>
<div className="mt-auto flex flex-wrap items-center gap-1">
{cards.map((c) => (
<MiniCard key={c} card={c} className="h-8 w-6 text-xl" />
))}
</div>
{pot !== undefined ? (
<span className="text-[11px] text-muted-foreground tabular-nums">pot {pot.toFixed(1)}bb</span>
) : null}
</button>
);
}
function DecisionCard({
node,
pot,
chosen,
live,
onPick,
onRewind,
}: {
node: NodeSummary;
/** The street's starting pot, for sizes as % of pot. */
pot?: number;
chosen?: string;
live: boolean;
onPick: (label: string) => void;
onRewind: () => void;
}) {
return (
// ui-exception: like the preflop rail, the card is "go back here" and
// holds its own option buttons, so it is a keyboard-operable div.
<div
role="button"
tabIndex={0}
onClick={onRewind}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onRewind();
}
}}
title={`Back to ${SEAT[node.player]}'s decision`}
className={`${RAIL_CARD} cursor-pointer ${live ? "border-foreground/50 bg-accent/50" : "border-border bg-card/40"}`}
>
<span className={`text-sm font-semibold ${live ? "text-foreground" : "text-muted-foreground"}`}>
{SEAT[node.player]}
</span>
<div className="flex flex-col">
{node.actions.map((a) => {
const isChosen = a.label === chosen;
const text = sizeLabel(a.label, node.path, pot);
const chips = display(a.label);
return (
// ui-exception: an option row inside a rail card, as on the preflop rail
<button
key={a.label}
type="button"
onClick={(e) => {
e.stopPropagation();
onPick(a.label);
}}
aria-pressed={isChosen || undefined}
title={text === chips ? undefined : chips}
className={`flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors ${
isChosen
? "bg-foreground/15 ring-1 ring-foreground/25"
: chosen !== undefined
? "opacity-45 hover:bg-accent hover:opacity-100"
: "hover:bg-accent"
}`}
>
<span className="flex min-w-0 items-center gap-1 truncate text-xs text-foreground">
<span className="size-2 shrink-0 rounded-[2px]" style={{ backgroundColor: colorOf(a.label) }} />
<span className={`truncate ${isChosen ? "font-semibold" : ""}`}>{text}</span>
</span>
<span className="shrink-0 text-[11px] font-semibold text-foreground tabular-nums">
{(a.freq * 100).toFixed(0)}%
</span>
</button>
);
})}
</div>
</div>
);
}
/** The acting range's sample as per-action columns, the preflop Explorer's layout. */
function breakdownOf(detail: NodeDetail, summary: NodeSummary, pot: number | undefined): BreakdownSection[] {
const labels = summary.actions.map((a) => a.label);
const hands = detail.hands.map((h) => {
const cards = cardsOf(h.combo);
return { h, cards, props: handProps(cardsToPloString(cards as [Card, Card, Card, Card])) };
});
return labels.map((label, i) => {
const rows: (BreakdownRow & { reach: number })[] = [];
for (const { h, cards, props } of hands) {
const freq = h.freqs[i] ?? 0;
if (freq <= 0.0005) continue;
const ev = h.evs ? h.evs[i] : null;
let bestOther: number | null = null;
if (h.evs) {
h.evs.forEach((e, j) => {
if (j !== i && (bestOther === null || e > bestOther)) bestOther = e;
});
}
rows.push({
key: h.combo,
cards,
freq,
evBb: ev,
evDiffBb: ev === null || bestOther === null ? null : ev - bestOther,
props,
reach: h.reach,
weight: freq * h.reach,
});
}
rows.sort(
(a, b) => (b.evBb ?? -Infinity) - (a.evBb ?? -Infinity) || b.freq - a.freq || b.reach - a.reach,
);
// Size as % of pot, with the chips alongside: "Bet 50% · 3bb".
const text = sizeLabel(label, summary.path, pot);
const chips = display(label);
const header = text === chips ? chips : `${text} · ${chips.split(" ")[1]}`;
return { key: label, label: header, color: colorOf(label), pct: summary.actions[i].freq * 100, rows };
});
}
function NodePanel({
id,
path,
summary,
street,
streetName,
board,
}: {
id: string;
path: string[];
summary: NodeSummary;
street: Street | null;
streetName: string;
board: string[];
}) {
const [detail, setDetail] = useState<NodeDetail | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
const qs = encodeURIComponent(path.join(","));
fetch(`${api()}/${id}/node?path=${qs}`)
.then((r) => json<NodeDetail>(r))
.then((d) => {
if (!cancelled) setDetail(d);
})
.catch((e: unknown) => {
if (!cancelled) setError(e instanceof Error ? e.message : "Could not load the hands.");
});
return () => {
cancelled = true;
};
}, [id, path]);
const sections = useMemo(() => (detail ? breakdownOf(detail, summary, street?.pot) : null), [detail, summary, street?.pot]);
return (
<div className="flex flex-col gap-3 rounded-xl border border-border bg-card/40 p-4">
<div className="flex flex-wrap items-baseline justify-between gap-2">
<h3 className="text-sm font-semibold text-foreground">
{SEAT[summary.player]} to act · {streetName}
{street?.pot !== undefined ? ` · pot ${street.pot.toFixed(1)}bb` : ""}
</h3>
</div>
{error ? <p className="text-xs text-destructive">{error}</p> : null}
{!detail && !error ? (
<div className="flex h-24 items-center justify-center">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div>
) : null}
{detail && sections ? (
<PloActionBreakdown sections={sections} board={board} sampleOf={detail.hands.length} />
) : null}
</div>
);
}
components/explorer/plo5-range-panel.tsx
"use client";
// PLO5 Explorer body. Pool % on the headers; the hand list is a top-by-EV
// slice of each action's HDV CSV (204k classes — never dumped whole).
import { useEffect, useMemo, useState, type ReactNode } from "react";
import { Loader2 } from "lucide-react";
import { MiniCard } from "@/components/trainer/cards";
import {
canonicalPlo5Hand,
encodePlo5RankFilter,
parsePlo5RankFilter,
} from "@/lib/plo5-ranges/canonical";
import {
canonicalPlo6Hand,
encodePlo6RankFilter,
parsePlo6RankFilter,
} from "@/lib/plo6-ranges/canonical";
import {
getPlo5HandStrategy,
getPlo5NodeList,
getPlo6HuHandStrategy,
getPlo6HuNodeList,
labelForAction,
sortActionsForDisplay,
type NodeAction,
type Plo5ActionList,
type Plo5HandStrategy,
type Plo5ListedHand,
} from "@/lib/solver/preflop";
import { colorActions, type PreflopActionItem } from "./preflop-strategy-grid";
import { ExplorerTabs } from "./explorer-tabs";
import { useExplorerUrl } from "./explorer-url";
import { PloRangeList } from "./plo-range-list";
import { Plo6BucketBars } from "./plo6-bucket-bars";
const LIST_PAGE = 200;
/** Seat-card aggregates from pool % (0–100), not per-hand weights. */
export function plo5ActionItems(actions: NodeAction[], stack: number): PreflopActionItem[] {
const colored = colorActions(sortActionsForDisplay(actions));
const denom = colored.reduce((s, { action }) => s + (action.poolPct ?? 0), 0) || 1;
return colored.map(({ action, color }) => ({
action,
label: labelForAction(action, stack),
color,
freq: (action.poolPct ?? 0) / denom,
combos: action.combos ?? 0,
}));
}
export function cardsOf(hand: string): string[] {
const compact = hand.replace(/[\s,]+/g, "");
const out: string[] = [];
for (let i = 0; i + 1 < compact.length; i += 2) {
out.push(compact[i].toUpperCase() + compact[i + 1].toLowerCase());
}
// High rank first (aces on the left), ties by suit.
return out.sort(
(a, b) => RANKS.indexOf(b[0]) - RANKS.indexOf(a[0]) || SUITS.indexOf(a[1]) - SUITS.indexOf(b[1]),
);
}
const RANKS = "23456789TJQKA";
const SUITS = "shdc";
export function HandCards({ hand }: { hand: string }) {
return (
<div className="flex items-center gap-[3px]">
{cardsOf(hand).map((card, i) => (
<MiniCard key={`${hand}-${i}`} card={card} className="h-[26px] w-5 text-base" />
))}
</div>
);
}
type HdvVariant = {
parseFilter: (q: string) => Record<string, number> | null;
encodeFilter: (f: Record<string, number>) => string;
canonical: (q: string) => string | null;
fetchList: (
stack: number,
history: string,
limit: number,
ranks?: string,
) => Promise<Plo5ActionList[]>;
fetchStrategy: (
stack: number,
history: string,
hand: string,
) => Promise<Plo5HandStrategy>;
placeholder: string;
help: ReactNode;
lookupError: string;
};
const PLO5_VARIANT: HdvVariant = {
parseFilter: parsePlo5RankFilter,
encodeFilter: encodePlo5RankFilter,
canonical: canonicalPlo5Hand,
fetchList: getPlo5NodeList,
fetchStrategy: getPlo5HandStrategy,
placeholder: "AK222 or AsAhKdKcQs",
help: (
<>
Filter by ranks (<span className="font-mono text-foreground">AK222</span>
) or look up a combo (
<span className="font-mono text-foreground">AsAhKdKcQs</span>
). Five ranks match that bag exactly; fewer ranks mean “at least these.”
</>
),
lookupError: "Use ranks (AK222) or five suited cards (AsAhKdKcQs).",
};
const PLO6HU_VARIANT: HdvVariant = {
parseFilter: parsePlo6RankFilter,
encodeFilter: encodePlo6RankFilter,
canonical: canonicalPlo6Hand,
fetchList: getPlo6HuNodeList,
fetchStrategy: getPlo6HuHandStrategy,
placeholder: "AAKKQJ or AsAhKdKcQsQh",
help: (
<>
Filter by ranks (<span className="font-mono text-foreground">AAKKQJ</span>
) or look up a six-card combo (
<span className="font-mono text-foreground">AsAhKdKcQsQh</span>
). Six ranks match that bag exactly; fewer ranks mean “at least these.”
</>
),
lookupError: "Use ranks (AAKKQJ) or six suited cards (AsAhKdKcQsQh).",
};
const HDV_BY_GAME = {
plo5: PLO5_VARIANT,
plo6hu: PLO6HU_VARIANT,
} as const;
/** One explorer for 4-, 5-, and 6-card Omaha. Buckets render when that game
* has a stored category tree; otherwise the Buckets tab says coming soon. */
export function PloExplorer({
game,
actions,
stack,
history,
}: {
game: "plo" | "plo5" | "plo6hu";
actions: NodeAction[];
stack: number;
history: string;
}) {
const variant = game === "plo" ? null : HDV_BY_GAME[game];
const colored = colorActions(sortActionsForDisplay(actions));
return (
<ExplorerTabs
buckets={
game === "plo6hu" ? (
<Plo6BucketBars history={history} stack={stack} actions={colored} />
) : undefined
}
explorer={
variant ? (
<HdvRangePanel actions={actions} stack={stack} history={history} variant={variant} />
) : (
<PloRangeList actions={actions} stack={stack} />
)
}
/>
);
}
function HdvRangePanel({
actions,
stack,
history,
variant,
}: {
actions: NodeAction[];
stack: number;
history: string;
variant: HdvVariant;
}) {
const colored = colorActions(sortActionsForDisplay(actions));
const denom = colored.reduce((s, { action }) => s + (action.poolPct ?? 0), 0) || 1;
// A rank filter is part of the shareable URL (?q=AK222); a single-hand
// lookup isn't, since it only runs on submit.
const url = useExplorerUrl();
const [query, setQuery] = useState(() => url.get("q") ?? "");
const [lookup, setLookup] = useState<Plo5HandStrategy | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [listed, setListed] = useState<Plo5ActionList[] | null>(null);
const [listLimit, setListLimit] = useState(LIST_PAGE);
const [listBusy, setListBusy] = useState(false);
const [listError, setListError] = useState<string | null>(null);
const rankKey = useMemo(() => {
const f = variant.parseFilter(query);
return f ? variant.encodeFilter(f) : "";
}, [query, variant]);
const [debouncedRanks, setDebouncedRanks] = useState(rankKey);
useEffect(() => {
const t = window.setTimeout(() => setDebouncedRanks(rankKey), 250);
return () => window.clearTimeout(t);
}, [rankKey]);
useEffect(() => {
url.set({ q: debouncedRanks || null });
}, [debouncedRanks, url]);
useEffect(() => {
let cancelled = false;
setListed(null);
setListLimit(LIST_PAGE);
setListError(null);
setListBusy(true);
variant.fetchList(stack, history, LIST_PAGE, debouncedRanks || undefined)
.then((rows) => {
if (!cancelled) setListed(rows);
})
.catch((err) => {
if (!cancelled) setListError(err instanceof Error ? err.message : "Could not load hands.");
})
.finally(() => {
if (!cancelled) setListBusy(false);
});
return () => {
cancelled = true;
};
}, [stack, history, debouncedRanks, variant]);
const loadMore = async () => {
const next = Math.min(listLimit + LIST_PAGE, 2000);
setListBusy(true);
setListError(null);
try {
setListed(await variant.fetchList(stack, history, next, debouncedRanks || undefined));
setListLimit(next);
} catch (err) {
setListError(err instanceof Error ? err.message : "Could not load more hands.");
} finally {
setListBusy(false);
}
};
const runLookup = async () => {
const hand = query.trim();
if (!hand) return;
if (!variant.canonical(hand)) {
setLookup(null);
if (variant.parseFilter(hand)) {
setError(null);
return;
}
setError(variant.lookupError);
return;
}
setBusy(true);
setError(null);
try {
setLookup(await variant.fetchStrategy(stack, history, hand));
} catch (err) {
setLookup(null);
setError(err instanceof Error ? err.message : "Lookup failed.");
} finally {
setBusy(false);
}
};
const queryBar = (
<>
<p className="text-xs text-muted-foreground">{variant.help}</p>
<form
className="flex flex-wrap items-center gap-2"
onSubmit={(e) => {
e.preventDefault();
void runLookup();
}}
>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={variant.placeholder}
spellCheck={false}
className="h-8 min-w-[180px] flex-1 rounded-md border border-border bg-background px-2.5 font-mono text-xs text-foreground"
/>
<button
type="submit"
disabled={busy || !query.trim()}
className="inline-flex h-8 items-center gap-1.5 rounded-md border border-border bg-card px-3 text-xs font-medium text-foreground hover:bg-accent disabled:opacity-50"
>
{busy ? <Loader2 className="size-3 animate-spin" /> : null}
Look up
</button>
</form>
{error ? <p className="text-xs text-destructive">{error}</p> : null}
</>
);
const rangeBody = (
<>
{lookup ? (
<div className="flex flex-col gap-2 rounded-xl border border-border bg-card/40 px-3 py-2.5">
<div className="flex flex-wrap items-center gap-2">
<HandCards hand={lookup.hdvHand} />
{lookup.isoMapped ? (
<span className="text-[11px] text-muted-foreground">
suit-mapped from {lookup.hand}
</span>
) : null}
</div>
<div className="flex flex-col">
{lookup.actions.map((a) => (
<div
key={a.action}
className="flex items-center justify-between gap-3 py-0.5 text-xs"
>
<span>{a.action.replace(/^Raise-([\d.]+)x$/, "Raise $1bb")}</span>
<span className="tabular-nums text-muted-foreground">
{(a.freq * 100).toFixed(1)}%
{a.ev_sb != null ? ` · ${(a.ev_sb / 2).toFixed(2)} bb` : ""}
</span>
</div>
))}
</div>
</div>
) : null}
{debouncedRanks ? (
<p className="text-xs text-muted-foreground">
Filtering ranks{" "}
<span className="font-mono text-foreground">{debouncedRanks}</span>
</p>
) : null}
{listError ? <p className="text-xs text-destructive">{listError}</p> : null}
<div className="grid gap-3 [grid-template-columns:repeat(auto-fit,minmax(280px,1fr))]">
{colored.map(({ action, color }) => {
const pct = ((action.poolPct ?? 0) / denom) * 100;
const block = listed?.find((a) => a.action === action.action);
return (
<HdvActionSection
key={action.action}
label={labelForAction(action, stack)}
color={color}
pct={pct}
rows={block?.listed ?? []}
total={block?.listedTotal ?? action.combos ?? 0}
busy={listBusy}
onMore={() => void loadMore()}
/>
);
})}
</div>
</>
);
return (
<div className="flex flex-col gap-4">
{queryBar}
{rangeBody}
</div>
);
}
/**
* One action's slice of a PLO5/PLO6 range: its pool share, then the hands
* that take it (top by EV) with each hand's frequency and EV. The Explorer
* lays these out side by side; the replayer's Ranges column tabs between them.
*/
/** Whole percents, but a sliver of a mix (0.3%) isn't shown as 0. */
function formatFreq(freq: number): string {
const pct = freq * 100;
return pct > 0 && pct < 0.95 ? pct.toFixed(1) : String(Math.round(pct));
}
export function HdvActionSection({
label,
color,
pct,
rows,
total,
busy,
onMore,
maxHeight = "max-h-[560px]",
}: {
label: string;
color: string;
/** Pool share of this action, 0–100. */
pct: number;
rows: Plo5ListedHand[];
/** Hands that take this action at all (rows is the top slice). */
total: number;
busy: boolean;
onMore?: () => void;
/** Height cap on the hand list (Tailwind class). */
maxHeight?: string;
}) {
const hasEv = rows.some((r) => r.ev != null);
const cols = hasEv
? "grid-cols-[minmax(0,1fr)_44px_52px]"
: "grid-cols-[minmax(0,1fr)_44px]";
return (
<section className="flex flex-col overflow-hidden rounded-xl border border-border bg-card/40">
<div
className="flex flex-col gap-1.5 px-3 py-2.5"
style={{ backgroundColor: `${color}26` }}
>
<div className="flex items-baseline justify-between gap-2">
<span className="text-sm font-medium text-foreground">{label}</span>
<span className="text-[11px] tabular-nums text-muted-foreground">
{total.toLocaleString("en-US")} {total === 1 ? "hand" : "hands"}
</span>
</div>
<div className="flex items-center gap-2">
<span className="text-base font-semibold tabular-nums text-foreground">
{pct.toFixed(1)}%
</span>
<div className="flex h-1.5 flex-1 overflow-hidden rounded-full bg-foreground/10">
<div style={{ width: `${pct}%`, backgroundColor: color }} />
</div>
</div>
</div>
<div className={`flex ${maxHeight} flex-col overflow-y-auto px-2 pb-2`}>
<div
className={`sticky top-0 z-10 grid items-center gap-2 bg-card px-1 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground/70 ${cols}`}
>
<span>Hand</span>
<span className="text-right">Freq %</span>
{hasEv ? <span className="text-right">EV bb</span> : null}
</div>
{busy && rows.length === 0 ? (
<div className="flex items-center gap-2 px-1 py-6 text-xs text-muted-foreground">
<Loader2 className="size-3 animate-spin" /> Loading hands…
</div>
) : rows.length === 0 ? (
<p className="py-6 text-center text-xs text-muted-foreground">
No hands listed for this action.
</p>
) : (
rows.map((r) => (
<div
key={r.hand}
className={`grid items-center gap-2 rounded px-1 py-[3px] hover:bg-accent/40 ${cols}`}
style={{ contentVisibility: "auto", containIntrinsicSize: "auto 30px" }}
>
<HandCards hand={r.hand} />
<span className="text-right text-[11px] tabular-nums text-foreground">
{formatFreq(r.freq)}
</span>
{hasEv ? (
<span className="text-right text-[11px] tabular-nums text-foreground">
{r.ev == null ? "—" : (r.ev / 2).toFixed(2)}
</span>
) : null}
</div>
))
)}
{onMore && rows.length > 0 && rows.length < total ? (
<button
type="button"
onClick={onMore}
disabled={busy}
className="mx-1 my-1 self-start rounded-full border border-border px-3 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:opacity-50"
>
{busy
? "Loading…"
: `Show more (${rows.length.toLocaleString("en-US")} of ${total.toLocaleString("en-US")})`}
</button>
) : null}
</div>
</section>
);
}
components/explorer/plo6-bucket-bars.tsx
"use client";
// Suit-bucket mixes for the PLO6 HU explorer. Frequencies come from the
// stored Hydra category tree, not a live scan of the 1.8M-hand range.
import { rangesUrl } from "@/lib/explorer/host";
import { useEffect, useState } from "react";
import { ChevronRight, Loader2 } from "lucide-react";
import type { NodeAction } from "@/lib/solver/preflop";
import { notifyPlanRequired } from "@/lib/access/plan-required";
type BucketNode = {
label: string;
weight_pct: number;
actions: Record<string, number>;
children?: BucketNode[];
};
type HeuristicsResponse = {
nodes?: { history: string; tree: BucketNode[] }[];
};
export function Plo6BucketBars({
history,
stack,
actions,
}: {
history: string;
stack: number;
actions: { action: NodeAction; color: string }[];
}) {
const [tree, setTree] = useState<BucketNode[] | null>(null);
const [open, setOpen] = useState<Set<string>>(new Set());
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let cancelled = false;
setTree(null);
setError(null);
setOpen(new Set());
const params = new URLSearchParams({
stack: String(stack),
history,
detail: "full",
minWeight: "0.5",
});
fetch(`${rangesUrl("plo6hu/heuristics")}?${params}`)
.then(async (res) => {
notifyPlanRequired(res.status);
if (!res.ok) throw new Error(`buckets ${res.status}`);
return (await res.json()) as HeuristicsResponse;
})
.then((data) => {
if (cancelled) return;
setTree(data.nodes?.[0]?.tree ?? []);
})
.catch(() => {
if (!cancelled) setError("Bucket frequencies are not stored for this node.");
});
return () => {
cancelled = true;
};
}, [history, stack]);
if (error) return null;
if (!tree) {
return (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="size-3 animate-spin" /> Loading buckets…
</div>
);
}
if (tree.length === 0) return null;
const toggle = (key: string) => {
setOpen((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
};
return (
<div className="flex flex-col gap-1">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1 px-1 pb-1 text-[10px] text-muted-foreground">
{actions.map(({ action, color }) => (
<span key={action.action} className="inline-flex items-center gap-1">
<span className="size-2 rounded-full" style={{ backgroundColor: color }} />
{action.action.replace(/^Raise-([\d.]+)x$/, "Raise $1bb")}
</span>
))}
<span>Top row is share of the range. Nested rows are share of the group above.</span>
</div>
{tree.map((node) => (
<BucketRow
key={node.label}
node={node}
path={node.label}
depth={0}
open={open}
onToggle={toggle}
actions={actions}
/>
))}
</div>
);
}
function BucketRow({
node,
path,
depth,
open,
onToggle,
actions,
}: {
node: BucketNode;
path: string;
depth: number;
open: Set<string>;
onToggle: (key: string) => void;
actions: { action: NodeAction; color: string }[];
}) {
const kids = node.children?.filter((child) => child.weight_pct > 0) ?? [];
const expanded = open.has(path);
const segments = actions
.map(({ action, color }) => ({
key: action.action,
label: action.action.replace(/^Raise-([\d.]+)x$/, "Raise $1bb"),
pct: node.actions[action.action] ?? 0,
color,
}))
.filter((segment) => segment.pct > 0);
return (
<div>
<button
type="button"
onClick={() => kids.length > 0 && onToggle(path)}
className="grid w-full grid-cols-[16px_minmax(0,1.2fr)_48px_minmax(140px,1fr)] items-center gap-2 rounded px-1 py-1 text-left hover:bg-accent/40"
style={{ paddingLeft: 4 + depth * 14 }}
>
<ChevronRight
className={`size-3.5 text-muted-foreground transition-transform ${
kids.length === 0 ? "invisible" : expanded ? "rotate-90" : ""
}`}
/>
<span className="truncate text-xs text-foreground">{node.label}</span>
<span className="text-right text-[11px] tabular-nums text-muted-foreground">
{node.weight_pct.toFixed(1)}%
</span>
<span className="flex min-w-0 flex-col gap-0.5">
<span className="flex h-2 overflow-hidden rounded-full bg-foreground/10">
{segments.map((segment) => (
<span
key={segment.key}
style={{ width: `${segment.pct}%`, backgroundColor: segment.color }}
/>
))}
</span>
<span className="truncate text-[10px] tabular-nums text-muted-foreground">
{segments.map((segment) => `${segment.label} ${segment.pct.toFixed(0)}`).join(" · ")}
</span>
</span>
</button>
{expanded
? kids.map((child) => (
<BucketRow
key={`${path}/${child.label}`}
node={child}
path={`${path}/${child.label}`}
depth={depth + 1}
open={open}
onToggle={onToggle}
actions={actions}
/>
))
: null}
</div>
);
}
components/explorer/postflop-hand-summary.tsx
"use client";
// GTO-Wizard-style hand summary for a postflop decision node: one row per
// combo the acting player can hold — the combo (suit-colored), a mini strategy
// bar (its action split), its EV in bb when the node carries EV (solve roots
// do; interior nodes don't), and its share of the reach-weighted range.
// Sorted by EV when present, else by range share.
import { useMemo } from "react";
import { ACTION_COLORS } from "@/components/solver/strategy-grid";
import type { SolverActionInfo, SolverHandStrategy } from "@/lib/solver/types";
import type { ComboWeights } from "@/lib/explorer/subgame";
import { MiniCard } from "@/components/trainer/cards";
function ComboLabel({ combo }: { combo: string }) {
const cards = [combo.slice(0, 2), combo.slice(2, 4)];
return (
<span className="inline-flex gap-0.5 text-xs font-semibold tabular-nums">
{cards.map((c, i) => (
<MiniCard key={i} card={c} className="h-5 w-4 text-[13px]" />
))}
</span>
);
}
interface Row {
combo: string;
freqs: number[];
weight: number;
ev?: number;
}
export function PostflopHandSummary({
actions,
hands,
reach,
evByCombo,
}: {
actions: SolverActionInfo[];
hands: SolverHandStrategy[];
/** Reach-weighted range of the acting player (drops folded-out combos). */
reach: ComboWeights | null;
/** Per-combo EV in bb, when this node is a solve root with `dump_ev`. */
evByCombo?: Map<string, number> | null;
}) {
const { rows, totalWeight, hasEv } = useMemo(() => {
const out: Row[] = [];
let totalWeight = 0;
let hasEv = false;
for (const hand of hands) {
const weight = reach ? (reach.get(hand.combo) ?? 0) : 1;
if (weight <= 0.0005) continue;
const ev = evByCombo?.get(hand.combo);
if (ev !== undefined) hasEv = true;
totalWeight += weight;
out.push({ combo: hand.combo, freqs: hand.freqs, weight, ev });
}
out.sort((a, b) => {
if (a.ev !== undefined && b.ev !== undefined) return b.ev - a.ev || b.weight - a.weight;
if (a.ev !== undefined) return -1;
if (b.ev !== undefined) return 1;
return b.weight - a.weight;
});
return { rows: out, totalWeight, hasEv };
}, [hands, reach, evByCombo]);
const cols = hasEv ? "52px minmax(0,1fr) 58px 56px" : "52px minmax(0,1fr) 62px";
return (
<div className="flex flex-col gap-2">
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
Hand summary
</span>
<div
className="grid gap-2 px-1 text-[10px] uppercase tracking-wide text-muted-foreground/70"
style={{ gridTemplateColumns: cols }}
>
<span>Hand</span>
<span>Strategy</span>
{hasEv ? <span className="text-right">EV bb</span> : null}
<span className="text-right">Range</span>
</div>
<div className="flex max-h-[420px] flex-col overflow-y-auto pr-0.5">
{rows.map((r) => {
const rangePct = totalWeight > 0 ? (r.weight / totalWeight) * 100 : 0;
return (
<div
key={r.combo}
className="grid items-center gap-2 rounded px-1 py-1 hover:bg-accent/30"
style={{ gridTemplateColumns: cols }}
>
<ComboLabel combo={r.combo} />
<div className="flex h-2 overflow-hidden rounded-full bg-white/[0.06]">
{r.freqs.map((f, a) =>
f <= 0.001 ? null : (
<div
key={a}
style={{ flexGrow: f, backgroundColor: ACTION_COLORS[actions[a].label] }}
/>
),
)}
</div>
{hasEv ? (
<span
className={`text-right text-[11px] tabular-nums ${
r.ev === undefined
? "text-muted-foreground/40"
: r.ev >= 0
? "text-emerald-400"
: "text-rose-400"
}`}
>
{r.ev === undefined ? "—" : `${r.ev >= 0 ? "+" : ""}${r.ev.toFixed(2)}`}
</span>
) : null}
<span className="text-right text-[11px] text-muted-foreground tabular-nums">
{rangePct.toFixed(1)}%
</span>
</div>
);
})}
{rows.length === 0 ? (
<p className="px-1 py-3 text-xs text-muted-foreground/70">No hands reach this node.</p>
) : null}
</div>
</div>
);
}
components/explorer/preflop-browser.tsx
"use client";
// Multiway preflop solution browser — the GTO-Wizard "Study" experience over
// our precomputed NLHE ranges (`/api/ranges/nl/v2`). The user picks a stack and
// walks the full 6-max tree one seat at a time; each acting seat's 13×13
// strategy renders with an aggregate action bar and a hand summary.
//
// The walk follows the dataset: after each action we advance to the next live
// seat clockwise and ask the dataset for its node. When the dataset has no node
// (404), the betting round has closed. Seats further round the table aren't
// dead space: each one shows its own actions greyed out (read from the
// fold-through node), and picking one skips there, folding everyone in between
// — so reaching a BTN-vs-BB spot is one click, not four folds.
//
// A heads-up close flows straight into
// postflop with no separate setup screen: the bar compacts to the navigator's
// scrolling shape, a FLOP card appears, a bottom drawer picks the three cards
// (same UI as picking a turn in the viewer), and the solve starts on its own —
// the acting card renders as a loading placeholder until the tree is ready.
import { useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from "react";
import { Loader2 } from "lucide-react";
import {
assignOopIp,
clampWeights,
formatBb,
getIcmTables,
getManifestForGame,
getNodeForGameOrNull,
getNodeForGameOrNullCached,
SEAT_ORDER,
type ExplorerGame,
lastPreflopAggressor,
nextActorAfter,
parseHistory,
ICM_ANTE_PER_SEAT_BB,
isIcmGame,
PLAY_ORDER,
raiseContextAt,
raiseSizesFor,
type IcmTable,
NLMTT8_ANTE_BB,
PLO5_ANTE_BB,
PLO6HU_ANTE_BB,
rootHistory,
type NodeAction,
type NodeResponse,
type Position,
type SeatState,
} from "@/lib/solver/preflop";
import { fullRange, type RangeWeights } from "@/lib/solver/range-model";
import {
PreflopStrategyGrid,
preflopActionItems,
type PreflopActionItem,
} from "./preflop-strategy-grid";
import { SolutionSelectorCard } from "./solution-selector";
import { PreflopHandSummary } from "./hand-summary";
import { defaultTable, groupForGame, gameForGroup } from "@/lib/explorer/solution-catalog";
import { ExplorerTabs } from "./explorer-tabs";
import { ploActionItems } from "./plo-range-list";
import { PloExplorer, plo5ActionItems } from "./plo5-range-panel";
import { Builder, type BuilderSeed } from "./builder";
import { BottomSheet } from "./bottom-sheet";
import { CardGridPicker } from "./card-picker";
import type { CustomSolutionBundle } from "@/lib/explorer/types";
import { MiniCard } from "@/components/trainer/cards";
import { PLO4HU_POSTFLOP_STACKS } from "@/lib/explorer/plo4hu-postflop-stacks";
import { Plo4HuPostflop } from "./plo4hu-postflop";
import { RailRow } from "./rail-row";
import { useExplorerUrl } from "./explorer-url";
import { explorerHost } from "@/lib/explorer/host";
import { buttonVariants } from "@/components/ui/button";
import {
parseAction,
parseGame,
parseLine,
parseStack,
parseTable,
} from "@/lib/explorer/share-url";
function CardText({ card }: { card: string }) {
return <MiniCard card={card} className="h-8 w-6 text-xl" />;
}
interface EndState {
/** "won" = folded to one player; "flop" = ≥2 players see a flop. */
reason: "won" | "flop";
survivors: Position[];
oop?: Position;
ip?: Position;
potBb: number;
effStackBb: number;
/** OOP called the last preflop raise rather than making it — so OOP has no
* donk range on the flop and the solve can prune that lead (see Builder). */
oopIsPreflopCaller?: boolean;
}
function endFromWalk(
walk: { seats: Record<Position, SeatState>; pot: number },
history: string,
order: Position[] = PLAY_ORDER,
): EndState {
const seats = walk.seats;
const survivors = order.filter((p) => !seats[p].folded);
const potBb = walk.pot;
const effStackBb = survivors.length
? Math.min(...survivors.map((p) => seats[p].remaining))
: 0;
if (survivors.length <= 1) return { reason: "won", survivors, potBb, effStackBb };
const out: EndState = { reason: "flop", survivors, potBb, effStackBb };
if (survivors.length === 2) {
const { oop, ip } = assignOopIp(survivors[0], survivors[1]);
out.oop = oop;
out.ip = ip;
const aggressor = lastPreflopAggressor(history, order);
out.oopIsPreflopCaller = aggressor !== null && aggressor !== oop;
}
return out;
}
export function PreflopBrowser({
onSaved,
game: lockedGame,
}: {
/** Fired after a custom solution is saved from the inline solve panel, so the
* page can refresh its saved-solutions library. */
onSaved?: (bundle: CustomSolutionBundle) => void;
/** Keep the walk on this dataset. Stack changes inside it still apply. */
game?: ExplorerGame;
}) {
// The view opens where the URL points (a shared link), and every change is
// written back, so the address bar is always a link to this exact spot.
const url = useExplorerUrl();
const [boot] = useState(() => {
const g = lockedGame ?? parseGame(url.get("game")) ?? "nl";
const line = parseLine(url.get("line"), g);
return {
game: g,
stack: parseStack(url.get("stack")) ?? 100,
// ICM sets: the stack table at that depth.
table: parseTable(url.get("table")),
history: line ?? rootHistory(g),
// The round-closing action only means something on a walked line.
close: line ? parseAction(url.get("close")) : null,
};
});
// A linked line past the root needs its seats' continue ranges (and any
// closing action) rebuilt from the dataset before the flop solve can seed.
const [restoring, setRestoring] = useState(
() => boot.history !== rootHistory(boot.game) || boot.close !== null,
);
const [stack, setStack] = useState(boot.stack);
const [stacks, setStacks] = useState<number[]>([boot.stack]);
// ICM sets: the stack table picked at this depth (a scenario id). The catalog
// resolves it, so a missing or stale id falls back to the depth's first table.
const [tablePick, setTablePick] = useState<string | null>(boot.table);
const [history, setHistory] = useState(boot.history);
const [node, setNode] = useState<NodeResponse | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [fetchedEnd, setFetchedEnd] = useState<EndState | null>(null);
const [selectorOpen, setSelectorOpen] = useState(false);
// Once a postflop solve is showing, the seat strip moves into the postflop
// navigator (as its leading cards) so the whole line is one continuous bar;
// we stop rendering the standalone strip here.
const [viewerActive, setViewerActive] = useState(false);
// Which dataset the browser walks. PLO renders a hand-class list instead of
// the 169-cell grid, and the postflop solve flow is NL-only.
const [game, setGame] = useState<ExplorerGame>(boot.game);
const order = SEAT_ORDER[game];
const icm = isIcmGame(game);
const scenario = icm ? (defaultTable(groupForGame(game), stack, tablePick)?.scenario ?? null) : null;
// The ICM tables' seat stacks and payouts, from the ranges discovery.
const [icmTables, setIcmTables] = useState<IcmTable[]>([]);
const icmTable = icm ? (icmTables.find((t) => t.scenario === scenario) ?? null) : null;
// The flop being assembled in the picker drawer (0–3 cards). At 3 the solve
// starts on its own — there is no setup form in this flow.
const [flop, setFlop] = useState<string[]>([]);
const [pickerOpen, setPickerOpen] = useState(false);
// The postflop solve's lifecycle as seen from the strip: the acting card is
// a loading placeholder while "running"; "failed" (error/cancel) turns it
// into a re-pick affordance. Distinguished from success via solvedRef,
// because the solved and running callbacks land in the same commit.
const [postflopRun, setPostflopRun] = useState<"idle" | "running" | "failed">("idle");
const solvedRef = useRef(false);
// A skip-ahead whose action closed the round: the fold-through history has to
// land in `history` (so the strip shows the folds), but the fetch effect that
// history change fires would find a live node there and undo the close. Set
// in the same commit as the history, it tells that effect to derive the end
// state instead of fetching. See `advanceFrom`.
const [pendingClose, setPendingClose] = useState<{
history: string;
action: NodeAction;
} | null>(null);
useEffect(() => {
let cancelled = false;
getManifestForGame(game)
.then((m) => {
if (cancelled) return;
setStacks(m.stacks);
setStack((s) => (m.stacks.includes(s) ? s : (m.stacks[0] ?? s)));
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [game]);
useEffect(() => {
if (!isIcmGame(game)) return;
let cancelled = false;
getIcmTables(game)
.then((t) => {
if (!cancelled) setIcmTables(t);
})
.catch(() => {});
return () => {
cancelled = true;
};
}, [game]);
// ICM tables: every seat posts a 0.125bb ante (1bb in the pot) and starts
// from its own stack; raises are priced from the feed's sizes, since the
// `Open` / `3B` tokens don't say how big they are.
const seatStacks = useMemo(() => {
if (!icmTable) return undefined;
const out: Partial<Record<Position, number>> = {};
for (const [p, bb] of Object.entries(icmTable.stacksBb) as [Position, number][]) {
out[p] = Math.max(0, bb - ICM_ANTE_PER_SEAT_BB);
}
return out;
}, [icmTable]);
const sizes = icm ? raiseSizesFor(game, scenario) : undefined;
// The sizes record grows as nodes load; its size re-runs the walks below.
const sizesSeen = sizes ? Object.keys(sizes).length : 0;
const walkAt = (h: string) => parseHistory(h, stack, order, anteBb, sizes, seatStacks);
const anteBb =
game === "plo5"
? PLO5_ANTE_BB
: game === "plo6hu"
? PLO6HU_ANTE_BB
: game === "nlmtt8"
? NLMTT8_ANTE_BB
: icm
? ICM_ANTE_PER_SEAT_BB * order.length
: 0;
const walk = useMemo(
() => walkAt(history),
// `walkAt` reads sizes/seatStacks; `sizesSeen` stands in for the record.
// eslint-disable-next-line react-hooks/exhaustive-deps
[history, stack, order, anteBb, seatStacks, sizesSeen, scenario],
);
// A skip-ahead's closing action isn't in `history` (the string stops at the
// seat that acted), so the end state it produces is derived here rather than
// fetched — the dataset would still answer with a live node at that history.
const closedEnd = useMemo(() => {
if (!pendingClose || pendingClose.history !== history) return null;
const seat = history.split("_").pop() as Position;
const w = walkAt(history);
const seats = {
...w.seats,
[seat]: { ...w.seats[seat], folded: pendingClose.action.kind === "fold" },
};
return endFromWalk(
{ seats, pot: w.pot },
`${history}_${pendingClose.action.action}`,
order,
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [pendingClose, history, stack, order, anteBb, seatStacks, sizesSeen, scenario]);
const end = closedEnd ?? fetchedEnd;
// Fetch the decision at the current history. A 404 means the betting round has
// closed on this line → derive the end state from who's still in.
useEffect(() => {
let cancelled = false;
// A skip-ahead already closed the round at this history (`closedEnd`) — the
// dataset has a live node there, so asking would undo the close.
if (closedEnd) return;
// A linked closed line: wait for the restore to set the close, rather than
// flashing the live node that sits at this history.
if (restoring && boot.close) return;
// An ICM set waits for a depth it has (the manifest corrects the stack).
if (icm && !scenario) return;
(async () => {
setLoading(true);
setError(null);
// Clear a stale end state up front: after a rewind out of a closed line
// the old `end` would otherwise keep the flop-drawer flow alive (and
// flash the picker open) until this fetch lands. A line closed by
// `advance` doesn't change the history, so it never hits this path.
setFetchedEnd(null);
try {
const n = await getNodeForGameOrNull(game, stack, history, scenario);
if (cancelled) return;
if (n) {
setNode(n);
setFetchedEnd(null);
} else {
setNode(null);
setFetchedEnd(
endFromWalk(walkAt(history), history, order),
);
}
} catch (err) {
if (!cancelled) {
setNode(null);
setError(err instanceof Error ? err.message : "No range here.");
}
} finally {
if (!cancelled) setLoading(false);
}
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [game, stack, scenario, history, order, anteBb, closedEnd, restoring, boot.close]);
// Rebuild a linked line: re-apply its closing action.
// A link to a stack or line the dataset no longer has falls back to the root.
useEffect(() => {
if (!restoring) return;
let cancelled = false;
(async () => {
const g = boot.game;
const fallback = () => {
setHistory(rootHistory(g));
setPendingClose(null);
};
try {
const m = await getManifestForGame(g);
if (!m.stacks.includes(boot.stack)) {
if (!cancelled) fallback();
return;
}
// The seats' continue ranges come from the line's past nodes (see
// `captured`), so only the closing action needs resolving here.
let close: { history: string; action: NodeAction } | null = null;
if (boot.close) {
const bootScenario = isIcmGame(g)
? (defaultTable(groupForGame(g), boot.stack, boot.table)?.scenario ?? null)
: null;
const n = await getNodeForGameOrNullCached(g, boot.stack, boot.history, bootScenario);
const a = n?.actions.find((x) => x.action === boot.close) ?? null;
if (a) close = { history: boot.history, action: a };
}
if (cancelled) return;
setPendingClose(close);
} catch {
if (!cancelled) fallback();
} finally {
if (!cancelled) setRestoring(false);
}
})();
return () => {
cancelled = true;
};
// Runs once for the linked view; `boot` never changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// Mirror the walk into the URL.
const closeAction =
pendingClose && pendingClose.history === history ? pendingClose.action.action : null;
useEffect(() => {
if (restoring) return;
url.set({
game,
stack: String(stack),
table: scenario,
line: history === rootHistory(game) ? null : history,
close: closeAction,
});
}, [url, restoring, game, stack, scenario, history, closeAction]);
/** Switch dataset and/or stack. History always restarts at this dataset's
* first actor — a leftover UTG string on the PLO5 LJ ring crashes the walk. */
const applyWalk = (nextGame: ExplorerGame, nextStack: number, nextTable: string | null = null) => {
// Filters and the open tab belong to the dataset being left.
if (nextGame !== game) url.set({ tab: null, f: null, q: null, s: null });
if (nextGame !== game) setIcmTables([]);
setGame(nextGame);
setStack(nextStack);
setTablePick(nextTable);
setHistory(rootHistory(nextGame));
setPendingClose(null);
setFetchedEnd(null);
setNode(null);
setError(null);
setViewerActive(false);
setFlop([]);
};
const changeGame = (next: ExplorerGame) => {
if (next === game) return;
applyWalk(next, stack);
};
const changeStack = (next: number) => {
applyWalk(game, next);
};
const actor = end ? null : walk.hero;
// Take `action` for `seat` at `base` (a history ending in that seat) and
// advance to the next live seat clockwise, capturing the seat's continue
// range; the effect then asks the dataset for the next node (or detects
// close). `base` is the current history for the acting card, and a
// fold-through history for a skip-ahead.
const advanceFrom = (base: string, action: NodeAction) => {
setViewerActive(false);
setPendingClose(null);
setError(null);
const next = nextActorAfter(base, action.action, stack, order);
if (!next) {
// This action closed the round. A history string stops at the seat that
// acts, so the action itself can't live there — `closedEnd` derives the
// end state from this instead. On a skip-ahead the folds still have to
// land in `history`.
setPendingClose({ history: base, action });
if (base !== history) setHistory(base);
return;
}
setHistory(`${base}_${action.action}_${next}`);
};
const advance = (action: NodeAction) => {
if (!node || actor == null) return;
advanceFrom(history, action);
};
// Rewind the line to one of its past decisions: `base` is the history at
// that decision (a prefix of the line, ending in the seat that acted there).
// Also fired from inside the postflop navigator, whose leading cards are
// this same rail.
const rewindTo = (base: string) => {
setViewerActive(false);
setPendingClose(null);
setHistory(base);
setError(null);
};
/** A node's action rows; `at` is the history the node sits at (its actor's
* spot prices the ICM raises as pot percentages). */
const itemsFor = (n: NodeResponse | null | undefined, at: string) => {
if (!n) return [];
if (icm) return preflopActionItems(n.actions, stack, raiseContextAt(walkAt(at)));
if (game === "nl" || game === "nlmtt8") return preflopActionItems(n.actions, stack);
if (game === "plo5" || game === "plo6hu") return plo5ActionItems(n.actions, stack);
return ploActionItems(n.actions, stack);
};
// While the next node loads, `node` still holds the previous decision —
// its rows must not appear (or be clickable) on the new actor's card.
const items = loading ? [] : itemsFor(node, history);
// The line so far, one entry per decision taken: the history at that
// decision (ending in the seat that acted) and the action chosen there. A
// round-closing action isn't in `history`, so it's appended from the close.
const decisions = useMemo(() => {
const tokens = history.split("_");
const out: { base: string; seat: Position; chosen: string }[] = [];
for (let i = 0; i + 1 < tokens.length; i += 2) {
out.push({
base: tokens.slice(0, i + 1).join("_"),
seat: tokens[i] as Position,
chosen: tokens[i + 1],
});
}
if (closeAction) {
out.push({ base: history, seat: tokens[tokens.length - 1] as Position, chosen: closeAction });
}
return out;
}, [history, closeAction]);
// Each past decision's node, so its card can list every option with the
// chosen one highlighted (GTO Wizard's rail) and seed the postflop ranges.
// Node reads are memoized, so walking back and forth doesn't re-fetch.
const pastKey = `${game}:${scenario}:${stack}:${decisions.map((d) => d.base).join("|")}`;
const [pastNodes, setPastNodes] = useState<{ key: string; nodes: (NodeResponse | null)[] }>({
key: "",
nodes: [],
});
useEffect(() => {
let cancelled = false;
if (decisions.length === 0) return;
Promise.all(
decisions.map((d) =>
getNodeForGameOrNullCached(game, stack, d.base, scenario).catch(() => null),
),
).then((nodes) => {
if (!cancelled) setPastNodes({ key: pastKey, nodes });
});
return () => {
cancelled = true;
};
}, [decisions, pastKey, game, stack, scenario]);
const readyPastNodes = pastNodes.key === pastKey ? pastNodes.nodes : null;
// Each seat's continue range on this line: the weights of the last
// non-fold action it took. Derived from the line itself, so a rewind or an
// opened link can never leave a stale range behind. Seeds the postflop solve.
const captured = useMemo(() => {
const out: Partial<Record<Position, RangeWeights>> = {};
if (!readyPastNodes) return null;
decisions.forEach((d, i) => {
const a = readyPastNodes[i]?.actions.find((x) => x.action === d.chosen);
if (a && a.kind !== "fold") out[d.seat] = clampWeights(a.weights);
});
return out;
}, [decisions, readyPastNodes]);
// Skip-ahead: every seat that hasn't acted yet on this line can be acted for
// directly — folding the actor and everyone between them and that seat. The
// value is the fold-through history ending at that seat, which is both what
// we fetch its (greyed-out) actions from and the base we advance from.
const skipTargets = useMemo(() => {
const out: Partial<Record<Position, string>> = {};
if (!node || actor == null) return out;
const actorIdx = order.indexOf(actor);
if (actorIdx === -1) return out;
const parts = [history, "Fold"];
for (let i = 1; i < order.length; i++) {
const p = order[(actorIdx + i) % order.length];
const seat = walk.seats[p];
if (seat.folded) continue;
// Wrapped around to a seat that already acted — a second orbit isn't
// reachable by folding, so the skip range stops here.
if (seat.action !== null) break;
out[p] = [...parts, p].join("_");
parts.push(p, "Fold");
}
return out;
}, [node, actor, order, history, walk]);
// Prefetch each skip target's node so its actions render in the strip. The
// result is stamped with the target set it belongs to, so a stale batch is
// ignored rather than cleared (no extra render on every step).
const skipKey = `${game}:${scenario}:${stack}:${Object.values(skipTargets).join("|")}`;
const [skipNodes, setSkipNodes] = useState<{
key: string;
nodes: Partial<Record<Position, NodeResponse | null>>;
}>({ key: "", nodes: {} });
useEffect(() => {
let cancelled = false;
const entries = Object.entries(skipTargets) as [Position, string][];
if (entries.length === 0) return;
Promise.all(
entries.map(async ([p, h]) => {
const n = await getNodeForGameOrNullCached(game, stack, h, scenario).catch(() => null);
return [p, n] as const;
}),
).then((pairs) => {
if (!cancelled) setSkipNodes({ key: skipKey, nodes: Object.fromEntries(pairs) });
});
return () => {
cancelled = true;
};
}, [skipTargets, skipKey, game, stack, scenario]);
const readySkipNodes = skipNodes.key === skipKey ? skipNodes.nodes : null;
// The rail, GTO Wizard style: one card per decision already taken on the
// line (every option listed, the chosen one highlighted; click the card to
// go back to that decision, or another option to branch from it), then the
// acting seat, then the seats still to act this orbit (greyed — picking one
// folds everyone in between). Rendered standalone and as the leading cards
// of the postflop navigator, so the whole hand reads as one bar.
const renderRail = () => {
const cards: ReactNode[] = decisions.map((d, i) => {
const at = walkAt(d.base);
return (
<PastDecisionCard
key={`past:${i}`}
position={d.seat}
isDealer={at.seats[d.seat]?.isDealer ?? false}
remaining={at.seats[d.seat]?.remaining ?? 0}
pot={at.pot}
chosen={d.chosen}
items={readyPastNodes ? itemsFor(readyPastNodes[i], d.base) : undefined}
onRewind={() => rewindTo(d.base)}
onPick={(a) => {
if (a.action === d.chosen) rewindTo(d.base);
else advanceFrom(d.base, a);
}}
/>
);
});
if (actor != null) {
cards.push(
<SeatStripCard
key={`actor:${decisions.length}`}
position={actor}
seat={walk.seats[actor]}
isActor
items={items}
pot={walk.pot}
loading={loading}
onAdvance={advance}
cardRef={actorCardRef}
/>,
);
for (const [p, skipHistory] of Object.entries(skipTargets) as [Position, string][]) {
cards.push(
<SeatStripCard
key={`skip:${p}`}
position={p}
seat={walk.seats[p]}
isActor={false}
skipItems={readySkipNodes ? itemsFor(readySkipNodes[p], skipHistory) : undefined}
skipLoading={!readySkipNodes}
pot={walk.pot}
loading={loading}
onAdvance={advance}
onSkip={(a) => advanceFrom(skipHistory, a)}
/>,
);
}
}
return cards;
};
// When the line closes 2-way we solve the postflop spot inline, seeded with
// each survivor's continue range. The board comes from the picker drawer.
// Hold'em only: the inline solver takes 169-class ranges, and a PLO node's
// weights are keyed by four-card classes, which `clampWeights` drops — the
// seed came out empty and the strip spun "solving…" forever (6-max PLO).
const solveSeed: BuilderSeed | null =
!restoring &&
captured !== null &&
INLINE_SOLVE_GAMES.has(game) &&
explorerHost().solver !== null &&
end?.reason === "flop" &&
end.survivors.length === 2 &&
end.oop &&
end.ip
? {
oopWeights: captured[end.oop] ?? fullRange(),
ipWeights: captured[end.ip] ?? fullRange(),
potBb: end.potBb,
effStackBb: end.effStackBb,
oopLabel: end.oop,
ipLabel: end.ip,
board: flop.length === 3 ? flop.join(" ") : "",
oopIsPreflopCaller: end.oopIsPreflopCaller,
}
: null;
// Heads-up PLO4 has its own postflop engine (blueprint flop solve, then
// turn/river re-solves), at the stacks it serves.
const ploHuPostflop =
!restoring &&
game === "plo4hu" &&
explorerHost().plo4huPostflop !== null &&
end?.reason === "flop" &&
end.survivors.length === 2 &&
PLO4HU_POSTFLOP_STACKS.includes(stack);
const twoWayFlop = solveSeed !== null || ploHuPostflop;
const flopDone = flop.length === 3;
// A different line (or stack) voids the flop pick and the solve lifecycle.
useEffect(() => {
setFlop([]);
setPostflopRun("idle");
solvedRef.current = false;
}, [game, stack, scenario, history, order]);
// The drawer opens on its own the moment a 2-way flop line closes — the pick
// IS the next step, no intermediate screen. Closing it leaves the dashed
// FLOP card in the strip as the way back in.
useEffect(() => {
if (twoWayFlop) setPickerOpen(true);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [twoWayFlop, stack, history]);
// Keep the decision in view as the rail grows: the acting card, with the
// last decision before it still showing, so a deep line doesn't push the
// choice off-screen (phones fit one or two cards). Once the line closes,
// the newest card (flop / loading actor) is the one to show. Instant, not
// smooth — smooth scrollTo is dropped in some embedded-Chromium contexts.
const stripRef = useRef<HTMLDivElement>(null);
const actorCardRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const el = stripRef.current;
if (!el) return;
const card = actorCardRef.current;
if (card && !end) {
const prev = card.previousElementSibling as HTMLElement | null;
const left = prev ? prev.offsetLeft : card.offsetLeft;
const right = card.offsetLeft + card.offsetWidth;
// Show the previous card too when it fits; never hide the actor.
el.scrollLeft = right - left <= el.clientWidth ? left : card.offsetLeft;
} else {
el.scrollLeft = el.scrollWidth;
}
}, [history, end, flop.length, postflopRun, twoWayFlop, loading]);
const repick = () => {
setFlop([]);
setPostflopRun("idle");
solvedRef.current = false;
setPickerOpen(true);
};
const selectSolution = (groupId: string, nextStack: number, nextTable?: string | null) => {
const next = gameForGroup(groupId) ?? game;
if (lockedGame && next !== lockedGame) return;
applyWalk(lockedGame ?? next, nextStack, nextTable ?? null);
};
const lockedGroupId = lockedGame ? groupForGame(lockedGame).id : undefined;
// The game card leads the bar on every street: preflop here, then pinned
// beside the postflop navigator's rail once a flop is showing.
const gameCard = (
<SolutionSelectorCard
group={groupForGame(game)}
stack={stack}
table={scenario}
availableStacks={stacks}
open={selectorOpen}
onOpenChange={setSelectorOpen}
onSelect={selectSolution}
onlyGroupId={lockedGroupId}
shareable
/>
);
return (
<div className="flex flex-col gap-4">
{/* The preflop bar is one row that scrolls horizontally: the solution
selector, then a fixed-width card per seat. It used to wrap onto
several rows because the solutions library hung off the selector as an
anchored popover a scroller would clip — the library is a side drawer
now, so the bar can stay the single line it reads best as, at any
width and any seat count.
The moment a 2-way flop line closes, the bar compacts to the postflop
navigator's shape — fixed-width cards in a scroller — and grows a FLOP
card (then the loading acting card), so reaching the flop reads as the
same bar extending rather than a screen change.
Once the solve lands, the seat cards move into the navigator (as its
leading fixed-width cards) and this row disappears. The game card
moves with them: the navigator pins it in the same spot (RailRow),
so it stays visible on the flop, turn and river. */}
{!viewerActive && !(ploHuPostflop && flopDone) ? (
twoWayFlop ? (
<RailRow lead={gameCard} scrollerRef={stripRef}>
{renderRail()}
<FlopStripCard flop={flop} onClick={flopDone ? repick : () => setPickerOpen(true)} />
{flopDone ? (
postflopRun === "failed" ? (
<button
type="button"
onClick={repick}
className="flex min-h-[104px] w-[136px] shrink-0 flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-destructive/50 bg-destructive/[0.06] p-2 text-center"
>
<span className="text-xs font-medium text-destructive">solve stopped</span>
<span className="text-[11px] text-muted-foreground">re-pick flop ↓</span>
</button>
) : (
// The next decision, loading: the OOP seat acts first postflop.
<div className="flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border border-foreground/50 bg-accent/50 p-2">
<div className="flex items-center justify-between">
<span className="text-xs font-semibold text-foreground">{end?.oop}</span>
<span className="text-[10px] text-muted-foreground tabular-nums">
pot {end?.potBb.toFixed(1)}
</span>
</div>
<div className="flex flex-1 items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="size-3.5 shrink-0 animate-spin" /> solving…
</div>
</div>
)
) : null}
</RailRow>
) : (
<RailRow lead={gameCard} scrollerRef={stripRef}>
{renderRail()}
</RailRow>
)
) : null}
{error ? <p className="text-xs text-destructive">{error}</p> : null}
{/* Line closed: solve the postflop inline (2-way, board picked), or
explain why not. Mounted only once the flop is complete — mounting IS
what starts the solve. */}
{end ? (
solveSeed && flopDone ? (
<InlineSolve
key={`${stack}:${history}:${flop.join("")}`}
seed={solveSeed}
stripPrefix={renderRail()}
stripLead={gameCard}
onSolvedChange={(s) => {
solvedRef.current = s;
setViewerActive(s);
}}
onSetupError={() => setPostflopRun("failed")}
onRunningChange={(r) =>
// `false` only means failure when a run was actually underway —
// the mirror also emits false on mount (e.g. while a pending
// previous-session solve holds the auto-solve).
setPostflopRun((prev) =>
r ? "running" : solvedRef.current ? "idle" : prev === "running" ? "failed" : prev,
)
}
onSaved={onSaved}
/>
) : ploHuPostflop && flopDone ? (
<Plo4HuPostflop
stack={stack}
line={decisions.map((d) => `${d.seat}_${d.chosen}`).join("_")}
flop={flop}
pot={end.potBb}
effStack={end.effStackBb}
stripPrefix={renderRail()}
stripLead={gameCard}
onRepickFlop={repick}
/>
) : twoWayFlop ? null : (
<EndCard end={end} />
)
) : loading && !node ? (
<div className="flex min-h-[200px] items-center justify-center text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
</div>
) : node ? (
game === "nl" || game === "nlmtt8" || icm ? (
<ExplorerTabs
explorer={
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,320px)]">
<PreflopStrategyGrid
actions={node.actions}
stack={stack}
raiseContext={icm ? raiseContextAt(walk) : undefined}
/>
<PreflopHandSummary actions={node.actions} evUnit={node.evUnit ?? "sb"} />
</div>
}
/>
) : (
<PloExplorer
game={game === "plo5" || game === "plo6hu" ? game : "plo"}
actions={node.actions}
stack={stack}
history={history}
/>
)
) : null}
{/* The flop picker — the same drawer + card UI as picking a turn card in
the viewer. Three cards complete the flop; the drawer closes itself
and the solve starts. */}
{pickerOpen && twoWayFlop && !viewerActive ? (
<BottomSheet title="Pick the flop" onClose={() => setPickerOpen(false)}>
<CardGridPicker
value={flop}
max={3}
onChange={(next) => {
setFlop(next);
setPostflopRun("idle");
solvedRef.current = false;
if (next.length === 3) setPickerOpen(false);
}}
/>
<span className="pb-2 text-[11px] text-muted-foreground/70">
Three cards — the solve starts the moment the flop is complete.
</span>
</BottomSheet>
) : null}
</div>
);
}
/** The FLOP card in the strip: dashed "pick cards ↓" while the drawer flow is
* open-ended, a street card once the three cards are in. Clicking either form
* reopens the drawer (a completed pick resets and re-picks). */
function FlopStripCard({ flop, onClick }: { flop: string[]; onClick: () => void }) {
if (flop.length === 3) {
return (
<button
type="button"
onClick={onClick}
title="Re-pick the flop"
className="flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border border-border bg-card/40 p-2 text-left transition-colors hover:border-foreground/30"
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">Flop</span>
<div className="mt-auto flex flex-wrap items-center gap-1 text-lg font-bold tabular-nums">
{flop.map((c, i) => (
<CardText key={i} card={c} />
))}
</div>
</button>
);
}
return (
<button
type="button"
onClick={onClick}
className="flex min-h-[104px] w-[136px] shrink-0 flex-col items-center justify-center gap-1 rounded-xl border border-dashed border-foreground/40 bg-accent/30 p-2 text-center"
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">Flop</span>
{flop.length > 0 ? (
<div className="flex items-center gap-1 text-lg font-bold tabular-nums">
{flop.map((c, i) => (
<CardText key={i} card={c} />
))}
</div>
) : null}
<span className="text-xs text-muted-foreground">pick cards ↓</span>
</button>
);
}
/** The inline postflop solve engine, mounted once the drawer has fixed the
* flop. No setup form up front (setupless — "Edit spot" still reopens it
* post-solve) and the solve starts on its own; the parent's strip renders the
* loading acting card off `onRunningChange` in the meantime. */
function InlineSolve({
seed,
stripPrefix,
stripLead,
onSolvedChange,
onRunningChange,
onSetupError,
onSaved,
}: {
seed: BuilderSeed;
/** The preflop seat cards, rendered as the leading cards of the postflop
* navigator's strip so the whole line is one continuous action bar. */
stripPrefix?: ReactNode;
/** The game card, pinned left of the navigator's strip. */
stripLead?: ReactNode;
/** Fired when the postflop result appears/clears — the parent hides its own
* seat strip while the navigator (with the prefix) is showing. */
onSolvedChange?: (solved: boolean) => void;
/** Mirrors the solve's running state into the parent's strip. */
onRunningChange?: (running: boolean) => void;
/** The solve was refused before it started (bad seed or input). */
onSetupError?: (message: string) => void;
onSaved?: (bundle: CustomSolutionBundle) => void;
}) {
// No header here: the postflop navigator continues straight off the preflop
// seat strip above, so the setup/flow reads as one continuous action bar.
return (
<Builder
layout="inline"
setupless
autoSolve
seed={seed}
stripPrefix={stripPrefix}
stripLead={stripLead}
onSolvedChange={onSolvedChange}
onRunningChange={onRunningChange}
onSetupError={onSetupError}
onSaved={(_summary, bundle) => onSaved?.(bundle)}
/>
);
}
/** One row per action: colour dot, label, frequency. Shared by every rail
* card so the acting, past and skip-ahead cards line up row for row. */
function ActionRow({
item,
onClick,
title,
tone = "live",
}: {
item: PreflopActionItem;
onClick: () => void;
title?: string;
/** live = acting seat; dim = skip-ahead or an option not taken on this
* line; chosen = the action taken at a past decision. */
tone?: "live" | "dim" | "chosen";
}) {
return (
<button
type="button"
onClick={(e) => {
// Rows sit inside a clickable past-decision card.
e.stopPropagation();
onClick();
}}
title={title}
aria-pressed={tone === "chosen" ? true : undefined}
className={`flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors ${
tone === "chosen"
? "bg-foreground/15 ring-1 ring-foreground/25"
: tone === "dim"
? "opacity-45 hover:bg-accent hover:opacity-100"
: "hover:bg-accent"
}`}
>
<span className="flex min-w-0 items-center gap-1 truncate text-xs text-foreground">
<span className="size-2 shrink-0 rounded-[2px]" style={{ backgroundColor: item.color }} />
<span className={`truncate ${tone === "chosen" ? "font-semibold" : ""}`}>{item.label}</span>
</span>
<span className="shrink-0 text-[11px] font-semibold text-foreground tabular-nums">
{(item.freq * 100).toFixed(0)}%
</span>
</button>
);
}
function SeatHeader({
position,
isDealer,
muted,
right,
}: {
position: Position;
isDealer: boolean;
muted?: boolean;
right: ReactNode;
}) {
return (
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<span
className={`text-sm font-semibold ${muted ? "text-muted-foreground" : "text-foreground"}`}
>
{position}
</span>
{isDealer ? (
<span className="flex size-3.5 items-center justify-center rounded-full bg-foreground text-[8px] font-bold text-background">
D
</span>
) : null}
</div>
{right}
</div>
);
}
/** Datasets whose ranges the inline postflop solve can take (169-class Hold'em
* weights). Heads-up PLO4 has its own engine (`Plo4HuPostflop`); the other PLO
* datasets end on an explanation card instead of a solve. */
const INLINE_SOLVE_GAMES: ReadonlySet<ExplorerGame> = new Set<ExplorerGame>(["nl", "nlmtt8"]);
const RAIL_CARD = "flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2";
/** A decision already taken on the line. Lists every option that seat had,
* with the one taken highlighted. Clicking the card goes back to that
* decision; clicking another option branches the line from there. */
function PastDecisionCard({
position,
isDealer,
remaining,
pot,
chosen,
items,
onRewind,
onPick,
}: {
position: Position;
isDealer: boolean;
/** The seat's stack when it acted. */
remaining: number;
pot: number;
/** The action token taken here (e.g. "Fold", "R2.5", "AI"). */
chosen: string;
/** That decision's options; undefined while its node loads. */
items?: PreflopActionItem[];
onRewind: () => void;
onPick: (a: NodeAction) => void;
}) {
const chosenItem = items?.find((it) => it.action.action === chosen);
return (
// ui-exception: the rail card holds its own option buttons (a past
// decision is both "go back here" and "take another option here"), so the
// card itself can't be a <button>; it is keyboard-operable instead.
<div
role="button"
tabIndex={0}
onClick={onRewind}
onKeyDown={(e) => {
if (e.target !== e.currentTarget) return;
if (e.key === "Enter" || e.key === " ") {
e.preventDefault();
onRewind();
}
}}
title={`Back to ${position}'s decision`}
aria-label={`${position}: ${chosenItem?.label ?? chosen}. Go back to this decision`}
className={`${RAIL_CARD} cursor-pointer border-border bg-card/40 text-left transition-colors hover:border-foreground/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring`}
>
<SeatHeader
position={position}
isDealer={isDealer}
muted
right={
<span className="text-[11px] font-medium text-muted-foreground tabular-nums">
{formatBb(remaining)}
</span>
}
/>
{items && items.length > 0 ? (
<div className="flex flex-col">
{items.map((it) => (
<ActionRow
key={it.action.action}
item={it}
tone={it.action.action === chosen ? "chosen" : "dim"}
title={
it.action.action === chosen
? `Back to ${position}'s decision`
: `${position} ${it.label} instead (pot ${pot.toFixed(1)})`
}
onClick={() => onPick(it.action)}
/>
))}
</div>
) : (
<div className="flex flex-1 items-center py-1">
<span className="inline-block max-w-full truncate rounded bg-accent px-2 py-0.5 text-xs font-semibold text-foreground">
{chosen}
</span>
</div>
)}
</div>
);
}
/** The acting seat (live action rows) or a seat still to act this orbit
* (the same rows greyed; picking one folds everyone in between). */
function SeatStripCard({
position,
seat,
isActor,
items,
skipItems,
skipLoading = false,
pot,
loading,
onAdvance,
onSkip,
cardRef,
}: {
position: Position;
seat: SeatState;
isActor: boolean;
/** Aggregate action rows for the acting seat (dot · label · freq %). */
items?: PreflopActionItem[];
/** Same rows, greyed, for a seat the user can skip ahead to. */
skipItems?: PreflopActionItem[];
/** That seat's node is still loading. */
skipLoading?: boolean;
/** Pot at the decision, shown on the acting card like postflop's navigator. */
pot: number;
loading: boolean;
onAdvance: (a: NodeAction) => void;
/** Take this action here, folding the actor and everyone in between. */
onSkip?: (a: NodeAction) => void;
cardRef?: Ref<HTMLDivElement>;
}) {
const header = (
<SeatHeader
position={position}
isDealer={seat.isDealer}
right={
isActor ? (
<span className="text-[10px] text-muted-foreground tabular-nums">
pot {pot.toFixed(1)}
</span>
) : (
<span className="text-[11px] font-medium text-muted-foreground tabular-nums">
{formatBb(seat.remaining)}
</span>
)
}
/>
);
let body: ReactNode;
if (isActor) {
body =
!items || items.length === 0 ? (
<span className="flex items-center gap-1.5 py-1 text-xs text-muted-foreground">
{loading ? <Loader2 className="size-3.5 animate-spin" /> : "—"}
</span>
) : (
<div className="flex flex-col">
{items.map((it) => (
<ActionRow key={it.action.action} item={it} onClick={() => onAdvance(it.action)} />
))}
</div>
);
} else if (onSkip && !skipLoading && skipItems && skipItems.length > 0) {
body = (
<div className="flex flex-col">
{skipItems.map((it) => (
<ActionRow
key={it.action.action}
item={it}
tone="dim"
title={`Skip ahead — folds everyone before ${position}`}
onClick={() => onSkip(it.action)}
/>
))}
</div>
);
} else {
body = (
<span className="py-1 text-xs text-muted-foreground/50">{skipLoading ? "…" : "—"}</span>
);
}
return (
<div
ref={cardRef}
className={`${RAIL_CARD} ${isActor ? "border-foreground/50 bg-accent/50" : "border-border bg-card/40"}`}
>
{header}
{body}
</div>
);
}
function EndCard({ end }: { end: EndState }) {
if (end.reason === "won") {
const winner = end.survivors[0];
return (
<div className="rounded-xl border border-border bg-card/40 px-4 py-3 text-sm text-muted-foreground">
Hand ends preflop — {winner ? `${winner} wins uncontested` : "everyone folded"}. No
postflop play on this line.
</div>
);
}
const summary = `${end.survivors.join(" / ")} — ${end.survivors.length}-way`;
const multiway = end.survivors.length >= 3;
// A host without the solver points heads-up lines to where they can be solved.
const elsewhere = multiway ? null : explorerHost().solveElsewhere;
return (
<div className="flex flex-col items-center gap-3 rounded-xl border border-dashed border-border bg-card/40 px-6 py-7 text-center">
<span className="text-sm font-medium text-foreground">
{multiway ? "This line goes multiway postflop" : "This line goes heads-up to the flop"}
</span>
<span className="text-xs text-muted-foreground">
{summary} · pot {end.potBb.toFixed(1)}bb · {end.effStackBb.toFixed(1)}bb behind.
</span>
{elsewhere ? (
<a href={elsewhere.href} className={buttonVariants({ variant: "outline", size: "sm" })}>
{elsewhere.label}
</a>
) : (
<span className="rounded-full border border-border px-3 py-1.5 text-xs text-muted-foreground/70">
{multiway
? "Multiway postflop solving isn’t available yet"
: "Postflop solving for this game isn’t in the Explorer yet. The preflop ranges above are complete."}
</span>
)}
</div>
);
}
components/explorer/preflop-strategy-grid.tsx
"use client";
// The 13×13 preflop strategy grid for the Explorer. Unlike the postflop
// `StrategyGrid` (which aggregates per-combo data), the preflop ranges API
// hands us each action's per-class frequency directly (`NodeAction.weights`),
// so a cell is just the stacked action split for that hand class.
import { useMemo } from "react";
import { ALL_HANDS, comboCountOf } from "@/lib/solver/range-model";
import {
sizedRaiseLabel,
sortActionsForDisplay,
type NodeAction,
type RaiseContext,
} from "@/lib/solver/preflop";
import { ACTION_COLORS, HandMatrix, type MatrixCell } from "@/components/solver/strategy-grid";
import { actionPalette } from "@/lib/pokerstudy/poker";
// Preflop reuses the postflop palette (ACTION_COLORS) so a color means the same
// thing on both sides of the flop. The one addition: preflop nodes can offer
// several raise sizes at once, so raises darken by size from the base Bet tone
// to stay distinguishable when stacked in a single cell.
const RAISE_PALETTE = actionPalette().raises;
/** Stable per-action colors for a node, ordered fold → call → raises → all-in. */
export function colorActions(actions: NodeAction[]): { action: NodeAction; color: string }[] {
const sorted = sortActionsForDisplay(actions);
let raiseIdx = 0;
return sorted.map((action) => {
let color: string;
if (action.kind === "fold") color = ACTION_COLORS.Fold;
else if (action.kind === "call") color = ACTION_COLORS.Call;
else if (action.kind === "allin") color = ACTION_COLORS.AllIn;
else color = RAISE_PALETTE[Math.min(raiseIdx++, RAISE_PALETTE.length - 1)];
return { action, color };
});
}
function labelFor(action: NodeAction, stack: number, ctx?: RaiseContext): string {
// A raise the feed sized (ICM sets) reads as a pot percentage.
const sized = ctx ? sizedRaiseLabel(action, ctx) : null;
if (sized) return sized;
if (action.kind === "fold") return "Fold";
if (action.action === "Limp") return "Limp";
if (action.kind === "call") return "Call";
if (action.kind === "allin" || action.action === "AI") return `All-in ${stack}`;
if (action.action === "Open") return "Open";
if (action.kind === "raise") return `Raise ${action.action}`;
return action.action;
}
/** One aggregate action row for the acting seat card: the action itself plus
* its display label, color, and combo-weighted frequency across the range —
* the same shape the postflop navigator's acting card renders. */
export interface PreflopActionItem {
action: NodeAction;
label: string;
color: string;
/** Aggregate frequency across the range, in [0, 1]. */
freq: number;
/** Combo-weighted count taking this action. */
combos: number;
}
/** Combo-weighted aggregate action frequencies, in display order. */
export function preflopActionItems(
actions: NodeAction[],
stack: number,
/** Where the actor stands; when given, sized raises read as pot percentages. */
ctx?: RaiseContext,
): PreflopActionItem[] {
const colored = colorActions(actions);
// Total combos in the range = combos that take any action on the highest-
// weight basis; use the sum over the fold action's domain as the denominator
// proxy is unreliable, so weight every class by its combo count once.
let rangeCombos = 0;
for (const hand of ALL_HANDS) {
const any = colored.some(({ action }) => (action.weights[hand] ?? 0) > 0);
if (any) rangeCombos += comboCountOf(hand);
}
const denom = rangeCombos || 1;
return colored.map(({ action, color }) => {
let combos = 0;
for (const hand of ALL_HANDS) {
const w = action.weights[hand] ?? 0;
if (w > 0) combos += w * comboCountOf(hand);
}
return { action, label: labelFor(action, stack, ctx), color, freq: combos / denom, combos };
});
}
export function PreflopStrategyGrid({
actions,
stack,
raiseContext,
}: {
actions: NodeAction[];
/** Effective stack in bb — only used for the legend's all-in label. */
stack: number;
/** Where the actor stands; when given, sized raises read as pot percentages. */
raiseContext?: RaiseContext;
}) {
const colored = useMemo(() => colorActions(actions), [actions]);
// Renders through the shared HandMatrix (the postflop grid's cells + legend),
// so preflop and postflop are literally the same grid. A class whose action
// frequencies sum to ~0 is out of range → the empty dark cell, like postflop.
const cells = useMemo<(MatrixCell | null)[]>(() => {
return ALL_HANDS.map((hand) => {
const freqs = colored.map(({ action }) => action.weights[hand] ?? 0);
const sum = freqs.reduce((s, f) => s + f, 0);
return sum > 0.001 ? { label: hand, freqs } : null;
});
}, [colored]);
const colors = useMemo(() => colored.map(({ color }) => color), [colored]);
const legend = useMemo(
() =>
colored.map(({ action, color }) => ({ label: labelFor(action, stack, raiseContext), color })),
[colored, stack, raiseContext],
);
const foldIndex = colored.findIndex(({ action }) => action.kind === "fold");
return (
<HandMatrix
cells={cells}
colors={colors}
legend={legend}
foldIndex={foldIndex < 0 ? undefined : foldIndex}
aggressiveFirst
/>
);
}
components/explorer/rail-row.tsx
"use client";
import type { ReactNode, Ref } from "react";
/** The Explorer's action bar: an optional fixed lead card (the game/solution
* card) and the horizontally scrolling rail of decision cards beside it.
* Shared by the preflop strip and both postflop navigators, so the game card
* stays put on every street instead of scrolling away with the line. On
* phones the lead stacks above the rail; from `sm` up it sits to its left. */
export function RailRow({
lead,
scrollerRef,
children,
}: {
lead?: ReactNode;
scrollerRef?: Ref<HTMLDivElement>;
children: ReactNode;
}) {
const rail = (
<div
ref={scrollerRef}
className="relative flex min-w-0 flex-1 items-stretch gap-2 overflow-x-auto pb-1"
>
{children}
</div>
);
if (!lead) return rail;
return (
<div className="flex flex-col gap-2 sm:flex-row sm:items-stretch">
<div className="w-full shrink-0 sm:w-[196px]">{lead}</div>
{rail}
</div>
);
}
components/explorer/range-grid-editor.tsx
"use client";
// An editable 13×13 range grid. Seeded from a walked preflop line but fully
// paintable: press and drag to set cells to full (1) or clear (0) — the drag
// target is decided by the first cell you touch (GTO-Wizard-style). Rendered
// inline in the Explorer's continuous solve panel so a player can tweak either
// survivor's continue range before solving the flop.
import { useCallback, useEffect, useRef } from "react";
import { RotateCcw } from "lucide-react";
import {
ALL_HANDS,
fullRange,
totalCombos,
type RangePlayer,
type RangeWeights,
} from "@/lib/solver/range-model";
import type { Position } from "@/lib/solver/preflop";
const FULL_COMBOS = 1326;
/** True for the suited/pair upper triangle+diagonal — used only for a faint tint. */
function isSuitedOrPair(index: number): boolean {
const r = Math.floor(index / 13);
const c = index % 13;
return r <= c;
}
export function RangeGridEditor({
pos,
role,
weights,
onChange,
seed,
}: {
pos: Position | string;
role: RangePlayer;
weights: RangeWeights;
onChange: (next: RangeWeights) => void;
/** The range as it came off the preflop line, for "reset to line". */
seed?: RangeWeights;
}) {
// Paint state: which value we're stamping while the pointer is down.
const painting = useRef<number | null>(null);
const paint = useCallback(
(hand: string, value: number) => {
if ((weights[hand] ?? 0) === value) return;
onChange({ ...weights, [hand]: value });
},
[weights, onChange],
);
const onCellDown = (hand: string) => {
const target = (weights[hand] ?? 0) >= 0.5 ? 0 : 1;
painting.current = target;
paint(hand, target);
};
const onCellEnter = (hand: string) => {
if (painting.current === null) return;
paint(hand, painting.current);
};
// Release the paint stroke anywhere on the document, not just over a cell.
useEffect(() => {
const stop = () => {
painting.current = null;
};
window.addEventListener("pointerup", stop);
window.addEventListener("pointercancel", stop);
return () => {
window.removeEventListener("pointerup", stop);
window.removeEventListener("pointercancel", stop);
};
}, []);
const combos = totalCombos(weights);
const pct = (combos / FULL_COMBOS) * 100;
const setAll = (mode: "full" | "clear" | "seed") => {
if (mode === "seed" && seed) onChange({ ...seed });
else if (mode === "full") onChange(fullRange());
else if (mode === "clear") onChange({});
};
return (
<div className="flex flex-col gap-2 rounded-xl border border-border bg-card/40 p-3">
<div className="flex items-center justify-between gap-2">
<div className="flex items-center gap-1.5">
<span className="text-sm font-semibold text-foreground">{pos}</span>
<span
className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${
role === "oop"
? "bg-foreground text-background"
: "border border-foreground/50 text-foreground"
}`}
>
{role.toUpperCase()}
</span>
</div>
<span className="text-[11px] tabular-nums text-muted-foreground">
{combos.toFixed(1)} combos · {pct.toFixed(1)}%
</span>
</div>
{/* The grid. touch-none so a drag paints instead of scrolling on mobile. */}
<div className="grid touch-none select-none grid-cols-[repeat(13,minmax(0,1fr))] gap-px">
{ALL_HANDS.map((hand, i) => {
const w = weights[hand] ?? 0;
const on = w > 0;
return (
<button
key={hand}
type="button"
onPointerDown={(e) => {
e.preventDefault();
onCellDown(hand);
}}
onPointerEnter={() => onCellEnter(hand)}
title={hand}
className={`flex aspect-square items-center justify-center rounded-[2px] text-[6px] font-medium leading-none transition-colors ${
on
? "bg-foreground text-background"
: isSuitedOrPair(i)
? "bg-foreground/10 text-muted-foreground/50"
: "bg-foreground/[0.04] text-muted-foreground/40"
}`}
style={on ? { opacity: 0.4 + 0.6 * Math.min(w, 1) } : undefined}
>
{hand}
</button>
);
})}
</div>
<div className="flex items-center gap-1.5">
<GridBtn onClick={() => setAll("full")}>Full</GridBtn>
<GridBtn onClick={() => setAll("clear")}>Clear</GridBtn>
{seed ? (
<GridBtn onClick={() => setAll("seed")}>
<RotateCcw className="size-3" /> Reset to line
</GridBtn>
) : null}
</div>
</div>
);
}
function GridBtn({ onClick, children }: { onClick: () => void; children: React.ReactNode }) {
return (
<button
type="button"
onClick={onClick}
className="flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-[11px] text-foreground transition-colors hover:bg-accent"
>
{children}
</button>
);
}
components/explorer/solution-selector.tsx
"use client";
// Solution selector. A compact card shows the current solution (format · stack
// · raises) with a "Change" button; clicking it opens the solutions drawer:
// the shared SidePanel in its wide size (a bottom drawer on phones, a wide
// right-hand panel on desktop) with game / format / players / rake facets
// (React Bits Pro App UI `filtering-1`) in a left rail beside one frame per
// solution set listing its stacks. Picking a browsable stack switches the
// Explorer. Solutions we can't walk yet are listed but inert: this is a picker,
// not a storefront: the one Download button hands the pack on screen to the
// download gate (`/api/downloads/[id]`). Downloads are Studio only: the gate
// sends everyone else to /pricing, and once the ranges session says the plan
// isn't Studio the button shows a lock pointing there instead.
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { Download, Link2, Lock, Settings2, ShoppingBag } from "lucide-react";
import { explorerHost } from "@/lib/explorer/host";
import { toast } from "sonner";
import type { Plan } from "@/lib/access/policy";
import { ensureRangesSession } from "@/lib/access/session-client";
import { SidePanel } from "@/components/ui/side-panel";
import {
ActiveFilterChips,
EmptyResults,
FacetGroup,
FacetRadioList,
FacetRail,
FilterToggleButton,
ResultChoice,
ResultFrame,
filteringTokens,
} from "@/components/blocks/filtering-1";
import {
defaultTable,
packIdFor,
raisesFor,
RAKE_TIER_LABEL,
solveCount,
SOLUTION_GROUPS,
type FormatKind,
type GameKind,
type PlayersKind,
type RakeTier,
type SolutionGroup,
} from "@/lib/explorer/solution-catalog";
interface Props {
group: SolutionGroup;
stack: number;
/** ICM sets: the stack table on screen (a scenario id). */
table?: string | null;
/** Stacks present in the ranges manifest (browsable rows gate on this). */
availableStacks: number[];
open: boolean;
onOpenChange: (open: boolean) => void;
onSelect: (groupId: string, stack: number, table?: string | null) => void;
/** When set, the drawer only lists stacks in this catalog group. */
onlyGroupId?: string;
/** Show a "Copy link" button for the current address (the explorer keeps
* its view in the URL, so the address is a link to this exact spot). */
shareable?: boolean;
}
/** Copy the page's address. The URL already carries the view, so this is the
* share link. Falls back to a prompt where the clipboard is blocked. */
async function copyCurrentLink() {
const href = window.location.href;
try {
await navigator.clipboard.writeText(href);
toast.success("Link copied", { description: "Anyone with the link opens this exact view." });
} catch {
window.prompt("Copy this link", href);
}
}
export function SolutionSelectorCard({
group,
stack,
table = null,
availableStacks,
open,
onOpenChange,
onSelect,
onlyGroupId,
shareable = false,
}: Props) {
const raises = raisesFor(group, stack);
const tableInfo = defaultTable(group, stack, table);
const packId = packIdFor(group.id, stack);
// Hosts that sell packs on a page (pokerdata.io) link there; pokerstudy.ai
// hands the pack to its download gate.
const host = explorerHost();
const downloadHref = packId && host.downloadHref ? host.downloadHref(packId) : null;
const packHref = packId && !downloadHref && host.packHref ? host.packHref(packId) : null;
// Null until the session read lands; the gate checks again on click.
const [plan, setPlan] = useState<Plan | null>(null);
useEffect(() => {
let live = true;
void ensureRangesSession().then((s) => {
if (live && s) setPlan(s.plan);
});
return () => {
live = false;
};
}, []);
const locked = plan !== null && plan !== "studio";
return (
<div className="relative w-full">
{/* Same frame as a strip card (min-h-[104px]) — it sits inline with them. */}
<div className="flex min-h-[104px] flex-col gap-1 rounded-xl border border-border bg-card/40 p-2.5">
<div className="flex items-start justify-between gap-1">
<span className="text-sm font-semibold leading-tight text-foreground">
{group.format.split(" · ")[0]}{" "}
<span className="whitespace-nowrap text-muted-foreground">
{stack}
<span className="align-super text-[9px]">bb</span>
</span>
</span>
<div className="flex shrink-0 items-center gap-1">
{packHref ? (
<Link
href={packHref}
title="Get this pack"
aria-label="Get this pack"
className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<ShoppingBag className="size-4" />
</Link>
) : downloadHref && locked ? (
<Link
href="/pricing?from=downloads"
title="Downloads are part of Studio"
aria-label="Downloads are part of Studio"
className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<Lock className="size-4" />
</Link>
) : downloadHref ? (
<a
href={downloadHref}
title="Download this pack"
aria-label="Download this pack"
className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<Download className="size-4" />
</a>
) : null}
{shareable ? (
// ui-exception: same icon button as Download / Change beside it, so the card's action row stays one set
<button
type="button"
onClick={() => void copyCurrentLink()}
title="Copy link to this view"
aria-label="Copy link to this view"
className="flex size-7 shrink-0 items-center justify-center rounded-md border border-border bg-card text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<Link2 className="size-4" />
</button>
) : null}
<button
type="button"
onClick={() => onOpenChange(!open)}
title="Change solution"
aria-label="Change solution"
className={`flex size-7 shrink-0 items-center justify-center rounded-md border transition-colors ${
open
? "border-foreground/50 bg-accent text-foreground"
: "border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground"
}`}
>
<Settings2 className="size-4" />
</button>
</div>
</div>
<ul className="flex flex-col gap-0.5 text-[11px] text-muted-foreground">
<li>• {group.format.split(" · ")[1] ?? group.format}</li>
{tableInfo ? (
<li className="truncate" title={`${tableInfo.label} table, ${stack}bb average`}>
• {tableInfo.label}, {stack}bb avg
</li>
) : (
<li className="truncate" title={raises ?? group.rake}>
• {raises ?? group.rake}
</li>
)}
</ul>
</div>
{open ? (
<SolutionsLibrary
group={group}
stack={stack}
table={tableInfo?.scenario ?? null}
availableStacks={availableStacks}
onlyGroupId={onlyGroupId}
onClose={() => onOpenChange(false)}
onSelect={(g, s, t) => {
onSelect(g, s, t);
onOpenChange(false);
}}
/>
) : null}
</div>
);
}
type Any = "any";
type Facets = {
game: Any | GameKind;
format: Any | FormatKind;
players: Any | PlayersKind;
rake: Any | RakeTier;
};
const NO_FILTERS: Facets = { game: "any", format: "any", players: "any", rake: "any" };
const GAME_FILTERS: { value: Any | GameKind; label: string }[] = [
{ value: "any", label: "All games" },
{ value: "holdem", label: "Hold'em" },
{ value: "omaha", label: "Omaha (PLO 4)" },
{ value: "plo5", label: "PLO 5" },
{ value: "plo6", label: "PLO 6" },
];
const FORMAT_FILTERS: { value: Any | FormatKind; label: string }[] = [
{ value: "any", label: "Any" },
{ value: "cash", label: "Cash" },
{ value: "tournament", label: "Tournaments" },
];
const PLAYER_FILTERS: { value: Any | PlayersKind; label: string }[] = [
{ value: "any", label: "Any" },
{ value: "hu", label: "Heads-up" },
{ value: "6max", label: "6-max" },
{ value: "8max", label: "8-max" },
{ value: "9max", label: "9-max" },
];
const RAKE_FILTERS: { value: Any | RakeTier; label: string }[] = [
{ value: "any", label: "Any" },
{ value: "low", label: RAKE_TIER_LABEL.low },
{ value: "mid", label: RAKE_TIER_LABEL.mid },
{ value: "high", label: RAKE_TIER_LABEL.high },
{ value: "chipev", label: RAKE_TIER_LABEL.chipev },
{ value: "icm", label: RAKE_TIER_LABEL.icm },
];
const PLAYERS_LABEL: Record<PlayersKind, string> = {
hu: "Heads-up",
"6max": "6-max",
"8max": "8-max",
"9max": "9-max",
};
/** Does a group pass every facet, optionally ignoring one (for its counts)? */
function matches(g: SolutionGroup, f: Facets, skip?: keyof Facets): boolean {
return (
(skip === "game" || f.game === "any" || g.game === f.game) &&
(skip === "format" || f.format === "any" || g.formatKind === f.format) &&
(skip === "players" || f.players === "any" || g.players === f.players) &&
(skip === "rake" || f.rake === "any" || g.rakeTier === f.rake)
);
}
function SolutionsLibrary({
group,
stack,
table,
availableStacks: _availableStacks,
onlyGroupId,
onClose,
onSelect,
}: {
group: SolutionGroup;
stack: number;
table: string | null;
availableStacks: number[];
onlyGroupId?: string;
onClose: () => void;
onSelect: (groupId: string, stack: number, table?: string | null) => void;
}) {
const [facets, setFacets] = useState<Facets>(NO_FILTERS);
// Phones show the rail on demand (it would push every solution below the fold).
const [railOpen, setRailOpen] = useState(false);
const set = <K extends keyof Facets>(key: K, value: Facets[K]) =>
setFacets((f) => ({ ...f, [key]: value }));
const groups = useMemo(
() =>
onlyGroupId
? SOLUTION_GROUPS.filter((g) => g.id === onlyGroupId)
: SOLUTION_GROUPS,
[onlyGroupId],
);
const shown = groups.filter((g) => matches(g, facets));
const solutionCount = (list: SolutionGroup[]) =>
list.reduce((n, g) => n + g.stacks.reduce((m, s) => m + solveCount(s), 0), 0);
const total = solutionCount(shown);
/** Facet options with the count each would show, given the other facets. */
const withCounts = <T extends string>(
key: keyof Facets,
options: { value: T; label: string }[],
field: (g: SolutionGroup) => string,
) =>
options.map((o) => ({
...o,
count: solutionCount(
groups.filter(
(g) => matches(g, facets, key) && (o.value === "any" || field(g) === o.value),
),
),
}));
const chips = (
[
["game", GAME_FILTERS],
["format", FORMAT_FILTERS],
["players", PLAYER_FILTERS],
["rake", RAKE_FILTERS],
] as const
).flatMap(([key, options]) =>
facets[key] === "any"
? []
: [
{
key,
label: (options as readonly { value: string; label: string }[]).find(
(o) => o.value === facets[key],
)!.label,
onRemove: () => set(key, "any"),
},
],
);
const filterable = !onlyGroupId;
const rail = (
<FacetRail>
<FacetGroup label="Game">
<FacetRadioList
name="solutions-game"
options={withCounts("game", GAME_FILTERS, (g) => g.game)}
value={facets.game}
onChange={(v) => set("game", v)}
/>
</FacetGroup>
<FacetGroup label="Format">
<FacetRadioList
name="solutions-format"
options={withCounts("format", FORMAT_FILTERS, (g) => g.formatKind)}
value={facets.format}
onChange={(v) => set("format", v)}
/>
</FacetGroup>
<FacetGroup label="Players">
<FacetRadioList
name="solutions-players"
options={withCounts("players", PLAYER_FILTERS, (g) => g.players)}
value={facets.players}
onChange={(v) => set("players", v)}
/>
</FacetGroup>
<FacetGroup label="Rake">
<FacetRadioList
name="solutions-rake"
options={withCounts("rake", RAKE_FILTERS, (g) => g.rakeTier)}
value={facets.rake}
onChange={(v) => set("rake", v)}
/>
</FacetGroup>
</FacetRail>
);
return (
<SidePanel
title="Solutions"
onClose={onClose}
size="wide"
bodyClassName="flex flex-col gap-5 px-5 py-5 md:flex-row md:gap-8"
>
{filterable ? (
// Facet rail on the left from md up; phones open it under "Filters" below.
<aside className="hidden w-56 shrink-0 self-start md:block">
{rail}
</aside>
) : null}
<div className="flex min-w-0 flex-1 flex-col gap-4">
<div className="flex flex-wrap items-center justify-between gap-3">
<p className={filteringTokens.metaText}>
<span className={`tabular-nums ${filteringTokens.text1}`}>{total}</span>{" "}
{total === 1 ? "solution" : "solutions"} in{" "}
<span className="tabular-nums">{shown.length}</span>{" "}
{shown.length === 1 ? "set" : "sets"}
</p>
{filterable ? (
<FilterToggleButton
className="md:hidden"
open={railOpen}
count={chips.length}
onClick={() => setRailOpen((v) => !v)}
/>
) : null}
</div>
{filterable && railOpen ? (
<div className="border-b border-border pb-5 md:hidden">{rail}</div>
) : null}
<ActiveFilterChips chips={chips} onClearAll={() => setFacets(NO_FILTERS)} />
{shown.length === 0 ? (
<EmptyResults
title="No solutions match these filters"
description="Clear a filter to see the rest of the library. Tournament solves are chip EV or ICM, so they don't show under a stakes filter."
onClear={() => setFacets(NO_FILTERS)}
/>
) : (
<div className="flex flex-col gap-3">
{shown.map((g) => (
<ResultFrame
key={g.id}
title={g.format}
meta={`Rake: ${g.rake.replace(/^rake /, "")}`}
tags={[
g.formatKind === "tournament" ? "Tournament" : "Cash",
RAKE_TIER_LABEL[g.rakeTier],
PLAYERS_LABEL[g.players],
]}
// Listed so the catalog reads honestly, but not walkable yet.
aside={g.browsable ? null : "Download only"}
muted={!g.browsable}
>
{g.stacks.some((s) => s.tables?.length) ? (
// ICM: one row per average depth, one choice per stack table
// (even stacks, a short or big stack in one seat, mixed).
<div className="flex flex-col gap-3">
{g.stacks.map((s) => (
<div key={s.stack} className="flex flex-col gap-1.5">
<span className={filteringTokens.captionText}>
{s.stack}bb average · {s.tables?.length ?? 0} tables
</span>
<div className="flex flex-wrap gap-2">
{(s.tables ?? []).map((t) => (
<ResultChoice
key={t.scenario}
label={t.label}
title={`${t.label}, ${s.stack}bb average · ${s.raises}`}
current={
g.id === group.id && s.stack === stack && t.scenario === table
}
disabled={!g.browsable}
onClick={() => onSelect(g.id, s.stack, t.scenario)}
/>
))}
</div>
</div>
))}
</div>
) : (
<div className="flex flex-wrap gap-2">
{g.stacks.map((s) => (
<ResultChoice
key={s.stack}
label={`${s.stack}bb`}
title={s.raises}
current={g.id === group.id && s.stack === stack}
disabled={!g.browsable}
onClick={() => onSelect(g.id, s.stack)}
/>
))}
</div>
)}
</ResultFrame>
))}
</div>
)}
</div>
</SidePanel>
);
}
components/explorer/solution-viewer.tsx
"use client";
// The postflop solution viewer (#231) — GTO-Wizard-style study view over a
// solved `CustomSolutionBundle`:
//
// • top bar: the action-sequence breadcrumb (street cards + each taken
// action, actor-labelled), clickable to jump back;
// • center: the 13×13 strategy matrix (stacked action-frequency cells);
// • right: the acting position + pot, an action summary (one wide bar per
// action: label, size, % of range, combos — click to advance), and the
// per-combo hand summary (strategy bar, EV, range share);
// • at chance nodes: a card picker over the live deck.
//
// The bundle only carries strategies to `dump_max_deals` chance deals past its
// start street. Picking a runout past that horizon solves the subgame on
// demand: the reach-weighted ranges at the chance node are derived by walking
// the bundle's own per-node strategies (lib/explorer/subgame.ts), the child
// request goes through the normal `/api/solver/jobs` flow, and the result is
// spliced in as a navigable sub-solution, cached client-side by path.
import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
import Link from "next/link";
import { ArrowLeft, Dumbbell, Loader2, Lock, Pencil, X } from "lucide-react";
import { StrategyGrid, ACTION_COLORS } from "@/components/solver/strategy-grid";
import { PostflopHandSummary } from "./postflop-hand-summary";
import { LockEditor } from "./lock-editor";
import { NodeEditModal } from "./node-edit-modal";
import { BottomSheet } from "./bottom-sheet";
import { startSolve, type SolveHandle } from "@/lib/solver/client";
import type {
LockedNode,
SolveRequest,
SolverProgress,
SolverResult,
} from "@/lib/solver/types";
import type { CustomSolutionBundle } from "@/lib/explorer/types";
import { buildAggregateLock, MAX_LOCKED_NODES } from "@/lib/explorer/locks";
import { carryForChild } from "@/lib/explorer/resolve-carry";
import {
actionSegment,
boardCards,
buildChildRequest,
dealCard,
isDealSegment,
isPathPrefix,
nextSegments,
nodeAtPath,
walkReach,
type ReachState,
} from "@/lib/explorer/subgame";
import { MiniCard } from "@/components/trainer/cards";
import { suitTile } from "@/components/trainer/theme";
import { RailRow } from "./rail-row";
// ---------------------------------------------------------------------------
// Card rendering (matches the Explorer's 4-color deck)
// ---------------------------------------------------------------------------
const SUIT_GLYPH: Record<string, string> = { s: "♠", h: "♥", d: "♦", c: "♣" };
function CardText({ card, className = "h-5 w-4 text-[13px]" }: { card: string; className?: string }) {
return <MiniCard card={card} className={className} />;
}
// ---------------------------------------------------------------------------
// Navigation model
// ---------------------------------------------------------------------------
interface SubSolve {
config: SolveRequest;
result: SolverResult;
/** How the child was rooted (#233): "gadget" = CFR-D safe re-solve with
* carried opponent-CFV promises (runout-averaged today, see
* resolve-carry.ts); "reach" = legacy reach-range bootstrap. */
resolveMode: "gadget" | "reach";
}
/** One node in the walked line — a street (board cards) or a taken action. */
interface Crumb {
index: number; // path.slice(0, index) jumps here
kind: "street" | "action";
text: string;
card?: string;
cards?: string[];
actor?: string;
/** The node this action was taken at is locked (#268) — either in the
* solve's dump (`locked: true`) or as a pending edit in this session. */
locked?: boolean;
}
/** Strategy-edit wiring (#268), passed by the builder when the bundle has a
* warm-startable base job. Absent (saved/sample solutions, AI solves,
* what-if results): the viewer is read-only, badges still render. */
export interface ViewerLocking {
/** Issue the locked re-solve with the collected edits. */
onResolve: (locks: LockedNode[]) => void;
/** A locked re-solve is currently running. */
busy: boolean;
}
/** Structural node editing (#390): change the ACTION SET (bet sizes / all-in)
* at one node and re-solve the whole tree. Passed by the builder — absent on
* saved/sample bundles, where the tree is fixed. Paths use the engine's
* node-edit encoding (deal steps as generic "deal"). */
export interface ViewerNodeEditing {
/** Apply one node's new sizes (pot fractions) + all-in flag, then re-solve. */
onApply: (path: string[], sizes: number[], allin: boolean) => void;
/** Drop every node edit in the tree, then re-solve. */
onClearAll: () => void;
/** Node-edit paths currently active (keys joined with a space). */
editedKeys: string[];
/** The re-solve is running. */
busy: boolean;
}
/** Viewer path → engine node-edit path: deal segments become generic "deal". */
const toEditPath = (path: readonly string[]) =>
path.map((s) => (isDealSegment(s) ? "deal" : s));
/** Aggregate, reach-weighted action at the acting node (shared strip ↔ panel). */
interface StripActionItem {
seg: string;
label: string;
add: number;
color: string;
freq: number;
combos: number;
}
const keyOf = (path: readonly string[]) => path.join(" ");
/** The solution (root bundle or spliced sub-solve) whose dump contains `path`. */
function containingSolution(
bundle: CustomSolutionBundle,
subs: Record<string, SubSolve>,
path: readonly string[],
): {
config: SolveRequest;
result: SolverResult;
base: string[];
resolveMode: SubSolve["resolveMode"] | null;
} {
let best: ReturnType<typeof containingSolution> = {
config: bundle.config,
result: bundle.result,
base: [],
resolveMode: null, // the root bundle is the equilibrium itself, not a re-solve
};
for (const [key, sub] of Object.entries(subs)) {
const base = key === "" ? [] : key.split(" ");
if (base.length > best.base.length && isPathPrefix(base, path)) {
best = { config: sub.config, result: sub.result, base, resolveMode: sub.resolveMode };
}
}
return best;
}
function streetNameForBoardLen(len: number): string {
if (len <= 3) return "Flop";
return len === 4 ? "Turn" : "River";
}
// ---------------------------------------------------------------------------
// Viewer
// ---------------------------------------------------------------------------
export function SolutionViewer({
bundle,
onBack,
drillHref,
embedded = false,
stripPrefix,
stripLead,
locking,
nodeEditing,
}: {
bundle: CustomSolutionBundle;
onBack?: () => void;
/** Link to drill this solution in the trainer. Set only for the user's own
* saved solves — they're the ones that become `custom:` drill packs. */
drillHref?: string;
/** Rendered as a continuation of another navigator (the Explorer's preflop
* strip): drops the redundant title header, keeps the breadcrumb + action
* selector so it reads as one continuous walk rather than a nested viewer. */
embedded?: boolean;
/** (embedded) Leading cards for the decision strip — the preflop seat cards,
* so the preflop line + postflop tree render as one continuous action bar. */
stripPrefix?: ReactNode;
/** (embedded) The game card, pinned left of the strip (above it on phones). */
stripLead?: ReactNode;
/** Enables "Edit strategy" node locking (#268) — see `ViewerLocking`. */
locking?: ViewerLocking;
/** Enables structural node edits (#390) — see `ViewerNodeEditing`. */
nodeEditing?: ViewerNodeEditing;
}) {
const [path, setPath] = useState<string[]>([]);
const [subs, setSubs] = useState<Record<string, SubSolve>>({});
const [solving, setSolving] = useState<{ card: string; street: string } | null>(null);
const [progress, setProgress] = useState<SolverProgress | null>(null);
const [solveError, setSolveError] = useState<string | null>(null);
// Pending strategy edits (#268), keyed by the absolute path — sent as
// aggregate locks on "Re-solve with edits". Kept even while browsing away
// so several nodes can be edited before one re-solve.
const [locks, setLocks] = useState<Record<string, { path: string[]; freqs: number[] }>>({});
// Path key the lock editor is open at — navigating elsewhere implicitly
// closes it (no effect needed: the key no longer matches).
const [editorAt, setEditorAt] = useState<string | null>(null);
// Same pattern for the structural Edit Node modal (#390).
const [nodeEditorAt, setNodeEditorAt] = useState<string | null>(null);
// (embedded) Chance-node card picking happens in a bottom drawer — the same
// fluid gesture as picking the flop in the Explorer. Auto-opens on arriving
// at a chance node; the strip's dashed card reopens it if dismissed.
const [chancePickerOpen, setChancePickerOpen] = useState(false);
const handleRef = useRef<SolveHandle | null>(null);
const solveSeq = useRef(0);
const { meta } = bundle;
const ctx = useMemo(() => containingSolution(bundle, subs, path), [bundle, subs, path]);
const rel = useMemo(() => path.slice(ctx.base.length), [path, ctx]);
const ctxNodes = useMemo(() => ctx.result.nodes ?? [], [ctx]);
const node = useMemo(() => nodeAtPath(ctxNodes, rel), [ctxNodes, rel]);
const segs = useMemo(() => nextSegments(ctxNodes, rel), [ctxNodes, rel]);
// ---- node locking (#268) ----------------------------------------------------
const pathKey = keyOf(path);
const pendingLock = locks[pathKey];
const lockCount = Object.keys(locks).length;
// Edits are scoped to the base solution's own dump: a spliced sub-solve is a
// different engine job whose action encoding (re-rooted pot → re-derived bet
// amounts) can drift from the base tree's path labels, and the base job's
// snapshot is what the locked re-solve warm-starts from.
const canEditHere = Boolean(locking) && !!node && ctx.base.length === 0;
const editingLock = editorAt === pathKey;
const setEditingLock = (open: boolean) => setEditorAt(open ? pathKey : null);
// Structural node edits share the same base-solution-only scope.
const canEditNodeHere = Boolean(nodeEditing) && !!node && ctx.base.length === 0;
const nodeEditOpen = nodeEditorAt === pathKey;
const nodeEdited =
canEditNodeHere && (nodeEditing?.editedKeys.includes(toEditPath(path).join(" ")) ?? false);
// The node as displayed: a pending aggregate lock overrides every combo's
// strategy, so the grid + summaries show exactly what the lock will play.
const displayNode = useMemo(() => {
if (!node || !pendingLock) return node;
return { ...node, hands: node.hands.map((h) => ({ ...h, freqs: pendingLock.freqs })) };
}, [node, pendingLock]);
const applyLock = (freqs: number[]) => {
setLocks((m) => ({ ...m, [pathKey]: { path: [...path], freqs } }));
setEditingLock(false);
};
const removeLock = () => {
setLocks((m) => {
const next = { ...m };
delete next[pathKey];
return next;
});
setEditingLock(false);
};
const resolveWithLocks = () => {
if (!locking || locking.busy) return;
try {
const lockedNodes = Object.values(locks).map((l) => {
const n = nodeAtPath(bundle.result.nodes ?? [], l.path);
if (!n) {
throw new Error(`locked node at "${l.path.join(" › ")}" is not in this solution`);
}
return buildAggregateLock(l.path, n, l.freqs);
});
locking.onResolve(lockedNodes);
} catch (e) {
setSolveError(e instanceof Error ? e.message : String(e));
}
};
// Full board = root board + every dealt card along the (absolute) path.
const baseBoard = useMemo(() => boardCards(bundle.config.board), [bundle]);
const runout = useMemo(
() => path.filter(isDealSegment).map(dealCard),
[path],
);
const fullBoard = useMemo(() => [...baseBoard, ...runout], [baseBoard, runout]);
// Reach state at the current point, inside the containing solution (whose
// config ranges already encode reach up to its root).
const reach: ReachState | null = useMemo(() => {
try {
return walkReach(ctx.config, ctx.result, rel);
} catch {
return null;
}
}, [ctx, rel]);
// Per-combo EV is only dumped at solve roots (the bundle's start node and
// each spliced sub-solve's start node).
const evByCombo = useMemo(() => {
if (rel.length !== 0) return null;
const m = new Map<string, number>();
for (const h of ctx.result.root.hands) if (h.ev !== undefined) m.set(h.combo, h.ev);
return m.size > 0 ? m : null;
}, [ctx, rel]);
const actorReach = node ? (node.player === 0 ? reach?.oop : reach?.ip) ?? null : null;
// Aggregate, reach-weighted action items for the summary panel — computed
// over the DISPLAYED strategy, so a pending lock's split shows everywhere.
const actionItems = useMemo(() => {
if (!displayNode) return [];
const n = displayNode.actions.length;
const sums = new Array<number>(n).fill(0);
let denom = 0;
for (const hand of displayNode.hands) {
const w = actorReach ? (actorReach.get(hand.combo) ?? 0) : 1;
if (w <= 0) continue;
denom += w;
for (let a = 0; a < n; a++) sums[a] += w * (hand.freqs[a] ?? 0);
}
return displayNode.actions.map((action, a) => ({
seg: actionSegment(action),
label: action.label,
add: action.add,
color: ACTION_COLORS[action.label],
freq: denom > 0 ? sums[a] / denom : 0,
combos: sums[a],
}));
}, [displayNode, actorReach]);
// ---- chance-node handling -------------------------------------------------
const isChance = !node && (segs.length > 0 ? segs.every(isDealSegment) : chanceHeuristic());
function chanceHeuristic(): boolean {
if (path.length === 0) return false;
const last = path[path.length - 1];
if (isDealSegment(last) || last === "Fold") return false;
if (fullBoard.length >= 5) return false;
if (reach && reach.effStack <= 0.01) return false;
return true;
}
const availableCards = useMemo(() => {
const set = new Set(segs.filter(isDealSegment).map(dealCard));
// Sub-solves rooted directly below this point are also instantly viewable.
for (const key of Object.keys(subs)) {
const base = key.split(" ");
if (base.length === path.length + 1 && isPathPrefix(path, base)) {
const seg = base[base.length - 1];
if (isDealSegment(seg)) set.add(dealCard(seg));
}
}
return set;
}, [segs, subs, path]);
const nextStreet = streetNameForBoardLen(fullBoard.length + 1);
// Open the drawer the moment an embedded walk lands on a chance node — the
// pick is the next decision, same gesture as the Explorer's flop drawer.
useEffect(() => {
if (embedded && isChance) setChancePickerOpen(true);
}, [embedded, isChance, pathKey]);
const pickCard = async (card: string) => {
if (solving) return;
const seg = `deal:${card}`;
const nextPath = [...path, seg];
if (availableCards.has(card)) {
setSolveError(null);
setPath(nextPath);
return;
}
// Solve the subgame rooted after this card, on demand. When the containing
// solution emitted CFR-D carry that is valid at this boundary, the child is
// a *safe* re-solve (gadget); otherwise it falls back to the reach-range
// bootstrap (#233, resolve-carry.ts).
let request: SolveRequest;
let resolveMode: SubSolve["resolveMode"] = "reach";
try {
const carry = carryForChild(ctx.config, ctx.result, rel, card);
request = buildChildRequest(
ctx.config,
ctx.result,
rel,
card,
carry ? { resolve: carry.resolve } : undefined,
);
if (carry) resolveMode = "gadget";
} catch (e) {
setSolveError(e instanceof Error ? e.message : String(e));
return;
}
const seq = ++solveSeq.current;
setSolving({ card, street: nextStreet.toLowerCase() });
setProgress(null);
setSolveError(null);
const handle = startSolve(request, (p) => {
if (solveSeq.current === seq) setProgress(p);
});
handleRef.current = handle;
try {
const outcome = await handle.promise;
setSubs((s) => ({
...s,
[keyOf(nextPath)]: { config: request, result: outcome.result, resolveMode },
}));
if (solveSeq.current === seq) setPath(nextPath);
} catch (e) {
if (solveSeq.current === seq) {
setSolveError(e instanceof Error ? e.message : String(e));
}
} finally {
if (solveSeq.current === seq) {
setSolving(null);
setProgress(null);
}
handleRef.current = null;
}
};
const cancelSolve = () => {
solveSeq.current++;
handleRef.current?.cancel().catch(() => {});
setSolving(null);
setProgress(null);
};
const jumpTo = (i: number) => {
if (solving) cancelSolve();
setSolveError(null);
setPath(path.slice(0, i));
};
// ---- breadcrumb model -------------------------------------------------------
const crumbs = useMemo<Crumb[]>(() => {
const out: Crumb[] = [
{
index: 0,
kind: "street",
text: streetNameForBoardLen(baseBoard.length),
cards: baseBoard,
},
];
for (let i = 0; i < path.length; i++) {
const seg = path[i];
if (isDealSegment(seg)) {
out.push({
index: i + 1,
kind: "street",
text: streetNameForBoardLen(baseBoard.length + path.slice(0, i + 1).filter(isDealSegment).length),
card: dealCard(seg),
});
continue;
}
const c = containingSolution(bundle, subs, path.slice(0, i));
const n = nodeAtPath(c.result.nodes ?? [], path.slice(c.base.length, i));
const actor = n ? (n.player === 0 ? meta.oopLabel : meta.ipLabel) : "?";
const locked = Boolean(n?.locked) || keyOf(path.slice(0, i)) in locks;
out.push({ index: i + 1, kind: "action", text: seg, actor, locked });
}
return out;
}, [path, bundle, subs, baseBoard, meta, locks]);
const actingLabel = node ? (node.player === 0 ? meta.oopLabel : meta.ipLabel) : null;
const isSubgame = ctx.base.length > 0;
// ---------------------------------------------------------------------------
return (
<div className="flex flex-col gap-4">
{/* Header: title + board + geometry. Dropped in embedded mode — the
Explorer's preflop strip already carries the spot context. */}
{embedded ? null : (
<div className="flex flex-wrap items-center justify-between gap-3">
<div className="flex min-w-0 items-center gap-3">
{onBack ? (
<button
type="button"
onClick={onBack}
aria-label="Back to solutions"
className="flex size-8 shrink-0 items-center justify-center rounded-md border border-border text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<ArrowLeft className="size-4" />
</button>
) : null}
<div className="flex min-w-0 flex-col">
<span className="truncate text-sm font-semibold text-foreground">{bundle.title}</span>
<span className="text-xs text-muted-foreground">
{meta.oopLabel} (OOP) vs {meta.ipLabel} (IP) · pot {meta.potBb.toFixed(1)}bb ·{" "}
{meta.effStackBb.toFixed(1)}bb behind · {meta.betSizing}
</span>
</div>
</div>
<div className="flex items-center gap-3">
{drillHref ? (
<Link
href={drillHref}
className="flex shrink-0 items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<Dumbbell className="size-3.5" />
Drill this spot
</Link>
) : null}
<span className="text-[11px] text-muted-foreground tabular-nums">
{/* Subgame re-solves are exact even inside an AI bundle, so their
exploitability is a real grade; the AI root solve has none. */}
{!isSubgame && bundle.config.aiSolve
? "AI solve · expl n/a"
: `expl ${ctx.result.exploitability.percent.toFixed(2)}%${
isSubgame
? ctx.resolveMode === "gadget"
? " (safe re-solve · CFR-D)"
: " (re-solved subgame · approx ranges)"
: ""
}`}
</span>
</div>
</div>
)}
{/* Embedded: a horizontal decision strip that extends the preflop action
bar (flop → postflop decisions), the action selector as navigator.
Standalone: the compact breadcrumb. */}
{embedded ? (
<DecisionStrip
prefix={stripPrefix}
lead={stripLead}
crumbs={crumbs}
actingLabel={actingLabel}
actingLocked={Boolean(node?.locked) || Boolean(pendingLock)}
pot={node ? node.pot : null}
actionItems={actionItems}
isChance={isChance}
nextStreet={nextStreet}
onChanceClick={() => setChancePickerOpen(true)}
onJump={jumpTo}
onPick={(seg) => {
setSolveError(null);
setPath([...path, seg]);
}}
editing={
canEditHere || canEditNodeHere
? {
pendingLock: Boolean(pendingLock),
dumpLocked: Boolean(node?.locked),
atCap: !pendingLock && lockCount >= MAX_LOCKED_NODES,
canEditNode: canEditNodeHere,
nodeEdited,
canLock: canEditHere,
onEditNode: () => setNodeEditorAt(pathKey),
onEditFreqs: () => setEditingLock(true),
}
: undefined
}
/>
) : (
<div className="flex flex-wrap items-center gap-1.5 rounded-xl border border-border bg-card/40 px-3 py-2 text-xs">
{crumbs.map((c, i) => {
const isCurrent = i === crumbs.length - 1;
return (
<span key={i} className="flex items-center gap-1.5">
{i > 0 ? <span className="text-zinc-600">›</span> : null}
<button
type="button"
onClick={() => jumpTo(c.index)}
className={`flex items-center gap-1 rounded-md px-1.5 py-0.5 transition-colors ${
isCurrent
? "bg-accent text-foreground"
: "text-muted-foreground hover:bg-accent/60 hover:text-foreground"
}`}
>
{c.kind === "street" ? (
<>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">
{c.text}
</span>
{c.cards?.map((card, j) => <CardText key={j} card={card} />)}
{c.card ? <CardText card={c.card} /> : null}
</>
) : (
<>
<span className="font-medium text-zinc-500">{c.actor}</span>
<span>{c.text}</span>
{c.locked ? <Lock className="size-3 text-amber-400" /> : null}
</>
)}
</button>
</span>
);
})}
{node && actingLabel ? (
<span className="ml-auto flex items-center gap-2 pl-2 text-[11px]">
{node.locked || pendingLock ? (
<span className="flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 font-semibold text-amber-400">
<Lock className="size-3" /> Locked
</span>
) : null}
<span className="rounded-full bg-foreground px-2 py-0.5 font-semibold text-background">
{actingLabel} to act
</span>
<span className="text-muted-foreground tabular-nums">
pot {node.pot.toFixed(1)}bb
</span>
</span>
) : null}
</div>
)}
{solveError ? (
<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-4 py-2.5 text-sm text-destructive">
{solveError}
</div>
) : null}
{node && displayNode ? (
<>
{/* ---- locked-node re-solve bar (#268) ----
The "Edit strategy" entry point lives on the node card itself
(DecisionStrip's lock icon), so this bar stays out of the way until
at least one node is actually locked and there is a re-solve to fire. */}
{locking && canEditHere && lockCount > 0 ? (
<div className="flex flex-wrap items-center gap-2 rounded-xl border border-border bg-card/40 px-3 py-2">
{node.locked ? (
<span className="flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] font-medium text-amber-400">
<Lock className="size-3" /> Locked in this solve
</span>
) : null}
{pendingLock ? (
<span className="flex items-center gap-1 rounded-full bg-amber-500/15 px-2 py-0.5 text-[11px] font-medium text-amber-400">
<Lock className="size-3" /> Locked — pending re-solve
</span>
) : null}
{pendingLock && !editingLock ? (
<button
type="button"
onClick={removeLock}
className="rounded-md border border-border bg-card px-2.5 py-1 text-[11px] font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
Remove lock
</button>
) : null}
<span className="ml-auto flex items-center gap-2">
<span className="text-[11px] text-muted-foreground tabular-nums">
{lockCount} node{lockCount === 1 ? "" : "s"} locked
</span>
<button
type="button"
onClick={resolveWithLocks}
disabled={locking.busy}
className="flex items-center gap-1.5 rounded-md bg-foreground px-2.5 py-1 text-[11px] font-semibold text-background transition-opacity hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"
>
{locking.busy ? (
<>
<Loader2 className="size-3 animate-spin" /> Re-solving…
</>
) : (
<>
<Lock className="size-3" /> Re-solve with edits
</>
)}
</button>
</span>
</div>
) : locking && isSubgame ? (
<p className="text-[11px] text-muted-foreground/70">
Strategy edits are available in the base solution only — this node is inside an
on-demand subgame re-solve.
</p>
) : null}
{editingLock ? (
<LockEditor
key={pathKey}
actions={node.actions}
pot={node.pot}
initial={pendingLock ? pendingLock.freqs : actionItems.map((it) => it.freq)}
hasLock={Boolean(pendingLock)}
onApply={applyLock}
onRemove={removeLock}
onCancel={() => setEditingLock(false)}
/>
) : null}
{nodeEditing && nodeEditOpen && canEditNodeHere ? (
<NodeEditModal
key={`ne-${pathKey}`}
actorLabel={actingLabel ?? ""}
pot={node.pot}
actions={node.actions}
hasEdits={nodeEditing.editedKeys.length > 0}
busy={nodeEditing.busy}
onConfirm={(sizes, allin) => {
setNodeEditorAt(null);
nodeEditing.onApply(toEditPath(path), sizes, allin);
}}
onClearAll={() => {
setNodeEditorAt(null);
nodeEditing.onClearAll();
}}
onClose={() => setNodeEditorAt(null)}
/>
) : null}
{embedded ? (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,320px)]">
<StrategyGrid
actions={displayNode.actions}
hands={displayNode.hands}
reach={actorReach}
/>
<PostflopHandSummary
actions={displayNode.actions}
hands={displayNode.hands}
reach={actorReach}
evByCombo={evByCombo}
/>
</div>
) : (
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_minmax(0,340px)]">
<StrategyGrid
actions={displayNode.actions}
hands={displayNode.hands}
reach={actorReach}
/>
<div className="flex flex-col gap-5">
{/* Action summary — one wide bar per action; click to advance */}
<div className="flex flex-col gap-2">
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">
Actions
</span>
<div className="flex flex-col gap-1.5">
{actionItems.map((it) => (
<button
key={it.seg}
type="button"
onClick={() => {
setSolveError(null);
setPath([...path, it.seg]);
}}
className="group flex flex-col gap-1.5 rounded-lg border border-border bg-card/40 px-3 py-2 text-left transition-colors hover:border-foreground/30 hover:bg-accent/40"
>
<div className="flex items-center justify-between gap-2">
<span className="flex items-center gap-2 text-sm font-medium text-foreground">
<span
className="size-3 shrink-0 rounded-[3px]"
style={{ backgroundColor: it.color }}
/>
{it.label}
{it.add > 0 ? (
<span className="text-xs text-muted-foreground tabular-nums">
{Math.round(it.add * 10) / 10}bb
{node.pot > 0 && (it.label === "Bet" || it.label === "Raise")
? ` · ${Math.round((it.add / node.pot) * 100)}% pot`
: ""}
</span>
) : null}
</span>
<span className="flex flex-col items-end leading-tight">
<span className="text-sm font-semibold text-foreground tabular-nums">
{(it.freq * 100).toFixed(1)}%
</span>
<span className="text-[10px] text-muted-foreground tabular-nums">
{it.combos.toFixed(1)} combos
</span>
</span>
</div>
<div className="h-1.5 w-full overflow-hidden rounded-full bg-white/[0.06]">
<div
className="h-full rounded-full"
style={{
width: `${Math.max(it.freq * 100, it.freq > 0 ? 1 : 0)}%`,
backgroundColor: it.color,
}}
/>
</div>
</button>
))}
</div>
</div>
<PostflopHandSummary
actions={displayNode.actions}
hands={displayNode.hands}
reach={actorReach}
evByCombo={evByCombo}
/>
</div>
</div>
)}
</>
) : isChance ? (
// Embedded: the picker lives in a bottom drawer (the strip's dashed
// card reopens it); a solve in flight keeps its progress visible even
// with the drawer dismissed. Standalone keeps the inline picker.
embedded ? (
<>
{chancePickerOpen ? (
<BottomSheet
title={`Pick the ${nextStreet.toLowerCase()} card`}
onClose={() => setChancePickerOpen(false)}
>
<ChanceCardPicker
inSheet
street={nextStreet}
dead={fullBoard}
available={availableCards}
solving={solving}
progress={progress}
onPick={pickCard}
onCancel={cancelSolve}
/>
</BottomSheet>
) : null}
{solving && !chancePickerOpen ? (
<div className="flex items-center gap-3 rounded-lg border border-border bg-card/40 px-4 py-2.5 text-sm text-muted-foreground">
<Loader2 className="size-4 shrink-0 animate-spin" />
<span className="tabular-nums">
Solving {solving.street} <CardText card={solving.card} className="h-5 w-4 align-middle text-[13px]" />…{" "}
{progress
? `iter ${progress.iter} · expl ${progress.percent.toFixed(2)}%`
: "starting"}
</span>
<button
type="button"
onClick={cancelSolve}
aria-label="Cancel solve"
className="ml-auto rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
) : null}
</>
) : (
<ChanceCardPicker
street={nextStreet}
dead={fullBoard}
available={availableCards}
solving={solving}
progress={progress}
onPick={pickCard}
onCancel={cancelSolve}
/>
)
) : (
<TerminalCard path={path} board={fullBoard} reach={reach} />
)}
</div>
);
}
// ---------------------------------------------------------------------------
// Decision strip — the horizontal action-bar navigator (embedded mode)
// ---------------------------------------------------------------------------
/** Edit controls on the acting card — pencil opens the structural Edit Node
* modal (#390), lock opens the frequency lock editor (#268). */
interface StripEditing {
pendingLock: boolean;
/** Locked in the solve's own dump — can't be removed from here. */
dumpLocked: boolean;
/** MAX_LOCKED_NODES reached and this node isn't one of them. */
atCap: boolean;
/** Structural node edits are available here (pencil shown). */
canEditNode: boolean;
/** This node has an active node edit (pencil highlighted). */
nodeEdited: boolean;
/** Frequency locking is available here (lock shown). */
canLock: boolean;
onEditNode: () => void;
onEditFreqs: () => void;
}
/** Extends the Explorer's preflop seat strip into postflop: a flop card, one
* card per taken action (click to rewind), and an active card whose action
* rows advance the line — GTO-Wizard's continuous navigator. */
function DecisionStrip({
prefix,
lead,
crumbs,
actingLabel,
actingLocked = false,
pot,
actionItems,
isChance,
nextStreet,
onChanceClick,
onJump,
onPick,
editing,
}: {
prefix?: ReactNode;
lead?: ReactNode;
crumbs: Crumb[];
actingLabel: string | null;
/** The acting node is locked (#268) — dump flag or pending edit. */
actingLocked?: boolean;
pot: number | null;
actionItems: StripActionItem[];
isChance: boolean;
nextStreet: string;
/** Reopens the chance-card drawer (the dashed card is the affordance). */
onChanceClick?: () => void;
onJump: (index: number) => void;
onPick: (seg: string) => void;
/** Present when the acting node is editable (base solution + locking on). */
editing?: StripEditing;
}) {
const CARD = "flex min-h-[104px] w-[136px] shrink-0 flex-col gap-1 rounded-xl border p-2";
const scrollerRef = useRef<HTMLDivElement>(null);
// Keep the newest (acting) card in view: the strip grows rightward as the
// line advances, and on macOS the overlay scrollbar gives no affordance that
// there's more to the right.
useEffect(() => {
// Instant, not smooth — smooth scrollTo is dropped entirely in some
// embedded-Chromium contexts. No rAF: it never fires in hidden tabs.
const el = scrollerRef.current;
if (el) el.scrollLeft = el.scrollWidth;
}, [crumbs.length, actingLabel, isChance]);
// Plain mouse wheels only scroll vertically — translate that into horizontal
// scroll while hovering the strip. Native listener: React's onWheel is
// passive, so it can't preventDefault the page scroll.
useEffect(() => {
const el = scrollerRef.current;
if (!el) return;
const onWheel = (e: WheelEvent) => {
if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) return; // trackpad h-swipe works natively
if (el.scrollWidth <= el.clientWidth) return;
el.scrollLeft += e.deltaY;
e.preventDefault();
};
el.addEventListener("wheel", onWheel, { passive: false });
return () => el.removeEventListener("wheel", onWheel);
}, []);
return (
<RailRow lead={lead} scrollerRef={scrollerRef}>
{prefix}
{crumbs.map((c, i) =>
c.kind === "street" ? (
<button
key={i}
type="button"
onClick={() => onJump(c.index)}
className={`${CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">{c.text}</span>
<div className="mt-auto flex flex-wrap items-center gap-1 text-lg font-bold tabular-nums">
{c.cards?.map((card, j) => <CardText key={j} card={card} className="h-8 w-6 text-xl" />)}
{c.card ? <CardText card={c.card} className="h-8 w-6 text-xl" /> : null}
</div>
</button>
) : (
<button
key={i}
type="button"
onClick={() => onJump(c.index)}
className={`${CARD} border-border bg-card/40 text-left transition-colors hover:border-foreground/30`}
>
<span className="flex items-center gap-1 text-xs font-semibold text-muted-foreground">
{c.actor}
{c.locked ? <Lock className="size-3 text-amber-400" /> : null}
</span>
<span className="mt-auto inline-block max-w-full truncate rounded bg-accent px-2 py-0.5 text-xs font-semibold text-foreground">
{c.text}
</span>
</button>
),
)}
{actingLabel ? (
<div
className={`flex min-h-[104px] shrink-0 flex-row rounded-xl border ${
editing ? "w-[184px]" : "w-[156px]"
} border-foreground/50 bg-accent/50`}
>
<div className="flex min-w-0 flex-1 flex-col gap-1 p-2">
<div className="flex items-center justify-between">
<span className="flex items-center gap-1 text-xs font-semibold text-foreground">
{actingLabel}
{actingLocked ? <Lock className="size-3 text-amber-400" /> : null}
</span>
{pot != null ? (
<span className="text-[10px] text-muted-foreground tabular-nums">
pot {pot.toFixed(1)}
</span>
) : null}
</div>
<div className="flex flex-col">
{actionItems.map((it) => (
<button
key={it.seg}
type="button"
onClick={() => onPick(it.seg)}
className="flex items-center justify-between gap-1 rounded px-1 py-0.5 text-left transition-colors hover:bg-accent"
>
<span className="flex min-w-0 items-center gap-1 truncate text-xs text-foreground">
<span
className="size-2 shrink-0 rounded-[2px]"
style={{ backgroundColor: it.color }}
/>
{it.label}
</span>
<span className="shrink-0 text-[11px] font-semibold text-foreground tabular-nums">
{(it.freq * 100).toFixed(0)}%
</span>
</button>
))}
</div>
</div>
{editing ? (
<div className="flex flex-col items-center gap-1 border-l border-foreground/20 p-1.5">
{editing.canEditNode ? (
<button
type="button"
onClick={editing.onEditNode}
title={editing.nodeEdited ? "Edit node (edited)" : "Edit node — bet sizes"}
aria-label="Edit node"
className={`rounded-md p-1 transition-colors ${
editing.nodeEdited
? "text-amber-400 hover:bg-amber-500/15"
: "text-muted-foreground hover:bg-accent hover:text-foreground"
}`}
>
<Pencil className="size-3.5" />
</button>
) : null}
{editing.canLock ? (
<button
type="button"
onClick={editing.onEditFreqs}
disabled={editing.atCap}
title={
editing.atCap
? `At most ${MAX_LOCKED_NODES} nodes can be locked per re-solve`
: "Lock strategy — edit frequencies"
}
aria-label="Lock strategy"
className={`rounded-md p-1 transition-colors disabled:cursor-not-allowed disabled:opacity-50 ${
editing.pendingLock || editing.dumpLocked
? "text-amber-400 hover:bg-amber-500/15"
: "text-muted-foreground hover:bg-accent hover:text-foreground"
}`}
>
<Lock className="size-3.5" />
</button>
) : null}
</div>
) : null}
</div>
) : isChance ? (
<button
type="button"
onClick={onChanceClick}
disabled={!onChanceClick}
className={`${CARD} items-center justify-center border-dashed border-foreground/40 bg-accent/30 text-center`}
>
<span className="text-[10px] uppercase tracking-wide text-zinc-500">{nextStreet}</span>
<span className="text-xs text-muted-foreground">pick a card ↓</span>
</button>
) : null}
</RailRow>
);
}
// ---------------------------------------------------------------------------
// Chance node: pick the next card
// ---------------------------------------------------------------------------
const RANKS = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"];
const SUITS = ["s", "h", "d", "c"] as const;
function ChanceCardPicker({
street,
dead,
available,
solving,
progress,
onPick,
onCancel,
inSheet = false,
}: {
street: string;
dead: string[];
available: Set<string>;
solving: { card: string; street: string } | null;
progress: SolverProgress | null;
onPick: (card: string) => void;
onCancel: () => void;
/** Rendered inside a BottomSheet: the sheet header already carries the title,
* and the sheet provides the frame — keep just the hint + grid. */
inSheet?: boolean;
}) {
const deadSet = new Set(dead);
const anyOnDemand = RANKS.some((r) =>
SUITS.some((s) => !deadSet.has(`${r}${s}`) && !available.has(`${r}${s}`)),
);
return (
<div
className={
inSheet
? "flex flex-col items-center gap-4 pb-2"
: "flex flex-col items-center gap-4 rounded-xl border border-border bg-card/40 px-4 py-6"
}
>
<div className="flex flex-col items-center gap-1 text-center">
{inSheet ? null : (
<span className="text-sm font-medium text-foreground">
Pick the {street.toLowerCase()} card
</span>
)}
<span className="text-xs text-muted-foreground">
{anyOnDemand
? "Dimmed cards aren't in this bundle — picking one solves that runout on demand (~5–15s)."
: "Every runout is in this bundle — pick any card."}
</span>
</div>
<div className="flex w-full max-w-[520px] flex-col gap-1">
{SUITS.map((suit) => (
<div key={suit} className="grid grid-cols-[repeat(13,minmax(0,1fr))] gap-1">
{RANKS.map((rank) => {
const card = `${rank}${suit}`;
const isDead = deadSet.has(card);
const instant = available.has(card);
const isSolvingThis = solving?.card === card;
return (
<button
key={card}
type="button"
disabled={isDead || !!solving}
onClick={() => onPick(card)}
style={{
backgroundColor: suitTile(suit).bg,
opacity: isDead ? 0.15 : isSolvingThis ? 1 : solving ? 0.35 : instant ? 1 : 0.55,
}}
className={`relative flex h-8 items-center justify-center rounded border border-white/25 text-sm font-bold text-white transition ${
isDead || solving ? "cursor-not-allowed" : "hover:brightness-110"
} ${isSolvingThis ? "ring-2 ring-white/80" : ""}`}
title={
isDead
? `${card} is dead`
: instant
? `${rank}${SUIT_GLYPH[suit]}`
: `${rank}${SUIT_GLYPH[suit]} — solved on demand`
}
>
{isSolvingThis ? <Loader2 className="size-4 animate-spin" /> : rank}
</button>
);
})}
</div>
))}
</div>
{solving ? (
<div className="flex items-center gap-3 rounded-lg border border-border bg-card/60 px-4 py-2.5 text-sm text-muted-foreground">
<Loader2 className="size-4 animate-spin" />
<span className="tabular-nums">
Solving {solving.street} <CardText card={solving.card} className="h-5 w-4 align-middle text-[13px]" />…{" "}
{progress
? `iter ${progress.iter} · expl ${progress.percent.toFixed(2)}%`
: "starting"}
</span>
<button
type="button"
onClick={onCancel}
aria-label="Cancel solve"
className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
) : null}
</div>
);
}
// ---------------------------------------------------------------------------
// Terminal states
// ---------------------------------------------------------------------------
function TerminalCard({
path,
board,
reach,
}: {
path: string[];
board: string[];
reach: ReachState | null;
}) {
const last = path[path.length - 1] ?? "";
let text: string;
if (last === "Fold") {
text = "The hand ends here — the last player folded.";
} else if (board.length >= 5) {
text = "Showdown — the river action is complete.";
} else if (reach && reach.effStack <= 0.01) {
text = "Both players are all-in — the remaining runout has no more decisions.";
} else {
text = "End of this line.";
}
return (
<div className="rounded-xl border border-dashed border-border bg-card/40 px-6 py-8 text-center text-sm text-muted-foreground">
{text}
</div>
);
}
components/explorer/tree-flow.tsx
"use client";
// React Flow game-tree visualization with EDITABLE nodes (reactflow.dev
// editable-nodes pattern). Every action node is a card: its bet/raise sizes
// are editable inline, and committing an edit lowers to the same engine
// `NodeEdit` records the Tree-edit strip uses — so pruning here changes the
// tree the solver ACTUALLY builds, not just the picture.
//
// After a solve (dump_nodes), edges carry the aggregate strategy frequency of
// their action: thick/bright = used, thin/dashed = ~never used → prime
// pruning candidates. Deal segments are normalized ("deal:Td" → "deal") and
// averaged, so a turn edge shows the mean frequency across every turn card.
import { useCallback, useEffect, useMemo, useState } from "react";
import {
Background,
Controls,
Handle,
MiniMap,
Position,
ReactFlow,
type Edge,
type Node,
type NodeProps,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { ChevronDown, ChevronRight, RotateCcw } from "lucide-react";
import { ACTION_COLORS } from "@/components/solver/strategy-grid";
import type { SolverResult } from "@/lib/solver/types";
import { buildFullTree, type FullTree, type FullTreeNode } from "@/lib/explorer/tree-sim";
import {
pathLabel,
type AllinChoice,
type NodeEdit,
type SizingBase,
type SizingGrid,
} from "./tree-sizing-editor";
// ---------------------------------------------------------------------------
// Frequency index — path key (deals normalized) → token → mean frequency.
// ---------------------------------------------------------------------------
const normalizeSeg = (s: string) => (s.startsWith("deal") ? "deal" : s);
const freqKey = (path: string[]) => path.map(normalizeSeg).join("|");
type FreqIndex = Map<string, Map<string, { sum: number; n: number }>>;
function buildFreqIndex(result: SolverResult | null | undefined): FreqIndex | null {
if (!result) return null;
const idx: FreqIndex = new Map();
const feed = (path: string[], node: { actions: { label: string; add: number }[]; hands: { freqs: number[] }[] }) => {
if (node.hands.length === 0) return;
const key = freqKey(path);
let byToken = idx.get(key);
if (!byToken) idx.set(key, (byToken = new Map()));
node.actions.forEach((a, i) => {
let mean = 0;
for (const h of node.hands) mean += h.freqs[i] ?? 0;
mean /= node.hands.length;
const token = pathLabel(a.label, a.add);
const acc = byToken.get(token) ?? { sum: 0, n: 0 };
acc.sum += mean;
acc.n += 1;
byToken.set(token, acc);
});
};
feed([], result.root);
for (const n of result.nodes ?? []) feed(n.path, n);
return idx.size > 0 ? idx : null;
}
const lookupFreq = (idx: FreqIndex | null, path: string[], token: string): number | null => {
const acc = idx?.get(freqKey(path))?.get(token);
return acc && acc.n > 0 ? acc.sum / acc.n : null;
};
// ---------------------------------------------------------------------------
// Layout — tidy left-to-right tree over the VISIBLE nodes only.
// ---------------------------------------------------------------------------
const NODE_W = 250;
const COL_GAP = 90;
const ROW_GAP = 18;
const nodeHeight = (n: FullTreeNode): number =>
n.kind === "action" ? 92 + n.actions.length * 19 : 40;
// ---------------------------------------------------------------------------
// Custom node components
// ---------------------------------------------------------------------------
interface ActionNodeData {
tree: FullTreeNode;
freqs: (number | null)[];
collapsed: boolean;
onToggleCollapse: (id: string) => void;
onCommitSizes: (path: string[], sizes: string) => void;
onToggleAllin: (path: string[]) => void;
onResetEdit: (path: string[]) => void;
[key: string]: unknown;
}
const fmtFrac = (f: number) => (Math.round(f * 100) / 100).toString();
function ActionNode({ data }: NodeProps<Node<ActionNodeData>>) {
const { tree, freqs, collapsed } = data;
const fracs = tree.actions.filter((a) => a.frac !== undefined).map((a) => fmtFrac(a.frac!));
const allinOn = tree.actions.some((a) => a.label === "AllIn");
// Local draft so typing doesn't rebuild the tree on every keystroke.
const [draft, setDraft] = useState<string | null>(null);
const shownSizes = draft ?? (tree.edit && tree.edit.sizes !== "" ? tree.edit.sizes : fracs.join(", "));
const commit = () => {
if (draft === null) return;
data.onCommitSizes(tree.path, draft);
setDraft(null);
};
return (
<div
className={`rounded-lg border bg-card text-left shadow-sm ${
tree.edit ? "border-amber-500/60" : "border-border"
}`}
style={{ width: NODE_W }}
>
<Handle type="target" position={Position.Left} className="!bg-border" />
<Handle type="source" position={Position.Right} className="!bg-border" />
<div className="flex items-center gap-1.5 border-b border-border/60 px-2 py-1.5">
<button
className="nodrag rounded p-0.5 hover:bg-accent"
onClick={() => data.onToggleCollapse(tree.id)}
title={collapsed ? "Expand subtree" : "Collapse subtree"}
>
{collapsed ? <ChevronRight size={12} /> : <ChevronDown size={12} />}
</button>
<span
className={`rounded px-1 text-[10px] font-bold uppercase ${
tree.role === "oop" ? "bg-sky-500/20 text-sky-400" : "bg-amber-500/20 text-amber-400"
}`}
>
{tree.role}
</span>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground">{tree.street}</span>
<span className="ml-auto text-[10px] tabular-nums text-muted-foreground">
pot {Math.round(tree.pot * 10) / 10}
{tree.toCall > 1e-9 ? ` · call ${Math.round(tree.toCall * 10) / 10}` : ""}
</span>
{tree.edit ? (
<button
className="nodrag rounded p-0.5 text-amber-400 hover:bg-accent"
onClick={() => data.onResetEdit(tree.path)}
title="Reset node edit"
>
<RotateCcw size={11} />
</button>
) : null}
</div>
<div className="flex flex-col px-2 py-1">
{tree.actions.map((a, i) => {
const f = freqs[i];
return (
<div key={a.token} className="flex items-center gap-1.5 py-px text-[11px] leading-[18px]">
<span
className="inline-block size-2 shrink-0 rounded-full"
style={{ backgroundColor: ACTION_COLORS[a.label] ?? "#888" }}
/>
<span className="truncate text-foreground">{a.token}</span>
{a.frac !== undefined ? (
<span className="text-muted-foreground/60">{Math.round(a.frac * 100)}%pot</span>
) : null}
{f !== null ? (
<span
className={`ml-auto tabular-nums ${
f < 0.005 ? "text-rose-400/80" : "text-muted-foreground"
}`}
>
{(f * 100).toFixed(f < 0.1 ? 1 : 0)}%
</span>
) : null}
</div>
);
})}
</div>
<div className="flex items-center gap-1.5 border-t border-border/60 px-2 py-1.5">
<input
className="nodrag h-6 w-0 flex-1 rounded border border-input bg-background px-1.5 text-[11px] text-foreground outline-none focus-visible:border-ring"
value={shownSizes}
placeholder='sizes, e.g. "0.33, 0.75" or "none"'
onChange={(e) => setDraft(e.target.value)}
onBlur={commit}
onKeyDown={(e) => {
if (e.key === "Enter") (e.target as HTMLInputElement).blur();
}}
spellCheck={false}
title="Bet/raise sizes at this node (pot fractions). 'none' = no bets here."
/>
<button
className={`nodrag rounded border px-1.5 py-0.5 text-[10px] ${
allinOn
? "border-rose-500/50 bg-rose-500/15 text-rose-300"
: "border-border text-muted-foreground"
}`}
onClick={() => data.onToggleAllin(tree.path)}
title="Toggle all-in at this node"
>
AI
</button>
</div>
</div>
);
}
interface LeafNodeData {
tree: FullTreeNode;
collapsed?: boolean;
onToggleCollapse?: (id: string) => void;
[key: string]: unknown;
}
function ChanceNode({ data }: NodeProps<Node<LeafNodeData>>) {
const { tree, collapsed } = data;
return (
<div
className="flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2.5 py-1.5 text-[11px] text-emerald-300"
style={{ minWidth: 90 }}
>
<Handle type="target" position={Position.Left} className="!bg-border" />
<Handle type="source" position={Position.Right} className="!bg-border" />
<button
className="nodrag rounded p-0.5 hover:bg-emerald-500/20"
onClick={() => data.onToggleCollapse?.(tree.id)}
title={collapsed ? "Expand runout" : "Collapse runout"}
>
{collapsed ? <ChevronRight size={11} /> : <ChevronDown size={11} />}
</button>
deal {tree.street}
</div>
);
}
const TERMINAL_STYLE: Record<string, string> = {
fold: "border-zinc-600/50 bg-zinc-700/20 text-zinc-400",
showdown: "border-violet-500/40 bg-violet-500/10 text-violet-300",
runout: "border-rose-500/40 bg-rose-500/10 text-rose-300",
};
const TERMINAL_LABEL: Record<string, string> = {
fold: "Fold ends",
showdown: "Showdown",
runout: "All-in runout",
};
function TerminalNode({ data }: NodeProps<Node<LeafNodeData>>) {
const { tree } = data;
return (
<div
className={`rounded-full border px-2.5 py-1.5 text-[11px] ${TERMINAL_STYLE[tree.terminal ?? "fold"]}`}
>
<Handle type="target" position={Position.Left} className="!bg-border" />
{TERMINAL_LABEL[tree.terminal ?? "fold"]} · {Math.round(tree.pot * 10) / 10}bb
</div>
);
}
const nodeTypes = { action: ActionNode, chance: ChanceNode, terminal: TerminalNode };
// ---------------------------------------------------------------------------
// The flow
// ---------------------------------------------------------------------------
export interface TreeFlowProps {
grid: SizingGrid;
base: SizingBase;
boardCards: number;
nodeEdits: NodeEdit[];
onNodeEditsChange: (edits: NodeEdit[]) => void;
/** Solve result (dump_nodes) — enables the frequency overlay. */
result?: SolverResult | null;
/** Node budget for the expansion. */
maxNodes?: number;
/** Called with tree stats whenever the tree rebuilds. */
onStats?: (t: FullTree) => void;
}
const samePath = (a: string[], b: string[]) =>
a.length === b.length && a.every((t, i) => t === b[i]);
export function TreeFlow({
grid,
base,
boardCards,
nodeEdits,
onNodeEditsChange,
result,
maxNodes = 4000,
onStats,
}: TreeFlowProps) {
// Collapse overrides: chance nodes default collapsed (the flop tree reads
// clean; expand a deal to open its runout), everything else expanded.
const [collapseOverride, setCollapseOverride] = useState<Map<string, boolean>>(new Map());
const isCollapsed = useCallback(
(n: FullTreeNode) => collapseOverride.get(n.id) ?? n.kind === "chance",
[collapseOverride],
);
const tree = useMemo(
() => buildFullTree(grid, nodeEdits, base, boardCards, maxNodes),
[grid, nodeEdits, base, boardCards, maxNodes],
);
useEffect(() => {
onStats?.(tree);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [tree]);
const freqIdx = useMemo(() => buildFreqIndex(result), [result]);
// ---- edit lowering ------------------------------------------------------
const upsertEdit = useCallback(
(path: string[], patch: Partial<Pick<NodeEdit, "sizes" | "allin">>) => {
const existing = nodeEdits.find((e) => samePath(e.path, path));
const next: NodeEdit = {
path: [...path],
sizes: patch.sizes ?? existing?.sizes ?? "",
allin: patch.allin ?? existing?.allin ?? "auto",
};
if (next.sizes.trim() === "" && next.allin === "auto") {
onNodeEditsChange(nodeEdits.filter((e) => !samePath(e.path, path)));
} else {
onNodeEditsChange([...nodeEdits.filter((e) => !samePath(e.path, path)), next]);
}
},
[nodeEdits, onNodeEditsChange],
);
const onCommitSizes = useCallback(
(path: string[], sizes: string) => upsertEdit(path, { sizes: sizes.trim() }),
[upsertEdit],
);
const onToggleAllin = useCallback(
(path: string[]) => {
// Flip against what the tree currently shows at that node.
const node = findByPath(tree.root, path);
const on = node?.actions.some((a) => a.label === "AllIn") ?? false;
const choice: AllinChoice = on ? "off" : "on";
upsertEdit(path, { allin: choice });
},
[tree, upsertEdit],
);
const onResetEdit = useCallback(
(path: string[]) => onNodeEditsChange(nodeEdits.filter((e) => !samePath(e.path, path))),
[nodeEdits, onNodeEditsChange],
);
// ---- layout -------------------------------------------------------------
const { nodes, edges } = useMemo(() => {
const nodes: Node[] = [];
const edges: Edge[] = [];
if (!tree.root) return { nodes, edges };
// Height of a subtree as laid out (collapsed nodes contribute just their
// own card height).
const subtreeHeight = (c: FullTreeNode): number => {
const cs = isCollapsed(c) ? [] : c.children;
if (cs.length === 0) return nodeHeight(c);
let total = 0;
for (const k of cs) total += subtreeHeight(k.child) + ROW_GAP;
return Math.max(nodeHeight(c), total - ROW_GAP);
};
const place = (n: FullTreeNode, depth: number, yTop: number): number => {
const h = nodeHeight(n);
const collapsed = isCollapsed(n);
const kids = collapsed ? [] : n.children;
let childrenH = 0;
const childTops: number[] = [];
for (const k of kids) {
childTops.push(yTop + childrenH);
childrenH += subtreeHeight(k.child) + ROW_GAP;
}
if (kids.length > 0) childrenH -= ROW_GAP;
const myH = Math.max(h, childrenH);
const y = yTop + myH / 2 - h / 2;
const data =
n.kind === "action"
? ({
tree: n,
freqs: n.actions.map((a) => lookupFreq(freqIdx, n.path, a.token)),
collapsed,
onToggleCollapse: toggle,
onCommitSizes,
onToggleAllin,
onResetEdit,
} satisfies ActionNodeData)
: ({ tree: n, collapsed, onToggleCollapse: toggle } satisfies LeafNodeData);
nodes.push({
id: n.id,
type: n.kind,
position: { x: depth * (NODE_W + COL_GAP), y },
data,
draggable: false,
connectable: false,
});
kids.forEach((k, i) => {
place(k.child, depth + 1, childTops[i]);
const f = n.kind === "action" ? lookupFreq(freqIdx, n.path, k.token) : null;
const w = f === null ? 1.5 : 1 + 5 * f;
const dead = f !== null && f < 0.005;
edges.push({
id: `${n.id}->${k.child.id}`,
source: n.id,
target: k.child.id,
type: "smoothstep",
label: f !== null ? `${(f * 100).toFixed(f < 0.1 && f > 0 ? 1 : 0)}%` : undefined,
labelStyle: { fontSize: 9, fill: "var(--muted-foreground, #999)" },
labelBgStyle: { fill: "transparent" },
style: {
strokeWidth: w,
opacity: f === null ? 0.5 : 0.25 + 0.75 * Math.min(1, f * 2),
strokeDasharray: dead ? "4 4" : undefined,
stroke: dead ? "#f43f5e" : undefined,
},
});
});
return myH;
};
// Local alias so data objects capture a stable name.
function toggle(id: string) {
setCollapseOverride((m) => {
const next = new Map(m);
const node = findById(tree.root, id);
const def = node?.kind === "chance";
const cur = next.get(id) ?? def;
next.set(id, !cur);
return next;
});
}
place(tree.root, 0, 0);
return { nodes, edges };
}, [tree, isCollapsed, freqIdx, onCommitSizes, onToggleAllin, onResetEdit]);
return (
<div className="h-full w-full">
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
fitView
fitViewOptions={{ padding: 0.15, maxZoom: 1 }}
minZoom={0.05}
proOptions={{ hideAttribution: true }}
nodesDraggable={false}
nodesConnectable={false}
elementsSelectable
>
<Background gap={24} size={1} />
<Controls showInteractive={false} />
<MiniMap pannable zoomable className="!bg-card" />
</ReactFlow>
</div>
);
}
function findByPath(root: FullTreeNode | null, path: string[]): FullTreeNode | null {
if (!root) return null;
if (samePath(root.path, path) && root.kind === "action") return root;
for (const k of root.children) {
const hit = findByPath(k.child, path);
if (hit) return hit;
}
return null;
}
function findById(root: FullTreeNode | null, id: string): FullTreeNode | null {
if (!root) return null;
if (root.id === id) return root;
for (const k of root.children) {
const hit = findById(k.child, id);
if (hit) return hit;
}
return null;
}
components/explorer/tree-sizing-editor.tsx
"use client";
// GTO-Wizard-style "Tree edit" for custom solves. Two layers, matching GTOW:
//
// • Street rules — flop/turn/river × OOP/IP bet sizes, raise sizes, all-in.
// • Node edits — click INTO a line (choose Bet 4 at the flop, see the raise
// node behind it, …) and override one specific node's sizes; the engine
// applies it to exactly that action path (`sizing.nodes`, chance steps
// generic "deal" so a turn-node edit spans every turn card).
//
// The strip shows the betting nodes along the currently selected line with
// their RESOLVED actions (node edit → street rule → base fields — the same
// precedence chain the engine's tree builder uses). Amounts are real chip
// counts computed by simulating the line, so a raise node shows raise-to
// totals over the grown pot, exactly like the tree the solver will build.
//
// Path label encoding must stay byte-identical to the engine's
// `tree::path_label` ("Bet 4", "Call 4", "Raise 12.4", 1-decimal amounts,
// bare "Check"/"Fold") — the engine REJECTS a node edit whose path matches
// no built node, so a drifted label fails loudly, not silently.
import { useEffect, useMemo, useState } from "react";
import { Pencil, Plus, RotateCcw, X } from "lucide-react";
import type { NodeSizingConfig, StreetSizingConfig, TreeSizingConfig } from "@/lib/solver/types";
export type AllinChoice = "auto" | "on" | "off";
export interface SizingCell {
/** Comma list of pot fractions ("0.33, 0.75"), "" = inherit, "none" = []. */
bets: string;
/** Same grammar; "" = inherit (mirrors bets when those are set). */
raises: string;
allin: AllinChoice;
}
export interface SizingGrid {
flop: { oop: SizingCell; ip: SizingCell };
turn: { oop: SizingCell; ip: SizingCell };
river: { oop: SizingCell; ip: SizingCell };
}
/** One node-specific edit, UI-side (text fields; lowered on Solve). */
export interface NodeEdit {
/** Engine-encoded action path from the start-street root. */
path: string[];
/** Comma list of pot fractions; "none" = no bets/raises at this node;
* "" = only the all-in choice is overridden. */
sizes: string;
allin: AllinChoice;
}
const STREETS = ["flop", "turn", "river"] as const;
export type StreetKey = (typeof STREETS)[number];
type Role = "oop" | "ip";
export const emptySizingCell = (): SizingCell => ({ bets: "", raises: "", allin: "auto" });
export const emptySizingGrid = (): SizingGrid => ({
flop: { oop: emptySizingCell(), ip: emptySizingCell() },
turn: { oop: emptySizingCell(), ip: emptySizingCell() },
river: { oop: emptySizingCell(), ip: emptySizingCell() },
});
/** The builder's base abstraction — what unedited nodes fall back to. */
export interface SizingBase {
betSizes: number[];
/** Empty = raises reuse betSizes (legacy engine chain). */
raiseSizes?: number[];
/** Empty = river reuses betSizes. */
riverBetSizes: number[];
addAllin: boolean;
maxAggressions: number;
riverMaxAggressions?: number;
potBb: number;
effStackBb: number;
}
/** Parse one sizes list: "" → undefined (inherit), "none"/"-"/"0" → [], else
* comma-separated positive pot fractions. Throws with a labelled message. */
export function parseCellSizes(raw: string, label: string): number[] | undefined {
const s = raw.trim();
if (!s) return undefined;
if (/^(none|-|0)$/i.test(s)) return [];
return s.split(",").map((t, i) => {
const n = Number(t.trim());
if (!Number.isFinite(n) || n <= 0) {
throw new Error(`${label} #${i + 1} must be a positive pot fraction (or "none")`);
}
return n;
});
}
/**
* Lower the street-rule grid + node edits to the engine's `sizing` config.
* Returns undefined when nothing is overridden (pure legacy geometry).
*/
export function sizingFromEditor(
grid: SizingGrid,
nodeEdits: NodeEdit[] = [],
): TreeSizingConfig | undefined {
const out: TreeSizingConfig = {};
for (const street of STREETS) {
const st: StreetSizingConfig = {};
for (const role of ["oop", "ip"] as const) {
const cell = grid[street][role];
const label = `${street} ${role.toUpperCase()}`;
const bets = parseCellSizes(cell.bets, `${label} bet size`);
const raises = parseCellSizes(cell.raises, `${label} raise size`);
if (bets !== undefined) st[`${role}_bet_sizes`] = bets;
if (raises !== undefined) st[`${role}_raise_sizes`] = raises;
if (cell.allin !== "auto") st[`${role}_allin`] = cell.allin === "on";
}
if (Object.keys(st).length > 0) out[street] = st;
}
const nodes: NodeSizingConfig[] = [];
for (const edit of nodeEdits) {
const sizes = parseCellSizes(edit.sizes, `node ${edit.path.join(" → ") || "root"} size`);
const node: NodeSizingConfig = { path: edit.path };
if (sizes !== undefined) node.sizes = sizes;
if (edit.allin !== "auto") node.allin = edit.allin === "on";
if (node.sizes !== undefined || node.allin !== undefined) nodes.push(node);
}
if (nodes.length > 0) out.nodes = nodes;
return Object.keys(out).length > 0 ? out : undefined;
}
/** Back-compat wrapper (older tests / callers without node edits). */
export function sizingFromGrid(grid: SizingGrid): TreeSizingConfig | undefined {
return sizingFromEditor(grid, []);
}
// ---------------------------------------------------------------------------
// Node-edit modal drafts (GTOW "Edit Node")
// ---------------------------------------------------------------------------
/**
* The size list in effect at a node, as pot **percents** — the modal's initial
* draft rows. A valid node edit wins; otherwise the street-rule resolution for
* the node's bet/raise context. An unparsable edit falls back to the rule,
* matching `simulateLine`'s preview behavior.
*/
export function nodeDraftPercents(node: {
toCall: number;
resolved: ResolvedNode;
edit?: NodeEdit;
}): number[] {
let fracs = node.toCall > 0 ? node.resolved.raises : node.resolved.bets;
if (node.edit) {
try {
const s = parseCellSizes(node.edit.sizes, "node size");
if (s !== undefined) fracs = s;
} catch {
/* keep the street-rule fallback */
}
}
return fracs.map((f) => round1(f * 100));
}
/**
* Lower modal draft rows (pot percents) to a `NodeEdit.sizes` string: comma
* pot fractions, or "none" for an empty draft (the explicit no-bets override —
* an empty string would mean "inherit" and silently undo the user's deletes).
* Zero/negative/NaN rows are dropped rather than erroring: the modal's number
* inputs can transiently hold "" while typing.
*/
export function draftPercentsToSizes(pcts: number[]): string {
const clean = pcts.filter((p) => Number.isFinite(p) && p > 0);
if (clean.length === 0) return "none";
// 4 decimals on the fraction keeps sub-percent sizes exact (0.33% pot →
// 0.0033) without float noise like 0.33000000000000004.
return clean.map((p) => String(Math.round(p * 100) / 10000)).join(", ");
}
/** What one node resolves to at street-rule level (mirrors tree.rs). */
export interface ResolvedNode {
bets: number[];
raises: number[];
allin: boolean;
betsInherited: boolean;
raisesInherited: boolean;
error?: string;
}
export function resolveNode(
grid: SizingGrid,
base: SizingBase,
street: StreetKey,
role: Role,
): ResolvedNode {
const cell = grid[street][role];
let bets: number[] | undefined;
let raises: number[] | undefined;
let error: string | undefined;
try {
bets = parseCellSizes(cell.bets, "bet size");
} catch (e) {
error = e instanceof Error ? e.message : String(e);
}
try {
raises = parseCellSizes(cell.raises, "raise size");
} catch (e) {
error = error ?? (e instanceof Error ? e.message : String(e));
}
const legacyBets =
street === "river" && base.riverBetSizes.length > 0 ? base.riverBetSizes : base.betSizes;
const legacyRaises =
street === "river" && base.riverBetSizes.length > 0
? base.riverBetSizes
: base.raiseSizes && base.raiseSizes.length > 0
? base.raiseSizes
: base.betSizes;
return {
bets: bets ?? legacyBets,
raises: raises ?? bets ?? legacyRaises,
allin: cell.allin === "auto" ? base.addAllin : cell.allin === "on",
betsInherited: bets === undefined,
raisesInherited: raises === undefined && bets === undefined,
error,
};
}
// ---------------------------------------------------------------------------
// Line simulation — mirrors the engine's builder math (tree.rs add_bets) so
// the strip shows the same nodes, actions, and chip amounts the solve builds.
// ---------------------------------------------------------------------------
/** Byte-identical to the engine's `tree::round1` for positive amounts. */
const round1 = (x: number) => Math.round(x * 10) / 10;
/** Engine `tree::path_label`: label + 1-decimal amount when chips move. */
export function pathLabel(label: string, add: number): string {
return add > 0 ? `${label} ${round1(add)}` : label;
}
export interface SimAction {
/** Path token, engine encoding ("Bet 4", "Call 4", "Check", "AllIn 98.1"). */
token: string;
label: "Check" | "Bet" | "Raise" | "AllIn" | "Call" | "Fold";
/** Chips this action adds. */
add: number;
/** Pot fraction (bets/raises only) for the % badge. */
frac?: number;
}
export interface SimNode {
street: StreetKey;
role: Role;
/** Pot BEFORE this player acts. */
pot: number;
toCall: number;
/** Path from the root to this node (engine encoding; deals as "deal"). */
path: string[];
actions: SimAction[];
/** Street-rule resolution behind this node (for the editor panel). */
resolved: ResolvedNode;
/** The node edit applied here, if any. */
edit?: NodeEdit;
}
interface SimState {
streetIdx: number; // index into the streets visible from the start street
pot: number;
stacks: [number, number];
paid: [number, number]; // this street
toCall: number;
player: 0 | 1;
aggressions: number;
path: string[];
}
const sameNodePath = (a: string[], b: string[]) =>
a.length === b.length && a.every((t, i) => t === b[i]);
/**
* Walk the tree along `chosen` (then a check/call default continuation),
* returning the decision nodes the strip renders. Stops when a fold ends the
* hand, stacks are empty (pure runout), or the river closes.
*/
export function simulateLine(
grid: SizingGrid,
nodeEdits: NodeEdit[],
base: SizingBase,
boardCards: number,
chosen: string[],
): SimNode[] {
const startIdx = boardCards >= 5 ? 2 : boardCards === 4 ? 1 : 0;
const streets = STREETS.slice(startIdx);
const maxAggrFor = (s: StreetKey) =>
s === "river" ? (base.riverMaxAggressions ?? base.maxAggressions) : base.maxAggressions;
const nodes: SimNode[] = [];
let st: SimState = {
streetIdx: 0,
pot: base.potBb,
stacks: [base.effStackBb, base.effStackBb],
paid: [0, 0],
toCall: 0,
player: 0,
aggressions: 0,
path: [],
};
let cursor = 0;
for (let guard = 0; guard < 64; guard++) {
const street = streets[st.streetIdx];
if (!street) break;
const role: Role = st.player === 0 ? "oop" : "ip";
const resolved = resolveNode(grid, base, street, role);
const edit = nodeEdits.find((e) => sameNodePath(e.path, st.path));
// Resolve this node's sizes/allin: node edit > street rule > base.
let sizes = st.toCall > 0 ? resolved.raises : resolved.bets;
let allin = resolved.allin;
if (edit) {
try {
const s = parseCellSizes(edit.sizes, "node size");
if (s !== undefined) sizes = s;
} catch {
/* invalid text — preview falls back to the street rule */
}
if (edit.allin !== "auto") allin = edit.allin === "on";
}
const stack = st.stacks[st.player];
const actions: SimAction[] = [];
const canAggress = st.aggressions < maxAggrFor(street) && stack > st.toCall + 1e-9;
if (st.toCall <= 1e-9) {
actions.push({ token: "Check", label: "Check", add: 0 });
} else {
actions.push({ token: "Fold", label: "Fold", add: 0 });
const callAmt = Math.min(st.toCall, stack);
actions.push({ token: pathLabel("Call", callAmt), label: "Call", add: callAmt });
}
if (canAggress) {
const potAfterCall = st.pot + st.toCall;
for (const f of sizes) {
const totalAdd = st.toCall + f * potAfterCall;
if (totalAdd >= stack - 1e-9) continue; // shove covers it
if (totalAdd <= st.toCall + 1e-9) continue;
actions.push({
token: pathLabel(st.toCall > 0 ? "Raise" : "Bet", totalAdd),
label: st.toCall > 0 ? "Raise" : "Bet",
add: totalAdd,
frac: f,
});
}
if (allin) {
actions.push({ token: pathLabel("AllIn", stack), label: "AllIn", add: stack });
}
}
nodes.push({
street,
role,
pot: st.pot,
toCall: st.toCall,
path: st.path,
actions,
resolved,
edit,
});
// Pick the next step: the chosen line while it lasts, then check/call.
let tok = cursor < chosen.length ? chosen[cursor++] : undefined;
if (tok !== undefined && !actions.some((a) => a.token === tok)) {
// The chosen line no longer exists (sizes changed under it) — fall back
// to the default continuation from here on.
tok = undefined;
cursor = chosen.length;
}
const act =
tok !== undefined
? actions.find((a) => a.token === tok)!
: (actions.find((a) => a.label === "Check") ?? actions.find((a) => a.label === "Call"))!;
// Apply the action (engine State transitions, HU).
const p = st.player;
const o = (1 - p) as 0 | 1;
if (act.label === "Fold") break;
if (act.label === "Check") {
if (p === 0) {
st = { ...st, player: 1, path: [...st.path, act.token] };
} else {
// check-check → next street
if (st.streetIdx + 1 >= streets.length) break; // river closes
st = {
...st,
streetIdx: st.streetIdx + 1,
paid: [0, 0],
toCall: 0,
player: 0,
aggressions: 0,
path: [...st.path, act.token, "deal"],
};
}
continue;
}
if (act.label === "Call") {
const stacks: [number, number] = [...st.stacks];
stacks[p] -= act.add;
const pot = st.pot + act.add;
if (stacks[p] <= 1e-9 || stacks[o] <= 1e-9) break; // all-in call → runout
if (st.streetIdx + 1 >= streets.length) break; // river call closes the hand
st = {
streetIdx: st.streetIdx + 1,
pot,
stacks,
paid: [0, 0],
toCall: 0,
player: 0,
aggressions: 0,
path: [...st.path, act.token, "deal"],
};
continue;
}
// Bet / Raise / AllIn
{
const stacks: [number, number] = [...st.stacks];
stacks[p] -= act.add;
const paid: [number, number] = [...st.paid];
paid[p] += act.add;
st = {
streetIdx: st.streetIdx,
pot: st.pot + act.add,
stacks,
paid,
toCall: paid[p] - paid[o],
player: o,
aggressions: st.aggressions + 1,
path: [...st.path, act.token],
};
}
}
return nodes;
}
// ---------------------------------------------------------------------------
// UI
// ---------------------------------------------------------------------------
const fmt = (n: number) => String(round1(n));
const CELL_INPUT =
"h-8 w-full rounded-md border border-input bg-card px-2 text-xs text-foreground outline-none transition-colors placeholder:text-muted-foreground/50 focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40";
function NodeCard({
node,
index,
selected,
nextToken,
onSelect,
onPickAction,
onEdit,
}: {
node: SimNode;
index: number;
selected: boolean;
/** The action this line continues with (highlighted). */
nextToken?: string;
onSelect: () => void;
onPickAction: (token: string) => void;
/** Open the Edit Node modal for this node. */
onEdit: () => void;
}) {
return (
<div
role="button"
tabIndex={0}
onClick={onSelect}
onKeyDown={(e) => {
if (e.key === "Enter" || e.key === " ") onSelect();
}}
aria-label={`Node ${index}: ${node.street} ${node.role.toUpperCase()}`}
className={`flex w-36 shrink-0 cursor-pointer flex-col gap-1 rounded-lg border px-2.5 py-2 transition-colors ${
selected
? "border-ring bg-card ring-2 ring-ring/40"
: "border-border bg-card/60 hover:border-ring/50"
}`}
>
<span className="flex items-center justify-between text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
{node.role.toUpperCase()}
<span className="flex items-center gap-1">
{node.edit ? (
<span className="rounded bg-amber-500/15 px-1 py-px text-[9px] font-medium normal-case text-amber-400">
node edit
</span>
) : !node.resolved.betsInherited || !node.resolved.raisesInherited ? (
<span className="rounded bg-foreground/10 px-1 py-px text-[9px] font-medium normal-case text-foreground">
street rule
</span>
) : null}
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onEdit();
}}
aria-label={`Edit node ${index}`}
className="rounded p-0.5 text-muted-foreground/60 transition-colors hover:bg-accent hover:text-foreground"
>
<Pencil className="size-3" />
</button>
</span>
</span>
{node.actions.map((a) => (
<button
key={a.token}
type="button"
onClick={(e) => {
e.stopPropagation();
onPickAction(a.token);
}}
className={`flex items-baseline justify-between rounded px-1.5 py-0.5 text-left text-[11px] tabular-nums transition-colors ${
nextToken === a.token
? "bg-foreground text-background"
: "bg-accent/60 text-foreground hover:bg-accent"
}`}
>
{a.label === "AllIn" ? `All-in ${fmt(a.add)}` : a.add > 0 ? `${a.label} ${fmt(a.add)}` : a.label}
{a.frac !== undefined ? (
<span
className={`text-[10px] ${nextToken === a.token ? "text-background/70" : "text-muted-foreground"}`}
>
{Math.round(a.frac * 100)}%
</span>
) : null}
</button>
))}
{node.actions.length <= 1 ? (
<span className="text-[10px] italic text-muted-foreground/70">check only</span>
) : null}
{node.resolved.error ? (
<span className="text-[9px] text-destructive">invalid — showing inherited</span>
) : null}
</div>
);
}
/**
* GTOW-style "Edit Node" modal: one row per bet/raise size (numeric % field +
* slider + remove), an add-size row, and an all-in row. Draft state is local —
* nothing touches the tree until Confirm. Fixed actions (Check/Fold/Call) are
* shown but not removable: the engine's node overrides shape *sizes*, never
* the passive actions.
*/
function NodeEditModal({
node,
hasAnyEdits,
onConfirm,
onRemoveEdit,
onRemoveAll,
onClose,
}: {
node: SimNode;
hasAnyEdits: boolean;
/** Commit the draft: a `NodeEdit.sizes` string + the all-in choice. */
onConfirm: (sizes: string, allin: AllinChoice) => void;
onRemoveEdit: () => void;
onRemoveAll: () => void;
onClose: () => void;
}) {
const [pcts, setPcts] = useState<(number | "")[]>(() => nodeDraftPercents(node));
const [allin, setAllin] = useState<AllinChoice>(node.edit?.allin ?? "auto");
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [onClose]);
const kind = node.toCall > 0 ? "Raise" : "Bet";
const fixed = node.actions.filter((a) => a.label === "Check" || a.label === "Fold" || a.label === "Call");
const shove = node.actions.find((a) => a.label === "AllIn");
const setPct = (i: number, v: number | "") =>
setPcts((p) => p.map((x, j) => (j === i ? v : x)));
const lineLabel = node.path.filter((t) => t !== "deal").join(" → ");
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
onClick={onClose}
role="presentation"
>
<div
role="dialog"
aria-modal="true"
aria-label={`Edit node: ${node.street} ${node.role.toUpperCase()}`}
onClick={(e) => e.stopPropagation()}
className="flex w-full max-w-md flex-col gap-3 rounded-xl border border-border bg-card p-4 shadow-xl"
>
<div className="flex items-start justify-between gap-2">
<div className="flex flex-col">
<span className="text-base font-semibold text-foreground">Edit Node</span>
<span className="text-[11px] text-muted-foreground">
{node.street} · {node.role.toUpperCase()} · pot {fmt(node.pot)}
{lineLabel ? ` · after ${lineLabel}` : ""}
{node.path.includes("deal") ? " (every runout card)" : ""}
</span>
</div>
<button
type="button"
onClick={onClose}
aria-label="Close"
className="rounded-md p-1 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-4" />
</button>
</div>
<div className="flex flex-col gap-1.5">
{/* Passive actions — part of the tree, not removable. */}
{fixed.map((a) => (
<div
key={a.label}
className="flex h-9 items-center justify-between rounded-md bg-accent/40 px-3 text-sm text-foreground"
>
<span>{a.add > 0 ? `${a.label} ${fmt(a.add)}` : a.label}</span>
<span className="text-[10px] uppercase tracking-wide text-muted-foreground/60">
fixed
</span>
</div>
))}
{/* One row per draft size. */}
{pcts.map((p, i) => (
<div
key={i}
className="flex h-9 items-center gap-2 rounded-md bg-accent/40 px-3 text-sm"
>
<span className="w-10 shrink-0 text-foreground">{kind}</span>
<input
type="number"
min={1}
value={p}
onChange={(e) =>
setPct(i, e.target.value === "" ? "" : Number(e.target.value))
}
aria-label={`${kind} size ${i + 1} (% of pot)`}
className="h-6 w-16 rounded border border-input bg-card px-1.5 text-right text-xs text-foreground outline-none tabular-nums focus-visible:border-ring"
/>
<span className="text-[11px] text-muted-foreground">%</span>
<input
type="range"
min={1}
max={200}
step={1}
value={typeof p === "number" ? Math.min(Math.max(p, 1), 200) : 1}
onChange={(e) => setPct(i, Number(e.target.value))}
aria-label={`${kind} size ${i + 1} slider`}
className="min-w-0 flex-1 accent-foreground"
/>
<button
type="button"
onClick={() => setPcts((prev) => prev.filter((_, j) => j !== i))}
aria-label={`Remove ${kind.toLowerCase()} size ${i + 1}`}
className="rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<X className="size-3.5" />
</button>
</div>
))}
{/* Add-size row. */}
<button
type="button"
onClick={() => setPcts((prev) => [...prev, 75])}
className="flex h-9 items-center justify-between rounded-md border border-dashed border-border px-3 text-sm text-muted-foreground transition-colors hover:border-ring/50 hover:text-foreground"
>
<span>{kind}</span>
<Plus className="size-4" />
</button>
{/* All-in row. */}
<div className="flex h-9 items-center justify-between rounded-md bg-accent/40 px-3 text-sm text-foreground">
<span>All-in{shove ? ` ${fmt(shove.add)}` : ""}</span>
<select
value={allin}
onChange={(e) => setAllin(e.target.value as AllinChoice)}
aria-label="All-in at this node"
className="h-6 rounded border border-input bg-card px-1 text-xs text-foreground outline-none focus-visible:border-ring"
>
<option value="auto">auto (street rule)</option>
<option value="on">yes</option>
<option value="off">no</option>
</select>
</div>
</div>
<div className="flex items-center justify-between gap-2 pt-1">
<div className="flex items-center gap-2">
{hasAnyEdits ? (
<button
type="button"
onClick={onRemoveAll}
className="text-[11px] text-muted-foreground transition-colors hover:text-foreground"
>
Delete All Node Edits
</button>
) : null}
{node.edit ? (
<button
type="button"
onClick={onRemoveEdit}
className="text-[11px] text-muted-foreground transition-colors hover:text-foreground"
>
Remove this edit
</button>
) : null}
</div>
<button
type="button"
onClick={() =>
onConfirm(
draftPercentsToSizes(pcts.map((p) => (typeof p === "number" ? p : NaN))),
allin,
)
}
className="rounded-md bg-foreground px-4 py-1.5 text-sm font-medium text-background transition-colors hover:bg-foreground/90"
>
Confirm
</button>
</div>
</div>
</div>
);
}
export function TreeSizingEditor({
grid,
onChange,
nodeEdits,
onNodeEditsChange,
boardCards,
base,
}: {
grid: SizingGrid;
onChange: (g: SizingGrid) => void;
nodeEdits: NodeEdit[];
onNodeEditsChange: (edits: NodeEdit[]) => void;
/** 3/4/5 → flop/turn/river start; earlier streets are hidden (never built). */
boardCards: number;
base: SizingBase;
}) {
// The action line the strip walks (engine path tokens), plus which node
// card is selected for editing.
const [line, setLine] = useState<string[]>([]);
const [selectedIdx, setSelectedIdx] = useState(0);
// The GTOW-style "Edit Node" modal, over the selected node.
const [modalOpen, setModalOpen] = useState(false);
const sim = useMemo(
() => simulateLine(grid, nodeEdits, base, boardCards, line),
[grid, nodeEdits, base, boardCards, line],
);
const sel = sim[Math.min(selectedIdx, sim.length - 1)];
const setCell = (street: StreetKey, role: Role, patch: Partial<SizingCell>) => {
onChange({
...grid,
[street]: { ...grid[street], [role]: { ...grid[street][role], ...patch } },
});
};
const nodeEditFor = (path: string[]) => nodeEdits.find((e) => sameNodePath(e.path, path));
const patchNodeEdit = (path: string[], patch: Partial<Omit<NodeEdit, "path">>) => {
const existing = nodeEditFor(path);
const next: NodeEdit = { path, sizes: "", allin: "auto", ...existing, ...patch };
const rest = nodeEdits.filter((e) => !sameNodePath(e.path, path));
// An all-default edit is no edit — drop the entry.
if (next.sizes.trim() === "" && next.allin === "auto") onNodeEditsChange(rest);
else onNodeEditsChange([...rest, next]);
};
const pickAction = (nodeIdx: number, token: string) => {
// Rebuild the chosen line: everything that led to this node + the pick.
// Navigation only — the Edit Node modal opens from the card's pencil.
setLine([...sim[nodeIdx].path, token]);
setSelectedIdx(nodeIdx + 1 <= sim.length ? nodeIdx + 1 : nodeIdx);
};
const cell = sel ? grid[sel.street][sel.role] : null;
const selEdit = sel ? nodeEditFor(sel.path) : undefined;
return (
<div className="flex flex-col gap-3">
{/* ---- Line strip ---- */}
<div className="flex items-start gap-2 overflow-x-auto pb-1">
{sim.map((node, i) => {
// Street header card before the first node of each street.
const header =
i === 0 || sim[i - 1].street !== node.street ? (
<div
key={`h-${node.street}`}
className="flex w-14 shrink-0 flex-col items-center justify-center gap-1 self-stretch rounded-lg border border-border bg-card/40 px-2 py-2"
>
<span className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
{node.street}
</span>
<span className="text-[10px] text-muted-foreground/70 tabular-nums">
pot {fmt(node.pot)}
</span>
</div>
) : null;
// The token this line takes out of this node (to highlight it).
const nextToken = sim[i + 1]
? sim[i + 1].path[node.path.length] // first token added after this node
: undefined;
return (
<div key={i} className="contents">
{header}
<NodeCard
node={node}
index={i}
selected={sel === node}
nextToken={nextToken}
onSelect={() => setSelectedIdx(i)}
onPickAction={(tok) => pickAction(i, tok)}
onEdit={() => {
setSelectedIdx(i);
setModalOpen(true);
}}
/>
</div>
);
})}
{line.length > 0 ? (
<button
type="button"
onClick={() => {
setLine([]);
setSelectedIdx(0);
}}
className="flex h-8 shrink-0 items-center gap-1 self-center rounded-md border border-border bg-card px-2 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<RotateCcw className="size-3" /> Reset line
</button>
) : null}
</div>
{/* ---- Editor for the selected node ---- */}
{sel && cell ? (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-card/40 p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-[11px] font-medium uppercase tracking-wide text-muted-foreground">
{sel.street} · {sel.role.toUpperCase()}
{sel.path.length > 0 ? (
<span className="ml-2 normal-case tracking-normal text-muted-foreground/70">
after {sel.path.filter((t) => t !== "deal").join(" → ")}
</span>
) : null}
</span>
<div className="flex items-center gap-2 text-[11px]">
<span className="rounded-md border border-border px-2 py-0.5 text-muted-foreground">
street rule: all {sel.street} {sel.role.toUpperCase()} nodes
</span>
<button
type="button"
onClick={() => setModalOpen(true)}
className="flex items-center gap-1 rounded-md bg-foreground px-2 py-0.5 font-medium text-background transition-colors hover:bg-foreground/90"
>
<Pencil className="size-3" /> Edit this node
</button>
</div>
</div>
{
<>
<div className="grid grid-cols-2 gap-3">
<label className="flex flex-col gap-1">
<span className="text-[11px] text-muted-foreground">Bet sizes (× pot)</span>
<input
value={cell.bets}
onChange={(e) => setCell(sel.street, sel.role, { bets: e.target.value })}
placeholder="inherit"
spellCheck={false}
aria-label={`${sel.street} ${sel.role.toUpperCase()} bet sizes`}
className={CELL_INPUT}
/>
</label>
<label className="flex flex-col gap-1">
<span className="text-[11px] text-muted-foreground">Raise sizes (× pot)</span>
<input
value={cell.raises}
onChange={(e) => setCell(sel.street, sel.role, { raises: e.target.value })}
placeholder="inherit"
spellCheck={false}
aria-label={`${sel.street} ${sel.role.toUpperCase()} raise sizes`}
className={CELL_INPUT}
/>
</label>
</div>
<div className="flex items-center justify-between gap-2">
<label className="flex items-center gap-2 text-[11px] text-muted-foreground">
All-in
<select
value={cell.allin}
onChange={(e) =>
setCell(sel.street, sel.role, { allin: e.target.value as AllinChoice })
}
aria-label={`${sel.street} ${sel.role.toUpperCase()} all-in`}
className="h-8 rounded-md border border-input bg-card px-1.5 text-xs text-foreground outline-none transition-colors focus-visible:border-ring focus-visible:ring-2 focus-visible:ring-ring/40"
>
<option value="auto">auto</option>
<option value="on">yes</option>
<option value="off">no</option>
</select>
</label>
{cell.bets.trim() !== "" || cell.raises.trim() !== "" || cell.allin !== "auto" ? (
<button
type="button"
onClick={() => setCell(sel.street, sel.role, emptySizingCell())}
className="rounded-md border border-border bg-card px-2 py-1 text-[11px] text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
Reset rule
</button>
) : null}
</div>
</>
}
</div>
) : null}
{/* ---- GTOW-style Edit Node modal ---- */}
{modalOpen && sel ? (
<NodeEditModal
// Remount per node/edit state so the draft always seeds fresh.
key={`${sel.path.join("|")}:${selEdit ? selEdit.sizes + selEdit.allin : "-"}`}
node={sel}
hasAnyEdits={nodeEdits.length > 0}
onConfirm={(sizes, allin) => {
patchNodeEdit(sel.path, { sizes, allin });
setModalOpen(false);
}}
onRemoveEdit={() => {
if (selEdit) onNodeEditsChange(nodeEdits.filter((e) => e !== selEdit));
setModalOpen(false);
}}
onRemoveAll={() => {
onNodeEditsChange([]);
setModalOpen(false);
}}
onClose={() => setModalOpen(false)}
/>
) : null}
{nodeEdits.length > 0 ? (
<span className="text-[11px] text-muted-foreground/70 tabular-nums">
{nodeEdits.length} node edit{nodeEdits.length === 1 ? "" : "s"} active — changing base
or street sizes can orphan a node edit; the solve will refuse it with the exact path.
</span>
) : null}
<span className="text-[11px] text-muted-foreground/70">
Click an action to walk into that line; click a card to select it. The panel edits the
street rule; the pencil (or "Edit this node") opens the Edit Node dialog for that
exact decision point, GTO-Wizard style. Blank street fields inherit; type{" "}
<code>none</code>
{" to remove bets or raises. Amounts are chips assuming the shown line."}
</span>
</div>
);
}
components/explorer/tree-visualization-modal.tsx
"use client";
// Near-fullscreen React Flow view of the game tree the solver will build.
// Editable nodes: change a node's sizes / all-in inline → lowered to engine
// `NodeEdit`s shared with the Tree-edit strip, so pruning here IS the solve
// config. After a solve the edges carry aggregate action frequencies — the
// bucket-analysis view for spotting sizes the solution never uses.
import { useEffect, useState } from "react";
import { X } from "lucide-react";
import { Button } from "@/components/ui/button";
import type { SolverResult } from "@/lib/solver/types";
import type { FullTree } from "@/lib/explorer/tree-sim";
import { TreeFlow } from "./tree-flow";
import type { NodeEdit, SizingBase, SizingGrid } from "./tree-sizing-editor";
interface TreeVisualizationModalProps {
open: boolean;
onOpenChange: (open: boolean) => void;
grid: SizingGrid;
base: SizingBase;
boardCards: number;
nodeEdits: NodeEdit[];
onNodeEditsChange: (edits: NodeEdit[]) => void;
result?: SolverResult | null;
onSolve: () => void;
isSolving?: boolean;
}
export function TreeVisualizationModal({
open,
onOpenChange,
grid,
base,
boardCards,
nodeEdits,
onNodeEditsChange,
result,
onSolve,
isSolving = false,
}: TreeVisualizationModalProps) {
const [stats, setStats] = useState<FullTree | null>(null);
useEffect(() => {
if (!open) return;
function onKey(e: KeyboardEvent) {
if (e.key === "Escape") onOpenChange(false);
}
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onOpenChange]);
if (!open) return null;
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4">
<div className="flex h-[92vh] w-[96vw] max-w-[1600px] flex-col overflow-hidden rounded-lg border border-border bg-card shadow-xl">
<div className="flex items-center gap-4 border-b border-border px-4 py-3">
<div className="min-w-0">
<h2 className="text-base font-semibold text-foreground">Game tree</h2>
<p className="truncate text-xs text-muted-foreground">
{stats
? `${stats.stats.actionNodes} action · ${stats.stats.chanceNodes} chance · ${stats.stats.terminalNodes} terminal nodes${stats.truncated ? " — TRUNCATED (node budget)" : ""}`
: "…"}
{" · "}
edit sizes on any node ("none" = prune all bets there); deals are collapsed —
expand to open the runout.
{result?.nodes
? " Edge % = aggregate frequency; dashed red = never used (prune it)."
: " Solve to overlay usage frequencies."}
</p>
</div>
<div className="ml-auto flex items-center gap-2">
{nodeEdits.length > 0 ? (
<>
<span className="text-xs text-amber-400">{nodeEdits.length} node edit(s)</span>
<Button size="sm" variant="outline" onClick={() => onNodeEditsChange([])}>
Clear edits
</Button>
</>
) : null}
<Button
size="sm"
onClick={() => {
onOpenChange(false);
onSolve();
}}
disabled={isSolving}
>
{isSolving ? "Solving…" : "Run solve"}
</Button>
<button
onClick={() => onOpenChange(false)}
className="rounded p-1 text-muted-foreground hover:bg-accent"
>
<X size={18} />
</button>
</div>
</div>
<div className="min-h-0 flex-1">
<TreeFlow
grid={grid}
base={base}
boardCards={boardCards}
nodeEdits={nodeEdits}
onNodeEditsChange={onNodeEditsChange}
result={result}
onStats={setStats}
/>
</div>
</div>
</div>
);
}
components/solver/scenario-strip.tsx
"use client";
import { useEffect, useState } from "react";
import { Loader2, Undo2 } from "lucide-react";
import {
ALL_HANDS,
fullRange,
totalCombos,
type RangePlayer,
type RangeWeights,
} from "@/lib/solver/range-model";
import {
clampWeights,
formatBb,
getManifest,
getNode,
labelForAction,
parseHistory,
PLAY_ORDER,
resolveAfterAction,
ROOT_HISTORY,
sortActionsForDisplay,
type NodeAction,
type NodeResponse,
type Position,
type SeatState,
} from "@/lib/solver/preflop";
const FULL_COMBOS = 1326;
export interface ResolvedScenario {
oop: RangeWeights;
ip: RangeWeights;
oopPos: Position;
ipPos: Position;
}
interface HeadsUp {
oop: Position;
ip: Position;
survivors: [Position, Position];
closedActor: Position;
closedHistory: string;
}
interface Props {
/** Emitted when the pot closes heads-up (ranges + seats) or the walk resets (null). */
onResolved: (r: ResolvedScenario | null) => void;
}
/**
* GTO-Wizard–style preflop strip for the solver. The user walks the NL tree one
* seat at a time; the moment a raise is called the pot closes to heads-up, the
* two survivors' ranges are handed up to the solver as OOP/IP, and a preview of
* each range is shown below the strip.
*/
export function ScenarioStrip({ onResolved }: Props) {
const [stack, setStack] = useState(100);
const [stacks, setStacks] = useState<number[]>([100]);
const [history, setHistory] = useState(ROOT_HISTORY);
const [node, setNode] = useState<NodeResponse | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [captured, setCaptured] = useState<Partial<Record<Position, RangeWeights>>>({});
const [headsUp, setHeadsUp] = useState<HeadsUp | null>(null);
const [resolved, setResolved] = useState<ResolvedScenario | null>(null);
// Discover the NL tree's available stacks for the picker.
useEffect(() => {
let cancelled = false;
getManifest()
.then((m) => {
if (cancelled) return;
setStacks(m.stacks);
setStack((s) => (m.stacks.includes(s) ? s : (m.stacks[0] ?? s)));
})
.catch(() => {});
return () => {
cancelled = true;
};
}, []);
const emit = (r: ResolvedScenario | null) => {
setResolved(r);
onResolved(r);
};
// A different stack is a different tree — re-root the walk. Handled here (not
// in an effect) so changing stack doesn't cascade renders.
const changeStack = (next: number) => {
setStack(next);
setHistory(ROOT_HISTORY);
setCaptured({});
setHeadsUp(null);
setError(null);
emit(null);
};
// Fetch the current decision node while walking (not once the pot has closed).
useEffect(() => {
if (headsUp) return;
let cancelled = false;
async function run() {
setLoading(true);
setError(null);
try {
const n = await getNode(stack, history);
if (!cancelled) setNode(n);
} catch (err) {
if (!cancelled) {
setNode(null);
setError(err instanceof Error ? err.message : "No range here.");
}
} finally {
if (!cancelled) setLoading(false);
}
}
run();
return () => {
cancelled = true;
};
}, [stack, history, headsUp]);
const advance = (action: NodeAction) => {
if (!node) return;
const nextCaptured = { ...captured, [node.actor]: clampWeights(action.weights) };
setCaptured(nextCaptured);
const res = resolveAfterAction(history, action.action, action.kind, stack);
if (res.kind === "terminal") {
setError("Everyone folded — no postflop spot on this line. Rewind and pick another action.");
return;
}
if (res.kind === "headsup") {
setHeadsUp({
oop: res.oop,
ip: res.ip,
survivors: res.survivors,
closedActor: node.actor,
closedHistory: history,
});
setError(null);
emit({
oop: nextCaptured[res.oop] ?? fullRange(),
ip: nextCaptured[res.ip] ?? fullRange(),
oopPos: res.oop,
ipPos: res.ip,
});
return;
}
setHistory(res.nextHistory);
};
// Rewind the line to `position` (an already-acted seat), pruning stale captures.
const jumpBack = (position: Position) => {
const base = headsUp ? headsUp.closedHistory : history;
const tokens = base.split("_");
const indices: number[] = [];
for (let i = 0; i < tokens.length; i += 2) if (tokens[i] === position) indices.push(i);
if (indices.length === 0) return;
const targetIdx = indices[indices.length - 1];
const newHistory = tokens.slice(0, targetIdx + 1).join("_");
const { seats, hero } = parseHistory(newHistory, stack);
const kept: Partial<Record<Position, RangeWeights>> = {};
for (const p of PLAY_ORDER) {
if (p === hero) continue;
if (captured[p] && seats[p].action && !seats[p].folded) kept[p] = captured[p];
}
setCaptured(kept);
setHeadsUp(null);
setError(null);
setHistory(newHistory);
emit(null);
};
const reset = () => {
setHeadsUp(null);
setCaptured({});
setError(null);
setHistory(ROOT_HISTORY);
emit(null);
};
// Build the per-seat view. While walking, parseHistory drives it. Once closed,
// mark the closing call, fold everyone but the two survivors, and badge OOP/IP.
const walk = parseHistory(headsUp ? headsUp.closedHistory : history, stack);
const seats = headsUp ? closedSeats(headsUp, walk.seats, stack) : walk.seats;
const actor: Position | null = headsUp ? null : walk.hero;
const roleOf = (p: Position): RangePlayer | null =>
headsUp ? (p === headsUp.oop ? "oop" : p === headsUp.ip ? "ip" : null) : null;
const atRoot = history === ROOT_HISTORY && !headsUp;
return (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-muted-foreground">Scenario</span>
<div className="flex items-center gap-2">
<label className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
Stack
<select
value={stack}
onChange={(e) => changeStack(Number(e.target.value))}
className="h-7 rounded-md border border-input bg-card px-1.5 text-xs text-foreground outline-none focus-visible:border-ring"
>
{stacks.map((s) => (
<option key={s} value={s}>
{s}bb
</option>
))}
</select>
</label>
<button
type="button"
onClick={reset}
disabled={atRoot}
className="flex items-center gap-1 rounded-md border border-border bg-card px-2 py-1 text-[11px] text-foreground transition-colors hover:bg-accent disabled:opacity-30"
>
<Undo2 className="size-3" /> Reset
</button>
</div>
</div>
<div className="flex gap-2 overflow-x-auto pb-1">
{PLAY_ORDER.map((p) => (
<SeatCard
key={p}
seat={seats[p]}
isActor={p === actor}
actions={p === actor && node?.actor === p ? node?.actions : undefined}
role={roleOf(p)}
stack={stack}
disabled={loading}
onSelectAction={advance}
onJumpBack={() => jumpBack(p)}
/>
))}
{loading && !headsUp ? (
<div className="flex min-h-[96px] w-12 shrink-0 items-center justify-center">
<Loader2 className="size-4 animate-spin text-muted-foreground" />
</div>
) : null}
</div>
{error ? <p className="text-[11px] text-destructive">{error}</p> : null}
{resolved ? (
<div className="grid grid-cols-2 gap-2">
<RangePreviewTile pos={resolved.oopPos} role="oop" weights={resolved.oop} />
<RangePreviewTile pos={resolved.ipPos} role="ip" weights={resolved.ip} />
</div>
) : (
<p className="text-[11px] text-muted-foreground/70">
Walk the preflop tree above until a raise is called — both players' ranges load
automatically. Or leave it for full (random) ranges.
</p>
)}
</div>
);
}
function SeatCard({
seat,
isActor,
actions,
role,
stack,
disabled,
onSelectAction,
onJumpBack,
}: {
seat: SeatState;
isActor: boolean;
actions?: NodeAction[];
role: RangePlayer | null;
stack: number;
disabled?: boolean;
onSelectAction: (a: NodeAction) => void;
onJumpBack: () => void;
}) {
const highlighted = isActor || !!role;
const sorted = actions ? sortActionsForDisplay(actions) : [];
const clickable = !isActor && !!seat.action;
const header = (
<>
<div className="flex items-center justify-between">
<div className="flex items-center gap-1.5">
<span
className={`text-sm font-semibold tracking-wide ${
highlighted ? "text-foreground" : seat.folded ? "text-muted-foreground/50" : "text-foreground"
}`}
>
{seat.position}
</span>
{seat.isDealer ? (
<span className="flex size-3.5 items-center justify-center rounded-full bg-foreground text-[8px] font-bold text-background">
D
</span>
) : null}
{role ? (
<span
className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${
role === "oop"
? "bg-foreground text-background"
: "border border-foreground/50 text-foreground"
}`}
>
{role.toUpperCase()}
</span>
) : null}
</div>
<span className={`text-[11px] font-medium ${seat.folded ? "text-muted-foreground/40" : "text-muted-foreground"}`}>
{formatBb(seat.remaining)}
</span>
</div>
{seat.committed > 0 ? (
<span className={`text-[10px] ${seat.folded ? "text-muted-foreground/30" : "text-muted-foreground/70"}`}>
in {formatBb(seat.committed)}
</span>
) : null}
</>
);
const body = isActor ? (
<div className="flex flex-col">
{sorted.length === 0 ? (
<span className="py-1 text-xs text-muted-foreground">—</span>
) : (
sorted.map((a) => (
<button
key={a.action}
type="button"
disabled={disabled}
onClick={() => onSelectAction(a)}
className="flex items-center justify-between rounded px-1 py-1 text-left text-xs text-foreground transition-colors hover:bg-accent disabled:opacity-40"
>
<span className="truncate">{labelForAction(a, stack)}</span>
<span className="size-2.5 shrink-0 rounded-full border border-muted-foreground/50" />
</button>
))
)}
</div>
) : (
<div className="flex flex-1 items-center py-1">
{seat.action ? (
<span
className={`inline-block max-w-full truncate rounded px-2 py-0.5 text-xs font-semibold ${
seat.folded
? "border border-border text-muted-foreground/60"
: "bg-accent text-foreground"
}`}
>
{seat.action}
</span>
) : (
<span className="text-xs text-muted-foreground/60">—</span>
)}
</div>
);
const className = `flex min-h-[96px] w-[124px] shrink-0 flex-col gap-1 rounded-xl border p-2 transition-colors ${
highlighted ? "border-foreground/40 bg-accent/40" : "border-border bg-card/40"
} ${clickable ? "cursor-pointer hover:border-foreground/30" : ""}`;
if (clickable) {
return (
<button type="button" onClick={onJumpBack} className={`${className} text-left`}>
{header}
{body}
</button>
);
}
return (
<div className={className}>
{header}
{body}
</div>
);
}
/** A non-interactive 13×13 thumbnail of a range — cells lit by weight. */
function RangeMini({ weights }: { weights: RangeWeights }) {
return (
<div className="grid size-16 shrink-0 grid-cols-[repeat(13,minmax(0,1fr))] gap-px">
{ALL_HANDS.map((hand) => {
const w = weights[hand] ?? 0;
return (
<div
key={hand}
className={w > 0 ? "bg-foreground" : "bg-foreground/10"}
style={w > 0 ? { opacity: 0.25 + 0.75 * Math.min(w, 1) } : undefined}
/>
);
})}
</div>
);
}
function RangePreviewTile({
pos,
role,
weights,
}: {
pos: Position;
role: RangePlayer;
weights: RangeWeights;
}) {
const combos = totalCombos(weights);
const pct = (combos / FULL_COMBOS) * 100;
return (
<div className="flex items-center gap-3 rounded-lg border border-border bg-card/40 p-2.5">
<RangeMini weights={weights} />
<div className="flex flex-col gap-0.5">
<div className="flex items-center gap-1.5">
<span className="text-sm font-semibold text-foreground">{pos}</span>
<span
className={`rounded px-1 py-px text-[8px] font-bold tracking-wide ${
role === "oop" ? "bg-foreground text-background" : "border border-foreground/50 text-foreground"
}`}
>
{role.toUpperCase()}
</span>
</div>
<span className="text-xs text-muted-foreground tabular-nums">{combos.toFixed(1)} combos</span>
<span className="text-xs text-muted-foreground tabular-nums">{pct.toFixed(1)}%</span>
</div>
</div>
);
}
/** Project the walking state onto the closed-pot view (mirror of mobile closedSeats). */
function closedSeats(
hu: HeadsUp,
walkSeats: Record<Position, SeatState>,
stack: number,
): Record<Position, SeatState> {
const survivors = new Set<Position>(hu.survivors);
const other = hu.survivors.find((p) => p !== hu.closedActor) ?? hu.closedActor;
const out = {} as Record<Position, SeatState>;
for (const p of PLAY_ORDER) {
const s = { ...walkSeats[p], isHero: false };
if (p === hu.closedActor) {
s.action = "Call";
s.committed = walkSeats[other].committed;
s.remaining = Math.max(0, stack - s.committed);
} else if (!survivors.has(p)) {
s.folded = true;
if (!s.action) s.action = "Fold";
}
out[p] = s;
}
return out;
}
components/solver/strategy-grid.tsx
"use client";
import { useMemo } from "react";
import type { SolverActionInfo, SolverHandStrategy } from "@/lib/solver/types";
import { HandMatrix, type MatrixCell } from "@/components/pokerstudy/hand-matrix";
import { RANGE_COLORS } from "@/lib/pokerstudy/poker";
// Ranks high-to-low; the 13×13 grid is indexed by these. Suited combos sit above
// the diagonal, offsuit below, pairs on it — the standard hand matrix.
const RANKS = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"];
// Per-action colors live in the registry core (lib/pokerstudy/poker.ts) so the
// installable components and the app paint ranges identically (the default
// Mint palette). Exported so every strategy surface uses this one palette.
export const ACTION_COLORS: Record<SolverActionInfo["label"], string> = RANGE_COLORS;
// The 13×13 matrix itself ships as the `hand-matrix` registry item; both the
// postflop `StrategyGrid` and the Explorer's preflop grid render through it.
export { HandMatrix, type MatrixCell };
function classOf(combo: string): { row: number; col: number; label: string } | null {
if (combo.length !== 4) return null;
const r1 = RANKS.indexOf(combo[0].toUpperCase());
const r2 = RANKS.indexOf(combo[2].toUpperCase());
if (r1 < 0 || r2 < 0) return null;
const suited = combo[1].toLowerCase() === combo[3].toLowerCase();
if (r1 === r2) {
const r = RANKS[r1];
return { row: r1, col: r1, label: `${r}${r}` };
}
const hi = Math.min(r1, r2); // smaller index = higher rank
const lo = Math.max(r1, r2);
const label = `${RANKS[hi]}${RANKS[lo]}${suited ? "s" : "o"}`;
// Suited above the diagonal (row=hi, col=lo); offsuit below (row=lo, col=hi).
return suited ? { row: hi, col: lo, label } : { row: lo, col: hi, label };
}
/** Below this share of a combo the hand is treated as not in the range. */
const REACH_EPS = 1e-9;
/**
* Aggregate the per-combo strategy into the 13×13 hand matrix, weighted by how
* often the acting player actually HOLDS each combo here.
*
* The weighting is not cosmetic. The engine solves — and dumps — a strategy at
* every infoset whether or not the line reaches it, so deep in a tree most
* dumped combos are hands the player can no longer have. Averaging those in
* unweighted made the grid disagree with the action summary next to it: on a
* turn node after a check-call, 168 of 329 dumped combos had zero reach and bet
* 63% between them, painting a wall of red under a "Bet 1%" header.
*
* `reach` is optional: solve roots (the /solver page, replays) query the full
* starting range, where every dumped combo is genuinely held and weight 1 is
* right. Passing it makes a class that is out of the range render as an empty
* square rather than as a fully-saturated cell.
*/
export function buildGrid(
actions: SolverActionInfo[],
hands: SolverHandStrategy[],
reach?: ReadonlyMap<string, number> | null,
): (MatrixCell | null)[][] {
const n = actions.length;
const sums = RANKS.map(() =>
RANKS.map(() => ({ freqs: new Array<number>(n).fill(0), weight: 0, label: "" })),
);
for (const hand of hands) {
const cls = classOf(hand.combo);
if (!cls) continue;
const w = reach ? (reach.get(hand.combo) ?? 0) : 1;
if (w <= REACH_EPS) continue;
const slot = sums[cls.row][cls.col];
slot.label = cls.label;
slot.weight += w;
for (let a = 0; a < n; a++) slot.freqs[a] += w * (hand.freqs[a] ?? 0);
}
return sums.map((rowArr) =>
rowArr.map((slot) =>
slot.weight <= REACH_EPS
? null
: { label: slot.label, freqs: slot.freqs.map((f) => f / slot.weight) },
),
);
}
export function StrategyGrid({
actions,
hands,
reach,
}: {
actions: SolverActionInfo[];
hands: SolverHandStrategy[];
/** Per-combo reach at this node. Omit at a solve root, where the dumped
* combos ARE the range; pass it anywhere the line has narrowed the range,
* so the grid agrees with the reach-weighted action summary. */
reach?: ReadonlyMap<string, number> | null;
}) {
const cells = useMemo(() => buildGrid(actions, hands, reach).flat(), [actions, hands, reach]);
const colors = useMemo(() => actions.map((a) => ACTION_COLORS[a.label]), [actions]);
const legend = useMemo(
() =>
actions.map((action) => ({
// add is a raw engine amount — round for display ("Bet 3.97", not
// "Bet 3.9749999999999996").
label: `${action.label}${action.add > 0 ? ` ${Math.round(action.add * 100) / 100}` : ""}`,
color: ACTION_COLORS[action.label],
})),
[actions],
);
const foldIndex = actions.findIndex((a) => a.label === "Fold");
return (
<HandMatrix
cells={cells}
colors={colors}
legend={legend}
foldIndex={foldIndex < 0 ? undefined : foldIndex}
aggressiveFirst
/>
);
}
lib/access/grant-scope.ts
import { DATA_ACCESS, type Dataset, type Plan } from "@/lib/access/policy";
/**
* The crypto-free half of the ranges grant: the header name, the payload
* shape, and what a scope allows. The trainer client imports this; signing
* and verifying stay in `grant.ts`, which needs `node:crypto` and so can
* only be bundled for the server.
*/
export const GRANT_HEADER = "x-ranges-grant";
export type StackGrant = "all" | number[];
export type RangesScope = Partial<Record<Dataset, StackGrant>>;
export type GrantPayload = {
v: 1;
plan: Plan;
/** Unix seconds. */
exp: number;
};
export function scopeForPlan(plan: Plan): RangesScope {
const scope: RangesScope = {};
for (const dataset of Object.keys(DATA_ACCESS) as Dataset[]) {
const grant = DATA_ACCESS[dataset].plans[plan];
if (!grant) continue;
scope[dataset] = grant === "all" ? "all" : [...grant.stacks];
}
return scope;
}
export function scopeAllows(scope: RangesScope | null | undefined, dataset: Dataset, stack: number): boolean {
if (!scope) return false;
const grant = scope[dataset];
if (grant === "all") return true;
return Array.isArray(grant) && grant.includes(stack);
}
lib/access/plan-required.ts
import { toast } from "sonner";
import { currentRangesPlan, forgetRangesSession } from "@/lib/access/session-client";
import { explorerHost } from "@/lib/explorer/host";
/**
* Client side of the data gate ([gate.ts]): when a ranges call comes back
* 401/403, tell the user why once, with a way forward, instead of letting the
* surface show a raw HTTP error.
*
* Both prompts are once per browser session (sessionStorage, falling back to
* once per page): a hand of a paid game fetches a node at every decision, and
* a toast at each one is noise, not information. The upgrade prompt never
* shows to a player whose session grant already says Pro, Studio or trial: a
* 403 there means a stale grant, so it is dropped and re-read instead. A
* no-op on the server.
*/
const SEEN_KEY = "pokerstudy.plan-prompt.v1";
const TOAST_ID = "plan-required";
const PAID_PLANS = new Set(["trial", "pro", "studio"]);
/** Prompts already shown on this page (the fallback when storage is blocked). */
const shownThisPage = new Set<"sign-in" | "upgrade">();
/**
* Clerk's signed-in bit from the page that mounted the trainer. `null` means
* Clerk hasn't reported yet. A 401 is a sign-in prompt only when this is
* explicitly false — a signed-in player with a stale cookie must not see it.
*/
let clerkSignedIn: boolean | null = null;
/** Set from the play / trainer shell as soon as `useAuth()` has loaded. */
export function setPlanPromptAuth(signedIn: boolean | null): void {
clerkSignedIn = signedIn;
}
export function resetPlanPromptForTests(): void {
clerkSignedIn = null;
shownThisPage.clear();
}
function seenThisSession(kind: "sign-in" | "upgrade"): boolean {
if (shownThisPage.has(kind)) return true;
try {
return window.sessionStorage?.getItem(`${SEEN_KEY}:${kind}`) === "1";
} catch {
return false;
}
}
function markSeen(kind: "sign-in" | "upgrade"): void {
shownThisPage.add(kind);
try {
window.sessionStorage?.setItem(`${SEEN_KEY}:${kind}`, "1");
} catch {
// Private mode / blocked storage: once per page still holds.
}
}
/** Call with any ranges response status; only 401/403 do anything. */
export function notifyPlanRequired(status: number): void {
if (status !== 401 && status !== 403) return;
if (typeof window === "undefined") return;
if (status === 401 && clerkSignedIn !== false) return;
const kind = status === 401 ? "sign-in" : "upgrade";
if (kind === "upgrade") {
const plan = currentRangesPlan();
if (plan && PAID_PLANS.has(plan)) {
// A paid grant was refused: it is stale (or the plan just changed).
// Re-read the plan on the next fetch rather than asking a paying
// player to upgrade.
forgetRangesSession();
return;
}
}
if (seenThisSession(kind)) return;
markSeen(kind);
const signIn = kind === "sign-in";
// A host with its own plans (pokerdata.io) words the prompt itself.
const custom = explorerHost().planPrompt?.[kind];
if (custom) {
toast(custom.title, {
id: TOAST_ID,
closeButton: true,
description: custom.description,
action: {
label: custom.label,
onClick: () => {
window.location.href = custom.href(window.location.pathname + window.location.search);
},
},
});
return;
}
toast(signIn ? "Sign in to study this spot" : "This spot is part of Pro and Studio", {
id: TOAST_ID,
closeButton: true,
description: signIn
? "6-max NL is free for everyone. Other games are part of Pro and Studio."
: "6-max NL is free for everyone. Upgrade for every other game.",
action: {
label: signIn ? "Sign in" : "See plans",
onClick: () => {
window.location.href = signIn
? `/sign-in?redirect_url=${encodeURIComponent(window.location.pathname)}`
: "/pricing";
},
},
});
}
lib/access/policy.ts
/**
* THE access table for solver data: which plan (or API key) may read which
* dataset. Every data route checks it through `requireDataAccess`
* ([gate.ts]), so changing who gets what is an edit to `DATA_ACCESS` below
* and nothing else.
*
* Pure (no DB, no Clerk) so it can be unit-tested and read at a glance.
*/
/**
* Who is asking, by plan. `guest` is no account at all; `trial` is a free
* account inside a code-redemption trial window (see lib/subscription).
*/
export type Plan = "guest" | "free" | "trial" | "pro" | "studio";
/**
* How the caller proved who they are. `api-key` is a Studio `psk_…` token
* (the programmatic / MCP path); `internal` is pokerdata.io's server proxy,
* which enforces its own subscription before calling us.
*/
export type Credential = "none" | "session" | "api-key" | "internal";
/** The datasets behind `/api/ranges/<dataset>/*`. */
export type Dataset =
| "nl"
| "nl9"
| "nlmtt8"
| "nlh8-hydra"
| "nlh8-icm"
| "nlhu"
| "plo"
| "plo4hu"
| "plo5"
| "plo6hu"
| "plo9";
/** What a plan may read of a dataset: all of it, or only some stack depths. */
export type Grant = "all" | { stacks: readonly number[] };
export type DataRule = {
/** Per-plan grant. A plan that isn't listed gets nothing. */
plans: Partial<Record<Plan, Grant>>;
/** Whether a Studio API key (`psk_…`) may read this dataset. */
apiKey: boolean;
};
const PAID: Partial<Record<Plan, Grant>> = { trial: "all", pro: "all", studio: "all" };
export const DATA_ACCESS: Record<Dataset, DataRule> = {
// 6-max NL is open to everyone, guests included, at every stack, so Train
// and Play work with no account: the App Store requires that (5.1.1(v),
// see #493), and app builds from before this gate send no credential at
// all. The other games are paid.
nl: { plans: { ...PAID, free: "all", guest: "all" }, apiKey: true },
nl9: { plans: PAID, apiKey: true },
nlmtt8: { plans: PAID, apiKey: true },
"nlh8-hydra": { plans: PAID, apiKey: true },
"nlh8-icm": { plans: PAID, apiKey: true },
nlhu: { plans: PAID, apiKey: true },
plo: { plans: PAID, apiKey: true },
plo4hu: { plans: PAID, apiKey: true },
plo5: { plans: PAID, apiKey: true },
plo6hu: { plans: PAID, apiKey: true },
plo9: { plans: PAID, apiKey: true },
};
export type AccessVerdict =
| { ok: true }
| { ok: false; reason: "sign-in" | "upgrade" };
/**
* May this caller read `dataset` at `stack`? Discovery (the manifest roots,
* which only list stacks and endpoints) is not checked here; callers gate the
* data endpoints only.
*/
export function checkDataAccess(
dataset: Dataset,
caller: { plan: Plan; credential: Credential },
stack: number,
): AccessVerdict {
if (caller.credential === "internal") return { ok: true };
const rule = DATA_ACCESS[dataset];
if (caller.credential === "api-key" && !rule.apiKey) {
return { ok: false, reason: "upgrade" };
}
const grant = rule.plans[caller.plan];
if (grant === "all") return { ok: true };
if (grant && grant.stacks.includes(stack)) return { ok: true };
return { ok: false, reason: caller.plan === "guest" ? "sign-in" : "upgrade" };
}
lib/access/session-client.ts
import { explorerHost } from "@/lib/explorer/host";
import type { Dataset } from "@/lib/access/policy";
import { trainerToken } from "@/lib/trainer/auth";
import {
scopeAllows as scopeGrants,
type GrantPayload,
type RangesScope,
} from "@/lib/access/grant-scope";
/**
* The trainer's one entitlement read. `/api/ranges/session` returns the plan,
* the stacks it may open, and a signed grant. Node fetches reuse that grant
* until it expires — they do not call this again.
*/
export type RangesSession = {
plan: GrantPayload["plan"];
exp: number;
token: string;
scope: RangesScope;
};
let clerkSignedIn: boolean | null = null;
let current: RangesSession | null = null;
let pending: Promise<RangesSession | null> | null = null;
export function rangesClerkSignedIn(): boolean | null {
return clerkSignedIn;
}
/** Called from the play / trainer shells as soon as Clerk has loaded. */
export function setRangesClerkSignedIn(signedIn: boolean | null): void {
clerkSignedIn = signedIn;
if (signedIn === false) {
current = null;
pending = null;
}
}
export function peekGrantToken(): string | null {
if (!current || current.exp * 1000 <= Date.now() + 5_000) return null;
return current.token;
}
/** The plan of the current, unexpired session grant, or null when there is none. */
export function currentRangesPlan(): GrantPayload["plan"] | null {
if (!current || current.exp * 1000 <= Date.now()) return null;
return current.plan;
}
/** Drop the cached grant so the next node fetch re-reads the plan. */
export function forgetRangesSession(): void {
current = null;
}
export function scopeAllows(dataset: Dataset, stack: number): boolean {
if (!current || current.exp * 1000 <= Date.now()) return false;
return scopeGrants(current.scope, dataset, stack);
}
export function rememberRangesSession(session: RangesSession | null): void {
current = session;
pending = null;
}
export function resetRangesSessionForTests(): void {
clerkSignedIn = null;
current = null;
pending = null;
}
/**
* One in-flight session read, shared by every caller. A fresh grant is
* returned without touching the network.
*/
export function ensureRangesSession(): Promise<RangesSession | null> {
if (clerkSignedIn === false) return Promise.resolve(null);
if (current && current.exp * 1000 > Date.now() + 60_000) return Promise.resolve(current);
if (pending) return pending;
pending = loadSession().finally(() => {
pending = null;
});
return pending;
}
async function loadSession(): Promise<RangesSession | null> {
// A host that gates its ranges feed itself has no session to read.
const sessionUrl = explorerHost().rangesSession;
if (!sessionUrl) return null;
try {
const headers: Record<string, string> = { Accept: "application/json" };
const token = await trainerToken().catch(() => null);
if (token) headers.Authorization = `Bearer ${token}`;
const res = await fetch(sessionUrl, { headers, credentials: "same-origin" });
if (!res.ok) return null;
const body = (await res.json()) as Partial<RangesSession>;
if (!body || typeof body.token !== "string" || typeof body.exp !== "number" || !body.scope) {
return null;
}
current = {
plan: body.plan ?? "free",
exp: body.exp,
token: body.token,
scope: body.scope,
};
return current;
} catch {
return null;
}
}
lib/explorer/bet-size.ts
/**
* Bet and raise sizes as a percentage of the pot, GTO Wizard's convention:
*
* - a bet is its chips over the pot before it: 3 into 6 is "Bet 50%";
* - a raise is the chips beyond the call over the pot after the call, so a
* pot-size raise is "Raise 100%" (the pot-limit maximum).
*
* The NL preflop tokens ("60%", "76%") and MonkerSolver's PLO size codes
* already use this convention; this module covers the PLO depth tags and the
* engine's postflop chip labels, which carry an amount instead.
*/
/** MonkerSolver PLO raise tokens: a depth tag, optionally size-coded ("Open-40075"). */
const PLO_RAISE_RE = /^(Open|3B|4B|5B|6B|7B|8B)(?:-(\d+))?$/;
/**
* Pot percentage of a MonkerSolver PLO raise token, or null when the token
* isn't one or its size code isn't a pot fraction. A bare depth tag is a pot
* raise (100%); size code 40000 + n is n% pot.
*/
export function ploRaisePotPct(token: string): number | null {
const m = token.match(PLO_RAISE_RE);
if (!m) return null;
if (m[2] === undefined) return 100;
const code = Number(m[2]);
return code > 40000 ? code - 40000 : null;
}
/** "Bet 3" → { kind: "Bet", amount: 3 }; labels without an amount give amount 0. */
function parseChipLabel(label: string): { kind: string; amount: number } {
const [kind, amt] = label.split(" ");
const amount = amt === undefined ? 0 : Number(amt);
return { kind, amount: Number.isFinite(amount) ? amount : 0 };
}
/**
* Pot percentage of a postflop bet or raise, from the street's starting pot and
* the actions before it on the street. Labels are the engine's ("Check",
* "Bet 3", "Call 3", "Raise 12.4", "AllIn 97"): the amount is the chips that
* action puts in. Players alternate, so the walk needs no seat. Null for
* anything that isn't a sized Bet or Raise.
*/
export function streetBetPotPct(streetPot: number, prior: string[], label: string): number | null {
const { kind, amount } = parseChipLabel(label);
if ((kind !== "Bet" && kind !== "Raise") || amount <= 0) return null;
const put = [0, 0];
prior.forEach((l, i) => {
put[i % 2] += parseChipLabel(l).amount;
});
const me = prior.length % 2;
const toCall = Math.max(0, put[1 - me] - put[me]);
const pot = streetPot + put[0] + put[1];
const raise = amount - toCall;
const base = pot + toCall;
if (base <= 0 || raise <= 0) return null;
return Math.round((raise / base) * 100);
}
lib/explorer/custom-solve.ts
// Custom postflop solve requests (#231): the one place that decides what a
// product-quality Explorer solve looks like. The builder UI, the offline
// sample-fixture generator (scripts/build-sample-solutions.ts), and the tests
// all build their engine configs through `buildPostflopSolveRequest`, so a
// user-built flop solution and the canonical fixtures share the same shape:
// dump_nodes + dump_ev, one chance deal of dumped depth, and the #220 river
// action abstraction that keeps a flop tree solvable in ~10-15 minutes.
//
// Client-safe: no server imports. The localStorage pending-solve record lives
// here too, because a flop solve outlives most tabs — the worker keeps jobs
// server-side, so the builder can resume by job id after a reload.
import type { SolveRequest, TreeSizingConfig } from "@/lib/solver/types";
/** Defaults matching the sample fixtures' product-quality profile. */
export const CUSTOM_SOLVE_DEFAULTS = {
/** Pot-fraction bet sizes on flop + turn. */
betSizes: [0.75],
addAllin: true,
/** 2, like the sample fixtures — NOT 3: with a single sizing + all-in, one
* extra raise level multiplies the dumped flop tree past Node's ~512MB
* string cap (measured live), which no client can read back. */
maxAggressions: 2,
/** Coarser river-only abstraction (#220) — keeps flop trees tractable. */
riverBetSizes: [0.75],
riverMaxAggressions: 2,
/** Ceiling only — the exploitability target or the convergence plateau
* stops the solve in practice. */
iterations: 2500,
/** Stop at 1% of pot — study grade. Range charts are visually identical to
* a 0.5% solve well before 1%, and deep spots decay ~1/iterations, so the
* old 0.5% default routinely ground to the iteration cap for precision
* nobody could see. Users who want 0.5% can type it. */
targetExploitability: 1.0,
/** Convergence-plateau early stop (#243 step 1, engine-side): end the solve
* once a progress chunk improves exploitability by less than this relative
* fraction (with the engine's built-in warmup + patience), i.e. when it has
* effectively converged — even if the typed target is unreachable for the
* spot. This is what keeps deep 100bb solves from running the full cap. */
convergencePlateau: 0.04,
/** Iterations for a depth-limited "AI solve" (no exploitability target —
* the net-leaf tree converges on iteration budget alone). */
aiIterations: 1000,
} as const;
export interface PostflopSolveSpec {
/** Board cards, space-separated: 3 (flop), 4 (turn), or 5 (river). */
board: string;
/** Pot at the start street, bb. */
potBb: number;
/** Chips behind each player, bb. */
effStackBb: number;
/** Engine range strings (169-grid classes or explicit combos). */
oopRange: string;
ipRange: string;
betSizes: number[];
addAllin: boolean;
maxAggressions: number;
/** Omit / empty to use `betSizes` on the river too. */
riverBetSizes?: number[];
riverMaxAggressions?: number;
/** Per-street, per-player tree overrides (GTO-Wizard-style tree editor).
* Unset cells inherit the flat fields above. Omit for the legacy tree. */
sizing?: TreeSizingConfig;
iterations: number;
targetExploitability?: number;
/** Relative per-chunk improvement below which the solve is considered
* converged (engine convergence_plateau). Omit to disable. */
convergencePlateau?: number;
/** Iterations between progress ticks (default 10). */
logInterval?: number;
/** Dumped chance-deal depth (default 1 — the fixture shape: a flop start
* dumps every turn subtree, rivers come from the viewer's on-demand
* solves; a turn start dumps every river subtree). */
dumpMaxDeals?: number;
/** Emit per-action EV on every dumped node — what turns a graded
* mistake into a bb figure instead of a bare tier. Off by default: it
* roughly doubles the dump's numeric payload, and a flop tree already sits
* close to the reader-side size ceiling `maxAggressions` guards. */
dumpActionEvs?: boolean;
/** Depth-limited "AI solve" (flop only): the tree ends in value-net leaves
* at the turn boundary, so the dump carries flop-street nodes only and
* every turn card resolves via the viewer's on-demand exact child solves. */
aiSolve?: boolean;
}
/** The exact engine request for a custom postflop solution. */
export function buildPostflopSolveRequest(spec: PostflopSolveSpec): SolveRequest {
const req: SolveRequest = {
variant: "nlhe",
limit: "nolimit",
board: spec.board.trim(),
pot: spec.potBb,
effective_stack: spec.effStackBb,
bet_sizes: spec.betSizes,
add_allin: spec.addAllin,
max_aggressions: spec.maxAggressions,
iterations: spec.iterations,
target_exploitability: spec.targetExploitability,
// Each progress report costs a full best-response evaluation, which is
// single-threaded in the engine — at 10 it can dominate deep-tree solve
// wall-clock (measured on a 96-core box: long serial plateaus between
// parallel CFR bursts). 50 keeps the progress line and the early-stop
// check alive at a fifth of the tax.
log_interval: spec.logInterval ?? 50,
dump_ev: true,
dump_nodes: true,
dump_max_deals: spec.dumpMaxDeals ?? 1,
...(spec.dumpActionEvs ? { dump_action_evs: true } : {}),
oop_range: spec.oopRange,
ip_range: spec.ipRange,
};
if (spec.convergencePlateau !== undefined) {
req.convergence_plateau = spec.convergencePlateau;
}
// Exact solves use PCFR+ (#253): ~1.9× fewer iterations to the same
// exploitability, verified on the convergence battery + prod spot. The
// depth-limited AI path stays on the engine default.
if (!spec.aiSolve) {
req.cfr_variant = "pcfr+";
// Always keep the snapshot (#262): it costs the worker a bounded LRU
// slot and makes the next same-geometry re-solve warm (seconds, not
// minutes). The AI path can't snapshot (net state isn't fingerprinted).
req.keep_snapshot = true;
// Emit the CFR-D carry for OOP (#233): the opponent-CFV promises that
// seed *safe* on-demand subgame re-solves in the viewer (resolve-carry.ts)
// instead of the unsafe reach-range bootstrap. Costs one EV walk at the
// root; exact solves only (a net-leaf tree would price promises off the
// net, unvalidated).
req.emit_carry_for = 0;
}
if (spec.riverBetSizes && spec.riverBetSizes.length > 0) {
req.river_bet_sizes = spec.riverBetSizes;
}
if (spec.riverMaxAggressions !== undefined) {
req.river_max_aggressions = spec.riverMaxAggressions;
}
if (spec.sizing && Object.keys(spec.sizing).length > 0) {
req.sizing = spec.sizing;
}
if (spec.aiSolve) req.aiSolve = true;
return req;
}
/** True when two requests describe the SAME solve geometry — board, tree
* shape, and ranges — so a warm start (#262) is valid between them. Only
* convergence knobs (iterations, target, plateau, log cadence) may differ;
* anything else changes the engine's snapshot fingerprint and would be
* rejected server-side, so the client never sends warm_start_from for it. */
export function sameSolveGeometry(a: SolveRequest, b: SolveRequest): boolean {
const eq = (x: unknown, y: unknown) => JSON.stringify(x ?? null) === JSON.stringify(y ?? null);
return (
a.board === b.board &&
a.pot === b.pot &&
a.effective_stack === b.effective_stack &&
eq(a.bet_sizes, b.bet_sizes) &&
a.add_allin === b.add_allin &&
a.max_aggressions === b.max_aggressions &&
eq(a.river_bet_sizes, b.river_bet_sizes) &&
a.river_max_aggressions === b.river_max_aggressions &&
eq(a.sizing, b.sizing) &&
a.oop_range === b.oop_range &&
a.ip_range === b.ip_range &&
a.variant === b.variant &&
a.limit === b.limit &&
!a.aiSolve === !b.aiSolve
);
}
/** A human ETA hint for the solve, by start street (and solve kind). */
export function solveEtaHint(boardCardCount: number, ai = false): string {
if (ai) return "AI flop solves take seconds–minutes (beta)";
if (boardCardCount <= 3) return "flop solves typically take 1–2 minutes";
if (boardCardCount === 4) return "turn solves typically take 1–2 minutes";
return "river solves typically take 1–2 minutes";
}
/**
* Friendlier copy for solve-submission failures. The worker queues excess
* jobs rather than rejecting them, so "busy" errors are rare — but a proxy or
* future limiter may still 429/503, and an unreachable worker 502s.
*/
export function describeSolveError(message: string): string {
const m = message.toLowerCase();
if (m.includes("unreachable") || m.includes("not configured")) {
return "The solver service is offline right now, so custom solves can't run. Please try again in a few minutes.";
}
if (m.includes("429") || m.includes("too many") || m.includes("busy") || m.includes("slot")) {
return "The solver is busy with other solves right now — your job will queue; retry in a moment if it doesn't start.";
}
return message;
}
// ---------------------------------------------------------------------------
// Pending-solve record — resume a long solve after a tab reload.
//
// The worker (`solve serve`) keeps every job in memory until the process
// restarts, and `/api/solver/jobs/:id` polls it statelessly, so the browser
// only needs to remember the job id + the request it posted. One slot is
// enough: the worker runs 2 concurrent solves and the builder starts one at a
// time.
// ---------------------------------------------------------------------------
const PENDING_KEY = "explorer.pendingSolve.v1";
export interface PendingSolve {
jobId: string;
request: SolveRequest;
/** Epoch ms when the job was accepted. */
startedAt: number;
/** Seat labels for the eventual save meta. */
oopLabel: string;
ipLabel: string;
/** Suggested title ("BB vs BTN · Ad 7c 2s"). */
title: string;
/** True when this is a depth-limited AI solve (affects the resume copy). */
ai?: boolean;
}
export function readPendingSolve(): PendingSolve | null {
try {
const raw = window.localStorage.getItem(PENDING_KEY);
if (!raw) return null;
const p = JSON.parse(raw) as PendingSolve;
if (!p || typeof p.jobId !== "string" || !p.request) return null;
return p;
} catch {
return null;
}
}
export function writePendingSolve(p: PendingSolve): void {
try {
window.localStorage.setItem(PENDING_KEY, JSON.stringify(p));
} catch {
/* storage full / private mode — resume is best-effort */
}
}
export function clearPendingSolve(): void {
try {
window.localStorage.removeItem(PENDING_KEY);
} catch {
/* ignore */
}
}
lib/explorer/host.ts
/**
* Where the shared Explorer (`explorer-app`) reads and writes, and which of its
* pokerstudy.ai-only features are on. The defaults are pokerstudy.ai's own
* same-origin routes; another host (pokerdata.io's /app/explorer) calls
* `setExplorerHost` once, before the Explorer mounts, to point the reads at its
* own proxies and switch off what it doesn't serve.
*
* A feed keeps the same contract wherever it is served: the `/api/ranges/*`
* layout (`/nl/v2/node?…`, `/plo5/node?…`), a 401/403 that the plan prompt
* explains, and a 404 on a node meaning the betting round closed there.
*/
export interface ExplorerHost {
/** Ranges feed root, the `/api/ranges/*` layout. */
ranges: string;
/**
* The ranges session (`<ranges>/session`): which plan the visitor's reads
* run under. Null when the host gates its feed itself (its proxy asserts
* the plan), so the Explorer never asks.
*/
rangesSession: string | null;
/**
* Custom postflop solves: the solver job routes (`/jobs`, `/jobs/:id`, …).
* Null switches the inline flop solve off; a heads-up line then ends on the
* end card, with `solveElsewhere` as its next step.
*/
solver: string | null;
/** Saving a custom solve (`POST`, `PATCH /:id`). Null hides Save. */
solutions: string | null;
/** Heads-up PLO4 blueprint flop + turn/river re-solves. Null switches them off. */
plo4huPostflop: string | null;
/**
* The download link for a pack in the solution picker, or null for none
* (the picker then shows `packHref` instead, when the host gives one).
*/
downloadHref: ((packId: string) => string) | null;
/** The host's page for a pack (to buy it), shown when there's no download. */
packHref: ((packId: string) => string | null) | null;
/** Where a closed heads-up line points when this host can't solve postflop. */
solveElsewhere: { href: string; label: string } | null;
/**
* The toast a refused ranges read (401 sign-in / 403 upgrade) shows. Null
* keeps pokerstudy.ai's plan copy. `href` may be a function of the page path.
*/
planPrompt: Record<"sign-in" | "upgrade", PlanPromptCopy> | null;
}
export interface PlanPromptCopy {
title: string;
description: string;
label: string;
href: (path: string) => string;
}
const POKERSTUDY: ExplorerHost = {
ranges: "/api/ranges",
rangesSession: "/api/ranges/session",
solver: "/api/solver",
solutions: "/api/explorer/solutions",
plo4huPostflop: "/api/explorer/plo4hu-postflop",
downloadHref: (packId) => `/api/downloads/${encodeURIComponent(packId)}`,
packHref: null,
solveElsewhere: null,
planPrompt: null,
};
let current: ExplorerHost = POKERSTUDY;
export function explorerHost(): ExplorerHost {
return current;
}
export function setExplorerHost(next: Partial<ExplorerHost>): void {
current = { ...current, ...next };
}
/** `<ranges>/<path>` — `rangesUrl("nl/v2/node?…")`. */
export function rangesUrl(path: string): string {
return `${current.ranges}/${path.replace(/^\//, "")}`;
}
lib/explorer/locks.ts
// Node-lock request construction (#268, P2 — the explorer UI half of node
// locking). The viewer collects strategy edits ("lock this node to these
// action frequencies"), and this module turns them into the engine's
// `locked_nodes` entries plus the full "re-solve with edits" request.
//
// The one rule that matters (PR #269's key finding): a locked re-solve must
// ALWAYS warm-start from the unlocked base solve's snapshot. A lock that
// zeroes an action gives the subtree behind it zero counterfactual reach, so
// a cold locked solve can never train the opponent's response there — it
// stays uniform forever and the result is silently wrong. So
// `buildLockedResolveRequest` requires a base job id; callers with no base
// snapshot must surface an error, never fall back to a cold locked solve.
//
// Client-safe: pure functions, no server imports.
import type { LockedNode, SolveRequest, SolverNode } from "@/lib/solver/types";
/**
* Hard cap on locks per solve. Shared with the jobs-proxy sanitizer so the
* client never builds a request the server would reject, and the worker never
* sees an unbounded array.
*/
export const MAX_LOCKED_NODES = 16;
/** Default convergence plateau for locked re-solves (see
* `buildLockedResolveRequest`) — matches CUSTOM_SOLVE_DEFAULTS. */
const LOCKED_SOLVE_PLATEAU = 0.04;
/**
* Normalize a raw frequency vector for a lock: clamp negatives to 0, scale to
* sum 1, and round to 4 decimals (with the residual folded into the largest
* entry so the sum stays at 1 up to float epsilon — the engine accepts ±0.001
* but there's no reason to spend the tolerance). Returns null when the vector
* is degenerate (empty, all zero, or non-finite).
*/
export function normalizeLockFreqs(raw: readonly number[]): number[] | null {
if (raw.length === 0) return null;
const clamped = raw.map((f) => (Number.isFinite(f) && f > 0 ? f : 0));
const sum = clamped.reduce((a, b) => a + b, 0);
if (sum <= 0) return null;
const out = clamped.map((f) => Math.round((f / sum) * 10000) / 10000);
// Fold the rounding residual into the largest entry.
const residual = 1 - out.reduce((a, b) => a + b, 0);
if (residual !== 0) {
let maxIdx = 0;
for (let i = 1; i < out.length; i++) if (out[i] > out[maxIdx]) maxIdx = i;
out[maxIdx] = Math.round((out[maxIdx] + residual) * 10000) / 10000;
}
return out;
}
/**
* Build an aggregate (`all_hands`) lock for the node at `path`: every combo of
* the acting player's range plays `freqs` verbatim. `freqs` is raw slider
* weight — normalized here. Throws on a shape mismatch or a degenerate vector,
* so the editor can't emit a lock the engine would reject.
*/
export function buildAggregateLock(
path: readonly string[],
node: Pick<SolverNode, "actions">,
freqs: readonly number[],
): LockedNode {
if (freqs.length !== node.actions.length) {
throw new Error(
`lock vector has ${freqs.length} frequencies but the node has ${node.actions.length} actions`,
);
}
const normalized = normalizeLockFreqs(freqs);
if (!normalized) {
throw new Error("lock frequencies must include at least one positive value");
}
return { path: [...path], all_hands: normalized };
}
/**
* The full "re-solve with edits" request (#268): the base solve's exact config
* with `locked_nodes` attached and `warm_start_from` pointing at the base
* job's snapshot. Throws rather than building a request that would be wrong or
* rejected:
* • no locks / too many locks;
* • an AI (depth-limited) base — those never snapshot, so the required warm
* start can't exist.
*
* Two deliberate knob changes vs the base:
* • `keep_snapshot: false` — a locked solve's own snapshot fingerprints
* iso=0 (#269 caveat) and must never become a later warm-start base; the
* unlocked base job stays the one warm-start source.
* • a convergence plateau is always set — the composed exploitability
* plateaus at the lock's floor (13% in #269's demo), so a base target like
* 1% is typically unreachable and the plateau is what actually ends the
* solve instead of grinding to the iteration cap.
*/
export function buildLockedResolveRequest(
base: SolveRequest,
locks: readonly LockedNode[],
baseJobId: string,
): SolveRequest {
if (locks.length === 0) throw new Error("no locked nodes — edit a strategy first");
if (locks.length > MAX_LOCKED_NODES) {
throw new Error(`at most ${MAX_LOCKED_NODES} nodes can be locked per solve`);
}
if (base.aiSolve) {
throw new Error(
"locked re-solves need the exact solve's snapshot — AI solves can't be edited",
);
}
if (!baseJobId) {
throw new Error("locked re-solves must warm-start from the base solve's job");
}
const req: SolveRequest = {
...base,
locked_nodes: locks.map((l) => ({ ...l, path: [...l.path] })),
warm_start_from: baseJobId,
keep_snapshot: false,
convergence_plateau: base.convergence_plateau ?? LOCKED_SOLVE_PLATEAU,
};
return req;
}
/** True when `err` means the warm-start snapshot is gone / rejected — the one
* failure a locked re-solve must NOT retry cold (see module header). */
export function isWarmStartFailure(message: string): boolean {
return /snapshot|warm/i.test(message);
}
lib/explorer/plo-filter.ts
/**
* PLO hand-property filtering for the range explorer.
*
* Ported from pokerdata.io's explorer (which took it from the mobile app), and
* pointed at the PLO hand helpers the trainer already ships here, so both
* surfaces classify a hand identically.
*
* Filter the 16,432 starting hands by suitedness, connectedness (rundown /
* gaps), pairing, and card height. Properties are derived from a canonical
* MonkerSolver string (see plo-hand.ts) so they line up exactly with the hands
* in a node's weights.
*/
import { parseHandString } from "@/lib/trainer/plo-hand";
import { rankIndex, type Rank } from "@/lib/trainer/hand";
export type Suitedness = "Double Suited" | "Single Suited" | "Rainbow";
export type Pairing = "Quads" | "Trips" | "Two Pair" | "One Pair" | "Unpaired";
export type Connect = "Rundown" | "One Gap" | "Two Gap" | null;
export type Height = "High" | "Low" | "High-Low";
export interface HandProps {
pairing: Pairing;
suitedness: Suitedness;
/** True when the hand holds a pair of aces (AAxx). */
hasAces: boolean;
/** Connectedness, only defined for four distinct ranks (else null). */
connect: Connect;
height: Height;
}
// Higher rank → higher value. A=12 … 2=0. (RANKS is 'AKQJT98765432'.)
function rankValue(r: Rank): number {
return 12 - rankIndex(r);
}
/** Sum of interior gaps spanned by a set of distinct rank values. */
function spanGaps(values: number[]): number {
const s = [...values].sort((a, b) => a - b);
return s[s.length - 1] - s[0] - (s.length - 1);
}
function connectedness(ranks: Rank[]): Connect {
const distinct = [...new Set(ranks)];
if (distinct.length !== 4) return null;
const base = distinct.map(rankValue);
let gaps = spanGaps(base);
// An ace also plays low for wheel-ish hands (A-2-3-4); take the tighter span.
if (distinct.includes("A")) {
gaps = Math.min(gaps, spanGaps(base.map((v) => (v === 12 ? -1 : v))));
}
if (gaps === 0) return "Rundown";
if (gaps === 1) return "One Gap";
if (gaps === 2) return "Two Gap";
return null;
}
function heightOf(ranks: Rank[]): Height {
// High cards are T,J,Q,K,A (rankIndex 0–4); everything else is low.
let high = 0;
let low = 0;
for (const r of ranks) {
if (rankIndex(r) <= 4) high++;
else low++;
}
if (low === 0) return "High";
if (high === 0) return "Low";
return "High-Low";
}
/** Derive filterable properties from a canonical PLO hand string. */
export function handProps(hand: string): HandProps {
const groups = parseHandString(hand);
const ranks = groups.flat() as Rank[];
const counts = new Map<Rank, number>();
for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);
const vals = [...counts.values()];
const maxOfRank = Math.max(...vals);
const pairs = vals.filter((v) => v >= 2).length;
let pairing: Pairing;
if (maxOfRank >= 4) pairing = "Quads";
else if (maxOfRank === 3) pairing = "Trips";
else if (pairs >= 2) pairing = "Two Pair";
else if (pairs === 1) pairing = "One Pair";
else pairing = "Unpaired";
const suited = groups.filter((g) => g.length >= 2).length;
const suitedness: Suitedness =
suited >= 2 ? "Double Suited" : suited === 1 ? "Single Suited" : "Rainbow";
return {
pairing,
suitedness,
hasAces: (counts.get("A") ?? 0) >= 2,
connect: connectedness(ranks),
height: heightOf(ranks),
};
}
export type FilterId =
| "ds"
| "ss"
| "rainbow"
| "rundown"
| "gap1"
| "gap2"
| "aces"
| "twopair"
| "trips"
| "unpaired"
| "high"
| "low"
| "highlow";
interface ChipDef {
id: FilterId;
label: string;
}
/**
* Chips grouped by dimension. Selecting multiple chips in one group is an OR;
* selecting across groups is an AND (e.g. Double Suited AND Rundown).
*/
export const FILTER_GROUPS: { key: string; chips: ChipDef[] }[] = [
{
key: "Suits",
chips: [
{ id: "ds", label: "Double Suited" },
{ id: "ss", label: "Single Suited" },
{ id: "rainbow", label: "Rainbow" },
],
},
{
key: "Shape",
chips: [
{ id: "rundown", label: "Rundown" },
{ id: "gap1", label: "1-Gap" },
{ id: "gap2", label: "2-Gap" },
],
},
{
key: "Pairs",
chips: [
{ id: "aces", label: "Aces" },
{ id: "twopair", label: "Two Pair" },
{ id: "trips", label: "Trips+" },
{ id: "unpaired", label: "Unpaired" },
],
},
{
key: "Height",
chips: [
{ id: "high", label: "High" },
{ id: "low", label: "Low" },
{ id: "highlow", label: "High-Low" },
],
},
];
const PREDICATE: Record<FilterId, (p: HandProps) => boolean> = {
ds: (p) => p.suitedness === "Double Suited",
ss: (p) => p.suitedness === "Single Suited",
rainbow: (p) => p.suitedness === "Rainbow",
rundown: (p) => p.connect === "Rundown",
gap1: (p) => p.connect === "One Gap",
gap2: (p) => p.connect === "Two Gap",
aces: (p) => p.hasAces,
twopair: (p) => p.pairing === "Two Pair",
trips: (p) => p.pairing === "Trips" || p.pairing === "Quads",
unpaired: (p) => p.pairing === "Unpaired",
high: (p) => p.height === "High",
low: (p) => p.height === "Low",
highlow: (p) => p.height === "High-Low",
};
/** A hand passes when, for every constrained dimension, it matches ≥1 chip. */
export function matchesFilters(p: HandProps, active: Set<FilterId>): boolean {
if (active.size === 0) return true;
for (const group of FILTER_GROUPS) {
const selected = group.chips.filter((c) => active.has(c.id));
if (selected.length === 0) continue;
if (!selected.some((c) => PREDICATE[c.id](p))) return false;
}
return true;
}
lib/explorer/plo4hu-postflop-stacks.ts
/** Heads-up PLO4 stack depths whose postflop the engine serves (one Monker postflop blueprint each). */
export const PLO4HU_POSTFLOP_STACKS: readonly number[] = [30, 50, 100, 200];
lib/explorer/resolve-carry.ts
// CFR-D promise extraction for on-demand subgame re-solves (#233).
//
// A cold child solve at a chance boundary is *unsafe*: it hands the opponent
// their full reach-weighted range unconditionally, as if they were never
// allowed to avoid the subgame (the engine measured that bootstrap at ~15% pot
// of extra exploitability in agent mode). The CFR-D gadget fixes this — the
// opponent's root behavior becomes "Terminate for the carried CFV promise, or
// Follow into the subgame" — but it needs those promises, and the only place
// the HTTP API emits them today is at the PARENT solve's root actions
// (`emit_carry_for` → `SolverResult.resolve.carry`).
//
// This module decides when that root carry is a valid promise vector for a
// child solve deeper in the tree, following the engine's own carry semantics
// (resolve_agent.rs):
//
// • promises pass through the OPPONENT's actions unchanged — CFVs are
// counterfactual, so conditioning on the opponent's choice would assume a
// policy for them;
// • promises do NOT pass through the RESOLVER's own later actions — each
// resolver decision needs a fresh re-solve whose carry covers it, and we
// only hold the parent root's. A path where the resolver acts again is
// therefore ineligible (return null → the caller falls back to the
// reach-range solve);
// • promises crossing a dealt card should be *pinned* on it
// (`node_cfvs_pinned`); the HTTP carry is the runout average, which the
// engine measured at ~4-5% pot of mispricing — still far better than the
// unsafe bootstrap, so we use it and flag the result `approximate`.
//
// Both limitations are closed by the worker's `POST /solve/:id/carry`
// endpoint when the parent solve's job kept its accumulator snapshot (#262):
// the worker reloads the parent, walks the path with exact reaches (any
// number of resolver decisions), and prices the promises pinned on the dealt
// card. `pinnedCarryForChild` below prefers that endpoint and returns
// `approximate: false`; this module's root-carry extraction stays as the
// fallback for parents with no live snapshot (saved bundles, gadget children
// — the engine cannot snapshot gadget solves — or an evicted/restarted
// worker).
//
// The resolver is fixed to OOP (player 0): postflop OOP acts first at every
// street root, so the parent root is always the resolver's decision and every
// child root opens with the resolver again — the shape the chain needs.
import { explorerHost } from "@/lib/explorer/host";
import type { ResolveConfig, SolveRequest, SolverResult } from "@/lib/solver/types";
import { actionSegment, dealCard, isDealSegment, nodeAtPath } from "./subgame";
/** The resolver whose perspective the viewer chain re-solves for (OOP). */
export const CHAIN_RESOLVER = 0 as const;
export interface CarryAttach {
/** Engine gadget config, ready to place on the child `SolveRequest`. */
resolve: ResolveConfig;
/** True when the promises crossed one or more dealt cards and are therefore
* runout-averaged rather than card-pinned (engine-measured ~4-5% pot of
* mispricing vs ~15% for no gadget at all). Surfaced in the viewer so a
* "safe re-solve" badge never overclaims. */
approximate: boolean;
}
/**
* The CFV promises for the subgame rooted after dealing `card` at the chance
* node reached by `path` through the parent solve — or null when the parent
* result carries none that are valid there (no `emit_carry_for` output, a PLO
* solve, the resolver acting more than once along the path, or every carried
* combo blocked by the runout).
*/
export function carryForChild(
config: SolveRequest,
result: SolverResult,
path: readonly string[],
card: string,
): CarryAttach | null {
// NLHE only — the engine rejects the gadget for PLO, and the 4-char combo
// blocker logic below assumes two-card combos.
if ((config.variant ?? "nlhe") !== "nlhe") return null;
const carry = result.resolve?.carry;
if (!carry || carry.length === 0) return null;
if (path.length === 0) return null;
// The parent root must be the resolver's decision and the path must open
// with one of its actions — that action indexes the carry vector.
if (result.root.player !== CHAIN_RESOLVER) return null;
const first = path[0];
if (isDealSegment(first)) return null;
const rootIdx = result.root.actions.findIndex((a) => actionSegment(a) === first);
if (rootIdx < 0 || rootIdx >= carry.length) return null;
const promises = carry[rootIdx];
if (!promises || promises.length === 0) return null;
// Walk the rest of the path: opponent actions and deals pass through;
// another resolver decision invalidates the root carry.
const dealt: string[] = [];
for (let i = 1; i < path.length; i++) {
const seg = path[i];
if (isDealSegment(seg)) {
dealt.push(dealCard(seg));
continue;
}
const node = nodeAtPath(result.nodes ?? [], path.slice(0, i));
if (!node) return null;
if (node.player === CHAIN_RESOLVER) return null;
}
dealt.push(card);
// Drop promise combos blocked by the cards dealt since the parent root.
const blocked = new Set(dealt.map((c) => `${c[0].toUpperCase()}${c[1].toLowerCase()}`));
const opponent_cfvs: [string, number][] = [];
for (const [combo, cfv] of promises) {
if (blocked.has(combo.slice(0, 2)) || blocked.has(combo.slice(2, 4))) continue;
opponent_cfvs.push([combo, cfv]);
}
if (opponent_cfvs.length === 0) return null;
return {
resolve: { resolver: CHAIN_RESOLVER, opponent_cfvs },
// `card` itself always crosses a deal; the promises were computed at the
// parent root, before any runout, so they are runout-averaged by
// construction. Only a same-street action chain with no deal would be
// exact, and a chance-boundary child never is.
approximate: true,
};
}
/**
* Fetch card-pinned promises from the worker for the subgame rooted after
* dealing `card` at the chance node reached by `path` through the parent
* solve — exact for any path, including lines where the resolver acts more
* than once. `jobId` must be the parent solve's worker job; it needs a kept
* snapshot (`keep_snapshot`, #262), so this only works for solves run in the
* current worker lifetime. Returns null on any failure (no snapshot, evicted,
* worker restarted, non-NLHE...) — the caller falls back to `carryForChild`.
*/
export async function fetchPinnedCarry(
jobId: string,
path: readonly string[],
card: string,
): Promise<CarryAttach | null> {
try {
const solver = explorerHost().solver;
if (!solver) return null;
const res = await fetch(`${solver}/jobs/${jobId}/carry`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify({ resolver: CHAIN_RESOLVER, path, card }),
});
if (!res.ok) return null;
const payload = (await res.json()) as { opponent_cfvs?: unknown };
const cfvs = payload.opponent_cfvs;
if (!Array.isArray(cfvs) || cfvs.length === 0) return null;
const opponent_cfvs: [string, number][] = [];
for (const entry of cfvs) {
if (
!Array.isArray(entry) ||
entry.length !== 2 ||
typeof entry[0] !== "string" ||
typeof entry[1] !== "number" ||
!Number.isFinite(entry[1])
) {
return null;
}
opponent_cfvs.push([entry[0], entry[1]]);
}
return {
resolve: { resolver: CHAIN_RESOLVER, opponent_cfvs },
// The worker pinned the promises on `card` with exact path reaches —
// this is the full CFR-D carry, not the runout-averaged root fallback.
approximate: false,
};
} catch {
return null;
}
}
/**
* The promises for a child re-solve, preferring the worker's pinned endpoint
* (exact, any path) when the parent has a live snapshot job, falling back to
* the client-side root-carry extraction (runout-averaged, root-anchored
* paths only), then to null — the unsafe reach bootstrap.
*/
export async function pinnedCarryForChild(
parentJobId: string | undefined,
config: SolveRequest,
result: SolverResult,
path: readonly string[],
card: string,
): Promise<CarryAttach | null> {
// NLHE only, mirroring carryForChild — don't ask the worker what the
// engine will reject anyway.
if ((config.variant ?? "nlhe") === "nlhe" && parentJobId && path.length > 0) {
const pinned = await fetchPinnedCarry(parentJobId, path, card);
if (pinned) return pinned;
}
return carryForChild(config, result, path, card);
}
lib/explorer/share-url.ts
// The Explorer's shareable state, as it lives in the /explorer query string.
//
// game dataset id (nl, plo, plo4hu, plo9, plo5, plo6hu, nlmtt8)
// stack stack depth in bb (the field's average on the ICM sets)
// table ICM sets only: the stack table, a scenario id ("33left-avg30-short-btn")
// line the walked history, e.g. "UTG_Fold_HJ_Raise2.5_CO" (omitted at the root)
// close the action that closed the round on `line` (a history stops at the
// seat that acted, so the closing action can't live in it)
// tab "buckets" when that range tab is open (Explorer is the default)
// f PLO filter chips, comma-separated ids ("ds,rundown")
// q PLO5/PLO6 rank filter text
// s PLO hand search in GTO Wizard syntax ("AA**:$ds", see lib/hand-search)
//
// Pure: parsing never throws, and anything malformed is dropped so a bad or
// stale link opens the default view instead of a broken one.
import { SEAT_ORDER, type ExplorerGame } from "@/lib/solver/preflop";
export const EXPLORER_GAMES = Object.keys(SEAT_ORDER) as ExplorerGame[];
export type ExplorerUrlKey = "game" | "stack" | "table" | "line" | "close" | "tab" | "f" | "q" | "s";
export const EXPLORER_URL_KEYS: ExplorerUrlKey[] = [
"game",
"stack",
"table",
"line",
"close",
"tab",
"f",
"q",
"s",
];
export type ExplorerUrlState = Partial<Record<ExplorerUrlKey, string>>;
// Action labels vary by dataset ("Fold", "Raise2.5", "60%", "AllIn"); `_` is
// the history separator, so anything else printable is allowed. Lines are
// only ever sent URL-encoded to the ranges API.
const ACTION_TOKEN = /^[^_\s<>"'`]{1,32}$/;
/** First query value for each known key, from Next's `searchParams` shape. */
export function pickExplorerParams(
params: Record<string, string | string[] | undefined>,
): ExplorerUrlState {
const out: ExplorerUrlState = {};
for (const key of EXPLORER_URL_KEYS) {
const raw = params[key];
const v = Array.isArray(raw) ? raw[0] : raw;
if (typeof v === "string" && v.length > 0 && v.length <= 400) out[key] = v;
}
return out;
}
export function parseGame(v: string | undefined): ExplorerGame | null {
return v && (EXPLORER_GAMES as string[]).includes(v) ? (v as ExplorerGame) : null;
}
export function parseStack(v: string | undefined): number | null {
if (!v || !/^\d{1,4}$/.test(v)) return null;
const n = Number(v);
return n > 0 ? n : null;
}
/** A history this dataset's walk can replay: starts at its first actor,
* alternates seat / action, and ends on a seat. */
export function parseLine(v: string | undefined, game: ExplorerGame): string | null {
if (!v) return null;
const order = SEAT_ORDER[game] as string[];
const tokens = v.split("_");
if (tokens.length % 2 === 0 || tokens[0] !== order[0]) return null;
for (let i = 0; i < tokens.length; i++) {
const ok = i % 2 === 0 ? order.includes(tokens[i]) : ACTION_TOKEN.test(tokens[i]);
if (!ok) return null;
}
return v;
}
/** An ICM stack table id (`33left-avg30-short-btn`), or null. */
export function parseTable(v: string | undefined): string | null {
return v && /^\d{1,3}left-avg\d{1,3}(?:\.\d+)?-[a-z0-9-]{1,24}$/.test(v) ? v : null;
}
export function parseAction(v: string | undefined): string | null {
return v && ACTION_TOKEN.test(v) ? v : null;
}
/** Merge `patch` into `search` (null/"" removes a key), keeping unrelated
* params, and return the query string with a leading "?" (or ""). */
export function mergeSearch(search: string, patch: ExplorerUrlState | Record<string, string | null>): string {
const params = new URLSearchParams(search);
for (const [k, v] of Object.entries(patch)) {
if (v == null || v === "") params.delete(k);
else params.set(k, v);
}
const s = params.toString();
return s ? `?${s}` : "";
}
lib/explorer/solution-catalog.ts
// Client-safe catalog of preflop solutions the Explorer can switch between —
// the data behind the GTO-Wizard-style solution selector. Grouped by game/
// format, mirroring the `/sims` catalog.
//
// `browsable` solutions are walkable in the Explorer (today: NLHE 6-max, served
// by `/api/ranges/nl`); the rest are download-only for now and deep-link to the
// `/sims` catalog. Stacks are gated at runtime against the ranges manifest, so a
// browsable row only opens if its dataset is actually present.
import type { ExplorerGame } from "@/lib/solver/preflop";
export interface SolutionStack {
/** Effective stack in bb. */
stack: number;
/** Raise/sizing tree, human-readable. */
raises: string;
/** "Pre-flop" | "Post-flop". */
type: "Pre-flop" | "Post-flop";
/** Approx download size label, e.g. "7 MB" (download-only groups). */
size?: string;
/**
* ICM sets: the stack tables solved at this average depth (one solve each,
* uneven stacks included), by scenario id. The first is the default.
*/
tables?: SolutionTable[];
}
/** One ICM stack table: a scenario of `/api/ranges/nlh8-icm`. */
export interface SolutionTable {
/** Scenario id, e.g. `33left-avg30-short-btn`. */
scenario: string;
/** Short label for a picker chip, e.g. "Short BTN". */
label: string;
}
export type GameKind = "holdem" | "omaha" | "plo5" | "plo6";
export type PlayersKind = "hu" | "6max" | "8max" | "9max";
/** Format facet: ring cash game or tournament. */
export type FormatKind = "cash" | "tournament";
/**
* Rake facet. Cash solves are tiered by the rake they were solved with, since
* rake (not blinds) is what changes a solver's strategy: a big cap in bb is
* what low stakes pay, a tiny cap is high stakes. `chipev` means no rake at
* all: tournament chip-EV solves and rake-free cash solves. `icm` is a
* tournament solve whose EVs are prize money (ICM), so no rake either.
* low: named micro/low stake (NL25) or cap of 1bb and up
* mid: cap from 0.1bb up to 1bb
* high: cap under 0.1bb
*/
export type RakeTier = "low" | "mid" | "high" | "chipev" | "icm";
export const FORMAT_LABEL: Record<FormatKind, string> = {
cash: "Cash",
tournament: "Tournament",
};
export const RAKE_TIER_LABEL: Record<RakeTier, string> = {
low: "Low stakes",
mid: "Mid stakes",
high: "High stakes",
chipev: "Chip EV",
icm: "ICM",
};
export interface SolutionGroup {
id: string;
/** Format line, e.g. "No-limit hold'em · 6-max". */
format: string;
/** Rake line, e.g. "rake 5%, 0.5bb cap". */
rake: string;
/** Game facet. */
game: GameKind;
/** Table-size facet. */
players: PlayersKind;
/** Short rake label for the table column, e.g. "NL25" / "PLO" / "none". */
rakeShort: string;
/** Format facet (cash / tournament). */
formatKind: FormatKind;
/** Rake facet; see {@link RakeTier} for how a group is tiered. */
rakeTier: RakeTier;
/** True when the Explorer can interactively browse this group. */
browsable: boolean;
stacks: SolutionStack[];
}
export const SOLUTION_GROUPS: SolutionGroup[] = [
{
id: "nlhe-6max",
format: "No-limit hold'em · 6-max",
rake: "rake 5%, 0.5bb cap",
game: "holdem",
players: "6max",
rakeShort: "NL25",
formatKind: "cash",
rakeTier: "low",
browsable: true,
stacks: [
{ stack: 20, raises: "Min + 55–100% pot + all-in", type: "Pre-flop" },
{ stack: 30, raises: "Min + 40–120% pot + all-in", type: "Pre-flop" },
{ stack: 40, raises: "Min + 45–120% pot + all-in", type: "Pre-flop" },
{ stack: 50, raises: "Min + 44–125% pot + all-in", type: "Pre-flop" },
{ stack: 70, raises: "45–175% pot + all-in", type: "Pre-flop" },
{ stack: 100, raises: "49–200% pot + all-in", type: "Pre-flop" },
{ stack: 150, raises: "49–200% pot + all-in", type: "Pre-flop" },
{ stack: 200, raises: "49–200% pot + all-in", type: "Pre-flop" },
],
},
{
id: "nlhe-mtt-8max",
format: "No-limit hold'em tournament · 8-max",
rake: "none — tournament chip EV, 1bb BB-ante",
game: "holdem",
players: "8max",
rakeShort: "MTT",
formatKind: "tournament",
rakeTier: "chipev",
browsable: true,
stacks: [
{ stack: 10, raises: "All-in / fold", type: "Pre-flop" },
{ stack: 15, raises: "Min + all-in", type: "Pre-flop" },
{ stack: 20, raises: "Min + pot% + all-in", type: "Pre-flop" },
{ stack: 30, raises: "Min + pot% + all-in", type: "Pre-flop" },
{ stack: 40, raises: "34% pot open + all-in", type: "Pre-flop" },
{ stack: 50, raises: "34% pot open + all-in", type: "Pre-flop" },
{ stack: 75, raises: "43% pot open + all-in", type: "Pre-flop" },
{ stack: 100, raises: "34% pot open + all-in", type: "Pre-flop" },
{ stack: 200, raises: "43% pot open + all-in", type: "Pre-flop" },
{ stack: 300, raises: "43% pot open + all-in", type: "Pre-flop" },
],
},
{
id: "nlhe-icm-ft",
format: "No-limit hold'em ICM · 8-max final table",
rake: "none — ICM final table: 8 left, 8 paid, $27,728 pool · 0.125bb ante per seat",
game: "holdem",
players: "8max",
rakeShort: "ICM",
formatKind: "tournament",
rakeTier: "icm",
browsable: true,
stacks: [
{
stack: 15,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "8left-avg15-even", label: "Even stacks" },
{ scenario: "8left-avg15-short-bb", label: "Short BB" },
{ scenario: "8left-avg15-short-co", label: "Short CO" },
{ scenario: "8left-avg15-mix-1", label: "Mixed 1" },
{ scenario: "8left-avg15-mix-2", label: "Mixed 2" },
{ scenario: "8left-avg15-big-btn", label: "Big BTN" },
{ scenario: "8left-avg15-big-utg", label: "Big UTG" },
],
},
{
stack: 20,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "8left-avg20-even", label: "Even stacks" },
{ scenario: "8left-avg20-short-bb", label: "Short BB" },
{ scenario: "8left-avg20-short-co", label: "Short CO" },
{ scenario: "8left-avg20-mix-1", label: "Mixed 1" },
{ scenario: "8left-avg20-mix-2", label: "Mixed 2" },
{ scenario: "8left-avg20-big-btn", label: "Big BTN" },
{ scenario: "8left-avg20-big-utg", label: "Big UTG" },
],
},
{
stack: 25,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "8left-avg25-even", label: "Even stacks" },
{ scenario: "8left-avg25-short-lj", label: "Short LJ" },
{ scenario: "8left-avg25-mix-1", label: "Mixed 1" },
{ scenario: "8left-avg25-mix-2", label: "Mixed 2" },
{ scenario: "8left-avg25-big-bb", label: "Big BB" },
{ scenario: "8left-avg25-big-hj", label: "Big HJ" },
],
},
{
stack: 30,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "8left-avg30-even", label: "Even stacks" },
{ scenario: "8left-avg30-short-btn", label: "Short BTN" },
{ scenario: "8left-avg30-short-utg", label: "Short UTG" },
{ scenario: "8left-avg30-mix-1", label: "Mixed 1" },
{ scenario: "8left-avg30-mix-2", label: "Mixed 2" },
{ scenario: "8left-avg30-big-sb", label: "Big SB" },
{ scenario: "8left-avg30-big-co", label: "Big CO" },
],
},
{
stack: 40,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "8left-avg40-short-bb", label: "Short BB" },
{ scenario: "8left-avg40-short-co", label: "Short CO" },
{ scenario: "8left-avg40-short-sb", label: "Short SB" },
{ scenario: "8left-avg40-mix-1", label: "Mixed 1" },
{ scenario: "8left-avg40-mix-2", label: "Mixed 2" },
{ scenario: "8left-avg40-big-bb", label: "Big BB" },
{ scenario: "8left-avg40-big-btn", label: "Big BTN" },
{ scenario: "8left-avg40-big-utg", label: "Big UTG" },
],
},
],
},
{
id: "nlhe-icm-bubble",
format: "No-limit hold'em ICM · 8-max near the bubble",
rake: "none — ICM near the bubble: 33 of 200 left, 30 paid, $40,000 pool · 0.125bb ante per seat",
game: "holdem",
players: "8max",
rakeShort: "ICM",
formatKind: "tournament",
rakeTier: "icm",
browsable: true,
stacks: [
{
stack: 15,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "33left-avg15-even", label: "Even stacks" },
{ scenario: "33left-avg15-short-bb", label: "Short BB" },
{ scenario: "33left-avg15-short-co", label: "Short CO" },
{ scenario: "33left-avg15-mix-1", label: "Mixed 1" },
{ scenario: "33left-avg15-mix-2", label: "Mixed 2" },
{ scenario: "33left-avg15-big-btn", label: "Big BTN" },
{ scenario: "33left-avg15-big-utg", label: "Big UTG" },
],
},
{
stack: 20,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "33left-avg20-even", label: "Even stacks" },
{ scenario: "33left-avg20-short-bb", label: "Short BB" },
{ scenario: "33left-avg20-short-co", label: "Short CO" },
{ scenario: "33left-avg20-mix-1", label: "Mixed 1" },
{ scenario: "33left-avg20-mix-2", label: "Mixed 2" },
{ scenario: "33left-avg20-big-btn", label: "Big BTN" },
{ scenario: "33left-avg20-big-utg", label: "Big UTG" },
],
},
{
stack: 25,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "33left-avg25-even", label: "Even stacks" },
{ scenario: "33left-avg25-short-lj", label: "Short LJ" },
{ scenario: "33left-avg25-mix-1", label: "Mixed 1" },
{ scenario: "33left-avg25-mix-2", label: "Mixed 2" },
{ scenario: "33left-avg25-big-bb", label: "Big BB" },
{ scenario: "33left-avg25-big-hj", label: "Big HJ" },
],
},
{
stack: 30,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "33left-avg30-even", label: "Even stacks" },
{ scenario: "33left-avg30-short-btn", label: "Short BTN" },
{ scenario: "33left-avg30-short-utg", label: "Short UTG" },
{ scenario: "33left-avg30-mix-1", label: "Mixed 1" },
{ scenario: "33left-avg30-mix-2", label: "Mixed 2" },
{ scenario: "33left-avg30-big-sb", label: "Big SB" },
{ scenario: "33left-avg30-big-co", label: "Big CO" },
],
},
{
stack: 40,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "33left-avg40-short-bb", label: "Short BB" },
{ scenario: "33left-avg40-short-co", label: "Short CO" },
{ scenario: "33left-avg40-short-sb", label: "Short SB" },
{ scenario: "33left-avg40-mix-1", label: "Mixed 1" },
{ scenario: "33left-avg40-mix-2", label: "Mixed 2" },
{ scenario: "33left-avg40-big-bb", label: "Big BB" },
{ scenario: "33left-avg40-big-btn", label: "Big BTN" },
{ scenario: "33left-avg40-big-utg", label: "Big UTG" },
],
},
],
},
{
id: "nlhe-icm-bubble35",
format: "No-limit hold'em ICM · 8-max near the bubble, multi-table",
rake: "none — ICM near the bubble: 35 of 200 left over several tables, 30 paid, $50,000 pool · 0.125bb ante per seat",
game: "holdem",
players: "8max",
rakeShort: "ICM",
formatKind: "tournament",
rakeTier: "icm",
browsable: true,
stacks: [
{
stack: 20,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "35left-avg20-even", label: "Even stacks" },
{ scenario: "35left-avg20-big-btn", label: "Big BTN" },
{ scenario: "35left-avg20-big-utg", label: "Big UTG" },
],
},
{
stack: 25,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "35left-avg25-even", label: "Even stacks" },
{ scenario: "35left-avg25-big-bb", label: "Big BB" },
],
},
{
stack: 30,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "35left-avg30-even", label: "Even stacks" },
{ scenario: "35left-avg30-big-co", label: "Big CO" },
],
},
{
stack: 40,
raises: "Open + 3-bet + all-in",
type: "Pre-flop",
tables: [
{ scenario: "35left-avg40-even", label: "Even stacks" },
{ scenario: "35left-avg40-short-bb", label: "Short BB" },
{ scenario: "35left-avg40-short-sb", label: "Short SB" },
{ scenario: "35left-avg40-big-bb", label: "Big BB" },
{ scenario: "35left-avg40-big-btn", label: "Big BTN" },
{ scenario: "35left-avg40-big-utg", label: "Big UTG" },
],
},
],
},
{
id: "plo-9max",
format: "Pot-limit Omaha · 9-max",
rake: "rake 5%, 2bb cap",
game: "omaha",
players: "9max",
rakeShort: "PLO",
formatKind: "cash",
rakeTier: "low",
browsable: false,
stacks: [
{ stack: 60, raises: "Pot + all-in", type: "Pre-flop", size: "4.3 GB" },
{ stack: 100, raises: "Pot + all-in", type: "Pre-flop", size: "8.9 GB" },
],
},
{
id: "plo-6max",
format: "Pot-limit Omaha · 6-max",
rake: "rake 5%, 1bb cap",
game: "omaha",
players: "6max",
rakeShort: "PLO",
formatKind: "cash",
rakeTier: "low",
// Walkable since the Explorer learned to render Omaha ranges as a
// hand-class list. PLO 9-max stays download-only: its bundles are too big
// for the whole-bundle ranges API (issues #35/#36), so /api/ranges/plo9
// has no data to serve.
browsable: true,
stacks: [
{ stack: 12, raises: "Pot + all-in", type: "Pre-flop", size: "23 MB" },
{ stack: 20, raises: "Pot + min-raise + all-in", type: "Pre-flop", size: "98 MB" },
{ stack: 30, raises: "Pot + all-in", type: "Pre-flop", size: "97 MB" },
{ stack: 40, raises: "Pot + all-in", type: "Pre-flop", size: "414 MB" },
{ stack: 50, raises: "Pot + all-in", type: "Pre-flop", size: "182 MB" },
{ stack: 75, raises: "Pot + all-in", type: "Pre-flop", size: "582 MB" },
{ stack: 100, raises: "Pot + all-in", type: "Pre-flop", size: "645 MB" },
{ stack: 150, raises: "Pot + all-in", type: "Pre-flop", size: "683 MB" },
{ stack: 200, raises: "Pot + all-in", type: "Pre-flop", size: "986 MB" },
],
},
{
id: "plo-hu",
format: "Pot-limit Omaha · Heads-up",
rake: "rake 4.5%, 0.045bb cap · no flop, no drop",
game: "omaha",
players: "hu",
rakeShort: "PLO",
formatKind: "cash",
rakeTier: "high",
// MonkerSolver blueprints (Nov 2026; 100bb, 200bb and 75bb on monker-2; 50bb, 40bb, 30bb, 20bb and 10bb on monker-1):
// SB may limp, every raise is pot-sized. Walkable through /api/ranges/plo4hu.
browsable: true,
stacks: [
{ stack: 10, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 20, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 30, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 40, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 50, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 75, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 100, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
{ stack: 200, raises: "Limp or pot raise + pot re-raises", type: "Pre-flop" },
],
},
{
id: "plo5-6max",
format: "Pot-limit Omaha 5 · 6-max",
rake: "rake 5%, 1bb cap · 1.2bb ante",
game: "plo5",
players: "6max",
rakeShort: "PLO5",
formatKind: "cash",
rakeTier: "low",
browsable: true,
stacks: [
{ stack: 100, raises: "4.7x open + raise tree", type: "Pre-flop" },
],
},
{
id: "plo6-hu",
format: "Pot-limit Omaha 6 · Heads-up",
rake: "rake 5%, 0.5bb cap · 0.4bb ante",
game: "plo6",
players: "hu",
rakeShort: "PLO6",
formatKind: "cash",
rakeTier: "mid",
browsable: true,
stacks: [
{ stack: 100, raises: "3.4x open + 10.6x / 32.2x / jam", type: "Pre-flop" },
],
},
{
id: "nlhe-hu",
format: "No-limit hold'em · Heads-up",
rake: "rake none",
game: "holdem",
players: "hu",
rakeShort: "none",
formatKind: "cash",
rakeTier: "chipev",
browsable: false,
stacks: [{ stack: 100, raises: "33%/75% pot + all-in", type: "Post-flop", size: "221 KB" }],
},
];
/** A flattened, filterable table row (one per group×stack). */
export interface SolutionRow {
group: SolutionGroup;
stack: SolutionStack;
}
export function allRows(): SolutionRow[] {
return SOLUTION_GROUPS.flatMap((group) => group.stacks.map((stack) => ({ group, stack })));
}
/** The single browsable group the Explorer walks today. */
export const BROWSABLE_GROUP = SOLUTION_GROUPS.find((g) => g.browsable)!;
/**
* Catalog groups ↔ the ranges datasets the Explorer can walk. Only browsable
* groups map; everything else is preview/download-only.
*/
const GROUP_GAME: Record<string, ExplorerGame> = {
"nlhe-6max": "nl",
"nlhe-mtt-8max": "nlmtt8",
"nlhe-icm-ft": "icmft",
"nlhe-icm-bubble": "icmbubble",
"nlhe-icm-bubble35": "icmbubble35",
"plo-6max": "plo",
"plo-hu": "plo4hu",
"plo5-6max": "plo5",
"plo6-hu": "plo6hu",
};
export function gameForGroup(groupId: string): ExplorerGame | null {
return GROUP_GAME[groupId] ?? null;
}
export function groupForGame(game: ExplorerGame): SolutionGroup {
const id = Object.keys(GROUP_GAME).find((k) => GROUP_GAME[k] === game);
return (id ? groupById(id) : undefined) ?? BROWSABLE_GROUP;
}
export function groupById(id: string): SolutionGroup | undefined {
return SOLUTION_GROUPS.find((g) => g.id === id);
}
/** Raise label for a group's stack (for the card subtitle). */
/**
* pokerdata.io's pack id prefix per catalog group, for the explorer's
* Download button: `<prefix>-<stack>bb` is the preflop pack that holds the
* solve on screen (ids match pokerdata's `src/lib/sims.ts`). Groups without
* a pack for sale map to nothing.
*/
const PACK_PREFIX: Record<string, string> = {
"nlhe-6max": "nlh-6max",
"nlhe-mtt-8max": "nlh-mtt-8max",
"plo-9max": "plo9-9max",
"plo-6max": "plo6-6max",
"plo5-6max": "plo5-6max",
};
/** The downloadable pack for a group at a stack, or null when none is sold. */
export function packIdFor(groupId: string, stack: number): string | null {
const prefix = PACK_PREFIX[groupId];
return prefix ? `${prefix}-${stack}bb` : null;
}
/** The stack tables at a depth (ICM sets), or [] where a depth is one solve. */
export function tablesFor(group: SolutionGroup, stack: number): SolutionTable[] {
return group.stacks.find((s) => s.stack === stack)?.tables ?? [];
}
/** The table a pick of (group, stack) opens: the named one if it's there, else the first. */
export function defaultTable(
group: SolutionGroup,
stack: number,
scenario?: string | null,
): SolutionTable | null {
const tables = tablesFor(group, stack);
return tables.find((t) => t.scenario === scenario) ?? tables[0] ?? null;
}
/** Number of solves a stack row stands for: one per table, else one. */
export function solveCount(s: SolutionStack): number {
return s.tables?.length || 1;
}
export function raisesFor(group: SolutionGroup, stack: number): string | undefined {
return group.stacks.find((s) => s.stack === stack)?.raises;
}
lib/explorer/subgame.ts
// Subgame extraction for the postflop solution viewer (#231).
//
// A saved `CustomSolutionBundle` carries the solved strategy at every action
// node up to `dump_max_deals` chance deals past the start street. Walking past
// that horizon (e.g. picking a river card in a flop bundle dumped at one deal)
// needs a *new* solve of the subgame rooted after the chosen card. This module
// derives that child `SolveRequest` from the bundle alone:
//
// • the reach-weighted ranges at the chance node — walk the per-node
// strategies from the root ranges, multiplying each combo's weight by the
// frequency of the action actually taken at every decision on the path,
// and zeroing combos blocked by dealt cards;
// • the pot and effective stack — accumulated from each taken action's
// chip `add` along the path (a chance node is only reachable with equal
// street contributions, so stack-behind = start stack − half the growth).
//
// Everything here is pure and client-safe; the viewer submits the produced
// request through the existing `/api/solver/jobs` plumbing.
import type {
ResolveConfig,
SolveRequest,
SolverActionInfo,
SolverNode,
SolverResult,
} from "@/lib/solver/types";
// Engine card order (solver-engine/src/card.rs): index = rank*4 + suit with
// ranks 2..A ascending and suits c<d<h<s. Combo strings put the higher card
// first ("AsAh"), so building keys in this order matches the engine's dump
// byte-for-byte — no normalization needed when joining maps to node hands.
const RANK_CHARS = "23456789TJQKA";
const SUIT_CHARS = "cdhs";
/** Engine ordinal of a card string ("Th" → 34); -1 when unparsable. */
export function cardOrd(card: string): number {
if (card.length !== 2) return -1;
const r = RANK_CHARS.indexOf(card[0].toUpperCase());
const s = SUIT_CHARS.indexOf(card[1].toLowerCase());
if (r < 0 || s < 0) return -1;
return r * 4 + s;
}
function ordToCard(ord: number): string {
return `${RANK_CHARS[ord >> 2]}${SUIT_CHARS[ord & 3]}`;
}
/** Canonical engine combo key: higher engine-ordinal card first. */
export function comboKey(a: string, b: string): string {
return cardOrd(a) >= cardOrd(b) ? `${a}${b}` : `${b}${a}`;
}
/** Per-combo weights keyed by the engine combo string ("AsAh"). */
export type ComboWeights = Map<string, number>;
/** Split a board string into its card list. */
export function boardCards(board: string): string[] {
return board.trim().split(/\s+/).filter(Boolean);
}
const WEIGHT_EPS = 5e-4;
/**
* Expand an NLHE engine range string into per-combo weights, excluding combos
* that collide with `dead` cards. Supports the grammar our own builders emit:
* `random`/`100`/`100%`, 169-grid classes (`AA`, `AKs`, `AKo`), and explicit
* combos (`AsKh`), each with an optional `:weight`.
*/
export function expandEngineRange(range: string, dead: ReadonlySet<string>): ComboWeights {
const out: ComboWeights = new Map();
const blocked = (card: string) => dead.has(card);
const set = (a: string, b: string, w: number) => {
if (w <= 0 || blocked(a) || blocked(b)) return;
out.set(comboKey(a, b), w);
};
const cleaned = range.trim().toLowerCase();
if (cleaned === "random" || cleaned === "100" || cleaned === "100%") {
for (let hi = 1; hi < 52; hi++) {
for (let lo = 0; lo < hi; lo++) set(ordToCard(hi), ordToCard(lo), 1);
}
return out;
}
for (const raw of range.split(",")) {
const tok = raw.trim();
if (!tok) continue;
const [body, weightStr] = splitWeight(tok);
const w = weightStr === undefined ? 1 : Number(weightStr);
if (!Number.isFinite(w)) throw new Error(`invalid weight in range token "${tok}"`);
// Explicit two-card combo, e.g. "AhKs".
if (body.length === 4 && isSuit(body[1]) && isSuit(body[3])) {
const a = `${body[0].toUpperCase()}${body[1].toLowerCase()}`;
const b = `${body[2].toUpperCase()}${body[3].toLowerCase()}`;
if (cardOrd(a) < 0 || cardOrd(b) < 0) throw new Error(`bad combo "${tok}"`);
set(a, b, w);
continue;
}
// 169-grid class: "AA", "AKs", "AKo".
const r1 = RANK_CHARS.indexOf(body[0]?.toUpperCase() ?? "");
const r2 = RANK_CHARS.indexOf(body[1]?.toUpperCase() ?? "");
const suffix = body.slice(2).toLowerCase();
if (r1 < 0 || r2 < 0 || (suffix !== "" && suffix !== "s" && suffix !== "o")) {
throw new Error(`unsupported range token "${tok}"`);
}
if (r1 === r2) {
if (suffix !== "") throw new Error(`pairs take no suffix: "${tok}"`);
for (let s1 = 0; s1 < 4; s1++)
for (let s2 = 0; s2 < s1; s2++)
set(`${RANK_CHARS[r1]}${SUIT_CHARS[s1]}`, `${RANK_CHARS[r1]}${SUIT_CHARS[s2]}`, w);
} else {
for (let s1 = 0; s1 < 4; s1++) {
for (let s2 = 0; s2 < 4; s2++) {
const suited = s1 === s2;
if (suffix === "s" && !suited) continue;
if (suffix === "o" && suited) continue;
set(`${RANK_CHARS[r1]}${SUIT_CHARS[s1]}`, `${RANK_CHARS[r2]}${SUIT_CHARS[s2]}`, w);
}
}
}
}
return out;
}
function splitWeight(tok: string): [string, string | undefined] {
const i = tok.indexOf(":");
return i < 0 ? [tok, undefined] : [tok.slice(0, i).trim(), tok.slice(i + 1).trim()];
}
function isSuit(c: string): boolean {
return SUIT_CHARS.includes(c.toLowerCase());
}
/** Serialize combo weights back to the engine grammar ("AsKh:0.42,…"). */
export function serializeComboRange(weights: ComboWeights): string {
const parts: string[] = [];
for (const [combo, w] of weights) {
if (w < WEIGHT_EPS) continue;
parts.push(w >= 0.9995 ? combo : `${combo}:${Number(w.toFixed(4))}`);
}
return parts.join(",");
}
// ---------------------------------------------------------------------------
// Node-tree helpers (shared by the viewer's navigation)
// ---------------------------------------------------------------------------
export function pathsEqual(a: readonly string[], b: readonly string[]): boolean {
return a.length === b.length && a.every((x, i) => x === b[i]);
}
export function isPathPrefix(prefix: readonly string[], path: readonly string[]): boolean {
return prefix.length <= path.length && prefix.every((x, i) => x === path[i]);
}
export function nodeAtPath(nodes: readonly SolverNode[], path: readonly string[]): SolverNode | null {
return nodes.find((n) => pathsEqual(n.path, path)) ?? null;
}
/** The distinct next path segments after `path`, in node order. */
export function nextSegments(nodes: readonly SolverNode[], path: readonly string[]): string[] {
const seen = new Set<string>();
const out: string[] = [];
for (const n of nodes) {
if (n.path.length <= path.length) continue;
if (!isPathPrefix(path, n.path)) continue;
const seg = n.path[path.length];
if (!seen.has(seg)) {
seen.add(seg);
out.push(seg);
}
}
return out;
}
/** The engine's path label for an action ("Bet 5.6", "Call") — must mirror
* `action_path_label` in solver-engine/src/api.rs (add rounded to 1dp). */
export function actionSegment(a: SolverActionInfo): string {
if (a.add > 0) return `${a.label} ${Math.round(a.add * 10) / 10}`;
return a.label;
}
export const DEAL_PREFIX = "deal:";
export function isDealSegment(seg: string): boolean {
return seg.startsWith(DEAL_PREFIX);
}
export function dealCard(seg: string): string {
return seg.slice(DEAL_PREFIX.length);
}
// ---------------------------------------------------------------------------
// Reach walk
// ---------------------------------------------------------------------------
export interface ReachState {
/** All cards on the board at this point (start board + dealt runouts). */
board: string[];
/** Total pot after the last taken action, in chips (= bb). */
pot: number;
/**
* Chips behind each player, assuming equal street contributions — exact at
* street boundaries (the only place a child solve is rooted) and at the
* start of the walk.
*/
effStack: number;
/** Reach-weighted OOP range (root range × taken-action frequencies). */
oop: ComboWeights;
/** Reach-weighted IP range. */
ip: ComboWeights;
}
/**
* Walk `path` through a solved bundle and return the reach state at its end.
* Every action-node prefix of `path` must exist in `result.nodes` (it does for
* any path the viewer can navigate to); deal segments just filter the ranges.
*/
export function walkReach(
config: SolveRequest,
result: SolverResult,
path: readonly string[],
): ReachState {
const nodes = result.nodes ?? [];
const board = boardCards(config.board);
const dead = new Set(board);
const oop = expandEngineRange(config.oop_range, dead);
const ip = expandEngineRange(config.ip_range, dead);
let pot = config.pot;
for (let i = 0; i < path.length; i++) {
const seg = path[i];
if (isDealSegment(seg)) {
const card = dealCard(seg);
board.push(card);
removeBlocked(oop, card);
removeBlocked(ip, card);
continue;
}
const node = nodeAtPath(nodes, path.slice(0, i));
if (!node) throw new Error(`no strategy node at "${path.slice(0, i).join(" › ")}"`);
const idx = node.actions.findIndex((a) => actionSegment(a) === seg);
if (idx < 0) throw new Error(`action "${seg}" not found at "${path.slice(0, i).join(" › ")}"`);
pot = node.pot + node.actions[idx].add;
const actor = node.player === 0 ? oop : ip;
const next: ComboWeights = new Map();
for (const hand of node.hands) {
const w = actor.get(hand.combo);
if (w === undefined || w <= 0) continue;
const nw = w * (hand.freqs[idx] ?? 0);
if (nw > WEIGHT_EPS) next.set(hand.combo, nw);
}
if (node.player === 0) {
oop.clear();
for (const [k, v] of next) oop.set(k, v);
} else {
ip.clear();
for (const [k, v] of next) ip.set(k, v);
}
}
const effStack = config.effective_stack - (pot - config.pot) / 2;
return { board, pot, effStack, oop, ip };
}
function removeBlocked(weights: ComboWeights, card: string) {
const upper = `${card[0].toUpperCase()}${card[1].toLowerCase()}`;
for (const combo of [...weights.keys()]) {
if (combo.slice(0, 2) === upper || combo.slice(2, 4) === upper) weights.delete(combo);
}
}
// ---------------------------------------------------------------------------
// Child solve request
// ---------------------------------------------------------------------------
/** Iteration ceiling for on-demand subgame solves — a turn/river subgame is
* tiny next to a flop tree, so the exploitability target stops it long before
* this in practice. */
const CHILD_MAX_ITERATIONS = 2000;
const CHILD_DEFAULT_TARGET = 0.4;
/**
* Build the `SolveRequest` for the subgame rooted after dealing `card` at the
* chance node reached by `path` (which must end exactly where a street closed).
* Ranges are the reach-weighted ranges at that point, minus combos blocked by
* the new card; geometry (pot / stack) is derived from the taken actions.
*/
export function buildChildRequest(
config: SolveRequest,
result: SolverResult,
path: readonly string[],
card: string,
opts?: {
/** CFR-D gadget config (#233) from `resolve-carry.ts`: when present the
* child is a *safe* re-solve (opponent may Terminate for their carried
* CFV), pinned to DCFR — the engine rejects the gadget under pcfr+. */
resolve?: ResolveConfig;
},
): SolveRequest {
const state = walkReach(config, result, path);
if (state.effStack <= 0.01) {
throw new Error("players are all-in — there are no more decisions to solve");
}
if (state.board.includes(card)) throw new Error(`${card} is already on the board`);
if (state.board.length >= 5) throw new Error("the board is already complete");
const oop = new Map(state.oop);
const ip = new Map(state.ip);
removeBlocked(oop, card);
removeBlocked(ip, card);
if (oop.size === 0 || ip.size === 0) {
throw new Error(`dealing ${card} leaves a player with no hands`);
}
const round2 = (x: number) => Math.round(x * 100) / 100;
const req: SolveRequest = {
variant: config.variant ?? "nlhe",
limit: config.limit ?? "nolimit",
board: [...state.board, card].join(" "),
pot: round2(state.pot),
effective_stack: round2(state.effStack),
bet_sizes: config.bet_sizes,
add_allin: config.add_allin,
max_aggressions: config.max_aggressions,
iterations: Math.min(config.iterations || CHILD_MAX_ITERATIONS, CHILD_MAX_ITERATIONS),
target_exploitability: config.target_exploitability ?? CHILD_DEFAULT_TARGET,
log_interval: 10,
dump_ev: true,
dump_nodes: true,
// One deal of depth: a turn-rooted child carries every river subtree, and a
// river-rooted child has no chance nodes at all.
dump_max_deals: 1,
// Follow the parent: a full-hand drill pack grades turn and river decisions
// out of these child solves, so they need per-action EV for the same reason
// the flop does. An Explorer re-solve's parent leaves it unset and
// pays nothing.
...(config.dump_action_evs ? { dump_action_evs: true } : {}),
oop_range: serializeComboRange(oop),
ip_range: serializeComboRange(ip),
};
// Preserve the parent's river action abstraction (#220) so a spliced
// subgame bets the same tree the bundle was solved with.
if (config.river_bet_sizes && config.river_bet_sizes.length > 0) {
req.river_bet_sizes = config.river_bet_sizes;
}
if (config.river_max_aggressions !== undefined) {
req.river_max_aggressions = config.river_max_aggressions;
}
// Preserve the parent's per-street sizing rules for the streets the child
// still contains, so a spliced subgame offers the same tree the bundle was
// configured with. Node-specific overrides are dropped: their paths are
// relative to the PARENT root and would either miss (engine rejects) or,
// worse, silently match a different node in the child tree.
if (config.sizing) {
const childStreets =
state.board.length + 1 === 4 ? (["turn", "river"] as const) : (["river"] as const);
const inherit: NonNullable<SolveRequest["sizing"]> = {};
for (const street of childStreets) {
if (config.sizing[street]) inherit[street] = config.sizing[street];
}
if (Object.keys(inherit).length > 0) req.sizing = inherit;
}
if (opts?.resolve) {
// Safe re-solve: attach the gadget and pin DCFR (the gadget rejects
// pcfr+). Snapshots can't combine with the gadget, so none are kept.
req.resolve = opts.resolve;
req.cfr_variant = "dcfr";
} else {
// No promises available — the child bootstraps on reach ranges. Emit
// carry from ITS root so navigation below it can chain safe re-solves,
// and keep its snapshot so deeper boundaries can fetch card-*pinned*
// promises from `POST /api/solver/jobs/:id/carry` (#233 — a gadget child
// can't: the engine rejects snapshots with `resolve`).
req.emit_carry_for = 0;
req.keep_snapshot = true;
}
return req;
}
lib/explorer/tree-sim.ts
// Full postflop game-tree expansion for the tree-visualization flow. Mirrors
// the engine's builder math EXACTLY the way tree-sizing-editor's simulateLine
// does (same action generation, same state transitions, same node-edit
// precedence chain) — but walks EVERY branch instead of one chosen line, so
// React Flow can render the whole tree the solver would build.
//
// Chance nodes are collapsed to a single generic "deal" step (matching the
// engine's node-edit path encoding), so the tree stays structural: a turn
// subtree stands for "every turn card", not 49 copies.
import {
parseCellSizes,
pathLabel,
resolveNode,
type NodeEdit,
type SimAction,
type SizingBase,
type SizingGrid,
type StreetKey,
} from "@/components/explorer/tree-sizing-editor";
export type Role = "oop" | "ip";
export type TreeKind = "action" | "chance" | "terminal";
export type TerminalKind = "fold" | "showdown" | "runout";
export interface FullTreeNode {
/** Path joined — unique across the tree. */
id: string;
/** Engine-encoded action path from the root (deals as generic "deal"). */
path: string[];
kind: TreeKind;
street: StreetKey;
/** Acting player (action nodes only). */
role?: Role;
/** Pot BEFORE this player acts (action) / final pot (terminal/chance). */
pot: number;
toCall: number;
/** Available actions (action nodes only; parallel to `children`). */
actions: SimAction[];
/** The node edit applied here, if any. */
edit?: NodeEdit;
terminal?: TerminalKind;
children: { token: string; child: FullTreeNode }[];
}
export interface FullTreeStats {
actionNodes: number;
chanceNodes: number;
terminalNodes: number;
maxDepth: number;
}
export interface FullTree {
root: FullTreeNode | null;
stats: FullTreeStats;
/** True when the node budget ran out — the tree shown is a prefix. */
truncated: boolean;
}
const STREETS = ["flop", "turn", "river"] as const;
interface BuildState {
streetIdx: number;
pot: number;
stacks: [number, number];
paid: [number, number];
toCall: number;
player: 0 | 1;
aggressions: number;
path: string[];
}
const sameNodePath = (a: string[], b: string[]) =>
a.length === b.length && a.every((t, i) => t === b[i]);
const idOf = (path: string[], suffix = "") =>
path.length === 0 && !suffix ? "root" : [...path, suffix].filter(Boolean).join("|");
/**
* Expand the full tree the engine would build for this abstraction. `maxNodes`
* bounds the walk (bigger abstractions explode combinatorially); when hit,
* `truncated` is set and the deepest branches are cut.
*/
export function buildFullTree(
grid: SizingGrid,
nodeEdits: NodeEdit[],
base: SizingBase,
boardCards: number,
maxNodes = 4000,
): FullTree {
const startIdx = boardCards >= 5 ? 2 : boardCards === 4 ? 1 : 0;
const streets = STREETS.slice(startIdx);
const maxAggrFor = (s: StreetKey) =>
s === "river" ? (base.riverMaxAggressions ?? base.maxAggressions) : base.maxAggressions;
let budget = maxNodes;
let truncated = false;
const stats: FullTreeStats = { actionNodes: 0, chanceNodes: 0, terminalNodes: 0, maxDepth: 0 };
const terminal = (
path: string[],
street: StreetKey,
kind: TerminalKind,
pot: number,
): FullTreeNode => {
stats.terminalNodes++;
stats.maxDepth = Math.max(stats.maxDepth, path.length);
return {
id: idOf(path, `#${kind}`),
path,
kind: "terminal",
street,
pot,
toCall: 0,
actions: [],
terminal: kind,
children: [],
};
};
function build(st: BuildState): FullTreeNode | null {
if (budget <= 0) {
truncated = true;
return null;
}
budget--;
const street = streets[st.streetIdx];
const role: Role = st.player === 0 ? "oop" : "ip";
const resolved = resolveNode(grid, base, street, role);
const edit = nodeEdits.find((e) => sameNodePath(e.path, st.path));
// Node edit > street rule > base — same chain as the engine / simulateLine.
let sizes = st.toCall > 0 ? resolved.raises : resolved.bets;
let allin = resolved.allin;
if (edit) {
try {
const s = parseCellSizes(edit.sizes, "node size");
if (s !== undefined) sizes = s;
} catch {
/* invalid text — preview falls back to the street rule */
}
if (edit.allin !== "auto") allin = edit.allin === "on";
}
const stack = st.stacks[st.player];
const actions: SimAction[] = [];
const canAggress = st.aggressions < maxAggrFor(street) && stack > st.toCall + 1e-9;
if (st.toCall <= 1e-9) {
actions.push({ token: "Check", label: "Check", add: 0 });
} else {
actions.push({ token: "Fold", label: "Fold", add: 0 });
const callAmt = Math.min(st.toCall, stack);
actions.push({ token: pathLabel("Call", callAmt), label: "Call", add: callAmt });
}
if (canAggress) {
const potAfterCall = st.pot + st.toCall;
for (const f of sizes) {
const totalAdd = st.toCall + f * potAfterCall;
if (totalAdd >= stack - 1e-9) continue; // shove covers it
if (totalAdd <= st.toCall + 1e-9) continue;
actions.push({
token: pathLabel(st.toCall > 0 ? "Raise" : "Bet", totalAdd),
label: st.toCall > 0 ? "Raise" : "Bet",
add: totalAdd,
frac: f,
});
}
if (allin) {
actions.push({ token: pathLabel("AllIn", stack), label: "AllIn", add: stack });
}
}
stats.actionNodes++;
stats.maxDepth = Math.max(stats.maxDepth, st.path.length);
const node: FullTreeNode = {
id: idOf(st.path),
path: st.path,
kind: "action",
street,
role,
pot: st.pot,
toCall: st.toCall,
actions,
edit,
children: [],
};
const p = st.player;
const o = (1 - p) as 0 | 1;
for (const act of actions) {
const childPath = [...st.path, act.token];
let child: FullTreeNode | null = null;
if (act.label === "Fold") {
child = terminal(childPath, street, "fold", st.pot);
} else if (act.label === "Check") {
if (p === 0) {
child = build({ ...st, player: 1, path: childPath });
} else if (st.streetIdx + 1 >= streets.length) {
child = terminal(childPath, street, "showdown", st.pot);
} else {
child = chance(childPath, st, [st.stacks[0], st.stacks[1]], st.pot);
}
} else if (act.label === "Call") {
const stacks: [number, number] = [...st.stacks];
stacks[p] -= act.add;
const pot = st.pot + act.add;
if (stacks[p] <= 1e-9 || stacks[o] <= 1e-9) {
child = terminal(childPath, street, "runout", pot);
} else if (st.streetIdx + 1 >= streets.length) {
child = terminal(childPath, street, "showdown", pot);
} else {
child = chance(childPath, st, stacks, pot);
}
} else {
// Bet / Raise / AllIn
const stacks: [number, number] = [...st.stacks];
stacks[p] -= act.add;
const paid: [number, number] = [...st.paid];
paid[p] += act.add;
child = build({
streetIdx: st.streetIdx,
pot: st.pot + act.add,
stacks,
paid,
toCall: paid[p] - paid[o],
player: o,
aggressions: st.aggressions + 1,
path: childPath,
});
}
if (child) node.children.push({ token: act.token, child });
}
return node;
}
/** Street-closing check/call → a "deal" chance node wrapping the next street. */
function chance(
closedPath: string[],
st: BuildState,
stacks: [number, number],
pot: number,
): FullTreeNode | null {
const nextStreet = streets[st.streetIdx + 1];
stats.chanceNodes++;
const next = build({
streetIdx: st.streetIdx + 1,
pot,
stacks,
paid: [0, 0],
toCall: 0,
player: 0,
aggressions: 0,
path: [...closedPath, "deal"],
});
const node: FullTreeNode = {
id: idOf(closedPath, "#deal"),
path: closedPath,
kind: "chance",
street: nextStreet,
pot,
toCall: 0,
actions: [],
children: next ? [{ token: "deal", child: next }] : [],
};
return node;
}
const root = build({
streetIdx: 0,
pot: base.potBb,
stacks: [base.effStackBb, base.effStackBb],
paid: [0, 0],
toCall: 0,
player: 0,
aggressions: 0,
path: [],
});
return { root, stats, truncated };
}
lib/explorer/types.ts
// Shared types for the Explorer: custom solutions the user builds, solves, and
// saves. No secrets here — safe to import from both client and server. The
// server-only Blob read/write lives in `store.ts`.
import type { SolveRequest, SolverResult } from "@/lib/solver/types";
/** Display metadata stored on the row + bundle so the catalog renders without
* fetching the (multi-MB) gzipped tree. */
export interface CustomSolutionMeta {
/** Pot at the start street, in bb (= chips). */
potBb: number;
/** Effective stack behind, in bb. */
effStackBb: number;
/** Human bet sizing, e.g. "75% pot + all-in". */
betSizing: string;
/** Out-of-position seat label, e.g. "OOP" or "BB". */
oopLabel: string;
/** In-position seat label, e.g. "IP" or "BTN". */
ipLabel: string;
/** Start street, derived from the board length. */
startStreet: "flop" | "turn" | "river";
/** True when solved via the AI (depth-limited) path. AI solves have no
* measurable exploitability — the 0 the engine reports must not be shown
* as if it were a grade. Absent on pre-AI saves. */
ai?: boolean;
}
/** The lightweight catalog entry the Explorer lists (mirrors the DB row, minus
* the heavy bundle which is fetched on open). */
export interface CustomSolutionSummary {
id: string;
title: string;
variant: "nlhe" | "plo";
kind: "postflop";
tags: string[];
board: string;
exploitabilityPct: number;
meta: CustomSolutionMeta;
createdAt: string;
updatedAt: string;
}
/** The full saved artifact: summary + the solved strategy tree (gzipped on
* Blob). `result.nodes` is the `dump_nodes` walk that powers the tree viewer. */
export interface CustomSolutionBundle {
id: string;
title: string;
tags: string[];
board: string;
meta: CustomSolutionMeta;
/** The SolveRequest it was solved from (re-open in the builder). */
config: SolveRequest;
/** The engine output, including the `dump_nodes` walk. */
result: SolverResult;
generatedAt: string;
}
/** Body of POST /api/explorer/solutions — the client solves, then saves. */
export interface SaveSolutionRequest {
title: string;
tags: string[];
config: SolveRequest;
result: SolverResult;
meta: CustomSolutionMeta;
}
/** Body of PATCH /api/explorer/solutions/[id] — rename / retag. */
export interface UpdateSolutionRequest {
title?: string;
tags?: string[];
}
/** Derive the start street from a board string ("Qs Jh 2h" → "flop"). */
export function streetForBoard(board: string): "flop" | "turn" | "river" {
const n = board.trim().split(/\s+/).filter(Boolean).length;
if (n <= 3) return "flop";
if (n === 4) return "turn";
return "river";
}
/** Human bet sizing label from the solve config. */
export function betSizingLabel(config: SolveRequest): string {
const pct = config.bet_sizes.map((b) => `${Math.round(b * 100)}%`).join("/");
const base = config.add_allin ? `${pct} pot + all-in` : `${pct} pot`;
// Per-street/per-player overrides make the flat summary a lie — say so.
return config.sizing ? `${base} · custom tree` : base;
}
lib/hand-search/index.ts
/**
* Hand search: GTO Wizard-style syntax for filtering Omaha (and Hold'em) hands.
*
* AK** an ace, a king and any two cards (order never matters)
* AxKx AxKy suit variables: same letter = same suit, different = different
* RRON RROO rank variables: R/P and O bind ranks (RR = a pair), N = a rank
* that appears once in the hand
* [AK]Q [T-A]s bracket lists of ranks, rank ranges, suits or exact cards
* $ds $0g $hp preflop macros (see PREFLOP_MACROS)
* TP NFD1 >2P postflop macros and category comparisons (need a board)
* a,b a:b a!b union, intersection, difference; !a = every hand but a;
* (…) grouping. `,` binds loosest; `:` and `!` read left to right.
*
* Hands are arrays of two-char cards ("As", "Td"). `parseHandQuery` never
* throws: bad syntax comes back as `{ ok: false, error, index }` for the UI.
* Pure and dependency-free so Train, the Explorer and pokerdata.io share one
* implementation.
*/
import { categoryIndex, postflopFacts, rankOf, suitOf, type PostflopFacts } from "./postflop";
export { CATEGORIES } from "./postflop";
// ── Macros ──────────────────────────────────────────────────────────────────
const BROADWAY = (r: number) => r >= 8; // T J Q K A
const WHEEL = (r: number) => r === 12 || r <= 3; // A 2 3 4 5
function rankCounts(hand: string[]): number[] {
const c = new Array(13).fill(0);
for (const card of hand) c[rankOf(card)]++;
return c;
}
/** Suit groups of the hand, largest first: [[cards of one suit], ...]. */
function suitGroups(hand: string[]): string[][] {
const m = new Map<string, string[]>();
for (const c of hand) m.set(suitOf(c), [...(m.get(suitOf(c)) ?? []), c]);
return [...m.values()].sort((a, b) => b.length - a.length);
}
/** Smallest total gap across any four distinct ranks of the hand (ace plays
* high or low), or Infinity with fewer than four distinct ranks. */
function minGaps(hand: string[]): number {
const distinct = [...new Set(hand.map(rankOf))];
if (distinct.length < 4) return Infinity;
let best = Infinity;
const span = (vals: number[]) => {
const s = [...vals].sort((a, b) => a - b);
return s[3] - s[0] - 3;
};
const n = distinct.length;
for (let a = 0; a < n; a++)
for (let b = a + 1; b < n; b++)
for (let c = b + 1; c < n; c++)
for (let d = c + 1; d < n; d++) {
const four = [distinct[a], distinct[b], distinct[c], distinct[d]];
best = Math.min(best, span(four));
if (four.includes(12)) best = Math.min(best, span(four.map((v) => (v === 12 ? -1 : v))));
}
return best;
}
const pairedRanks = (hand: string[]) =>
rankCounts(hand)
.map((n, r) => ({ n, r }))
.filter((x) => x.n >= 2);
const isDs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2).length >= 2 && suitGroups(h)[0].length === 2;
const isSs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2).length === 1 && suitGroups(h)[0].length === 2;
const hasAce = (cards: string[]) => cards.some((c) => rankOf(c) === 12);
const suitedPairs = (h: string[]) => suitGroups(h).filter((g) => g.length === 2);
const broadwayCount = (h: string[]) => h.filter((c) => BROADWAY(rankOf(c))).length;
/** Broadway cards beside one ace (other aces count as Broadway). */
function aceSideBroadways(h: string[]): number {
const i = h.findIndex((c) => rankOf(c) === 12);
if (i < 0) return -1;
return broadwayCount(h.filter((_, j) => j !== i));
}
export interface MacroDoc {
name: string;
help: string;
}
const PREFLOP: Record<string, { help: string; test: (h: string[]) => boolean }> = {
"0g": { help: "Zero-gap rundown: four connected ranks", test: (h) => minGaps(h) === 0 },
"1g": { help: "One-gap rundown: four ranks with one gap", test: (h) => minGaps(h) === 1 },
"2g": { help: "Two-gap rundown: four ranks with two gaps", test: (h) => minGaps(h) === 2 },
b: { help: "Broadway hands: every card T or higher", test: (h) => h.every((c) => BROADWAY(rankOf(c))) },
dp: { help: "Two pair: two distinct paired ranks", test: (h) => pairedRanks(h).length >= 2 },
tp: { help: "Two pair (same as $dp)", test: (h) => pairedRanks(h).length >= 2 },
dsdn: {
help: "Double-suited, double nut: both suited pairs hold an ace",
test: (h) => isDs(h) && suitedPairs(h).every(hasAce),
},
dsn: { help: "Double-suited, nut: a suited pair holds an ace", test: (h) => isDs(h) && suitedPairs(h).some(hasAce) },
dsnn: { help: "Double-suited, non-nut: no ace in either suited pair", test: (h) => isDs(h) && !suitedPairs(h).some(hasAce) },
hp: { help: "High pair: a pair of TT or higher", test: (h) => pairedRanks(h).some((p) => p.r >= 8) },
mp: { help: "Middle pair: a pair from 99 to 66", test: (h) => pairedRanks(h).some((p) => p.r >= 4 && p.r <= 7) },
lp: { help: "Low pair: a pair of 55 or lower", test: (h) => pairedRanks(h).some((p) => p.r <= 3) },
mt: { help: "Monotone: every card the same suit", test: (h) => suitGroups(h).length === 1 },
np: { help: "No pairs: every rank different", test: (h) => pairedRanks(h).length === 0 },
nt: { help: "No trips: no rank three or more times (pairs allowed)", test: (h) => Math.max(...rankCounts(h)) <= 2 },
op: {
help: "One pair only: exactly one paired rank, no trips",
test: (h) => pairedRanks(h).length === 1 && pairedRanks(h)[0].n === 2,
},
rb: { help: "Rainbow: every card a different suit", test: (h) => suitGroups(h).every((g) => g.length === 1) },
ssn: { help: "Single-suited, nut: the suited pair holds an ace", test: (h) => isSs(h) && suitedPairs(h).some(hasAce) },
ssnn: { help: "Single-suited, non-nut: no ace in the suited pair", test: (h) => isSs(h) && !suitedPairs(h).some(hasAce) },
ts: { help: "Triple-suited: three cards of one suit", test: (h) => suitGroups(h)[0].length === 3 },
w: { help: "Wheel hands: every card A, 2, 3, 4 or 5", test: (h) => h.every((c) => WHEEL(rankOf(c))) },
a0b: { help: "Ace with no Broadway side cards", test: (h) => aceSideBroadways(h) === 0 },
a1b: { help: "Ace with one Broadway side card", test: (h) => aceSideBroadways(h) === 1 },
a2b: { help: "Ace with two Broadway side cards", test: (h) => aceSideBroadways(h) === 2 },
a3b: { help: "Ace with three Broadway side cards", test: (h) => aceSideBroadways(h) === 3 },
"1b": { help: "Exactly one Broadway card", test: (h) => broadwayCount(h) === 1 },
"2b": { help: "Exactly two Broadway cards", test: (h) => broadwayCount(h) === 2 },
"3b": { help: "Exactly three Broadway cards", test: (h) => broadwayCount(h) === 3 },
"4b": { help: "Four Broadway cards", test: (h) => broadwayCount(h) === 4 },
ds: { help: "Double-suited: two suited pairs", test: isDs },
ss: { help: "Single-suited: one suited pair, the rest offsuit", test: isSs },
};
export const PREFLOP_MACROS: MacroDoc[] = Object.entries(PREFLOP).map(([k, v]) => ({ name: `$${k}`, help: v.help }));
const POSTFLOP_HELP: Record<string, string> = {
RF: "Royal flush",
SF: "Straight flush",
QS: "Four of a kind",
FH: "Full house",
FL: "Any flush",
FLN: "Nut flush",
FLN2: "Second-nut flush",
FLNN: "Flush below the second nut",
STR: "Any straight",
STRN: "Nut straight",
STR2: "Second-nut straight",
STRNN: "Straight below the second nut",
SET: "Set: pocket pair plus a board card",
SETT: "Top set",
SETM: "Middle set",
SETB: "Bottom set",
TRIPS: "Trips: one hole card plus a board pair",
"2P": "Any two pair",
"2PTT": "Top two pair",
"2PTB": "Two pair including top pair",
"2PB": "Other two pair (no top pair)",
PAIR: "Any pair",
OP: "Overpair",
TP: "Top pair",
MP: "Middle pair",
BP: "Bottom pair",
UP: "Underpair",
AIR: "High card only",
};
const DRAW_HELP: Record<string, string> = {
SFD: "Straight flush draw",
FD: "Flush draw (any)",
NFD1: "Nut flush draw",
NFD2: "Second-nut flush draw",
FDNN: "Flush draw below the second nut",
DFD: "Double flush draw (two suits)",
SD: "Straight draw (any)",
OESD: "Open-ender: two ranks complete a straight (8 outs)",
NOESD: "Nut open-ender: both ranks make the nut straight",
GS: "Gutshot: one rank completes a straight (4 outs)",
NGS: "Nut gutshot",
WRAP: "Wrap: three or more ranks complete a straight, none to the nuts",
NWRAP: "Nut wrap: three or more ranks, at least one to the nut straight",
BDFD: "Backdoor flush draw (any, flop only)",
BDFD1: "One backdoor flush draw",
BDFD2: "Two backdoor flush draws",
FDB: "Flush-draw blocker: a card of the suit with two on the board",
SDB: "Straight-draw blocker: a card whose rank would put a new straight on the board",
};
export const POSTFLOP_MACROS: MacroDoc[] = Object.entries(POSTFLOP_HELP).map(([name, help]) => ({ name, help }));
export const DRAW_MACROS: MacroDoc[] = Object.entries(DRAW_HELP).map(([name, help]) => ({ name, help }));
const BOARD_WORDS = new Set([...Object.keys(POSTFLOP_HELP), ...Object.keys(DRAW_HELP)]);
// ── AST ─────────────────────────────────────────────────────────────────────
interface CardToken {
/** Allowed ranks (null = any), or a variable. */
ranks: Set<number> | null;
rankVar: string | null;
/** Allowed suits (null = any), or a variable. */
suits: Set<string> | null;
suitVar: string | null;
/** Exact cards from a bracket like [AsKd] (overrides ranks/suits when set). */
cards: ((rank: number, suit: string) => boolean) | null;
}
type Node =
| { kind: "union"; items: Node[] }
| { kind: "inter"; a: Node; b: Node }
| { kind: "diff"; a: Node; b: Node }
| { kind: "not"; a: Node }
| { kind: "pattern"; tokens: CardToken[]; explicitRanks: Set<number> }
| { kind: "pre"; name: string }
| { kind: "post"; name: string }
| { kind: "cmp"; op: ">" | "<"; cat: number };
export interface HandQuery {
source: string;
/** True when the query uses a postflop/draw macro or a `>`/`<` comparison. */
needsBoard: boolean;
/** True when the query names an exact suit (s, h, d, c). Suit-isomorphic
* hand classes then have to be tested suit by suit. */
usesExactSuits: boolean;
/** Does this concrete hand match? `board` is needed for postflop macros
* (without one they never match). */
test(hand: string[], board?: string[]): boolean;
}
export type ParseResult = { ok: true; query: HandQuery } | { ok: false; error: string; index: number };
class ParseError extends Error {
constructor(
message: string,
public index: number,
) {
super(message);
}
}
// ── Tokenizer ───────────────────────────────────────────────────────────────
type Tok = { t: "op"; v: string; i: number } | { t: "word"; v: string; i: number };
const OPS = new Set([",", ":", "!", "(", ")", ">", "<"]);
function tokenize(src: string): Tok[] {
const out: Tok[] = [];
let i = 0;
while (i < src.length) {
const ch = src[i];
if (/\s/.test(ch)) {
i++;
continue;
}
if (OPS.has(ch)) {
out.push({ t: "op", v: ch, i });
i++;
continue;
}
const start = i;
let word = "";
while (i < src.length && !OPS.has(src[i]) && !/\s/.test(src[i])) {
if (src[i] === "[") {
const close = src.indexOf("]", i);
if (close < 0) throw new ParseError("Unclosed [ bracket", i);
word += src.slice(i, close + 1);
i = close + 1;
} else {
word += src[i];
i++;
}
}
out.push({ t: "word", v: word, i: start });
}
return out;
}
// ── Pattern parser ──────────────────────────────────────────────────────────
const RANK_MAP: Record<string, number> = {};
"23456789TJQKA".split("").forEach((c, i) => {
RANK_MAP[c] = i;
RANK_MAP[c.toLowerCase()] = i;
});
const SUITS = "shdc";
const SUIT_VARS = "wxyz";
const RANK_VARS: Record<string, string> = { R: "R", P: "R", O: "O", N: "N", r: "R", p: "R", o: "O", n: "N" };
function parseBracket(body: string, at: number): { ranks: Set<number> | null; suits: Set<string> | null; cards: CardToken["cards"] } {
const items = body.split(",").join("");
const rankSet = new Set<number>();
const suitOnly = new Set<string>();
const exact = new Set<string>();
let i = 0;
if (!items.length) throw new ParseError("Empty [ ] list", at);
while (i < items.length) {
const c = items[i];
if (c in RANK_MAP) {
const r = RANK_MAP[c];
if (items[i + 1] === "-" && items[i + 2] in RANK_MAP) {
const r2 = RANK_MAP[items[i + 2]];
for (let x = Math.min(r, r2); x <= Math.max(r, r2); x++) rankSet.add(x);
i += 3;
continue;
}
if (i + 1 < items.length && SUITS.includes(items[i + 1])) {
exact.add(`${r}${items[i + 1]}`);
i += 2;
continue;
}
rankSet.add(r);
i++;
continue;
}
if (SUITS.includes(c)) {
suitOnly.add(c);
i++;
continue;
}
throw new ParseError(`"${c}" can't go in a [ ] list`, at + 1 + i);
}
// Only suits: a suit list for the card (any rank).
if (rankSet.size === 0 && exact.size === 0) return { ranks: null, suits: suitOnly, cards: null };
if (exact.size === 0 && suitOnly.size === 0) return { ranks: rankSet, suits: null, cards: null };
// Mixed: any of the listed ranks, suits or exact cards.
return {
ranks: null,
suits: null,
cards: (r, s) => rankSet.has(r) || suitOnly.has(s) || exact.has(`${r}${s}`),
};
}
function parsePattern(word: string, at: number): Node {
const tokens: CardToken[] = [];
const explicitRanks = new Set<number>();
let nCount = 0;
let i = 0;
while (i < word.length) {
const c = word[i];
const tok: CardToken = { ranks: null, rankVar: null, suits: null, suitVar: null, cards: null };
if (c === "*") {
i++;
} else if (c in RANK_VARS) {
const v = RANK_VARS[c];
// Every N is its own unique rank.
tok.rankVar = v === "N" ? `N${nCount++}` : v;
i++;
} else if (c in RANK_MAP) {
tok.ranks = new Set([RANK_MAP[c]]);
explicitRanks.add(RANK_MAP[c]);
i++;
} else if (c === "[") {
const close = word.indexOf("]", i);
const b = parseBracket(word.slice(i + 1, close), at + i);
tok.ranks = b.ranks;
tok.suits = b.suits;
tok.cards = b.cards;
i = close + 1;
} else if (c === "$") {
throw new ParseError(`Unknown macro "${word}"`, at);
} else {
throw new ParseError(
SUITS.includes(c) || SUIT_VARS.includes(c)
? `Suit "${c}" needs a rank before it (use * for any rank)`
: `"${c}" isn't a rank, suit or operator`,
at + i,
);
}
// Optional suit.
const s = word[i];
if (s !== undefined) {
if (SUITS.includes(s)) {
tok.suits = intersectSuits(tok.suits, new Set([s]));
i++;
} else if (SUIT_VARS.includes(s)) {
tok.suitVar = s;
i++;
} else if (s === "[") {
const close = word.indexOf("]", i);
const body = word.slice(i + 1, close).split(",").join("");
if (body.length && [...body].every((ch) => SUITS.includes(ch))) {
tok.suits = intersectSuits(tok.suits, new Set(body));
i = close + 1;
}
}
}
tokens.push(tok);
}
if (tokens.length > 6) throw new ParseError("A hand pattern has at most 6 cards", at);
return { kind: "pattern", tokens, explicitRanks };
}
function intersectSuits(a: Set<string> | null, b: Set<string>): Set<string> {
return a ? new Set([...a].filter((x) => b.has(x))) : b;
}
// ── Expression parser ───────────────────────────────────────────────────────
function parse(src: string): Node {
const toks = tokenize(src);
let p = 0;
const peek = () => toks[p];
const isOp = (v: string) => peek()?.t === "op" && peek()!.v === v;
const parseUnion = (): Node => {
const items = [parseInter()];
while (isOp(",")) {
p++;
items.push(parseInter());
}
return items.length === 1 ? items[0] : { kind: "union", items };
};
const parseInter = (): Node => {
let a = parseUnary();
while (isOp(":") || isOp("!")) {
const op = toks[p++].v;
const b = parseUnary();
a = op === ":" ? { kind: "inter", a, b } : { kind: "diff", a, b };
}
return a;
};
const parseUnary = (): Node => {
if (isOp("!")) {
p++;
return { kind: "not", a: parseUnary() };
}
return parsePrimary();
};
const parsePrimary = (): Node => {
const tok = peek();
if (!tok) throw new ParseError("Expected a hand, macro or (", src.length);
if (tok.t === "op") {
if (tok.v === "(") {
p++;
const inner = parseUnion();
if (!isOp(")")) throw new ParseError("Missing )", peek()?.i ?? src.length);
p++;
return inner;
}
if (tok.v === ">" || tok.v === "<") {
p++;
const w = peek();
if (!w || w.t !== "word") throw new ParseError(`${tok.v} needs a hand category, e.g. ${tok.v}2P`, tok.i);
const cat = categoryIndex(w.v);
if (cat === undefined) {
throw new ParseError(`${tok.v} works with AIR, PAIR, 2P, SET, STR, FL, FH, QS, SF or RF`, w.i);
}
p++;
return { kind: "cmp", op: tok.v, cat };
}
throw new ParseError(`Unexpected "${tok.v}"`, tok.i);
}
p++;
if (tok.v.startsWith("$")) {
const name = tok.v.slice(1).toLowerCase();
if (!(name in PREFLOP)) throw new ParseError(`Unknown macro "${tok.v}"`, tok.i);
return { kind: "pre", name };
}
if (BOARD_WORDS.has(tok.v)) return { kind: "post", name: tok.v };
return parsePattern(tok.v, tok.i);
};
if (toks.length === 0) throw new ParseError("Empty search", 0);
const node = parseUnion();
if (p < toks.length) {
const t = toks[p];
throw new ParseError(
t.t === "word" ? `Missing operator before "${t.v}" (use , to combine)` : `Unexpected "${t.v}"`,
t.i,
);
}
return node;
}
// ── Evaluation ──────────────────────────────────────────────────────────────
interface Ctx {
hand: string[];
board: string[] | undefined;
facts: PostflopFacts | null | undefined;
}
function factsOf(ctx: Ctx): PostflopFacts | null {
if (ctx.facts === undefined) ctx.facts = ctx.board ? postflopFacts(ctx.hand, ctx.board) : null;
return ctx.facts;
}
function matchPattern(tokens: CardToken[], explicitRanks: Set<number>, hand: string[]): boolean {
if (tokens.length > hand.length) return false;
const counts = rankCounts(hand);
const used = new Array(hand.length).fill(false);
const rankVars = new Map<string, number>();
const suitVars = new Map<string, string>();
const fits = (tok: CardToken, card: string): (() => void) | null => {
const r = rankOf(card);
const s = suitOf(card);
if (tok.cards && !tok.cards(r, s)) return null;
if (tok.ranks && !tok.ranks.has(r)) return null;
if (tok.suits && !tok.suits.has(s)) return null;
let undoRank = false;
let undoSuit = false;
if (tok.rankVar) {
const bound = rankVars.get(tok.rankVar);
if (bound === undefined) {
if (explicitRanks.has(r)) return null;
for (const v of rankVars.values()) if (v === r) return null;
if (tok.rankVar.startsWith("N") && counts[r] !== 1) return null;
rankVars.set(tok.rankVar, r);
undoRank = true;
} else if (bound !== r) return null;
}
if (tok.suitVar) {
const bound = suitVars.get(tok.suitVar);
if (bound === undefined) {
for (const v of suitVars.values()) {
if (v === s) {
if (undoRank) rankVars.delete(tok.rankVar!);
return null;
}
}
suitVars.set(tok.suitVar, s);
undoSuit = true;
} else if (bound !== s) {
if (undoRank) rankVars.delete(tok.rankVar!);
return null;
}
}
return () => {
if (undoRank) rankVars.delete(tok.rankVar!);
if (undoSuit) suitVars.delete(tok.suitVar!);
};
};
const go = (k: number): boolean => {
if (k === tokens.length) return true;
for (let i = 0; i < hand.length; i++) {
if (used[i]) continue;
const undo = fits(tokens[k], hand[i]);
if (!undo) continue;
used[i] = true;
const ok = go(k + 1);
used[i] = false;
undo();
if (ok) return true;
}
return false;
};
return go(0);
}
function evaluate(node: Node, ctx: Ctx): boolean {
switch (node.kind) {
case "union":
return node.items.some((n) => evaluate(n, ctx));
case "inter":
return evaluate(node.a, ctx) && evaluate(node.b, ctx);
case "diff":
return evaluate(node.a, ctx) && !evaluate(node.b, ctx);
case "not":
return !evaluate(node.a, ctx);
case "pattern":
return matchPattern(node.tokens, node.explicitRanks, ctx.hand);
case "pre":
return PREFLOP[node.name].test(ctx.hand);
case "post": {
const f = factsOf(ctx);
return !!f && f.tags.has(node.name);
}
case "cmp": {
const f = factsOf(ctx);
if (!f) return false;
return node.op === ">" ? f.category >= node.cat : f.category < node.cat;
}
}
}
function walk(node: Node, fn: (n: Node) => void) {
fn(node);
if (node.kind === "union") node.items.forEach((n) => walk(n, fn));
else if (node.kind === "inter" || node.kind === "diff") {
walk(node.a, fn);
walk(node.b, fn);
} else if (node.kind === "not") walk(node.a, fn);
}
export function parseHandQuery(source: string): ParseResult {
try {
const ast = parse(source);
let needsBoard = false;
let usesExactSuits = false;
walk(ast, (n) => {
if (n.kind === "post" || n.kind === "cmp") needsBoard = true;
if (n.kind === "pattern" && n.tokens.some((t) => t.suits || t.cards)) usesExactSuits = true;
});
return {
ok: true,
query: {
source,
needsBoard,
usesExactSuits,
test: (hand, board) => evaluate(ast, { hand, board, facts: undefined }),
},
};
} catch (err) {
if (err instanceof ParseError) return { ok: false, error: err.message, index: err.index };
throw err;
}
}
// ── Suit-isomorphic hand classes ────────────────────────────────────────────
const SUIT_PERMS: string[][] = (() => {
const out: string[][] = [];
const perm = (rest: string[], acc: string[]) => {
if (!rest.length) out.push(acc);
rest.forEach((s, i) => perm([...rest.slice(0, i), ...rest.slice(i + 1)], [...acc, s]));
};
perm(SUITS.split(""), []);
return out;
})();
/**
* Does a suit-isomorphism class match? `cards` is any one member of the class
* (e.g. from `ploStringToCards`). When the query names exact suits, or a board
* is given, every suit relabelling of the class is tried and the class matches
* if any member does; otherwise the representative alone decides.
*/
export function matchesHandClass(query: HandQuery, cards: string[], board?: string[]): boolean {
if (!query.usesExactSuits && !board) return query.test(cards);
const seen = new Set<string>();
const blocked = new Set(board ?? []);
for (const perm of SUIT_PERMS) {
const mapped = cards.map((c) => c[0] + perm[SUITS.indexOf(c[1])]);
if (mapped.some((c) => blocked.has(c))) continue;
const key = [...mapped].sort().join("");
if (seen.has(key)) continue;
seen.add(key);
if (query.test(mapped, board)) return true;
}
return false;
}
lib/hand-search/postflop.ts
/**
* Board-aware hand facts for the hand-search language: made-hand category and
* its sub-class (top pair, nut flush, ...), draws and blockers.
*
* Cards are two-char strings ("As", "Td"). Ranks are numbered 0 (deuce) to
* 12 (ace). Omaha rules (exactly two hole cards and three board cards) apply
* when the hand has four or more cards; with two hole cards any five of the
* seven play, as in Hold'em.
*
* Pure and dependency-free so Train, the Explorer and pokerdata.io can share it.
*/
export const RANK_CHARS = "23456789TJQKA";
export const SUIT_CHARS = "shdc";
export function rankOf(card: string): number {
return RANK_CHARS.indexOf(card[0]);
}
export function suitOf(card: string): string {
return card[1];
}
/** Top-level made-hand categories, weakest first. `>`/`<` compare on these. */
export const CATEGORIES = ["AIR", "PAIR", "2P", "SET", "STR", "FL", "FH", "QS", "SF", "RF"] as const;
export type Category = (typeof CATEGORIES)[number];
const CAT_INDEX: Record<string, number> = {
AIR: 0,
PAIR: 1,
"2P": 2,
SET: 3,
TRIPS: 3,
STR: 4,
FL: 5,
FH: 6,
QS: 7,
SF: 8,
RF: 9,
};
/** Index of a top-level category name (TRIPS and SET share three of a kind). */
export function categoryIndex(name: string): number | undefined {
return CAT_INDEX[name];
}
// ── Five-card evaluation ────────────────────────────────────────────────────
interface Five {
/** 0 high card … 8 straight flush (9 = royal, reported separately). */
cat: number;
value: number;
/** For straights: the high rank (3 = five-high wheel). */
straightHigh: number;
/** For flushes: the flush suit. */
flushSuit: string | null;
/** Ranks of the made combination (pair rank, trips rank, …), high first. */
groups: number[];
}
// High card, pair, two pair, trips, straight, flush, full house, quads, straight flush.
const C_HIGH = 0,
C_PAIR = 1,
C_2P = 2,
C_TRIPS = 3,
C_STR = 4,
C_FL = 5,
C_FH = 6,
C_QUADS = 7,
C_SF = 8;
function straightHighOf(ranks: number[]): number {
const set = new Set(ranks);
if (set.size !== 5) return -1;
const s = [...set].sort((a, b) => b - a);
if (s[0] - s[4] === 4) return s[0];
// Wheel: A-5-4-3-2.
if (s[0] === 12 && s[1] === 3 && s[4] === 0) return 3;
return -1;
}
function evalFive(cards: string[]): Five {
const ranks = cards.map(rankOf);
const suits = cards.map(suitOf);
const flush = suits.every((s) => s === suits[0]);
const sh = straightHighOf(ranks);
const counts = new Map<number, number>();
for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);
// Groups ordered by count, then rank.
const groups = [...counts.entries()].sort((a, b) => b[1] - a[1] || b[0] - a[0]);
const shape = groups.map((g) => g[1]).join("");
let cat: number;
if (sh >= 0 && flush) cat = C_SF;
else if (shape === "41") cat = C_QUADS;
else if (shape === "32") cat = C_FH;
else if (flush) cat = C_FL;
else if (sh >= 0) cat = C_STR;
else if (shape === "311") cat = C_TRIPS;
else if (shape === "221") cat = C_2P;
else if (shape === "2111") cat = C_PAIR;
else cat = C_HIGH;
const order = sh >= 0 && (cat === C_STR || cat === C_SF) ? [sh] : groups.map((g) => g[0]);
let value = cat;
for (let i = 0; i < 5; i++) value = value * 13 + (order[i] ?? 0);
return {
cat,
value,
straightHigh: cat === C_STR || cat === C_SF ? sh : -1,
flushSuit: flush ? suits[0] : null,
groups: groups.filter((g) => g[1] >= 2).map((g) => g[0]),
};
}
function combos<T>(items: T[], k: number): T[][] {
const out: T[][] = [];
const pick = (start: number, acc: T[]) => {
if (acc.length === k) {
out.push(acc);
return;
}
for (let i = start; i <= items.length - (k - acc.length); i++) pick(i + 1, [...acc, items[i]]);
};
pick(0, []);
return out;
}
interface Best extends Five {
/** The hole cards the best five uses. */
holeUsed: string[];
}
function bestHand(hole: string[], board: string[]): Best | null {
const omaha = hole.length >= 4;
let best: Best | null = null;
const consider = (h: string[], b: string[]) => {
const f = evalFive([...h, ...b]);
if (!best || f.value > best.value) best = { ...f, holeUsed: h };
};
if (omaha) {
if (board.length < 3) return null;
for (const h of combos(hole, 2)) for (const b of combos(board, 3)) consider(h, b);
} else {
const all = [...hole, ...board];
if (all.length < 5) return null;
for (const five of combos(all, 5)) {
const h = five.filter((c) => hole.includes(c));
consider(h, five.filter((c) => !hole.includes(c)));
}
}
return best;
}
// ── Straights by rank only ──────────────────────────────────────────────────
/** Five-rank windows, ace-high first, wheel last. */
const WINDOWS: { high: number; ranks: number[] }[] = (() => {
const out: { high: number; ranks: number[] }[] = [];
for (let high = 12; high >= 4; high--) out.push({ high, ranks: [high, high - 1, high - 2, high - 3, high - 4] });
out.push({ high: 3, ranks: [3, 2, 1, 0, 12] });
return out;
})();
/** Highest straight these hole ranks make with these board ranks, or -1. */
function heroStraightHigh(hole: number[], board: number[], omaha: boolean): number {
const holeSet = new Set(hole);
const boardSet = new Set(board);
for (const w of WINDOWS) {
if (omaha) {
// Two hole ranks + three board ranks covering the window exactly.
const fromBoard = w.ranks.filter((r) => boardSet.has(r));
if (fromBoard.length < 3) continue;
for (const [a, b] of combos(w.ranks, 2)) {
if (!holeSet.has(a) || !holeSet.has(b)) continue;
if (w.ranks.filter((r) => r !== a && r !== b).every((r) => boardSet.has(r))) return w.high;
}
} else if (w.ranks.every((r) => holeSet.has(r) || boardSet.has(r))) {
// Hold'em: the board alone counts only if a hole card could be swapped in,
// which it always can, so any cover is a straight.
return w.high;
}
}
return -1;
}
/** Straight highs possible on a board for some holding, best first. */
function possibleStraightHighs(board: number[]): number[] {
const boardSet = new Set(board);
return WINDOWS.filter((w) => w.ranks.filter((r) => boardSet.has(r)).length >= 3).map((w) => w.high);
}
// ── Facts ───────────────────────────────────────────────────────────────────
export interface PostflopFacts {
/** Index into CATEGORIES. */
category: number;
/** Every made-hand and draw macro this hand satisfies. */
tags: Set<string>;
}
/** Nut rank of a flush: 0 = nut, 1 = second nut, 2 = lower, by the hero's top
* hole card of the suit against the ranks of that suit not on the board. */
function flushNutLevel(hole: string[], board: string[], suit: string): number {
const onBoard = new Set(board.filter((c) => suitOf(c) === suit).map(rankOf));
const available: number[] = [];
for (let r = 12; r >= 0; r--) if (!onBoard.has(r)) available.push(r);
const top = Math.max(-1, ...hole.filter((c) => suitOf(c) === suit).map(rankOf));
const idx = available.indexOf(top);
return idx < 0 ? 2 : Math.min(idx, 2);
}
export function postflopFacts(hole: string[], board: string[]): PostflopFacts | null {
if (board.length < 3 || board.length > 5) return null;
const best = bestHand(hole, board);
if (!best) return null;
const omaha = hole.length >= 4;
const tags = new Set<string>();
const boardRanks = board.map(rankOf);
const distinctBoard = [...new Set(boardRanks)].sort((a, b) => b - a);
const top = distinctBoard[0];
const bottom = distinctBoard[distinctBoard.length - 1];
const holeHas = (r: number) => best.holeUsed.some((c) => rankOf(c) === r);
let category: number;
switch (best.cat) {
case C_SF:
category = best.straightHigh === 12 ? 9 : 8;
tags.add("SF");
if (category === 9) tags.add("RF");
break;
case C_QUADS:
category = 7;
tags.add("QS");
break;
case C_FH:
category = 6;
tags.add("FH");
break;
case C_FL: {
category = 5;
tags.add("FL");
const lvl = flushNutLevel(best.holeUsed, board, best.flushSuit!);
tags.add(lvl === 0 ? "FLN" : lvl === 1 ? "FLN2" : "FLNN");
break;
}
case C_STR: {
category = 4;
tags.add("STR");
const idx = possibleStraightHighs(boardRanks).indexOf(best.straightHigh);
tags.add(idx === 0 ? "STRN" : idx === 1 ? "STR2" : "STRNN");
break;
}
case C_TRIPS: {
category = 3;
const t = best.groups[0];
const fromHole = best.holeUsed.filter((c) => rankOf(c) === t).length;
if (fromHole >= 2) {
tags.add("SET");
if (t === top) tags.add("SETT");
else if (t === bottom) tags.add("SETB");
else tags.add("SETM");
} else if (fromHole === 1) {
tags.add("TRIPS");
}
break;
}
case C_2P: {
category = 2;
tags.add("2P");
const [hi, lo] = best.groups;
const made = (r: number) => boardRanks.includes(r) && holeHas(r);
const second = distinctBoard[1];
if (made(top) && second !== undefined && made(second) && (hi === top || lo === top) && (hi === second || lo === second)) {
tags.add("2PTT");
}
if (made(top) && (hi === top || lo === top) && made(hi === top ? lo : hi)) tags.add("2PTB");
else tags.add("2PB");
break;
}
case C_PAIR: {
category = 1;
tags.add("PAIR");
const p = best.groups[0];
const holeCount = best.holeUsed.filter((c) => rankOf(c) === p).length;
if (holeCount === 2 && !boardRanks.includes(p)) {
if (p > top) tags.add("OP");
else if (p < bottom) tags.add("UP");
} else if (holeCount >= 1) {
if (p === top) tags.add("TP");
else if (p === bottom) tags.add("BP");
else tags.add("MP");
}
break;
}
default:
category = 0;
tags.add("AIR");
}
// Draws only exist with cards to come.
if (board.length < 5) addDraws(hole, board, omaha, best, tags);
addBlockers(hole, board, tags);
return { category, tags };
}
function suitCount(cards: string[], s: string): number {
return cards.filter((c) => suitOf(c) === s).length;
}
function addDraws(hole: string[], board: string[], omaha: boolean, best: Best, tags: Set<string>) {
// Flush draws: one more card of the suit completes a flush.
let fdSuits = 0;
for (const s of SUIT_CHARS) {
const h = suitCount(hole, s);
const b = suitCount(board, s);
const isFd = omaha ? h >= 2 && b === 2 : h >= 1 && h + b === 4 && b <= 3;
if (!isFd) continue;
fdSuits++;
tags.add("FD");
const lvl = flushNutLevel(hole, board, s);
tags.add(lvl === 0 ? "NFD1" : lvl === 1 ? "NFD2" : "FDNN");
}
if (fdSuits >= 2) tags.add("DFD");
// Backdoor flush draws: flop only, two more of the suit needed.
if (board.length === 3) {
let bd = 0;
for (const s of SUIT_CHARS) {
const h = suitCount(hole, s);
const b = suitCount(board, s);
if (omaha ? h >= 2 && b === 1 : h >= 1 && h + b === 3) bd++;
}
if (bd >= 1) tags.add("BDFD");
if (bd === 1) tags.add("BDFD1");
if (bd >= 2) tags.add("BDFD2");
}
const seen = new Set([...hole, ...board]);
const unseen: string[] = [];
for (const r of RANK_CHARS) for (const s of SUIT_CHARS) if (!seen.has(r + s)) unseen.push(r + s);
// Straight-flush draw: some card to come makes a straight flush.
if (best.cat < C_SF) {
for (const c of unseen) {
const nb = bestHand(hole, [...board, c]);
if (nb && nb.cat === C_SF) {
tags.add("SFD");
break;
}
}
}
// Straight draws, by the ranks that complete one (no draw if already made).
const holeRanks = hole.map(rankOf);
const boardRanks = board.map(rankOf);
if (heroStraightHigh(holeRanks, boardRanks, omaha) >= 0) return;
const unseenByRank = new Array(13).fill(0);
for (const c of unseen) unseenByRank[rankOf(c)]++;
let outRanks = 0;
let nutRanks = 0;
for (let r = 0; r < 13; r++) {
if (unseenByRank[r] === 0) continue;
const nb = [...boardRanks, r];
const high = heroStraightHigh(holeRanks, nb, omaha);
if (high < 0) continue;
outRanks++;
if (possibleStraightHighs(nb)[0] === high) nutRanks++;
}
if (outRanks === 0) return;
tags.add("SD");
if (outRanks === 1) {
tags.add("GS");
if (nutRanks === 1) tags.add("NGS");
} else if (outRanks === 2) {
tags.add("OESD");
if (nutRanks === 2) tags.add("NOESD");
} else {
tags.add(nutRanks > 0 ? "NWRAP" : "WRAP");
}
}
function addBlockers(hole: string[], board: string[], tags: Set<string>) {
if (board.length >= 5) return;
// Flush-draw blocker: a card of a suit with exactly two on the board.
for (const s of SUIT_CHARS) {
if (suitCount(board, s) === 2 && suitCount(hole, s) >= 1) {
tags.add("FDB");
break;
}
}
// Straight-draw blocker: holds a rank that would let a new straight onto
// the board if it came (an out for the straight draws out there).
const boardRanks = board.map(rankOf);
const before = new Set(possibleStraightHighs(boardRanks));
for (const c of hole) {
const r = rankOf(c);
if (boardRanks.includes(r)) continue;
if (possibleStraightHighs([...boardRanks, r]).some((h) => !before.has(h))) {
tags.add("SDB");
break;
}
}
}
lib/nl-ranges/range.ts
/**
* A preflop range as the solver exports it: a map from 169 hand-classes
* ("AA", "AKs", "AKo", …) to a weight in [0, 1] — the frequency with which a
* given action is taken with that class.
*
* Stored on the 169-grid (not expanded to 1326 concrete combos). Combo math is
* derived lazily: a pair is 6 combos, a suited class 4, an offsuit class 12.
* If you ever need card-removal against known cards, expand at the call site.
*/
const RANKS = "AKQJT98765432";
/** Concrete combos a 169-grid class represents, ignoring card removal. */
export function comboCount(hand: string): number {
if (hand.length === 2) {
// pair: two equal ranks, e.g. "AA", "22"
return hand[0] === hand[1] && RANKS.includes(hand[0]) ? 6 : 0;
}
if (hand.length === 3 && RANKS.includes(hand[0]) && RANKS.includes(hand[1])) {
if (hand[2] === "s") return 4; // suited: "AKs"
if (hand[2] === "o") return 12; // offsuit: "AKo"
}
return 0; // unrecognized label
}
export class Range {
/** hand-class → weight in [0, 1]. Includes 0-weight entries verbatim. */
readonly weights: ReadonlyMap<string, number>;
/** hand-class → EV in small blinds, when the bundle carries it (v2+). */
readonly evs: ReadonlyMap<string, number>;
/** Original CSV exactly as stored (e.g. "AA:1.0,A2s:0.0,…"). */
readonly raw: string;
constructor(
weights: Map<string, number>,
raw: string,
evs: Map<string, number> = new Map(),
) {
this.weights = weights;
this.evs = evs;
this.raw = raw;
}
/**
* Parse a stored range CSV. Each entry is "hand:freq" (v1 bundles) or
* "hand:freq:ev" (v2 bundles carry EV in small blinds). NL hand-classes
* ("AA", "AKs", "AKo") never contain `:`, so the first `:` splits the hand
* from its values and an optional second `:` splits freq from EV. Malformed
* pairs are skipped. Tolerant of both formats for safe rollout.
*/
static parse(raw: string): Range {
const weights = new Map<string, number>();
const evs = new Map<string, number>();
for (const part of raw.split(",")) {
const s = part.trim();
if (!s) continue;
const i = s.indexOf(":");
if (i === -1) continue;
const hand = s.slice(0, i).trim();
const rest = s.slice(i + 1);
const j = rest.indexOf(":");
const w = Number(j === -1 ? rest : rest.slice(0, j));
if (!hand || Number.isNaN(w)) continue;
weights.set(hand, w);
if (j !== -1) {
const ev = Number(rest.slice(j + 1));
if (!Number.isNaN(ev)) evs.set(hand, ev);
}
}
return new Range(weights, raw, evs);
}
/** Build a range from an explicit weight map (no raw source). */
static from(weights: Map<string, number>): Range {
const raw = [...weights].map(([h, w]) => `${h}:${w}`).join(",");
return new Range(weights, raw);
}
/** Weight of a single class (0 if absent). */
freq(hand: string): number {
return this.weights.get(hand) ?? 0;
}
/** EV (small blinds) of a single class, or undefined if not carried. */
ev(hand: string): number | undefined {
return this.evs.get(hand);
}
/** Classes with weight strictly above `minFreq`, in stored order. */
hands(minFreq = 0): string[] {
const out: string[] = [];
for (const [hand, w] of this.weights) if (w > minFreq) out.push(hand);
return out;
}
/** Weighted concrete-combo count (Σ weight × comboCount). */
combos(): number {
let total = 0;
for (const [hand, w] of this.weights) total += w * comboCount(hand);
return total;
}
/** Plain object view (handy for JSON / snapshots). */
toObject(): Record<string, number> {
return Object.fromEntries(this.weights);
}
/**
* Combine ranges by summing per-class weights, clamped to [0, 1]. Used to
* collapse a node's non-fold actions into one "continuing" range: a class's
* continue frequency is the sum of its frequencies across each action.
*/
static union(ranges: Range[]): Range {
const merged = new Map<string, number>();
for (const r of ranges) {
for (const [hand, w] of r.weights) {
merged.set(hand, Math.min(1, (merged.get(hand) ?? 0) + w));
}
}
return Range.from(merged);
}
}
lib/plo-ranges/combos.ts
/**
* Expand MonkerSolver suit-grouping hand classes into the concrete four-card
* combos the native solver's PLO range grammar expects.
*
* The PLO ranges store keeps weights on 16,432 suit-isomorphic hand classes
* written in MonkerSolver notation (parentheses wrap cards sharing a suit), e.g.
*
* AAAA four aces, each a different suit → 1 concrete combo
* (2A)AA A-A-A-2, the 2 suited to one ace → 12 concrete combos
* (KA)(KA) A-A-K-K double-suited → 36 concrete combos
* AKQJ four broadways, all different suits → 256 concrete combos
*
* The solver engine (`solver-engine/src/range.rs::parse_plo`) only accepts
* `random` or an explicit comma-list of concrete combos like `AhKhQsJs:0.5`. To
* feed real preflop ranges to the solver we must expand each class into its
* concrete combos.
*
* Doing this by reasoning about suit permutations per pattern is error-prone, so
* instead we enumerate all C(52,4) = 270,725 concrete combos once, compute each
* one's suit-isomorphism *signature* with the exact same algorithm used to parse
* the MonkerSolver strings (ported from `mobile/src/lib/trainer/plo-hand.ts`),
* and build a `signature → combos` index. Expanding a class is then a lookup:
* its signature is computed the same way, so the mapping is correct by
* construction. See `combos.test.ts` for the correctness gate.
*/
// Ranks high→low so a lower index means a higher rank — matches the trainer's
// `rankIndex` (mobile/src/lib/trainer/hand.ts). Within a group the canonical
// order is ascending by index, i.e. highest rank written first ("A2", "AKQJ").
const RANKS = "AKQJT98765432";
const SUITS = ["c", "d", "h", "s"] as const;
function rankIndex(r: string): number {
return RANKS.indexOf(r);
}
/** Sort rank chars ascending by index (highest rank first). */
function sortRanks(ranks: string[]): string[] {
return [...ranks].sort((a, b) => rankIndex(a) - rankIndex(b));
}
function compareRankStr(a: string, b: string): number {
const n = Math.min(a.length, b.length);
for (let i = 0; i < n; i++) {
const d = rankIndex(a[i]) - rankIndex(b[i]);
if (d !== 0) return d;
}
return a.length - b.length;
}
/**
* Order-independent signature of a hand's suit partition. Two hands are
* suit-isomorphic iff their signatures match. Groups (cards sharing a suit) are
* sorted by size desc, then by rank, so the form is canonical regardless of
* which actual suits are used. Identical to the trainer's `signature`.
*/
function signature(groups: string[][]): string {
return groups
.map((g) => g.join(""))
.sort((a, b) => b.length - a.length || compareRankStr(a, b))
.join("/");
}
/** Parse a MonkerSolver class string into suit groups (parens = same suit). */
export function parseHandString(s: string): string[][] {
const groups: string[][] = [];
let i = 0;
while (i < s.length) {
if (s[i] === "(") {
const j = s.indexOf(")", i);
if (j === -1) throw new Error(`unbalanced '(' in hand class "${s}"`);
groups.push(sortRanks(s.slice(i + 1, j).split("")));
i = j + 1;
} else {
groups.push([s[i]]);
i += 1;
}
}
return groups;
}
/** Signature of a MonkerSolver class string. */
export function signatureOfClass(s: string): string {
return signature(parseHandString(s));
}
// ─── signature → concrete combos index ─────────────────────────────────────
/** All 52 cards as "<rank><suit>" strings (e.g. "Ah"). */
function allCards(): string[] {
const cards: string[] = [];
for (const r of RANKS) for (const s of SUITS) cards.push(`${r}${s}`);
return cards;
}
/** Signature of a concrete 4-card combo (group its cards by suit). */
export function signatureOfCombo(cards: string[]): string {
const bySuit = new Map<string, string[]>();
for (const c of cards) {
const arr = bySuit.get(c[1]);
if (arr) arr.push(c[0]);
else bySuit.set(c[1], [c[0]]);
}
const groups = [...bySuit.values()].map(sortRanks);
return signature(groups);
}
let INDEX: Map<string, string[]> | null = null;
/**
* Build (once) the `signature → concrete-combo strings` index over all 270,725
* four-card combos. Each combo string is the engine's explicit form, e.g.
* "AhKhQsJs" (rank+suit per card). Cached for the lifetime of the process.
*/
function comboIndex(): Map<string, string[]> {
if (INDEX) return INDEX;
const cards = allCards();
const index = new Map<string, string[]>();
const n = cards.length;
for (let a = 0; a < n; a++) {
for (let b = a + 1; b < n; b++) {
for (let c = b + 1; c < n; c++) {
for (let d = c + 1; d < n; d++) {
const combo = [cards[a], cards[b], cards[c], cards[d]];
const sig = signatureOfCombo(combo);
const bucket = index.get(sig);
const str = combo.join("");
if (bucket) bucket.push(str);
else index.set(sig, [str]);
}
}
}
}
INDEX = index;
return index;
}
/** The concrete combos for a single MonkerSolver class, e.g. "(2A)AA". */
export function combosForClass(handClass: string): string[] {
return comboIndex().get(signatureOfClass(handClass)) ?? [];
}
/** Every four-card combo: C(52,4). The denominator for range percentages. */
export const TOTAL_PLO_COMBOS = 270725;
let COUNTS: Map<string, number> | null = null;
/**
* `signature → concrete-combo count`. Same enumeration as `comboIndex()` but
* keeps only the counts (~16k numbers rather than 270,725 strings), which is
* all the range-weighting math needs — a full index costs ~145MB of resident
* memory in a function that only wants to divide by 270,725.
*/
function comboCounts(): Map<string, number> {
if (COUNTS) return COUNTS;
const cards = allCards();
const counts = new Map<string, number>();
const n = cards.length;
for (let a = 0; a < n; a++) {
for (let b = a + 1; b < n; b++) {
for (let c = b + 1; c < n; c++) {
for (let d = c + 1; d < n; d++) {
const sig = signatureOfCombo([cards[a], cards[b], cards[c], cards[d]]);
counts.set(sig, (counts.get(sig) ?? 0) + 1);
}
}
}
}
COUNTS = counts;
return counts;
}
/**
* How many concrete combos a MonkerSolver class covers, e.g. "AAAA" → 1,
* "(2A)AA" → 12. Weighting a range's classes by this is what turns a class
* count into a comparable "% of all hands" (the PLO analogue of NL's VPIP).
*/
export function comboCountForClass(handClass: string): number {
return comboCounts().get(signatureOfClass(handClass)) ?? 0;
}
/**
* The same count as `comboCountForClass`, worked out from the class string
* instead of by enumerating all 270,725 combos, so client code can weight by
* combos without a half-second warm-up. Each suit group takes a distinct suit:
* 4!/(4-g)! ways for g groups, divided by the orderings of identical groups
* ("(2A)AA" → 24 / 2! = 12, "AAAA" → 24 / 4! = 1). `combos.test.ts` checks it
* against the enumeration for every class.
*/
export function classComboCount(handClass: string): number {
let groups: string[][];
try {
groups = parseHandString(handClass);
} catch {
return 0;
}
const g = groups.length;
if (g === 0 || g > 4) return 0;
let ways = 1;
for (let i = 0; i < g; i++) ways *= 4 - i;
const same = new Map<string, number>();
for (const grp of groups) {
const k = grp.join("");
same.set(k, (same.get(k) ?? 0) + 1);
}
for (const m of same.values()) for (let i = 2; i <= m; i++) ways /= i;
return ways;
}
// ─── range expansion ───────────────────────────────────────────────────────
/** A token already in the engine's explicit form: 4 rank+suit pairs. */
const EXPLICIT_COMBO = /^[2-9TJQKA][cdhs][2-9TJQKA][cdhs][2-9TJQKA][cdhs][2-9TJQKA][cdhs]$/i;
/**
* Expand a PLO range expressed over MonkerSolver hand classes into the engine's
* explicit-combo grammar.
*
* Input is a comma-list of `class[:weight]` tokens (the same CSV the ranges
* store serves, e.g. `AAAA:1,(2A)AA:0.5`). `random`/`100` pass straight through.
* Tokens already in explicit-combo form (`AhKhQsJs`) are passed through too, so
* power users can hand-write combos. Every concrete combo of a class inherits
* the class weight; weight-1 combos are emitted bare and weighted combos as
* `combo:weight`. Unknown classes that expand to nothing are skipped.
*
* Returns the engine range string. Throws on a malformed weight.
*/
export function expandMonkerRange(spec: string): string {
const cleaned = spec.trim().toLowerCase();
if (cleaned === "" || cleaned === "random" || cleaned === "100" || cleaned === "100%") {
return "random";
}
const parts: string[] = [];
for (const raw of spec.split(",")) {
const tok = raw.trim();
if (!tok) continue;
const colon = tok.indexOf(":");
const body = colon === -1 ? tok : tok.slice(0, colon).trim();
let weight = 1;
if (colon !== -1) {
// A class CSV may carry "class:freq:ev"; only the first value is the weight.
const w = Number(tok.slice(colon + 1).split(":")[0].trim());
if (!Number.isFinite(w)) throw new Error(`invalid weight in "${tok}"`);
weight = w;
}
if (weight <= 0) continue;
if (EXPLICIT_COMBO.test(body)) {
parts.push(weight >= 0.999 ? body : `${body}:${round(weight)}`);
continue;
}
const combos = combosForClass(body);
for (const combo of combos) {
parts.push(weight >= 0.999 ? combo : `${combo}:${round(weight)}`);
}
}
return parts.join(",");
}
function round(w: number): number {
return Number(w.toFixed(3));
}
lib/plo5-ranges/canonical.ts
/**
* Five-card Omaha combos as this HydraSolver export stores them: 10 characters,
* ranks then suits, cards sorted by rank (2–A) then suit (s, h, d, c).
*
* Sample stored spelling: `2s2h2d2c3s`. User input (`Ah Kd Kc Qs 2s`, `ahkd…`)
* has to land on the same string, or a suit-isomorph of it, or a lookup misses
* a hand that is actually in the tree.
*
* The pack is a 204k HDV bucket-map, not the 2.6M combinadic space. Preflop,
* suit relabelings are the same game — `hdvOrbit` tries the user's spelling
* first, then the other ≤23 suit permutations.
*/
const RANK_HI = "AKQJT98765432";
const RANK_ORDER = "23456789TJQKA";
const SUIT_ORDER = "shdc";
const RANK_VALUE: Record<string, number> = Object.fromEntries(
[...RANK_ORDER].map((r, i) => [r, i]),
);
const SUIT_VALUE: Record<string, number> = Object.fromEntries(
[...SUIT_ORDER].map((s, i) => [s, i]),
);
export function comboStrength(hand: string): number {
let s = 0;
for (let i = 0; i + 1 < hand.length; i += 2) {
s += RANK_VALUE[hand[i].toUpperCase()] ?? 0;
}
return s;
}
const SUIT_CHARS = new Set(["s", "h", "d", "c", "S", "H", "D", "C"]);
/**
* Rank multiset from a typed filter. `AK222` and `AsKh2d2c2s` both become
* {A:1, K:1, 2:3}. Returns null when the string isn't 1–5 ranks.
*/
export function parsePlo5RankFilter(input: string): Record<string, number> | null {
const compact = input.replace(/[\s,]+/g, "");
if (!compact) return null;
const ranks: string[] = [];
let i = 0;
while (i < compact.length) {
const r = compact[i].toUpperCase();
if (RANK_VALUE[r] === undefined) return null;
ranks.push(r);
i++;
if (i < compact.length && SUIT_CHARS.has(compact[i])) i++;
}
if (ranks.length < 1 || ranks.length > 5) return null;
const counts: Record<string, number> = {};
for (const r of ranks) counts[r] = (counts[r] ?? 0) + 1;
return counts;
}
export function handRankCounts(hand: string): Record<string, number> {
const compact = hand.replace(/[\s,]+/g, "");
const counts: Record<string, number> = {};
for (let i = 0; i + 1 < compact.length; i += 2) {
const r = compact[i].toUpperCase();
counts[r] = (counts[r] ?? 0) + 1;
}
return counts;
}
/** Five ranks → exact bag. Fewer ranks → hand must include at least those counts. */
export function handMatchesRankFilter(hand: string, filter: Record<string, number>): boolean {
const have = handRankCounts(hand);
const needed = Object.values(filter).reduce((s, n) => s + n, 0);
if (needed >= 5) {
const keys = new Set([...Object.keys(have), ...Object.keys(filter)]);
for (const k of keys) if ((have[k] ?? 0) !== (filter[k] ?? 0)) return false;
return true;
}
for (const [r, n] of Object.entries(filter)) {
if ((have[r] ?? 0) < n) return false;
}
return true;
}
export function encodePlo5RankFilter(filter: Record<string, number>): string {
return Object.entries(filter)
.sort((a, b) => RANK_HI.indexOf(a[0]) - RANK_HI.indexOf(b[0]))
.map(([r, n]) => r.repeat(n))
.join("");
}
/** Canonical 10-char combo, or null if the string isn't five distinct cards. */
export function canonicalPlo5Hand(input: string): string | null {
const compact = input.replace(/[\s,]+/g, "");
if (compact.length !== 10) return null;
const cards: string[] = [];
const seen = new Set<string>();
for (let i = 0; i < 10; i += 2) {
const rank = compact[i].toUpperCase();
const suit = compact[i + 1].toLowerCase();
if (RANK_VALUE[rank] === undefined || SUIT_VALUE[suit] === undefined) {
return null;
}
const card = rank + suit;
if (seen.has(card)) return null;
seen.add(card);
cards.push(card);
}
cards.sort((a, b) => {
const rd = RANK_VALUE[a[0]] - RANK_VALUE[b[0]];
return rd !== 0 ? rd : SUIT_VALUE[a[1]] - SUIT_VALUE[b[1]];
});
return cards.join("");
}
function suitPerms(): string[][] {
const suits = ["s", "h", "d", "c"];
const out: string[][] = [];
const used = [false, false, false, false];
const cur: string[] = [];
const walk = () => {
if (cur.length === 4) {
out.push([...cur]);
return;
}
for (let i = 0; i < 4; i++) {
if (used[i]) continue;
used[i] = true;
cur.push(suits[i]);
walk();
cur.pop();
used[i] = false;
}
};
walk();
return out;
}
const SUIT_PERMS = suitPerms();
/** Suit-isomorphism orbit. Index 0 is the user's canonical cards. */
export function hdvOrbit(input: string): string[] | null {
const canon = canonicalPlo5Hand(input);
if (!canon) return null;
const ranks: string[] = [];
const suits: string[] = [];
for (let i = 0; i < 10; i += 2) {
ranks.push(canon[i]);
suits.push(canon[i + 1]);
}
const seen = new Set<string>([canon]);
for (const perm of SUIT_PERMS) {
const map: Record<string, string> = {
s: perm[0],
h: perm[1],
d: perm[2],
c: perm[3],
};
const remapped: string[] = [];
for (let i = 0; i < 5; i++) remapped.push(ranks[i] + map[suits[i]]);
const next = canonicalPlo5Hand(remapped.join(""));
if (next) seen.add(next);
}
const rest = [...seen].filter((h) => h !== canon).sort();
return [canon, ...rest];
}
function compareRankStr(a: string, b: string): number {
const n = Math.min(a.length, b.length);
for (let i = 0; i < n; i++) {
const d = RANK_HI.indexOf(a[i]) - RANK_HI.indexOf(b[i]);
if (d !== 0) return d;
}
return a.length - b.length;
}
/** Monker-style grouping: parentheses wrap ranks that share a suit. */
export function plo5IsoClass(input: string): string | null {
const canon = canonicalPlo5Hand(input);
if (!canon) return null;
const bySuit = new Map<string, string[]>();
for (let i = 0; i < 10; i += 2) {
const r = canon[i];
const s = canon[i + 1];
const arr = bySuit.get(s);
if (arr) arr.push(r);
else bySuit.set(s, [r]);
}
const groups = [...bySuit.values()].map((g) =>
[...g].sort((a, b) => RANK_HI.indexOf(a) - RANK_HI.indexOf(b)).join(""),
);
groups.sort((a, b) => b.length - a.length || compareRankStr(a, b));
return groups.map((g) => (g.length > 1 ? `(${g})` : g)).join("");
}
lib/plo5-ranges/categories.ts
/**
* Preflop hand categories for five-card Omaha, the way a player sorts a
* range: pairing and suitedness first (unpaired double suited, one pair
* single suited, …), then the structure inside (rundowns, broadway counts,
* the pair's rank). Pure functions of the ten-character combo, so the
* server can fold a 204k-hand node into a tree and the explorer can filter
* its lists by the same keys.
*/
import type { CsvRow } from "./csv";
const RANK_ORDER = "23456789TJQKA";
const BROADWAY_MIN = RANK_ORDER.indexOf("T");
export type Pairing = "unpaired" | "pair" | "two_pair" | "trips" | "quads";
export type Suitedness = "ds" | "ss";
/** A top-level row: pairing × suitedness, or quads on their own. */
export type TopKey = `${Exclude<Pairing, "quads">}_${Suitedness}` | "quads";
export type UnpairedShape = "rundown5" | "rundown4" | "broadway3" | "broadway2" | "ragged";
export type PairRank = "AA" | "KK" | "QQ" | "JJ" | "TT" | "mid" | "low";
export interface HandCategory {
top: TopKey;
/** The structure row under `top`; quads and trips have none. */
child: UnpairedShape | PairRank | null;
}
const PAIRING_LABEL: Record<Pairing, string> = {
unpaired: "Unpaired",
pair: "One pair",
two_pair: "Two pair",
trips: "Trips",
quads: "Quads",
};
const SUIT_LABEL: Record<Suitedness, string> = { ds: "double suited", ss: "single suited" };
const SHAPE_LABEL: Record<UnpairedShape, string> = {
rundown5: "5-card rundown (≤2 gaps)",
rundown4: "4-card rundown (≤2 gaps)",
broadway3: "3 broadway",
broadway2: "2 broadway + 3 low",
ragged: "Ragged",
};
const PAIR_LABEL: Record<PairRank, string> = {
AA: "Aces",
KK: "Kings",
QQ: "Queens",
JJ: "Jacks",
TT: "Tens",
mid: "Nines to sixes",
low: "Fives to deuces",
};
const UNPAIRED_SHAPES: readonly UnpairedShape[] = ["rundown5", "rundown4", "broadway3", "broadway2", "ragged"];
const PAIR_RANKS: readonly PairRank[] = ["AA", "KK", "QQ", "JJ", "TT", "mid", "low"];
/** Top rows in display order. */
export const TOP_KEYS: readonly TopKey[] = [
"unpaired_ds",
"unpaired_ss",
"pair_ds",
"pair_ss",
"two_pair_ds",
"two_pair_ss",
"trips_ds",
"trips_ss",
"quads",
];
export function topLabel(top: TopKey): string {
if (top === "quads") return PAIRING_LABEL.quads;
const [pairing, suit] = splitTop(top);
return `${PAIRING_LABEL[pairing]} ${SUIT_LABEL[suit]}`;
}
export function childLabel(child: UnpairedShape | PairRank): string {
return child in SHAPE_LABEL ? SHAPE_LABEL[child as UnpairedShape] : PAIR_LABEL[child as PairRank];
}
function splitTop(top: Exclude<TopKey, "quads">): [Exclude<Pairing, "quads">, Suitedness] {
const i = top.lastIndexOf("_");
return [top.slice(0, i) as Exclude<Pairing, "quads">, top.slice(i + 1) as Suitedness];
}
/** Children a top row can have, in display order. */
export function childrenOf(top: TopKey): readonly (UnpairedShape | PairRank)[] {
if (top === "quads") return [];
const [pairing] = splitTop(top);
if (pairing === "unpaired") return UNPAIRED_SHAPES;
if (pairing === "trips") return [];
return PAIR_RANKS;
}
function ranksOf(hand: string): number[] {
const out: number[] = [];
for (let i = 0; i + 1 < hand.length; i += 2) {
const r = RANK_ORDER.indexOf(hand[i].toUpperCase());
if (r >= 0) out.push(r);
}
return out;
}
function suitsOf(hand: string): string[] {
const out: string[] = [];
for (let i = 0; i + 1 < hand.length; i += 2) out.push(hand[i + 1].toLowerCase());
return out;
}
/** Fewest gaps across `n` of these distinct ranks (sorted); an ace counts low too. */
function fewestGaps(distinct: readonly number[], n: number): number {
const sets = [distinct];
if (distinct.includes(12)) sets.push([-1, ...distinct.filter((r) => r !== 12)]);
let best = Infinity;
for (const ranks of sets) {
for (let i = 0; i + n - 1 < ranks.length; i++) {
const gaps = ranks[i + n - 1] - ranks[i] - (n - 1);
if (gaps < best) best = gaps;
}
}
return best;
}
function pairRank(rank: number): PairRank {
const r = RANK_ORDER[rank];
if (r === "A" || r === "K" || r === "Q" || r === "J" || r === "T") return `${r}${r}` as PairRank;
return rank >= RANK_ORDER.indexOf("6") ? "mid" : "low";
}
/** Sort a five-card combo into its category. */
export function categorizePlo5Hand(hand: string): HandCategory {
const ranks = ranksOf(hand);
const counts = new Map<number, number>();
for (const r of ranks) counts.set(r, (counts.get(r) ?? 0) + 1);
const multiplicities = [...counts.values()].sort((a, b) => b - a);
const suitCounts = new Map<string, number>();
for (const s of suitsOf(hand)) suitCounts.set(s, (suitCounts.get(s) ?? 0) + 1);
const suitedPairs = [...suitCounts.values()].filter((n) => n >= 2).length;
const suit: Suitedness = suitedPairs >= 2 ? "ds" : "ss";
if (multiplicities[0] >= 4) return { top: "quads", child: null };
if (multiplicities[0] === 3) return { top: `trips_${suit}`, child: null };
const paired = [...counts.entries()].filter(([, n]) => n >= 2).map(([r]) => r);
if (paired.length >= 2) {
return { top: `two_pair_${suit}`, child: pairRank(Math.max(...paired)) };
}
if (paired.length === 1) {
return { top: `pair_${suit}`, child: pairRank(paired[0]) };
}
const distinct = [...counts.keys()].sort((a, b) => a - b);
const broadway = distinct.filter((r) => r >= BROADWAY_MIN).length;
let child: UnpairedShape;
if (fewestGaps(distinct, 5) <= 2) child = "rundown5";
else if (fewestGaps(distinct, 4) <= 2) child = "rundown4";
// Four broadway cards always sit within a 4-card rundown, so 3 is the top count here.
else if (broadway === 3) child = "broadway3";
else if (broadway === 2) child = "broadway2";
else child = "ragged";
return { top: `unpaired_${suit}`, child };
}
/** Does a hand sit in a row? A top key matches its whole family; `top:child` one structure. */
export function matchesPlo5Category(hand: string, key: string): boolean {
const cat = categorizePlo5Hand(hand);
const colon = key.indexOf(":");
if (colon < 0) return cat.top === key;
return cat.top === key.slice(0, colon) && cat.child === key.slice(colon + 1);
}
/** Any of the keys; no keys means everything. */
export function matchesPlo5Categories(hand: string, keys: readonly string[]): boolean {
if (keys.length === 0) return true;
const cat = categorizePlo5Hand(hand);
return keys.some((key) => {
const colon = key.indexOf(":");
return colon < 0 ? cat.top === key : cat.top === key.slice(0, colon) && cat.child === key.slice(colon + 1);
});
}
/** Parse the `cats` query param: comma-separated keys, unknown ones dropped. */
export function parsePlo5CategoryKeys(raw: string | null | undefined): string[] {
if (!raw) return [];
const out: string[] = [];
for (const key of raw.split(",")) {
const k = key.trim();
if (!k) continue;
const colon = k.indexOf(":");
const top = (colon < 0 ? k : k.slice(0, colon)) as TopKey;
if (!TOP_KEYS.includes(top)) continue;
if (colon >= 0 && !(childrenOf(top) as readonly string[]).includes(k.slice(colon + 1))) continue;
out.push(k);
}
return out;
}
export interface CategoryNode {
key: string;
label: string;
/** Share of the range's reach-weighted hands (0–1). */
share: number;
/** Reach-weighted action split inside the row, parallel to `actions`; null when nothing reaches. */
mix: number[] | null;
children: CategoryNode[];
}
export interface CategoryTree {
/** The node's options, in the tree's own order; `mix` rows follow it. */
actions: string[];
/** Reach-weighted hand count of the range. */
combos: number;
nodes: CategoryNode[];
}
/**
* Fold a node's hands into the tree. `freqs` is each option's hand→frequency
* at the node (parallel to `actions`); `reach` is how much of a hand is
* still in the actor's range here (1 at a first decision).
*/
export function buildPlo5CategoryTree(
actions: readonly string[],
freqs: readonly ReadonlyMap<string, number>[],
reach: (hand: string) => number,
): CategoryTree {
type Acc = { w: number; mix: number[] };
const acc = new Map<string, Acc>();
const add = (key: string, w: number, f: readonly number[]) => {
let a = acc.get(key);
if (!a) acc.set(key, (a = { w: 0, mix: new Array<number>(actions.length).fill(0) }));
a.w += w;
for (let i = 0; i < actions.length; i++) a.mix[i] += w * f[i];
};
const hands = new Set<string>();
for (const m of freqs) for (const hand of m.keys()) hands.add(hand);
let total = 0;
const f = new Array<number>(actions.length);
for (const hand of hands) {
const w = reach(hand);
if (!(w > 0)) continue;
let fs = 0;
for (let i = 0; i < actions.length; i++) {
f[i] = freqs[i].get(hand) ?? 0;
fs += f[i];
}
if (fs > 0) for (let i = 0; i < actions.length; i++) f[i] /= fs;
const cat = categorizePlo5Hand(hand);
total += w;
add(cat.top, w, f);
if (cat.child) add(`${cat.top}:${cat.child}`, w, f);
}
const node = (key: string, label: string, children: CategoryNode[] = []): CategoryNode | null => {
const a = acc.get(key);
if (!a || !(a.w > 0)) return null;
const mixTotal = a.mix.reduce((s, x) => s + x, 0);
return {
key,
label,
share: total > 0 ? Math.round((a.w / total) * 1e4) / 1e4 : 0,
mix: mixTotal > 0 ? a.mix.map((x) => Math.round((x / mixTotal) * 1000) / 1000) : null,
children,
};
};
const nodes: CategoryNode[] = [];
for (const top of TOP_KEYS) {
const children = childrenOf(top)
.map((c) => node(`${top}:${c}`, childLabel(c)))
.filter((x): x is CategoryNode => !!x);
const n = node(top, topLabel(top), children);
if (n) nodes.push(n);
}
return { actions: [...actions], combos: Math.round(total * 100) / 100, nodes };
}
const SUITS = "shdc";
const SUIT_PERMS: number[][] = [];
(function walk(cur: number[], used: boolean[]) {
if (cur.length === 4) {
SUIT_PERMS.push([...cur]);
return;
}
for (let i = 0; i < 4; i++) {
if (used[i]) continue;
used[i] = true;
cur.push(i);
walk(cur, used);
cur.pop();
used[i] = false;
}
})([], [false, false, false, false]);
/**
* How many dealt combos a stored bucket stands for. The pack lists one or
* more suit-reduced spellings per suit-permutation orbit; the orbit's real
* combos are split evenly across the spellings it does list. `hand` must be
* canonical (cards sorted by rank, then s/h/d/c).
*/
export function storedComboWeight(hand: string, stored: ReadonlySet<string>): number {
const ranks: string[] = [];
const suits: number[] = [];
for (let i = 0; i + 1 < hand.length; i += 2) {
ranks.push(hand[i]);
suits.push(SUITS.indexOf(hand[i + 1]));
}
const n = ranks.length;
const orbit = new Set<string>();
let present = 0;
const mapped = new Array<number>(n);
for (const perm of SUIT_PERMS) {
for (let i = 0; i < n; i++) mapped[i] = perm[suits[i]];
// Ranks are already in order; only cards of one rank need re-sorting by suit.
let out = "";
for (let i = 0; i < n; ) {
let j = i + 1;
while (j < n && ranks[j] === ranks[i]) j++;
if (j - i === 1) out += ranks[i] + SUITS[mapped[i]];
else {
const run = mapped.slice(i, j).sort((a, b) => a - b);
for (const m of run) out += ranks[i] + SUITS[m];
}
i = j;
}
if (orbit.has(out)) continue;
orbit.add(out);
if (stored.has(out)) present++;
}
return orbit.size / Math.max(1, present);
}
/** Rows of one edge CSV as a hand→frequency map. */
export function freqMap(rows: readonly CsvRow[]): Map<string, number> {
const out = new Map<string, number>();
for (const r of rows) out.set(r.hand, r.freq);
return out;
}
lib/plo5-ranges/csv.ts
/**
* Point-lookup over a PLO5 range CSV (`hand:freq`, `hand:freq:ev`, or
* `hand:freq:ev:evSource:evStdErr` for an estimated EV and its standard error
* in big blinds; see `scripts/hydra-json-to-plo5-csv.mjs`).
* The PLO5 export stores EV in big blinds (folding the SB reads -0.5, the BB
* -1), unlike the PLO6 HU export's small blinds. Every PLO5 reader returns it
* in small blinds (`EV_SB_PER_FILE_UNIT`), the unit Explorer, coach and
* grades expect (`ev_sb`, shown as `ev / 2`).
* Records are newline-separated (the HDV dump), unlike PLO6's comma join.
*/
import { comboStrength } from "./canonical";
/**
* `evSource` / `evStdErr` (bb) are present only when the export marked the EV
* as an estimate with a standard error; an exact EV carries neither.
*/
export type CsvHit = { freq: number; ev: number | null; evSource?: string; evStdErr?: number };
export type CsvRow = { hand: string; freq: number; ev: number | null; evSource?: string; evStdErr?: number };
/** The file's EV unit (bb) in small blinds. */
const EV_SB_PER_FILE_UNIT = 2;
function parseHit(rest: string): CsvHit {
const [freqField, evField, sourceField, stdErrField] = rest.split(":");
const freq = Number(freqField);
if (!Number.isFinite(freq)) return { freq: 0, ev: null };
if (evField === undefined) return { freq, ev: null };
const ev = Number(evField) * EV_SB_PER_FILE_UNIT;
if (!Number.isFinite(ev)) return { freq, ev: null };
const hit: CsvHit = { freq, ev };
if (sourceField) hit.evSource = sourceField;
const evStdErr = stdErrField === undefined ? NaN : Number(stdErrField);
if (Number.isFinite(evStdErr)) hit.evStdErr = evStdErr;
return hit;
}
function recordStart(csv: string, hand: string): number {
const needle = `${hand}:`;
if (csv.startsWith(needle)) return 0;
const nl = csv.indexOf(`\n${needle}`);
if (nl >= 0) return nl + 1;
const comma = csv.indexOf(`,${needle}`);
if (comma >= 0) return comma + 1;
return -1;
}
function recordEnd(csv: string, start: number): number {
let end = csv.length;
for (let i = start; i < csv.length; i++) {
const c = csv[i];
if (c === "\n" || c === "\r" || c === ",") {
end = i;
break;
}
}
return end;
}
export function lookupCsv(csv: string, hand: string): CsvHit {
if (!hand || !csv) return { freq: 0, ev: null };
const start = recordStart(csv, hand);
if (start < 0) return { freq: 0, ev: null };
const rec = csv.slice(start, recordEnd(csv, start));
const first = rec.indexOf(":");
if (first < 0) return { freq: 0, ev: null };
return parseHit(rec.slice(first + 1));
}
/**
* A fold's EV is the chips the actor already put in, the same for every hand,
* so any row's EV is the node's fold EV. Null when the file stores no EV.
*/
export function foldEvOf(csv: string): number | null {
if (!csv) return null;
const rec = csv.slice(0, recordEnd(csv, 0));
const first = rec.indexOf(":");
return first < 0 ? null : parseHit(rec.slice(first + 1)).ev;
}
export function csvHasHand(csv: string, hand: string): boolean {
if (!hand || !csv) return false;
return recordStart(csv, hand) >= 0;
}
export function firstStoredHdv(csv: string, hands: readonly string[]): string | null {
if (!hands.length || !csv) return null;
if (csvHasHand(csv, hands[0])) return hands[0];
for (const hand of hands) {
if (csvHasHand(csv, hand)) return hand;
}
return null;
}
function walkCsv(csv: string, visit: (hand: string, hit: CsvHit) => void): void {
let i = 0;
while (i < csv.length) {
const end = recordEnd(csv, i);
const rec = csv.slice(i, end);
const colon = rec.indexOf(":");
if (colon > 0) visit(rec.slice(0, colon), parseHit(rec.slice(colon + 1)));
i = end + 1;
if (csv[end] === "\r" && csv[i] === "\n") i++;
}
}
/** Every nonzero (or above `minFreq`) row. Used to build Explorer breakdowns. */
export function parseCsvHands(csv: string, minFreq = 0): CsvRow[] {
const out: CsvRow[] = [];
if (!csv) return out;
walkCsv(csv, (hand, hit) => {
if (hit.freq > minFreq) out.push({ hand, ...hit });
});
return out;
}
function compareRows(a: CsvRow, b: CsvRow): number {
const ea = a.ev;
const eb = b.ev;
if (ea != null && eb != null && ea !== eb) return eb - ea;
if (ea != null && eb == null) return -1;
if (ea == null && eb != null) return 1;
if (a.freq !== b.freq) return b.freq - a.freq;
return comboStrength(b.hand) - comboStrength(a.hand);
}
export function topCsvHands(
csv: string,
limit: number,
minFreq = 0,
match?: (hand: string) => boolean,
): { rows: CsvRow[]; total: number } {
const all = match
? parseCsvHands(csv, minFreq).filter((r) => match(r.hand))
: parseCsvHands(csv, minFreq);
all.sort(compareRows);
return { rows: limit > 0 ? all.slice(0, limit) : all, total: all.length };
}
export function indexCsvNeedles(
csv: string,
needles: readonly string[],
): Map<string, CsvHit> {
const want = new Set(needles.filter(Boolean));
const out = new Map<string, CsvHit>();
if (!csv || want.size === 0) return out;
let i = 0;
while (i < csv.length && out.size < want.size) {
const end = recordEnd(csv, i);
const rec = csv.slice(i, end);
const colon = rec.indexOf(":");
if (colon > 0) {
const hand = rec.slice(0, colon);
if (want.has(hand) && !out.has(hand)) {
out.set(hand, parseHit(rec.slice(colon + 1)));
}
}
i = end + 1;
if (csv[end] === "\r" && csv[i] === "\n") i++;
}
return out;
}
lib/plo6-ranges/canonical.ts
/**
* Six-card Omaha combos as this HydraSolver export stores them: 12 characters,
* ranks then suits, cards sorted by rank (2–A) then suit (s, h, d, c).
*
* The source `.rng` files use that order (`2s2h2d2c3s3h`), so user input
* (`Ah Kd Kc Qs Qh 2s`, `ahkd…`) has to land on the same string or a lookup
* misses a hand that is actually in the tree.
*
* HDV is not a fuzzy cluster: Hydra stores ~1.86M concrete suitings of the
* 20.4M combinadic 6-card space. Preflop, suit relabelings of a hand are the
* same game, and empirically every random 6-card deal has at least one
* stored orbit member (orbit siblings share freq/EV). `hdvOrbit` is that
* map — exact spelling first, then the other ≤23 suit permutations.
*/
const RANK_HI = "AKQJT98765432";
const RANK_ORDER = "23456789TJQKA";
const SUIT_ORDER = "shdc";
const RANK_VALUE: Record<string, number> = Object.fromEntries(
[...RANK_ORDER].map((r, i) => [r, i]),
);
const SUIT_VALUE: Record<string, number> = Object.fromEntries(
[...SUIT_ORDER].map((s, i) => [s, i]),
);
/** Rank-sum used to pick the most interesting sample hands (aces-high first). */
export function comboStrength(hand: string): number {
let s = 0;
for (let i = 0; i + 1 < hand.length; i += 2) {
s += RANK_VALUE[hand[i].toUpperCase()] ?? 0;
}
return s;
}
/**
* Canonical 12-char combo, or null if the string isn't six distinct cards.
* Accepts spaced (`As Ah Kd Kc Qs Qh`) or concatenated form, any case.
*/
export function canonicalPlo6Hand(input: string): string | null {
const compact = input.replace(/[\s,]+/g, "");
if (compact.length !== 12) return null;
const cards: string[] = [];
const seen = new Set<string>();
for (let i = 0; i < 12; i += 2) {
const rank = compact[i].toUpperCase();
const suit = compact[i + 1].toLowerCase();
if (RANK_VALUE[rank] === undefined || SUIT_VALUE[suit] === undefined) {
return null;
}
const card = rank + suit;
if (seen.has(card)) return null;
seen.add(card);
cards.push(card);
}
cards.sort((a, b) => {
const rd = RANK_VALUE[a[0]] - RANK_VALUE[b[0]];
return rd !== 0 ? rd : SUIT_VALUE[a[1]] - SUIT_VALUE[b[1]];
});
return cards.join("");
}
function suitPerms(): string[][] {
const out: string[][] = [];
const s = [...SUIT_ORDER];
const rec = (i: number) => {
if (i === s.length) {
out.push([...s]);
return;
}
for (let j = i; j < s.length; j++) {
[s[i], s[j]] = [s[j], s[i]];
rec(i + 1);
[s[i], s[j]] = [s[j], s[i]];
}
};
rec(0);
return out;
}
const SUIT_PERMS = suitPerms();
/**
* Suit-isomorphism orbit of a 6-card combo in Hydra spelling. Index 0 is the
* user's own canonical cards; the rest are the other suit relabelings.
*/
export function hdvOrbit(input: string): string[] | null {
const canon = canonicalPlo6Hand(input);
if (!canon) return null;
const ranks: string[] = [];
const suits: string[] = [];
for (let i = 0; i < 12; i += 2) {
ranks.push(canon[i]);
suits.push(canon[i + 1]);
}
const seen = new Set<string>([canon]);
for (const perm of SUIT_PERMS) {
const map: Record<string, string> = {
s: perm[0],
h: perm[1],
d: perm[2],
c: perm[3],
};
const remapped: string[] = [];
for (let i = 0; i < 6; i++) remapped.push(ranks[i] + map[suits[i]]);
const next = canonicalPlo6Hand(remapped.join(""));
if (next) seen.add(next);
}
const rest = [...seen].filter((h) => h !== canon).sort();
return [canon, ...rest];
}
function compareRankStr(a: string, b: string): number {
const n = Math.min(a.length, b.length);
for (let i = 0; i < n; i++) {
const d = RANK_HI.indexOf(a[i]) - RANK_HI.indexOf(b[i]);
if (d !== 0) return d;
}
return a.length - b.length;
}
/**
* Suit-isomorphism class in Monker-style grouping: parentheses wrap ranks
* that share a suit, ranks high-first, groups by size then rank.
* `QsQhKdKcAsAh` → `(AQ)(AQ)KK`.
*/
export function plo6IsoClass(input: string): string | null {
const canon = canonicalPlo6Hand(input);
if (!canon) return null;
const bySuit = new Map<string, string[]>();
for (let i = 0; i < 12; i += 2) {
const r = canon[i];
const s = canon[i + 1];
const arr = bySuit.get(s);
if (arr) arr.push(r);
else bySuit.set(s, [r]);
}
const groups = [...bySuit.values()].map((g) =>
[...g].sort((a, b) => RANK_HI.indexOf(a) - RANK_HI.indexOf(b)).join(""),
);
groups.sort((a, b) => b.length - a.length || compareRankStr(a, b));
return groups.map((g) => (g.length > 1 ? `(${g})` : g)).join("");
}
const SUIT_CHARS = new Set(["s", "h", "d", "c", "S", "H", "D", "C"]);
/**
* Rank multiset from a typed filter. `AAKKQJ` and `AsAhKdKcQsJh` both become
* {A:2, K:2, Q:1, J:1}. Returns null when the string isn't 1–6 ranks.
*/
export function parsePlo6RankFilter(input: string): Record<string, number> | null {
const compact = input.replace(/[\s,]+/g, "");
if (!compact) return null;
const ranks: string[] = [];
let i = 0;
while (i < compact.length) {
const r = compact[i].toUpperCase();
if (RANK_VALUE[r] === undefined) return null;
ranks.push(r);
i++;
if (i < compact.length && SUIT_CHARS.has(compact[i])) i++;
}
if (ranks.length < 1 || ranks.length > 6) return null;
const counts: Record<string, number> = {};
for (const r of ranks) counts[r] = (counts[r] ?? 0) + 1;
return counts;
}
export function encodePlo6RankFilter(filter: Record<string, number>): string {
return Object.entries(filter)
.sort((a, b) => RANK_HI.indexOf(a[0]) - RANK_HI.indexOf(b[0]))
.map(([r, n]) => r.repeat(n))
.join("");
}
function handRankCounts(hand: string): Record<string, number> {
const compact = hand.replace(/[\s,]+/g, "");
const counts: Record<string, number> = {};
for (let i = 0; i + 1 < compact.length; i += 2) {
const r = compact[i].toUpperCase();
counts[r] = (counts[r] ?? 0) + 1;
}
return counts;
}
/** Six ranks → exact bag. Fewer ranks → hand must include at least those counts. */
export function handMatchesRankFilter(
hand: string,
filter: Record<string, number>,
): boolean {
const have = handRankCounts(hand);
const needed = Object.values(filter).reduce((s, n) => s + n, 0);
if (needed >= 6) {
const keys = new Set([...Object.keys(have), ...Object.keys(filter)]);
for (const k of keys) if ((have[k] ?? 0) !== (filter[k] ?? 0)) return false;
return true;
}
for (const [r, n] of Object.entries(filter)) {
if ((have[r] ?? 0) < n) return false;
}
return true;
}
lib/solver/client.ts
// Browser client for the solver, talking to the same-origin `/api/solver/*`
// proxy. Because it's same-origin the Clerk session cookie rides along
// automatically — no Authorization header, no CORS.
//
// We drive the job by *polling* `GET /api/solver/jobs/:id`, not a single
// long-lived SSE stream. A flop tree solves for minutes; an SSE connection held
// open that long is torn down by the serverless proxy once the solve outlives
// the function's max duration (the browser sees `net::ERR_TIMED_OUT`, or the
// read loop ends without a `done` event). The solve itself runs server-side in a
// background task, independent of any connection, so short repeated polls
// complete a solve of any length. Live `iter · expl` progress rides along on the
// worker's `running` response when present.
import { explorerHost } from "@/lib/explorer/host";
import type { SolveRequest, SolverProgress, SolverResult } from "./types";
/** The solver routes on this host; solving is off where the host has none. */
function solverApi(): string {
const api = explorerHost().solver;
if (!api) throw new Error("Solving isn't available here.");
return api;
}
export interface SolveOutcome {
result: SolverResult;
/** True when the solve was cancelled — the result is the partial strategy. */
cancelled: boolean;
}
export interface SolveHandle {
/** The worker's job id, once the POST has been accepted. */
jobId: Promise<string>;
/**
* True when the shared solve cache answered this request, so no worker job (and
* therefore no warm-start snapshot) exists. A caller that needs to chain off
* this solve — a locked re-solve does — must re-run it with `noCache: true`.
*/
cached: Promise<boolean>;
/** Resolves with the final (or partial, if cancelled) strategy. */
promise: Promise<SolveOutcome>;
/** Cooperatively stop the solve; the worker returns the partial strategy. */
cancel: () => Promise<void>;
}
/** Kick off a solve and return a handle to track / cancel it. */
export function startSolve(
config: SolveRequest,
onProgress?: (p: SolverProgress) => void,
): SolveHandle {
let resolveJob!: (id: string) => void;
let rejectJob!: (err: unknown) => void;
const jobId = new Promise<string>((res, rej) => {
resolveJob = res;
rejectJob = rej;
});
let resolveCached!: (cached: boolean) => void;
const cached = new Promise<boolean>((res) => {
resolveCached = res;
});
let cancelRequested = false;
const promise = (async (): Promise<SolveOutcome> => {
const created = await fetch(`${solverApi()}/jobs`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json" },
body: JSON.stringify(config),
});
if (!created.ok) {
const err = new Error(await errorText(created));
rejectJob(err);
resolveCached(false);
throw err;
}
const { job_id: id, cached: fromCache } = (await created.json()) as {
job_id: string;
cached?: boolean;
};
resolveJob(id);
resolveCached(Boolean(fromCache));
if (cancelRequested) await postCancel(id).catch(() => {});
return pollOutcome(id, onProgress);
})();
// Don't let an unobserved jobId rejection crash the page.
jobId.catch(() => {});
const cancel = async () => {
cancelRequested = true;
const id = await jobId.catch(() => null);
if (id) await postCancel(id).catch(() => {});
};
return { jobId, cached, promise, cancel };
}
/**
* Re-attach to a solve that's already running (or finished) on the worker —
* e.g. after a tab reload mid-flop-solve. The worker keeps jobs server-side,
* so this is just the polling half of `startSolve` against a known job id.
* A job the worker no longer knows (restart) rejects with its 404 message.
*/
export function resumeSolve(
jobId: string,
onProgress?: (p: SolverProgress) => void,
): SolveHandle {
return {
jobId: Promise.resolve(jobId),
// A `cache-…` id is a cache hit being re-attached to; anything else is a
// real worker job.
cached: Promise.resolve(jobId.startsWith("cache-")),
promise: pollOutcome(jobId, onProgress),
cancel: async () => {
await postCancel(jobId).catch(() => {});
},
};
}
function postCancel(jobId: string): Promise<Response> {
return fetch(`${solverApi()}/jobs/${jobId}/cancel`, { method: "POST" });
}
/** Shape of `GET /api/solver/jobs/:id` (proxied straight from the worker). */
interface PollBody {
status: "running" | "done";
cancelled?: boolean;
/** Latest tick while running; absent on older workers (graceful: no ticks). */
progress?: SolverProgress;
result?: SolverResult;
}
/**
* Poll the job to completion and resolve with the terminal outcome. A cancelled
* solve still resolves — the worker returns the partial (valid) strategy it
* reached, flagged `cancelled`.
*
* Polls start snappy so a sub-second river solve resolves fast, then back off so
* a multi-minute flop solve barely touches the network. Transient blips (a
* dropped poll, a 502/504 from the proxy) are tolerated for a few attempts so
* they don't abort a solve that's still running fine on the worker.
*/
async function pollOutcome(
jobId: string,
onProgress?: (p: SolverProgress) => void,
): Promise<SolveOutcome> {
const MIN_INTERVAL = 400;
const MAX_INTERVAL = 3000;
const MAX_TRANSIENT_FAILURES = 5;
let interval = MIN_INTERVAL;
let transientFailures = 0;
const backoff = async () => {
await delay(interval);
interval = Math.min(Math.round(interval * 1.5), MAX_INTERVAL);
};
// A transient failure burns one of the retry budget, then backs off; throws
// (ending the solve) once the budget is exhausted.
const tolerate = async (message: string) => {
if (++transientFailures > MAX_TRANSIENT_FAILURES) throw new Error(message);
await backoff();
};
for (;;) {
let res: Response;
try {
res = await fetch(`${solverApi()}/jobs/${jobId}`, {
headers: { Accept: "application/json" },
});
} catch (err) {
// Network-level failure (offline, DNS, connection reset): retry.
await tolerate((err as Error)?.message || "network error");
continue;
}
// A gateway hiccup (proxy/worker briefly unreachable) is retryable; any
// other non-OK, non-202 status is a terminal error (404 job gone, 422 solve
// error, 401 auth).
if (res.status === 502 || res.status === 503 || res.status === 504) {
await tolerate(await errorText(res));
continue;
}
if (!res.ok && res.status !== 202) throw new Error(await errorText(res));
transientFailures = 0;
const body = (await res.json()) as PollBody;
if (body.status === "done") {
if (!body.result) throw new Error("solver returned a malformed result");
return { result: body.result, cancelled: Boolean(body.cancelled) };
}
// Still running: surface the latest progress tick if the worker sent one.
if (body.progress) onProgress?.(body.progress);
await backoff();
}
}
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function errorText(res: Response): Promise<string> {
const text = await res.text().catch(() => "");
try {
const j = JSON.parse(text) as { error?: string };
if (j?.error) return j.error;
} catch {
/* not JSON */
}
return text.slice(0, 200) || `request failed (${res.status})`;
}
lib/solver/preflop.ts
// Preflop-tree walk for the solver's scenario selector.
//
// Ported from the desktop/mobile app (mobile/src/lib/trainer/parse-history.ts +
// mobile/src/lib/solver/scenario.ts). The native solver is two-player, but the
// NL preflop tree is 6-max; this module walks the tree one seat at a time and
// collapses the line to heads-up the moment a raise is called, handing the two
// survivors' ranges to the solver as OOP/IP.
import { ALL_HANDS, type RangeWeights } from "@/lib/solver/range-model";
import { notifyPlanRequired } from "@/lib/access/plan-required";
import { rangesUrl } from "@/lib/explorer/host";
import { ploRaisePotPct } from "@/lib/explorer/bet-size";
import type { CategoryTree } from "@/lib/plo5-ranges/categories";
export type Position =
| "UTG"
| "UTG1"
| "UTG2"
| "LJ"
| "MP"
| "HJ"
| "CO"
| "BTN"
| "SB"
| "BB";
/** Datasets the Explorer can walk. */
export type ExplorerGame =
| "nl"
| "plo"
| "plo4hu"
| "plo9"
| "plo5"
| "plo6hu"
| "nlmtt8"
| IcmGame;
/**
* The 8-max tournament ICM sets, one per stage of the tournament. All three
* read `/api/ranges/nlh8-icm`; a stage is the scenarios with that many
* players left, and a scenario (one stack table) is picked inside it.
*/
export type IcmGame = "icmft" | "icmbubble" | "icmbubble35";
/** Players left in the tournament for each ICM stage. */
export const ICM_PLAYERS_LEFT: Record<IcmGame, number> = {
icmft: 8,
icmbubble: 33,
icmbubble35: 35,
};
export function isIcmGame(game: ExplorerGame): game is IcmGame {
return game in ICM_PLAYERS_LEFT;
}
/** Ante every seat posts on the ICM tables (8 × 0.125 = 1bb in the pot). */
export const ICM_ANTE_PER_SEAT_BB = 0.125;
export type ActionKind = "fold" | "call" | "raise" | "allin" | "other";
export interface NodeAction {
action: string;
kind: ActionKind;
/** hand → frequency in [0, 1] for this action. */
weights: Record<string, number>;
/** hand → EV in small blinds for this action (v2 bundles only). */
evs?: Record<string, number>;
sizePct?: number;
combos?: number;
/** Reach-weighted pool % (0–100). PLO5 nodes omit per-hand weights. */
poolPct?: number;
/** Hands that take this action at 100% (PLO5 HDV samples). */
always?: string[];
/** Mixed-strategy sample combos (PLO5). `freq` is 0–1. */
mixed?: { hand: string; freq: number }[];
/** Raise-to in bb, when the feed sizes the raise (NL MTT and ICM tokens). */
sizeBb?: number | null;
}
export interface NodeResponse {
game: "nl";
stack: number;
history: string;
actor: Position;
actions: NodeAction[];
continuingCombos?: number;
/** Unit of `evs`: small blinds, or tournament dollars on the ICM sets. */
evUnit?: "sb" | "usd";
}
/** Wire shape from any ranges `/node` — PLO5 uses `hands` instead of `combos`. */
export interface ExplorerNodeRaw {
game?: string;
stack: number;
history: string;
actor: Position;
continuingCombos?: number;
evUnit?: string;
actions: Array<
NodeAction & {
hands?: number;
}
>;
}
export interface Manifest {
game: "nl";
generatedAt: string;
stacks: number[];
positions: Position[];
}
export interface SeatState {
position: Position;
action: string | null;
committed: number;
remaining: number;
folded: boolean;
isHero: boolean;
isDealer: boolean;
}
export interface ParsedTable {
seats: Record<Position, SeatState>;
pot: number;
hero: Position;
}
// 6-max preflop play order (CW from UTG). MP isn't present in the dataset.
export const PLAY_ORDER: Position[] = ["UTG", "HJ", "CO", "BTN", "SB", "BB"];
/**
* Preflop play order (clockwise from UTG) per dataset. The 6-max datasets have
* no MP; the 9-max PLO bundles name their early seats UTG1/UTG2/LJ.
*/
export const SEAT_ORDER: Record<ExplorerGame, Position[]> = {
nl: PLAY_ORDER,
plo: PLAY_ORDER,
// Heads-up: the SB is the button and acts first preflop.
plo4hu: ["SB", "BB"],
plo9: ["UTG", "UTG1", "UTG2", "LJ", "HJ", "CO", "BTN", "SB", "BB"],
nlmtt8: ["UTG", "UTG1", "LJ", "HJ", "CO", "BTN", "SB", "BB"],
icmft: ["UTG", "UTG1", "LJ", "HJ", "CO", "BTN", "SB", "BB"],
icmbubble: ["UTG", "UTG1", "LJ", "HJ", "CO", "BTN", "SB", "BB"],
icmbubble35: ["UTG", "UTG1", "LJ", "HJ", "CO", "BTN", "SB", "BB"],
// HydraSolver 6-max PLO5: first actor is LJ (HUD UTG).
plo5: ["LJ", "HJ", "CO", "BTN", "SB", "BB"],
plo6hu: ["BTN", "BB"],
};
// Postflop acting order (blinds first). The earlier player is out of position.
// Early-position seats (UTG/UTG1/UTG2/LJ) keep clock order so 8-max / 9-max
// assignOopIp does not treat a missing index as earliest-to-act.
export const POSTFLOP_ORDER: Position[] = [
"SB",
"BB",
"UTG",
"UTG1",
"UTG2",
"LJ",
"HJ",
"CO",
"BTN",
];
/** Dead ante on the HydraSolver PLO5 6-max 100bb tree. */
export const PLO5_ANTE_BB = 1.2;
/** Dead ante on the HydraSolver PLO6 HU 100bb tree. */
export const PLO6HU_ANTE_BB = 0.4;
/** BB-ante posted as dead chips on the 8-max MTT ladder. */
export const NLMTT8_ANTE_BB = 1;
const ROOT_HISTORY = "UTG";
/** First actor on this dataset — UTG for the Monker 6/9-max packs, LJ for PLO5. */
export function rootHistory(game: ExplorerGame): string {
return SEAT_ORDER[game][0];
}
// ─── Ranges API client (same-origin /api/ranges/nl) ────────────────────────
const cache = new Map<string, Promise<unknown>>();
async function getJson<T>(path: string): Promise<T> {
const hit = cache.get(path) as Promise<T> | undefined;
if (hit) return hit;
const promise = (async () => {
const res = await fetch(path, { headers: { Accept: "application/json" } });
if (!res.ok) {
notifyPlanRequired(res.status);
const body = await res.text().catch(() => "");
throw new Error(`GET ${path} -> ${res.status}: ${body.slice(0, 200)}`);
}
return (await res.json()) as T;
})();
cache.set(path, promise);
promise.catch(() => cache.delete(path));
return promise;
}
export function getManifest(): Promise<Manifest> {
return getJson<Manifest>(rangesUrl("nl"));
}
/**
* Route prefix per dataset. NL reads v2 because those bundles carry per-hand EV;
* the PLO datasets already do.
*/
const GAME_PATH: Record<ExplorerGame, string> = {
nl: "nl/v2",
plo: "plo",
plo4hu: "plo4hu",
plo9: "plo9",
plo5: "plo5",
plo6hu: "plo6hu",
nlmtt8: "nlmtt8",
icmft: "nlh8-icm",
icmbubble: "nlh8-icm",
icmbubble35: "nlh8-icm",
};
function gameBase(game: ExplorerGame): string {
return rangesUrl(GAME_PATH[game]);
}
export function getManifestForGame(game: ExplorerGame): Promise<Manifest> {
if (isIcmGame(game)) {
return getIcmTables(game).then((tables) => ({
game: "nl",
generatedAt: "",
stacks: [...new Set(tables.map((t) => t.stackBb))].sort((a, b) => a - b),
positions: SEAT_ORDER[game],
}));
}
return getJson<Manifest>(gameBase(game));
}
/** One ICM stack table (a scenario of `/api/ranges/nlh8-icm`). */
export interface IcmTable {
/** Scenario id, e.g. `33left-avg30-short-btn`. */
scenario: string;
/** The field's average stack: the depth the table is listed under. */
stackBb: number;
/** The table's label from the solve (`even`, `short-btn`, `mix-1`, …). */
label: string;
/** Each seat's starting stack in bb, before the ante. */
stacksBb: Partial<Record<Position, number>>;
/** Payouts, best place first, in tournament dollars. */
payouts: number[];
paidPlaces: number | null;
poolUsd: number | null;
}
interface IcmDiscovery {
scenarios: {
scenario: string;
stackBb: number;
playersLeft: number;
table: {
label?: string;
stacksBb?: Partial<Record<Position, number>>;
icm?: { payouts?: number[]; paidPlaces?: number; poolUsd?: number };
} | null;
}[];
}
/** The stack tables of one ICM stage, shallowest first. */
export async function getIcmTables(game: IcmGame): Promise<IcmTable[]> {
const d = await getJson<IcmDiscovery>(gameBase(game));
const left = ICM_PLAYERS_LEFT[game];
return d.scenarios
.filter((s) => s.playersLeft === left)
.map((s) => ({
scenario: s.scenario,
stackBb: s.stackBb,
label: s.table?.label ?? s.scenario.replace(/^\d+left-avg[\d.]+-/, ""),
stacksBb: s.table?.stacksBb ?? {},
payouts: s.table?.icm?.payouts ?? [],
paidPlaces: s.table?.icm?.paidPlaces ?? null,
poolUsd: s.table?.icm?.poolUsd ?? null,
}))
.sort((a, b) => a.stackBb - b.stackBb);
}
/**
* Raise-to sizes the feed has reported, per dataset (game plus ICM scenario):
* `"<history>_<token>"` → bb. Filled as nodes load, read by `parseHistory`
* to price tokens like `Open` / `3B` that don't encode their size.
*/
const raiseSizes = new Map<string, Record<string, number>>();
function datasetKey(game: ExplorerGame, scenario?: string | null): string {
return scenario ? `${game}:${scenario}` : game;
}
/** The raise-to sizes seen so far on this dataset (a live, growing record). */
export function raiseSizesFor(game: ExplorerGame, scenario?: string | null): Record<string, number> {
const key = datasetKey(game, scenario);
let rec = raiseSizes.get(key);
if (!rec) {
rec = {};
raiseSizes.set(key, rec);
}
return rec;
}
/**
* `getNodeV2OrNull` for any dataset — the Explorer's game-aware read. Same
* contract: null at a history the dataset has no decision for (HTTP 404), i.e.
* the preflop round closed on this line.
*/
export async function getNodeForGameOrNull(
game: ExplorerGame,
stack: number,
history: string,
/** ICM sets: the stack table to read (`33left-avg30-even`). */
scenario?: string | null,
): Promise<NodeResponse | null> {
const params =
isIcmGame(game) && scenario
? new URLSearchParams({ scenario, history })
: new URLSearchParams({ stack: String(stack), history });
const res = await fetch(`${gameBase(game)}/node?${params.toString()}`, {
headers: { Accept: "application/json" },
});
if (res.status === 404) return null;
if (!res.ok) {
notifyPlanRequired(res.status);
const body = await res.text().catch(() => "");
throw new Error(`GET node -> ${res.status}: ${body.slice(0, 200)}`);
}
const node = normalizeExplorerNode(game, (await res.json()) as ExplorerNodeRaw);
const sizes = raiseSizesFor(game, scenario);
for (const a of node.actions) {
if (a.sizeBb != null && a.sizeBb > 0) sizes[`${history}_${a.action}`] = a.sizeBb;
}
return node;
}
/** PLO5 nodes carry pool % + samples, not per-hand weights. Other games pass through. */
export function normalizeExplorerNode(_game: ExplorerGame, raw: ExplorerNodeRaw): NodeResponse {
return {
game: "nl",
stack: raw.stack,
history: raw.history,
actor: raw.actor,
continuingCombos: raw.continuingCombos,
...(raw.evUnit === "usd" ? { evUnit: "usd" as const } : {}),
actions: (raw.actions ?? []).map((a) => ({
action: a.action,
kind: a.action === "AI" ? "allin" : a.kind,
weights: a.weights ?? {},
evs: a.evs,
sizePct: a.sizePct,
combos: a.combos ?? a.hands,
poolPct: a.poolPct,
always: a.always,
mixed: a.mixed,
...(a.sizeBb != null ? { sizeBb: a.sizeBb } : {}),
})),
};
}
const nodeCache = new Map<string, Promise<NodeResponse | null>>();
/**
* `getNodeForGameOrNull` memoized per (game, stack, history) — including the
* null (404) answer. The Explorer prefetches a node for every seat the user
* could skip ahead to, and those fold-through histories repeat constantly as
* the walk moves back and forth, so they must not re-hit the network.
*/
export function getNodeForGameOrNullCached(
game: ExplorerGame,
stack: number,
history: string,
scenario?: string | null,
): Promise<NodeResponse | null> {
const key = `${datasetKey(game, scenario)}:${stack}:${history}`;
const hit = nodeCache.get(key);
if (hit) return hit;
const promise = getNodeForGameOrNull(game, stack, history, scenario);
nodeCache.set(key, promise);
promise.catch(() => nodeCache.delete(key));
return promise;
}
export function getNode(stack: number, history: string): Promise<NodeResponse> {
const params = new URLSearchParams({ stack: String(stack), history });
return getJson<NodeResponse>(`${rangesUrl("nl/node")}?${params.toString()}`);
}
/**
* Same decision node as `getNode`, read from the v2 dataset whose bundles also
* carry per-hand EV (small blinds) on each action. v2 mirrors v1's coverage
* (all stacks/positions), so the Explorer reads v2 to power its EV column.
*/
export function getNodeV2(stack: number, history: string): Promise<NodeResponse> {
const params = new URLSearchParams({ stack: String(stack), history });
return getJson<NodeResponse>(`${rangesUrl("nl/v2/node")}?${params.toString()}`);
}
/**
* Like `getNodeV2`, but returns null when the dataset has no decision at this
* history (HTTP 404) — i.e. the preflop betting round has closed on this line.
* The Explorer uses this to walk the full multiway tree and detect the end of
* preflop, rather than assuming where the line stops. Throws on real failures.
*/
export async function getNodeV2OrNull(
stack: number,
history: string,
): Promise<NodeResponse | null> {
const params = new URLSearchParams({ stack: String(stack), history });
const res = await fetch(`${rangesUrl("nl/v2/node")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
if (res.status === 404) return null;
if (!res.ok) {
notifyPlanRequired(res.status);
const body = await res.text().catch(() => "");
throw new Error(`GET node -> ${res.status}: ${body.slice(0, 200)}`);
}
return (await res.json()) as NodeResponse;
}
export { ROOT_HISTORY };
export interface Plo5HandStrategy {
hand: string;
hdvHand: string;
isoMapped: boolean;
actions: { action: string; kind: ActionKind; freq: number; ev_sb: number | null }[];
}
export interface Plo5ListedHand {
hand: string;
freq: number;
ev: number | null;
}
export interface Plo5ActionList {
action: string;
kind: ActionKind;
poolPct: number;
hands: number;
listed: Plo5ListedHand[];
listedTotal: number;
}
/** Per-action hand list for the Explorer breakdown (top by EV). */
export async function getPlo5NodeList(
stack: number,
history: string,
limit = 200,
ranks?: string,
minFreq?: number,
cats?: readonly string[],
): Promise<Plo5ActionList[]> {
const params = new URLSearchParams({
stack: String(stack),
history,
list: "1",
limit: String(limit),
});
if (ranks) params.set("ranks", ranks);
if (minFreq) params.set("minFreq", String(minFreq));
if (cats?.length) params.set("cats", cats.join(","));
const res = await fetch(`${rangesUrl("plo5/node")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
const data = (await res.json().catch(() => null)) as
| { error?: string; actions?: Plo5ActionList[] }
| null;
notifyPlanRequired(res.status);
if (!res.ok) throw new Error(data?.error || `GET plo5 list -> ${res.status}`);
return data?.actions ?? [];
}
/** Point-lookup one five-card combo at a PLO5 node. */
/** The node's hand-category tree (shares + action splits), reach-weighted. */
export async function getPlo5Categories(stack: number, history: string): Promise<CategoryTree> {
const params = new URLSearchParams({ stack: String(stack), history });
const res = await fetch(`${rangesUrl("plo5/categories")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
const data = (await res.json().catch(() => null)) as (CategoryTree & { error?: string }) | null;
notifyPlanRequired(res.status);
if (!res.ok) throw new Error(data?.error || `GET plo5 categories -> ${res.status}`);
if (!data) throw new Error("GET plo5 categories -> empty body");
return data;
}
export async function getPlo5HandStrategy(
stack: number,
history: string,
hand: string,
): Promise<Plo5HandStrategy> {
const params = new URLSearchParams({ stack: String(stack), history, hand });
const res = await fetch(`${rangesUrl("plo5/node")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
const data = (await res.json().catch(() => null)) as
| (Plo5HandStrategy & { error?: string })
| null;
notifyPlanRequired(res.status);
if (!res.ok) {
throw new Error(data?.error || `GET plo5 hand -> ${res.status}`);
}
if (!data) throw new Error("GET plo5 hand -> empty body");
return data;
}
/** Per-action hand list for the PLO6 HU Explorer breakdown (top by EV). */
export async function getPlo6HuNodeList(
stack: number,
history: string,
limit = 200,
ranks?: string,
): Promise<Plo5ActionList[]> {
const params = new URLSearchParams({
stack: String(stack),
history,
list: "1",
limit: String(limit),
});
if (ranks) params.set("ranks", ranks);
const res = await fetch(`${rangesUrl("plo6hu/node")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
const data = (await res.json().catch(() => null)) as
| { error?: string; actions?: Plo5ActionList[] }
| null;
notifyPlanRequired(res.status);
if (!res.ok) throw new Error(data?.error || `GET plo6hu list -> ${res.status}`);
return data?.actions ?? [];
}
/** Point-lookup one six-card combo at a PLO6 HU node. */
export async function getPlo6HuHandStrategy(
stack: number,
history: string,
hand: string,
): Promise<Plo5HandStrategy> {
const params = new URLSearchParams({ stack: String(stack), history, hand });
const res = await fetch(`${rangesUrl("plo6hu/node")}?${params.toString()}`, {
headers: { Accept: "application/json" },
});
const data = (await res.json().catch(() => null)) as
| (Plo5HandStrategy & { error?: string })
| null;
notifyPlanRequired(res.status);
if (!res.ok) {
throw new Error(data?.error || `GET plo6hu hand -> ${res.status}`);
}
if (!data) throw new Error("GET plo6hu hand -> empty body");
return data;
}
// ─── History parsing (mirror of mobile parse-history.ts) ───────────────────
// PLO raises are MonkerSolver depth tags, optionally size-disambiguated
// ("Open", "3B", "Open-40075"). NL raises are always "<pct>%", so the two
// namespaces can't collide.
const PLO_RAISE_RE = /^(Open|3B|4B|5B|6B|7B|8B)(?:-(\d+))?$/;
const PLO_RAISE_LABEL: Record<string, string> = {
Open: "Pot",
"3B": "3-Bet",
"4B": "4-Bet",
"5B": "5-Bet",
"6B": "6-Bet",
"7B": "7-Bet",
"8B": "8-Bet",
};
const PLO5_RAISE_RE = /^Raise-(\d+(?:\.\d+)?)x$/i;
function isAllInToken(token: string): boolean {
return token === "AI" || token === "AllIn";
}
function isRaiseToken(token: string): boolean {
return token.endsWith("%") || PLO_RAISE_RE.test(token) || PLO5_RAISE_RE.test(token);
}
function displayAction(token: string): string {
if (token === "Fold") return "Fold";
if (token === "Call") return "Call";
if (token === "Check") return "Check";
if (isAllInToken(token)) return "All-in";
const plo5 = token.match(PLO5_RAISE_RE);
if (plo5) return `Raise ${plo5[1]}bb`;
const plo = token.match(PLO_RAISE_RE);
if (plo) return PLO_RAISE_LABEL[plo[1]] ?? token;
return token;
}
function sumCommitted(seats: Record<Position, SeatState>, order: Position[]): number {
let s = 0;
for (const p of order) s += seats[p].committed;
return s;
}
/**
* Walk a preflop history into a table state. `order` selects the dataset's seat
* ring (6-max by default, 9-max for the PLO 9-max bundles).
*/
export function parseHistory(
history: string,
stackBb: number,
order: Position[] = PLAY_ORDER,
anteBb = 0,
/**
* Raise-to in bb per line (`"<history>_<token>"` → bb), from the feed's
* `sizeBb` (see `raiseSizesFor`). A sized raise wins over decoding its
* token and is shown as a GTO Wizard pot percentage. Only the ICM sets pass it.
*/
sizes?: Record<string, number>,
/** Per-seat stacks behind when they differ (ICM tables); else every seat has `stackBb`. */
seatStacks?: Partial<Record<Position, number>>,
): ParsedTable {
const stackOf = (p: Position) => seatStacks?.[p] ?? stackBb;
const seats: Record<Position, SeatState> = Object.create(null);
for (const p of order) {
seats[p] = {
position: p,
action: null,
committed: 0,
remaining: stackOf(p),
folded: false,
isHero: false,
isDealer: p === "BTN",
};
}
if (seats.SB) seats.SB.committed = 0.5;
else if (seats.BTN && !seats.SB) seats.BTN.committed = 0.5;
if (seats.BB) seats.BB.committed = 1;
const tokens = history.split("_");
let prevIdx = -1;
let toCall = 1;
for (let i = 0; i + 1 < tokens.length; i += 2) {
const pos = tokens[i] as Position;
const action = tokens[i + 1];
const posIdx = order.indexOf(pos);
if (posIdx === -1) continue;
if (prevIdx >= 0) {
let cur = (prevIdx + 1) % order.length;
while (cur !== posIdx) {
const s = seats[order[cur]];
if (!s.folded && s.action === null) {
s.folded = true;
s.action = "Fold";
}
cur = (cur + 1) % order.length;
}
}
seats[pos].action = displayAction(action);
const sized = sizes?.[`${tokens.slice(0, i + 1).join("_")}_${action}`];
if (sized !== undefined && action !== "Fold" && action !== "Call" && action !== "Limp") {
// The feed's raise-to: GTO Wizard's percent is the chips beyond the
// call over the pot after the call.
const raiseTo = Math.min(stackOf(pos), sized);
const callExtra = Math.max(0, toCall - seats[pos].committed);
const potAfterCall = sumCommitted(seats, order) + anteBb + callExtra;
if (isAllInToken(action) || raiseTo >= stackOf(pos)) {
seats[pos].action = "All-in";
} else if (potAfterCall > 0) {
seats[pos].action = `Raise ${Math.round(((raiseTo - toCall) / potAfterCall) * 100)}%`;
}
seats[pos].committed = raiseTo;
toCall = Math.max(toCall, raiseTo);
} else if (action === "Fold") {
seats[pos].folded = true;
} else if (action === "Call" || action === "Limp" || action === "Check") {
seats[pos].committed = toCall;
} else if (isAllInToken(action)) {
seats[pos].committed = stackOf(pos);
toCall = Math.max(toCall, stackOf(pos));
} else if (action.endsWith("%")) {
const potBefore = sumCommitted(seats, order);
const raiseTo = toCall + (parseFloat(action) / 100) * potBefore;
seats[pos].committed = raiseTo;
toCall = raiseTo;
} else if (PLO_RAISE_RE.test(action)) {
// Every PLO raise in these packs is pot-sized (capped by the stack):
// raise-to = call amount + pot after the call.
const potBefore = sumCommitted(seats, order);
const raiseTo = Math.min(stackBb, toCall + (potBefore + (toCall - seats[pos].committed)));
seats[pos].committed = raiseTo;
toCall = raiseTo;
} else {
const plo5 = action.match(PLO5_RAISE_RE);
if (plo5) {
// Hydra "Raise-4.7x" is raise-to in big blinds.
const raiseTo = Math.min(stackBb, parseFloat(plo5[1]));
seats[pos].committed = raiseTo;
toCall = raiseTo;
}
}
prevIdx = posIdx;
}
const rawHero = (tokens[tokens.length - 1] || order[0]) as Position;
const hero = (order.includes(rawHero) ? rawHero : order[0]) as Position;
const heroIdx = order.indexOf(hero);
if (seats[hero]) seats[hero].isHero = true;
if (prevIdx >= 0 && heroIdx !== -1) {
let cur = (prevIdx + 1) % order.length;
while (cur !== heroIdx) {
const s = seats[order[cur]];
if (!s.folded && s.action === null) {
s.folded = true;
s.action = "Fold";
}
cur = (cur + 1) % order.length;
}
}
for (const p of order) {
seats[p].remaining = Math.max(0, stackOf(p) - seats[p].committed);
}
return { seats, pot: sumCommitted(seats, order) + anteBb, hero };
}
/**
* The last seat to raise or jam preflop — the aggressor who takes the betting
* lead into the flop. `null` in an unraised pot (nobody has the lead). The
* history may end with a bare actor position (no action yet); that trailing
* token is ignored, so pass `${history}_${action}` to include a just-taken
* action that isn't in the history string yet.
*/
export function lastPreflopAggressor(
history: string,
order: Position[] = PLAY_ORDER,
): Position | null {
const tokens = history.split("_");
let aggressor: Position | null = null;
for (let i = 0; i + 1 < tokens.length; i += 2) {
const pos = tokens[i] as Position;
const action = tokens[i + 1];
if (order.indexOf(pos) === -1) continue;
if (isAllInToken(action) || isRaiseToken(action)) aggressor = pos;
}
return aggressor;
}
/** The seat that acts after `action` is taken; null if the line terminates. */
export function nextActorAfter(
history: string,
action: string,
stackBb: number,
order: Position[] = PLAY_ORDER,
): Position | null {
const { seats } = parseHistory(history, stackBb, order);
const tokens = history.split("_");
const actor = tokens[tokens.length - 1] as Position;
const actorIdx = order.indexOf(actor);
if (actorIdx === -1) return null;
const liveAfter = new Set<Position>();
for (const p of order) if (!seats[p].folded) liveAfter.add(p);
if (action === "Fold") liveAfter.delete(actor);
for (let i = 1; i <= order.length; i++) {
const cand = order[(actorIdx + i) % order.length];
if (liveAfter.has(cand)) return cand;
}
return null;
}
// ─── Heads-up scenario resolution (mirror of mobile scenario.ts) ───────────
/** Assign OOP/IP by postflop order — the earlier-acting seat is OOP. */
export function assignOopIp(a: Position, b: Position): { oop: Position; ip: Position } {
const ia = POSTFLOP_ORDER.indexOf(a);
const ib = POSTFLOP_ORDER.indexOf(b);
return ia <= ib ? { oop: a, ip: b } : { oop: b, ip: a };
}
/** Keep only known 169-grid classes, clamped to [0, 1] (drops zero/stray keys). */
export function clampWeights(weights: RangeWeights): RangeWeights {
const next: RangeWeights = {};
for (const hand of ALL_HANDS) {
const w = weights[hand];
if (w && w > 0) next[hand] = Math.min(w, 1);
}
return next;
}
/** The highest-committed non-folded seat other than `actor` (blinds count). */
function mostRecentRaiser(
seats: Record<Position, SeatState>,
actor: Position,
): { position: Position; committed: number } | null {
let best: { position: Position; committed: number } | null = null;
for (const p of PLAY_ORDER) {
if (p === actor) continue;
const s = seats[p];
if (s.folded) continue;
if (!best || s.committed > best.committed) best = { position: p, committed: s.committed };
}
return best;
}
export type ResolveResult =
| { kind: "walk"; nextHistory: string }
| { kind: "headsup"; survivors: [Position, Position]; oop: Position; ip: Position }
| { kind: "terminal" };
/**
* Given the current history (ending in the actor) and the action they took,
* return the next state of the heads-up walk. See the mobile module for the
* precise fold/call/re-raise routing rules.
*/
export function resolveAfterAction(
history: string,
action: string,
actionKind: string,
stack: number,
): ResolveResult {
const { seats } = parseHistory(history, stack);
const tokens = history.split("_");
const actor = tokens[tokens.length - 1] as Position;
const agg = mostRecentRaiser(seats, actor);
const facingRaise = !!agg && agg.committed > 1;
if (actionKind === "fold") {
let live = 0;
for (const p of PLAY_ORDER) if (!seats[p].folded && p !== actor) live++;
if (live <= 1) return { kind: "terminal" };
const next = nextActorAfter(history, action, stack);
if (!next) return { kind: "terminal" };
return { kind: "walk", nextHistory: `${history}_${action}_${next}` };
}
if (actionKind === "call") {
if (facingRaise && agg) {
const { oop, ip } = assignOopIp(agg.position, actor);
return { kind: "headsup", survivors: [agg.position, actor], oop, ip };
}
const next = nextActorAfter(history, action, stack);
if (!next) return { kind: "terminal" };
return { kind: "walk", nextHistory: `${history}_${action}_${next}` };
}
// raise or allin
if (facingRaise && agg) {
return {
kind: "walk",
nextHistory: buildReturnHistory(history, action, seats, actor, agg.position),
};
}
const next = nextActorAfter(history, action, stack);
if (!next) return { kind: "terminal" };
return { kind: "walk", nextHistory: `${history}_${action}_${next}` };
}
/** After a re-raise, route action back to `responder`, folding seats in between. */
function buildReturnHistory(
history: string,
action: string,
seats: Record<Position, SeatState>,
actor: Position,
responder: Position,
): string {
const parts = [history, action];
const actorIdx = PLAY_ORDER.indexOf(actor);
for (let i = 1; i <= PLAY_ORDER.length; i++) {
const seat = PLAY_ORDER[(actorIdx + i) % PLAY_ORDER.length];
if (seat === responder) break;
if (!seats[seat].folded) parts.push(seat, "Fold");
}
parts.push(responder);
return parts.join("_");
}
// ─── Display helpers ───────────────────────────────────────────────────────
const KIND_ORDER: Record<string, number> = { fold: 0, call: 1, raise: 2, allin: 3, other: 4 };
export function sortActionsForDisplay(actions: NodeAction[]): NodeAction[] {
return [...actions].sort((a, b) => {
const ka = KIND_ORDER[a.kind] ?? 99;
const kb = KIND_ORDER[b.kind] ?? 99;
if (ka !== kb) return ka - kb;
return (a.sizePct ?? a.sizeBb ?? 0) - (b.sizePct ?? b.sizeBb ?? 0);
});
}
/** Where the actor stands, for labelling a sized raise as a pot percentage. */
export interface RaiseContext {
/** Pot before the actor acts, antes included. */
potBb: number;
/** The amount to call to (the largest commitment so far). */
toCallBb: number;
/** What the actor has in already. */
committedBb: number;
/** The actor's stack, all in (committed + behind). */
stackBb: number;
}
/**
* GTO Wizard's label for a raise the feed sized (`sizeBb`): the chips beyond
* the call over the pot after the call ("Raise 29%"); a raise to the whole
* stack is "All-in <stack>". Null when the action isn't a sized raise.
*/
export function sizedRaiseLabel(action: NodeAction, ctx: RaiseContext): string | null {
if (action.kind !== "raise" && action.kind !== "allin") return null;
if (action.sizeBb == null || action.sizeBb <= 0) return null;
const to = Math.min(action.sizeBb, ctx.stackBb);
if (action.kind === "allin" || action.action === "AI" || to >= ctx.stackBb - 1e-6) {
return `All-in ${formatBb(to)}`;
}
const potAfterCall = ctx.potBb + Math.max(0, ctx.toCallBb - ctx.committedBb);
if (potAfterCall <= 0) return null;
return `Raise ${Math.round(((to - ctx.toCallBb) / potAfterCall) * 100)}%`;
}
/** The actor's `RaiseContext` from a parsed walk. */
export function raiseContextAt(table: ParsedTable): RaiseContext {
const seat = table.seats[table.hero];
let toCall = 0;
for (const p of Object.keys(table.seats) as Position[]) {
toCall = Math.max(toCall, table.seats[p].committed);
}
return {
potBb: table.pot,
toCallBb: toCall,
committedBb: seat?.committed ?? 0,
stackBb: (seat?.committed ?? 0) + (seat?.remaining ?? 0),
};
}
export function labelForAction(action: NodeAction, stack: number): string {
if (action.kind === "fold") return "Fold";
if (action.action === "Limp") return "Limp";
if (action.action === "Check") return "Check";
if (action.kind === "call") return "Call";
if (action.kind === "allin" || action.action === "AI") return `All-in ${stack}`;
if (action.action === "Open") return "Open";
const plo5 = action.action.match(PLO5_RAISE_RE);
if (plo5) return `Raise ${plo5[1]}bb`;
if (action.kind === "raise") return `Raise ${action.action}`;
return action.action;
}
/**
* `labelForAction` for the MonkerSolver PLO packs: raises read as a percentage
* of the pot, GTO Wizard style ("Open" and "3B" are pot raises, "Raise 100%";
* "Open-40075" is "Raise 75%"). Not for NL, whose "Open" token isn't pot-sized.
*/
export function ploLabelForAction(action: NodeAction, stack: number): string {
if (action.kind === "raise") {
const pct = ploRaisePotPct(action.action);
if (pct !== null) return `Raise ${pct}%`;
}
return labelForAction(action, stack);
}
export function formatBb(v: number): string {
if (v < 100) return v.toFixed(v % 1 === 0 ? 0 : 1);
return Math.round(v).toString();
}
lib/solver/range-model.ts
// Range model shared by the solver's scenario selector and the solve call.
//
// A range is a 169-class map (hand → weight in [0, 1]) — the same shape the NL
// ranges API returns (NodeAction.weights). At solve time we serialize it to the
// solver-engine grammar (see solver-engine/src/range.rs), which parses `AA`,
// `AKs`, `AKo`, and `hand:weight` tokens, plus `random` for a full range.
import { comboCount } from "@/lib/nl-ranges/range";
export type RangeWeights = Record<string, number>;
export type RangePlayer = "oop" | "ip";
const RANKS = "AKQJT98765432";
/**
* Every 169 hand-class in grid order: suited upper-right, offsuit lower-left,
* pairs on the diagonal ("AA", "AKs", …, "32o"). Higher rank is written first.
*/
export const ALL_HANDS: string[] = (() => {
const hands: string[] = [];
for (let r = 0; r < 13; r++) {
for (let c = 0; c < 13; c++) {
const hi = RANKS[Math.min(r, c)];
const lo = RANKS[Math.max(r, c)];
if (r === c) hands.push(`${RANKS[r]}${RANKS[r]}`);
else if (r < c) hands.push(`${hi}${lo}s`);
else hands.push(`${hi}${lo}o`);
}
}
return hands;
})();
/** Concrete combos a class represents, ignoring card removal (pair 6, suited 4, offsuit 12). */
export function comboCountOf(hand: string): number {
return comboCount(hand);
}
/** Weighted concrete-combo count (Σ weight × comboCount). */
export function totalCombos(weights: RangeWeights): number {
let total = 0;
for (const hand of ALL_HANDS) {
const w = weights[hand] ?? 0;
if (w > 0) total += w * comboCountOf(hand);
}
return total;
}
/** A full range — every class at weight 1 (equivalent to the engine's `random`). */
export function fullRange(): RangeWeights {
const weights: RangeWeights = {};
for (const hand of ALL_HANDS) weights[hand] = 1;
return weights;
}
export function isEmptyRange(weights: RangeWeights): boolean {
return ALL_HANDS.every((hand) => (weights[hand] ?? 0) <= 0);
}
export function isFullRange(weights: RangeWeights): boolean {
return ALL_HANDS.every((hand) => (weights[hand] ?? 0) >= 0.999);
}
/**
* Serialize to the solver-engine range grammar. A full range collapses to
* `random`; otherwise we emit `hand` for full-weight classes and `hand:weight`
* for partial ones, comma-joined. Zero-weight classes are omitted.
*/
export function weightsToEngineString(weights: RangeWeights): string {
if (isFullRange(weights)) return "random";
const parts: string[] = [];
for (const hand of ALL_HANDS) {
const w = weights[hand] ?? 0;
if (w <= 0) continue;
parts.push(w >= 0.999 ? hand : `${hand}:${Number(w.toFixed(3))}`);
}
return parts.join(",");
}
lib/solver/types.ts
// Solver wire types — mirror the `solve` engine's JSON schema (solver-engine
// `src/api.rs`) and the `/api/solver/*` proxy responses. Kept in sync by hand
// with the Rust `Config`/`Output` structs.
/** Game variant. NLHE uses the 169-class grid; PLO uses 4-card combos. */
export type SolverVariant = "nlhe" | "plo";
export interface SolverConfig {
/** Game variant. Omitted = "nlhe" (the engine default). */
variant?: SolverVariant;
/** Board cards, e.g. "Qs Jh 2h" (3/4/5 cards → flop/turn/river). */
board: string;
start_street?: "flop" | "turn" | "river";
/** Dead money in the middle at the start. */
pot: number;
/** Chips behind each player. */
effective_stack: number;
/** Bet/raise sizes as pot fractions, e.g. [0.5, 1]. */
bet_sizes: number[];
/** Always offer a shove. */
add_allin: boolean;
/** Max bets+raises per street. */
max_aggressions: number;
/** River-only bet sizes (pot fractions) — a coarser river action abstraction
* (#220) that keeps flop trees solvable. Empty/omitted = use `bet_sizes`. */
river_bet_sizes?: number[];
/** River-only aggression cap. Omitted = `max_aggressions` on the river too. */
river_max_aggressions?: number;
/** GTO-Wizard-style per-street, per-player tree overrides. Unset fields fall
* back to the flat fields above; `[]` is meaningful (no bets/raises for
* that player on that street). HU postflop only. */
sizing?: TreeSizingConfig;
/** Betting limit: "nolimit" (default) or "pot" (required for PLO). */
limit?: "nolimit" | "pot";
/** OOP (player 0) range; "random" = full. */
oop_range: string;
/** IP (player 1) range. */
ip_range: string;
/** Max DCFR iterations. */
iterations: number;
/** Optional early stop: exploitability as a percent of the pot. */
target_exploitability?: number;
/** Optional early stop: end once a progress chunk improves exploitability
* by less than this relative fraction (engine convergence plateau, #243). */
convergence_plateau?: number;
/** CFR variant: "dcfr" (engine default) or "pcfr+" (predictive CFR+ —
* ~1.9× fewer iterations to a given exploitability, #253). */
cfr_variant?: "dcfr" | "pcfr+";
/** Keep this job's accumulator snapshot on the worker so a follow-up solve
* can warm-start from it (#262). Worker holds the last few, LRU. */
keep_snapshot?: boolean;
/** Warm-start from a previous job's snapshot (same tree geometry + ranges —
* the engine fingerprint-rejects any mismatch). Job id, never a path. */
warm_start_from?: string;
/** Iterations between progress ticks (0 = none). */
log_interval: number;
/** Also return per-combo EV (expected chips) at the root. */
dump_ev?: boolean;
/** With `dump_nodes`, also return each dumped node's per-action EV, for that
* node's own acting player. Roughly doubles the numeric payload of a
* dump, so it is opt-in per solve rather than on everywhere. */
dump_action_evs?: boolean;
/** Walk and return every action node's strategy (the full betting tree). */
dump_nodes?: boolean;
/** When dumping nodes, stop the walk after this many chance deals past the
* start street (0 = start-street decisions only). Caps the dumped tree size. */
dump_max_deals?: number;
/** Node locks (#268): each listed action node plays its given strategy
* verbatim while the rest of the tree re-equilibrates against it. Locked
* re-solves must ALWAYS pair with `warm_start_from` (the unlocked base
* job): a lock that zeroes an action leaves its subtree with zero
* counterfactual reach, so a COLD locked solve can never train the
* response there and reads silently wrong (PR #269). */
locked_nodes?: LockedNode[];
/** CFR-D re-solving gadget (#233). Present = this solve is a *safe* subgame
* re-solve: the opponent's root behavior becomes the augmented game (per
* combo, Terminate and collect the carried CFV, or Follow into the
* subgame), so the answer stays consistent with the parent equilibrium
* instead of assuming the opponent always enters. NLHE only. The engine
* rejects it together with `cfr_variant: "pcfr+"` (the gadget stays DCFR)
* and with snapshot warm starts (gadget state lives outside the
* accumulators). */
resolve?: ResolveConfig;
/** Bootstrap carry (#233): on a plain (non-gadget) solve, also return
* `SolverResult.resolve` holding the opponent CFV promises for the given
* resolver (0 = OOP, 1 = IP) — the seed for the first re-solve below this
* node. Ignored by the engine when `resolve` is set. */
emit_carry_for?: 0 | 1;
}
/**
* CFR-D gadget input (#233), mirroring the engine's `ResolveConfig`.
*
* `opponent_cfvs` are the promises produced by the parent solve — one entry per
* opponent combo, in chips. They come from `SolverResult.resolve.carry[i]` of
* the parent, where `i` indexes the resolver's root action that was taken.
* Never hand-authored: a wrong promise silently biases the whole subgame.
*/
export interface ResolveConfig {
/** 0 = re-solve for OOP (IP is the constrained opponent), 1 = the reverse. */
resolver: 0 | 1;
/** `[combo, cfv]` pairs — the opponent's counterfactual value promises. */
opponent_cfvs: [string, number][];
}
/** CFR-D gadget output (#233), mirroring the engine's `ResolveOutput`. */
export interface ResolveOutput {
/** Per-combo average Follow frequency — the opponent's reconstructed entry
* probability. Multiply by their base range for the range this re-solve
* believes they actually bring in. */
avg_follow: [string, number][];
/** Per resolver root action (same order as `root.actions`): the opponent's
* per-combo CFVs, i.e. the promises to carry into the next re-solve after
* taking that action. Empty when the root isn't the resolver's decision. */
carry: [string, number][][];
}
/** One street's sizing overrides — mirror of the engine's `StreetSizingConfig`
* (api.rs). All pot fractions. */
export interface StreetSizingConfig {
oop_bet_sizes?: number[];
ip_bet_sizes?: number[];
/** Raise (2nd+ aggression) sizes. Omitted = mirror the player's street bet
* sizes when set, else the legacy raise chain. */
oop_raise_sizes?: number[];
ip_raise_sizes?: number[];
/** Offer a shove on this street. Omitted = global `add_allin`. */
oop_allin?: boolean;
ip_allin?: boolean;
/** Street aggression cap. Omitted = the legacy cap chain. */
max_aggressions?: number;
}
/** One node-specific override (GTOW deep tree editing) — mirror of the
* engine's `NodeSizingConfig`. `path` uses the `dump_nodes` encoding
* ("Check", "Bet 4", "Call 4", amounts 1-decimal; chance steps "deal" =
* every runout card). The engine rejects a path that matches no node. */
export interface NodeSizingConfig {
path: string[];
/** Pot-fraction sizes for this node's bets/raises; `[]` = none. */
sizes?: number[];
allin?: boolean;
}
/** Per-street sizing overrides — mirror of the engine's `SizingConfig`. */
export interface TreeSizingConfig {
flop?: StreetSizingConfig;
turn?: StreetSizingConfig;
river?: StreetSizingConfig;
/** Node-specific overrides; win over the street rules. */
nodes?: NodeSizingConfig[];
}
/**
* One locked node (#268), mirroring the engine's `LockedNode` (api.rs).
* Exactly one of `hands` / `all_hands` must be present.
*/
export interface LockedNode {
/** Action path from the root in the `dump_nodes` encoding — "Check",
* "Bet 3.2" (amounts rounded to 1 decimal), "deal:Td"; `[]` = the root. */
path: string[];
/** Per-combo lock: combo string ("AhKs") → one frequency per action,
* parallel to the node's action list (dump order). Unlisted live combos
* lock to uniform unless `default: "reject"`. */
hands?: Record<string, number[]>;
/** Aggregate lock: one frequency vector applied to every combo of the
* acting player's range. Mutually exclusive with `hands`. */
all_hands?: number[];
/** What live combos not listed in `hands` play: "uniform" (default) or
* "reject" (error unless every live combo is listed). */
default?: "uniform" | "reject";
}
/** A reference to a stored PLO preflop range, resolved server-side. */
export interface PloRangeRef {
stack: number;
/** Range spot path ending in an action, e.g. "UTG_Fold_…_BTN_Open". */
spot: string;
}
/**
* The body POSTed to `/api/solver/jobs`. Extends the engine config with optional
* PLO range references: when present (PLO only), the server resolves them to full
* ranges and overrides `oop_range` / `ip_range`, so huge ranges never ship to the
* browser. The ref fields are stripped before the config reaches the worker.
*/
export interface SolveRequest extends SolverConfig {
oop_range_ref?: PloRangeRef;
ip_range_ref?: PloRangeRef;
/**
* "AI solve": ask the server for a depth-limited flop solve that terminates
* at the turn boundary with the value net (GTO-Wizard-AI-style — fast but
* approximate). Translated server-side to `depth_limited` + the deployment's
* net path; the raw engine fields are never client-settable.
*/
aiSolve?: boolean;
/**
* Skip the shared solve cache and run this on the worker even if a stored
* result would have answered it. Needed when the *job* matters and not just
* the strategy: a locked re-solve warm-starts from the base job's worker
* snapshot (#269), which a cached answer doesn't have. Proxy-level — stripped
* before the config reaches the worker.
*/
noCache?: boolean;
}
/** One streamed progress tick from a running solve. */
export interface SolverProgress {
iter: number;
chips: number;
percent: number;
elapsed_seconds: number;
}
export type SolverActionLabel = "Fold" | "Check" | "Call" | "Bet" | "Raise" | "AllIn";
export interface SolverActionInfo {
label: SolverActionLabel;
/** Chips added by taking this action. */
add: number;
}
export interface SolverHandStrategy {
/** Combo string: 4 chars for NLHE ("AsAh"), 8 chars for PLO ("AsAhKsKd"). */
combo: string;
/** Frequency per action, parallel to `root.actions`. */
freqs: number[];
/** Per-combo EV in chips (present only when the solve set `dump_ev`). */
ev?: number;
/** Chips this combo gives up by taking each action instead of the best action
* the solved profile actually plays, parallel to `freqs` and never negative
* (present only when the solve set `dump_action_evs`). The best played action
* is exactly 0. Already measured from the acting player's own seat — no sign
* flip on the consumer side.
*
* A loss rather than an absolute EV because it is what a trainer needs and it
* is the smaller of the two on the wire (measured on a converged flop pack:
* 15.4MB vs 16.4MB gzipped per board). */
ev_loss?: number[];
}
/**
* One action node from the engine's `dump_nodes` walk (see `api.rs`). The
* `path` is the action labels from the root to this node, e.g. ["Bet 5.6",
* "Call"]; runout deals appear as "deal:Td" segments.
*/
export interface SolverNode {
path: string[];
player: 0 | 1 | 2;
/** Total pot at this node before the player acts (chips = bb here). */
pot: number;
actions: SolverActionInfo[];
hands: SolverHandStrategy[];
/** True when this node was locked in the solve (#268) — `hands` is the
* locked strategy verbatim, not a CFR average. Serde-skipped when false. */
locked?: boolean;
}
export interface SolverResult {
exploitability: { chips: number; percent: number };
iterations_run: number;
elapsed_seconds: number;
tree: {
action_nodes: number;
chance_nodes: number;
terminal_nodes: number;
strategy_floats: number;
};
root: {
player: 0 | 1 | 2;
actions: SolverActionInfo[];
hands: SolverHandStrategy[];
};
/** Every action node's strategy — present only when the solve set `dump_nodes`. */
nodes?: SolverNode[];
/** CFR-D output (#233) — present when the solve set `emit_carry_for` (the
* bootstrap promises) or ran the gadget via `resolve`. */
resolve?: ResolveOutput;
}
lib/trainer/auth.ts
"use client";
/**
* Clerk session-token provider for the trainer's API calls.
*
* On pokerstudy.ai, `/api/trainer/*` is deliberately excluded from the Clerk
* middleware matcher (see proxy.ts): it is the CORS-open bridge the mobile app
* talks to, and those handlers verify a Bearer JWT themselves. `auth()`
* therefore cannot read the session cookie on those routes — so the web trainer
* authenticates the same way mobile does, with a Bearer token. pokerdata.io
* (which installs this file from the registry with the shared Explorer) sends
* the same token to its own same-origin routes. `<TrainerApp/>` registers the
* getter from Clerk's `useAuth()` before mounting the drill loops.
*/
type TokenGetter = (options?: { skipCache?: boolean }) => Promise<string | null>;
let getToken: TokenGetter | null = null;
/**
* First `getToken()` call, kicked off the moment a provider registers. Clerk
* answers `null` — not a promise that waits — while it is still minting the
* session's first token, so without this warm-up the opening deal of a session
* goes out unauthenticated and eats a 401 + retry.
*/
let primer: Promise<string | null> | null = null;
export function setTrainerTokenProvider(fn: TokenGetter | null): void {
getToken = fn;
if (!fn) {
primer = null;
return;
}
// Registration re-runs on every render of the host; only warm once.
primer ??= fn().catch(() => null);
}
/**
* The current session token, or null when signed out / not yet registered.
* `skipCache` forces Clerk to mint a fresh one, which is what a 401 retry wants.
*/
export async function trainerToken(options?: { skipCache?: boolean }): Promise<string | null> {
if (!getToken) return null;
try {
// Let the warm-up settle first: it means Clerk has a token to hand back
// rather than the `null` it returns mid-mint.
if (primer) await primer;
const token = await getToken(options);
if (token) return token;
// Still nothing (a session restore that outran the warm-up) — one short
// wait beats an unauthenticated request, which the server answers with a
// 401 the user sees as a failed deal.
await new Promise((resolve) => setTimeout(resolve, 250));
return await getToken(options);
} catch {
return null;
}
}
lib/trainer/hand.ts
import type { HandClass } from '@/lib/trainer/types';
export const RANKS = 'AKQJT98765432';
export const SUITS = ['c', 'd', 'h', 's'] as const;
export type Suit = (typeof SUITS)[number];
export type Rank = (typeof RANKS)[number];
export type Card = `${Rank}${Suit}`;
export function rankIndex(r: Rank): number {
return RANKS.indexOf(r);
}
export function cardsToClass(c1: Card, c2: Card): HandClass {
const r1 = c1[0] as Rank;
const r2 = c2[0] as Rank;
const s1 = c1[1];
const s2 = c2[1];
if (r1 === r2) return `${r1}${r2}`;
const [hi, lo] = rankIndex(r1) < rankIndex(r2) ? [r1, r2] : [r2, r1];
return `${hi}${lo}${s1 === s2 ? 's' : 'o'}`;
}
export function dealHand(rng: () => number = Math.random): [Card, Card] {
const deck: Card[] = [];
for (const r of RANKS) for (const s of SUITS) deck.push(`${r}${s}` as Card);
const i = Math.floor(rng() * deck.length);
const first = deck[i];
deck.splice(i, 1);
const j = Math.floor(rng() * deck.length);
const second = deck[j];
return [first, second];
}
export function cardSuitColor(suit: Suit): 'red' | 'black' {
return suit === 'h' || suit === 'd' ? 'red' : 'black';
}
/**
* Four-color deck: a distinct, vivid color per suit so suits read at a glance
* (used as a solid card-tile background with white text). Spades use a slate
* rather than near-black so the tile stays visible on the dark app background.
*/
export const SUIT_COLOR_4: Record<Suit, string> = {
s: '#39414f', // spades — slate
h: '#FF3366', // hearts — red
d: '#20A4F3', // diamonds — blue
c: '#1f9d57', // clubs — green
};
// Each glyph carries the text-presentation variation selector (U+FE0E) so
// Android renders it as monochrome text that respects our white `color` style,
// instead of substituting a fixed-color emoji glyph (which ignored the color and
// showed up dark). No-op on iOS, where these already render as text.
export function suitGlyph(suit: Suit): string {
switch (suit) {
case 's':
return '♠︎';
case 'h':
return '♥︎';
case 'd':
return '♦︎';
case 'c':
return '♣︎';
}
}
lib/trainer/plo-hand.ts
/**
* PLO (4-card) hand engine for the trainer.
*
* MonkerSolver names each starting hand with suit-grouping notation over the
* 16,432 suit-isomorphism classes — parentheses wrap cards sharing a suit, e.g.
*
* AAAA four aces (each a different suit)
* (2A)AA A-A-A-2 with the 2 suited to one ace
* (KA)(KA) AAKK double-suited
* AKQJ four broadways, all different suits (rainbow)
*
* We don't reproduce MonkerSolver's exact output ordering. Instead we parse the
* 16,432 known strings into an order-independent *signature* (ranks grouped by
* suit) and build a signature → string lookup. A dealt 4-card hand computes the
* same signature (group its cards by suit) and looks up the canonical string —
* validated as an exact bijection + deal-side roundtrip against the live data.
*/
import { PLO_HAND_STRINGS } from './plo-hands';
import { RANKS, SUITS, type Card, type Rank, type Suit, rankIndex } from './hand';
export type HandCategory =
| 'Unpaired Double Suited'
| 'Unpaired Single Suited'
| 'Unpaired Rainbow'
| 'One Pair Double Suited'
| 'One Pair Single Suited'
| 'One Pair Rainbow'
| 'Two Pair Double Suited'
| 'Two Pair Single Suited'
| 'Two Pair Rainbow'
| 'Trips Single Suited'
| 'Trips Rainbow'
| 'Quads Rainbow';
/** A group of ranks sharing one suit, sorted ascending by rank. */
type Group = Rank[];
/** Parse a canonical string into suit groups (parens = same-suit group). */
export function parseHandString(s: string): Group[] {
const groups: Group[] = [];
let i = 0;
while (i < s.length) {
if (s[i] === '(') {
const j = s.indexOf(')', i);
const ranks = s.slice(i + 1, j).split('') as Rank[];
groups.push(sortRanks(ranks));
i = j + 1;
} else {
groups.push([s[i] as Rank]);
i += 1;
}
}
return groups;
}
function sortRanks(ranks: Rank[]): Rank[] {
return [...ranks].sort((a, b) => rankIndex(a) - rankIndex(b));
}
/**
* Order-independent signature of a hand's suit partition. Two hands are
* suit-isomorphic iff their signatures match. Groups are sorted by (size desc,
* ranks) so the representation is canonical regardless of suit labelling.
*/
function signature(groups: Group[]): string {
return groups
.map((g) => g.join(''))
.map((g) => ({ g, key: g }))
.sort((a, b) => b.g.length - a.g.length || compareRankStr(a.g, b.g))
.map((x) => x.g)
.join('/');
}
function compareRankStr(a: string, b: string): number {
for (let i = 0; i < Math.min(a.length, b.length); i++) {
const d = rankIndex(a[i] as Rank) - rankIndex(b[i] as Rank);
if (d !== 0) return d;
}
return a.length - b.length;
}
// Built once: signature → canonical MonkerSolver string.
let SIG_TO_STRING: Map<string, string> | null = null;
function sigToString(): Map<string, string> {
if (SIG_TO_STRING) return SIG_TO_STRING;
const map = new Map<string, string>();
for (const s of PLO_HAND_STRINGS) map.set(signature(parseHandString(s)), s);
SIG_TO_STRING = map;
return map;
}
/** Group 4 dealt cards by suit and return the canonical MonkerSolver string. */
export function cardsToPloString(cards: [Card, Card, Card, Card]): string {
const bySuit = new Map<Suit, Rank[]>();
for (const c of cards) {
const r = c[0] as Rank;
const su = c[1] as Suit;
const arr = bySuit.get(su);
if (arr) arr.push(r);
else bySuit.set(su, [r]);
}
const groups = [...bySuit.values()].map(sortRanks);
const sig = signature(groups);
const str = sigToString().get(sig);
if (!str) {
// Should never happen — the 16,432 set is exhaustive. Fall back to a stable
// string so the UI degrades instead of crashing.
return cards.map((c) => c[0]).join('');
}
return str;
}
/** Deal a random 4-card PLO hand and its canonical string. */
export function dealPloHand(rng: () => number = Math.random): {
cards: [Card, Card, Card, Card];
hand: string;
} {
const deck: Card[] = [];
for (const r of RANKS) for (const s of SUITS) deck.push(`${r}${s}` as Card);
const picked: Card[] = [];
for (let k = 0; k < 4; k++) {
const idx = Math.floor(rng() * deck.length);
picked.push(deck[idx]);
deck.splice(idx, 1);
}
const cards = picked as [Card, Card, Card, Card];
return { cards, hand: cardsToPloString(cards) };
}
/** Classify a parsed hand into the viewer's category buckets. */
export function categorizeGroups(groups: Group[]): HandCategory {
const counts = new Map<Rank, number>();
for (const g of groups) for (const r of g) counts.set(r, (counts.get(r) ?? 0) + 1);
const values = [...counts.values()];
const pairs = values.filter((v) => v >= 2).length;
const maxOfRank = Math.max(...values);
let pairing: string;
if (maxOfRank >= 4) pairing = 'Quads';
else if (maxOfRank === 3) pairing = 'Trips';
else if (pairs >= 2) pairing = 'Two Pair';
else if (pairs === 1) pairing = 'One Pair';
else pairing = 'Unpaired';
const suited = groups.filter((g) => g.length >= 2).length;
const suitedness = suited >= 2 ? 'Double Suited' : suited === 1 ? 'Single Suited' : 'Rainbow';
return `${pairing} ${suitedness}` as HandCategory;
}
/** Classify a canonical hand string. */
export function categorizeHand(hand: string): HandCategory {
return categorizeGroups(parseHandString(hand));
}
/**
* Expand a canonical string into 4 concrete display cards, assigning a distinct
* suit per group so the parenthesised cards visibly share a suit. Deterministic
* (for stable rendering); suits are cosmetic since ranges are suit-isomorphic.
*/
export function ploStringToCards(hand: string): Card[] {
const groups = parseHandString(hand);
const cards: Card[] = [];
groups.forEach((g, gi) => {
const suit = SUITS[gi % SUITS.length];
for (const r of g) cards.push(`${r}${suit}` as Card);
});
return cards;
}