From 961f54fd7ef45ff0738778f2f8d9964eec91e2fa Mon Sep 17 00:00:00 2001 From: BAK Date: Mon, 28 Sep 2026 15:01:03 +0200 Subject: [PATCH 1/5] feat(replay): analyse the position on screen in the background ? runs the bounded placement-only analysis on a copy of the entry on screen and shows its badge, choice, explanation, up to four candidates with their bounds and the completed work. Seeking, leaving or pressing ? again cancels the search and drops its result; the analysis outranks the record's details when rows are short and reaches the status line when there is no panel. Nothing is written. --- .github/scripts/test-windows.ps1 | 3 +- internal/app/replay.go | 73 +- internal/app/replay_analysis.go | 436 ++++++++++++ internal/app/replay_analysis_test.go | 977 +++++++++++++++++++++++++++ internal/app/replay_test.go | 4 +- internal/cli/game.go | 4 +- internal/e2e/replay_analysis_test.go | 194 ++++++ 7 files changed, 1677 insertions(+), 14 deletions(-) create mode 100644 internal/app/replay_analysis.go create mode 100644 internal/app/replay_analysis_test.go create mode 100644 internal/e2e/replay_analysis_test.go diff --git a/.github/scripts/test-windows.ps1 b/.github/scripts/test-windows.ps1 index b75da40..4be5baa 100644 --- a/.github/scripts/test-windows.ps1 +++ b/.github/scripts/test-windows.ps1 @@ -73,7 +73,8 @@ $required = @( 'TestAnalyzeInputsDescribeTheSameRecordEntry', 'TestAnalyzeTerminalAndUnsearchedResultsAreExplicit', 'TestAnalyzeRefusalsDoNotWriteState', - 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame' + 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame', + 'TestReplayAnalysisFromTheMenu' ) $missing = @($required | Where-Object { -not $passes.ContainsKey($_) }) $missingStorage = @() diff --git a/internal/app/replay.go b/internal/app/replay.go index bda5cd1..3f4c890 100644 --- a/internal/app/replay.go +++ b/internal/app/replay.go @@ -34,6 +34,11 @@ type ReplayScreen struct { stuck string // jump is the entry-number input, open only while a number is being typed. jump entryJump + // analysis is the engine's reading of the entry on screen, once the player + // has asked for one, and analyser is what reads it: bot.Analyze unless a + // test has put something else in its place. + analysis replayAnalysis + analyser replayAnalyser // winning is the run of pegs that won the game, worked out once when the // screen opens: it cannot change, and it belongs to one position — the last // one, where the chain the record ends in is actually on the board. @@ -196,7 +201,8 @@ var replayKeys = []replayKey{ {ui.ActMoveUp, nil, "five", func(s *ReplayScreen) tea.Cmd { s.seek(s.step() - replayJump); return nil }}, {ui.ActEdgeTop, nil, "ends", func(s *ReplayScreen) tea.Cmd { s.seek(0); return nil }}, {ui.ActEdgeBottom, nil, "ends", func(s *ReplayScreen) tea.Cmd { s.seek(s.entries()); return nil }}, - {ui.ActQuit, []string{"esc"}, "leaves", func(*ReplayScreen) tea.Cmd { return Back() }}, + {ui.ActNone, []string{"?"}, "analyse", func(s *ReplayScreen) tea.Cmd { return s.toggleAnalysis() }}, + {ui.ActQuit, []string{"esc"}, "leaves", func(s *ReplayScreen) tea.Cmd { s.analysis.drop(); return Back() }}, } // replayHints renders the footer's key parts, taking the labels from the keymap @@ -269,6 +275,10 @@ func NewReplayScreen(d Deps, saved gamestore.Saved) (Screen, error) { // Init satisfies tea.Model. func (s *ReplayScreen) Init() tea.Cmd { return nil } +// Depart stops an analysis still running when the program ends with the review +// open: the engine would be working for a screen that is no longer there. +func (s *ReplayScreen) Depart() { s.analysis.drop() } + // Update satisfies tea.Model. func (s *ReplayScreen) Update(msg tea.Msg) (tea.Model, tea.Cmd) { switch m := msg.(type) { @@ -288,6 +298,10 @@ func (s *ReplayScreen) Update(msg tea.Msg) (tea.Model, tea.Cmd) { s.jump.insert(strings.TrimSpace(m.Content)) } } + case replayAnalysisDoneMsg: + s.analysis.finish(m) + case replayAnalysisTickMsg: + return s, s.analysis.tick(m) } return s, nil } @@ -371,6 +385,10 @@ func (s *ReplayScreen) jumpToEntry() { // says so in the panel, rather than leaving a board that is neither where the // player was nor where they asked to be. func (s *ReplayScreen) seek(to int) { + // An analysis belongs to the position it was asked about. Moving through the + // record cancels one still running and puts away one already shown, so that + // neither can be read against a position it was not computed for. + s.analysis.drop() if err := s.cursor.seek(to); err != nil { s.stuck = err.Error() return @@ -414,6 +432,12 @@ func (s *ReplayScreen) View() tea.View { if s.step() == s.entries() { s.board.Highlights = s.winning } + // An analysis marks the holes it refers to, but only on the position it + // read: anywhere else they would be advice about a different board. A + // finished position has nothing to advise, so the chain stays where it is. + if marks := s.analysis.highlights(s.step()); len(marks) > 0 { + s.board.Highlights = marks + } board := s.board.Render(s.current(), st, arr.BoardAvailW, arr.BoardAvailH) panel := s.panel(arr.PanelW, arr.PanelH) status := s.status(arr.Width) @@ -435,25 +459,34 @@ func (s *ReplayScreen) focus() (game.Point, bool) { return game.Point{}, false } -// status is the bottom row: where in the record the player is, then what the -// keys do, dropped from the end when the terminal is too narrow for all of it. +// status is the bottom row: what the player is doing, then where in the record +// they are, then what the keys do, dropped from the end when the terminal is +// too narrow for all of it. // // At the widths that have no room for a panel it is the whole of the interface, -// so the entry input is drawn here as well as there, and what is wrong with a -// number comes before the keys that would fix it. +// so the entry input and the analysis are drawn here as well as there, and what +// is wrong with a number comes before the keys that would fix it. func (s *ReplayScreen) status(width int) string { // These are record entries rather than moves: a draw offer is an entry that // changes nothing on the board, so counting them as moves disagreed with // every other surface's move count. counter := fmt.Sprintf("step %d of %d", s.step(), s.entries()) + parts := make([]string, 0, len(s.hints)+3) if s.jump.open { note := s.jump.note() fieldWidth := max(3, width-ansi.StringWidth(note)-1) - input := note + " " + s.jump.edit.render(shellStyles(s.deps), fieldWidth) - return hintLine(width, input, counter, keyLabel(s.confirm...)+" jump", "esc cancel") + parts = append(parts, note+" "+s.jump.edit.render(shellStyles(s.deps), fieldWidth)) + } + // A part wider than the row is shortened here, with a mark, rather than + // clipped at the edge of the frame: the frame pulls a marked cut back to a + // whole word, and an unmarked one ends wherever the edge fell. + if a := s.analysisStatus(); a != "" { + parts = append(parts, truncateText(a, width)) } - parts := make([]string, 0, len(s.hints)+1) parts = append(parts, counter) + if s.jump.open { + return hintLine(width, append(parts, keyLabel(s.confirm...)+" jump", "esc cancel")...) + } return hintLine(width, append(parts, s.hints...)...) } @@ -462,7 +495,10 @@ func (s *ReplayScreen) status(width int) string { // // The list is promised its share of the rows before the prose is given any. The // panel below a board is four rows at its smallest, and one that spent every row -// on titles and results would leave a review with nothing to review. +// on titles and results would leave a review with nothing to review. An +// analysis the player has asked for is promised its lead next, ahead of the +// record's details: a panel that spent its last rows on those showed nothing +// at all after ?, not even that a search was running. func (s *ReplayScreen) panel(width, height int) []string { if width <= 0 || height <= 0 { return nil @@ -471,10 +507,27 @@ func (s *ReplayScreen) panel(width, height int) []string { // The input goes first because it is what the player is doing. out = append(out, clampLines(s.jump.lines(shellStyles(s.deps), width), height)...) list := min(s.entries()+1, max(1, height/2)) - if room := height - len(out) - list; room > 1 { + // The analysis's lead is set aside with the blank line that closes it. + lead := s.analysisLead(width) + reserve := 0 + if lead > 0 { + reserve = lead + 1 + } + if room := height - len(out) - list - reserve; room > 1 { out = append(out, clampLines(s.describe(width), room-1)...) out = append(out, "") } + if room := height - len(out) - list; room > 0 { + // The closing blank line is given up before any of the lead is: in the + // smallest panel the badge and the state of the search sit directly on + // the list, which beats a badge that says nothing about the search. + if block := s.analysisLines(width, max(room-1, min(room, lead))); len(block) > 0 { + out = append(out, block...) + if len(out) < height-list { + out = append(out, "") + } + } + } return append(out, s.entryList(width, height-len(out))...) } diff --git a/internal/app/replay_analysis.go b/internal/app/replay_analysis.go new file mode 100644 index 0000000..021145c --- /dev/null +++ b/internal/app/replay_analysis.go @@ -0,0 +1,436 @@ +package app + +import ( + "context" + "fmt" + "strings" + "sync/atomic" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/BAKocska/twixtui/internal/bot" + "github.com/BAKocska/twixtui/internal/game" +) + +// replayAnalyser reads one position. The replay screen calls bot.Analyze +// through it; a test puts something in its place that it can hold, release and +// inspect, which is how a cancelled or overtaken search is made to happen on +// cue rather than by timing. +type replayAnalyser func(context.Context, *game.Game, bot.AnalysisOptions) (bot.AnalysisResult, error) + +// replayCandidateRows is how many of the engine's candidates the panel lists. +// The first few are the ones the search spent its effort on; the rest of the +// shortlist is mostly bounded from above and says little a reviewer can use. +const replayCandidateRows = 4 + +// replayAnalysisJob is one analysis the player asked for: the entry it reads, +// when it started, how to stop it, and the last iteration the search finished. +// +// The job is also the analysis's generation. A message names the job it +// answers, and the screen takes it only while that job is the one it is +// waiting on, so a result the player has moved past — or one addressed to a +// replay that has since been closed and opened again — is dropped instead of +// being shown against a position it was not computed for. A counter would do +// the first and not the second: two screens count from the same place. +type replayAnalysisJob struct { + entry int + started time.Time + cancel context.CancelFunc + // latest is written by the search each time an iteration finishes and read + // by Update on a tick. The atomic pointer is the whole of the hand-off: the + // search never touches the screen, and the screen never waits on the + // search. + latest atomic.Pointer[bot.AnalysisProgress] +} + +// tick schedules the next look at the job's progress. The interval is the +// game screen's thinking indicator's, so the two move at the same pace. +func (j *replayAnalysisJob) tick() tea.Cmd { + return tea.Tick(gsSpinnerInterval, func(at time.Time) tea.Msg { + return replayAnalysisTickMsg{job: j, at: at} + }) +} + +// replayAnalysisDoneMsg is the outcome of one analysis. +type replayAnalysisDoneMsg struct { + job *replayAnalysisJob + result bot.AnalysisResult + err error +} + +// replayAnalysisTickMsg advances the running indicator and picks up the last +// iteration the search finished. +type replayAnalysisTickMsg struct { + job *replayAnalysisJob + at time.Time +} + +// replayAnalysis is the engine's reading of one entry of the record, from the +// moment it is asked for until the player moves on. +// +// It is a review action and nothing more. It is asked for with a key, it reads +// a copy of the position on screen, it keeps nothing once the player moves, and +// it writes nothing anywhere: whether the game it reviews was played with +// hints is a fact about that game, not about what its reviewer may look at. +type replayAnalysis struct { + job *replayAnalysisJob + running bool + // canceled records that the player stopped the search with the key that + // started it, so the panel can say so rather than going quiet. + canceled bool + // done means result and err hold what the search answered. + done bool + result bot.AnalysisResult + err error + // marks are the holes the result refers to, the recommended one first. They + // are worked out once, when the result arrives, rather than per frame. + marks []game.Point + + // progress, spinner and elapsed are what the panel shows while the search + // runs. progress is the last finished iteration, nil until one finishes. + progress *bot.AnalysisProgress + spinner int + elapsed time.Duration +} + +// start begins reading pos, the position after entry entries. pos must be a +// copy nothing else touches: the search makes and unmakes moves on it from +// another goroutine, and the cursor's own game is moved by the next seek. +// +// The options are the analysis defaults — the hint's placement-only policy +// under its two-second guard — with an observer added, so what the replay +// shows is what bot.Analyze gives any other caller. +func (a *replayAnalysis) start(run replayAnalyser, pos *game.Game, entry int) tea.Cmd { + a.drop() + if run == nil { + run = bot.Analyze + } + ctx, cancel := context.WithCancel(context.Background()) + job := &replayAnalysisJob{entry: entry, started: time.Now(), cancel: cancel} + *a = replayAnalysis{job: job, running: true} + opts := bot.AnalysisOptions{ + // This runs on the search's goroutine, inside the search. The snapshot + // is the observer's own, so storing it is all that happens here. + OnComplete: func(p bot.AnalysisProgress) { job.latest.Store(&p) }, + } + return tea.Batch( + func() tea.Msg { + res, err := run(ctx, pos, opts) + return replayAnalysisDoneMsg{job: job, result: res, err: err} + }, + job.tick(), + ) +} + +// stop is the analysis key pressed while the search runs: the search is +// cancelled, and whatever it would have answered is not waited for. +func (a *replayAnalysis) stop() { + if a.job != nil { + a.job.cancel() + } + a.running = false + a.canceled = true + a.progress = nil +} + +// drop cancels a search in flight and forgets everything about the analysis, +// which is what moving through the record and leaving the review both do. The +// job goes with it, so a message still on its way finds nothing to answer. +func (a *replayAnalysis) drop() { + if a.job != nil { + a.job.cancel() + } + *a = replayAnalysis{} +} + +// finish takes in a finished search. Anything but the search the screen is +// still waiting on is ignored. +func (a *replayAnalysis) finish(m replayAnalysisDoneMsg) { + if m.job == nil || m.job != a.job || !a.running { + return + } + // The search has returned; cancelling releases what its context holds. + a.job.cancel() + a.running = false + a.progress = nil + a.done = true + a.result, a.err = m.result, m.err + a.marks = nil + if m.err == nil && m.result.Recommended != nil { + move := *m.result.Recommended + a.marks = make([]game.Point, 0, len(m.result.Highlight)+1) + a.marks = append(a.marks, move) + for _, p := range m.result.Highlight { + if p != move { + a.marks = append(a.marks, p) + } + } + } +} + +// tick advances the indicator and reads the last finished iteration off the +// job. A tick for any other job ends its own chain rather than starting a +// second one beside the current search's. +func (a *replayAnalysis) tick(m replayAnalysisTickMsg) tea.Cmd { + if m.job == nil || m.job != a.job || !a.running { + return nil + } + a.spinner++ + a.elapsed = max(m.at.Sub(m.job.started), 0) + if p := m.job.latest.Load(); p != nil { + a.progress = p + } + return m.job.tick() +} + +// on reports whether the analysis belongs to entry. Seeking drops it, so this +// is the second of two locks rather than the only one: a result is never drawn +// against an entry it was not computed for. +func (a *replayAnalysis) on(entry int) bool { return a.job != nil && a.job.entry == entry } + +// shown reports whether a result for entry is on screen. +func (a *replayAnalysis) shown(entry int) bool { return a.on(entry) && a.done && a.err == nil } + +// highlights are the holes to mark on the board at entry: the recommended move +// first, then the holes the engine's explanation names. There are none for any +// other entry, and none for a finished position, which has no move to advise. +func (a *replayAnalysis) highlights(entry int) []game.Point { + if !a.shown(entry) { + return nil + } + return a.marks +} + +// toggleAnalysis is the analysis key. It reads the position on screen, stops a +// reading still running, or puts away one already shown — the last because the +// marks it puts on the board are in the way of looking at the board itself. +// A reading that failed or was stopped is asked for again. +func (s *ReplayScreen) toggleAnalysis() tea.Cmd { + a := &s.analysis + switch { + case a.running: + a.stop() + return nil + case a.shown(s.step()): + a.drop() + return nil + } + return a.start(s.analyser, s.current().Clone(), s.step()) +} + +// analysisLines is the analysis block of the panel, at most rows lines of it, +// and nothing at all when no analysis belongs to the entry on screen. +func (s *ReplayScreen) analysisLines(width, rows int) []string { + if width <= 0 || rows <= 0 || !s.analysis.on(s.step()) { + return nil + } + return clampLines(s.analysis.lines(width), rows) +} + +// analysisLead is how many rows the analysis block is promised in the panel — +// its badge, and where the analysis stands — and 0 when no analysis belongs to +// the entry on screen. The panel sets these rows aside before it gives the +// record's own details any: the details read the same at every entry, and the +// analysis is what the player has just asked for. +func (s *ReplayScreen) analysisLead(width int) int { + if width <= 0 || !s.analysis.on(s.step()) { + return 0 + } + return len(s.analysis.lead(width)) +} + +// analysisStatus is the analysis's part of the status line, and empty when no +// analysis belongs to the entry on screen. A terminal with no room for a panel +// has nowhere else to show it. +func (s *ReplayScreen) analysisStatus() string { + if !s.analysis.on(s.step()) { + return "" + } + return s.analysis.brief() +} + +// indicator is a running search in the fewest words: that it runs, and for +// how long. +func (a *replayAnalysis) indicator() string { + return fmt.Sprintf("analysing %s %s", + gsSpinnerFrames[a.spinner%len(gsSpinnerFrames)], replaySeconds(a.elapsed)) +} + +// brief is the analysis in the few words a status line has room for. It keeps +// the qualification the panel spells out: a hole comes with its policy badge +// and with "not proven", the caveat as an item of its own after the pair, so a +// line cut short gives up the caveat before the badge — the same pair a game's +// status line keeps for a hint. +func (a *replayAnalysis) brief() string { + r := a.result + switch { + case a.running: + return a.indicator() + case a.canceled: + return "analysis canceled" + case a.err != nil: + return "analysis failed" + case r.Result.Over(): + return "game over: no move to advise" + case r.Recommended == nil: + return "engine returned no move" + } + return fmt.Sprintf("%s %s · not proven", *r.Recommended, r.Policy.Label()) +} + +// lead is the beginning of the block: the badge, and one sentence saying where +// the analysis stands — running, stopped, refused, over, or the move it chose. +// Everything after it qualifies or details that sentence, so a panel with rows +// for nothing else still shows this much. +func (a *replayAnalysis) lead(width int) []string { + // The badge is the policy the search runs under. Until a result arrives + // that is the one policy bot.Analyze searches with; after, it is the one + // the result itself states. + policy := bot.PlacementOnlyPolicy() + if a.done && a.err == nil { + policy = a.result.Policy + } + out := []string{replayAnalysisHeader(policy.Label(), width)} + + r := a.result + var state string + switch { + case a.running: + state = a.indicator() + " · ? cancels" + case a.canceled: + state = "canceled; ? starts it again" + case a.err != nil: + // The error is the engine's, but it is text all the same, and the + // panel draws nothing a terminal would act on. + state = "the engine could not analyse this position: " + replayLabel(a.err.Error()) + case r.Result.Over(): + state = "the game is over here, " + describeOutcome(r.Result) + ", so there is no move to advise" + case r.Recommended == nil: + state = "the engine returned no move" + default: + state = fmt.Sprintf("%s is the engine's choice under a bounded search, not a proven best move", *r.Recommended) + } + return append(out, wrapText(state, width)...) +} + +// lines renders the block, most important line first, because a short panel +// keeps the beginning and drops the end: the lead, then what stands behind it. +// +// The engine's own words — its headline and detail, and its account of the +// policy it searched under — are shown as it wrote them. What this adds is what +// the numbers are: which move the search settled on and that it is a choice, +// what each candidate's score is a bound on, and how much work stands behind +// them. A result is never called the best move, because a bounded search under +// a placement-only policy cannot establish one. +func (a *replayAnalysis) lines(width int) []string { + out := make([]string, 0, 16) + out = append(out, a.lead(width)...) + add := func(text string) { out = append(out, truncateText(text, width)) } + wrap := func(text string) { out = append(out, wrapText(text, width)...) } + + r := a.result + switch { + case a.running: + if p := a.progress; p != nil { + wrap(fmt.Sprintf("completed so far: depth %d, %d nodes, %s", + p.Stats.Depth, p.Stats.Nodes, replaySeconds(p.Stats.Elapsed))) + } + return out + case a.canceled, a.err != nil, r.Result.Over(), r.Recommended == nil: + return out + } + + if h := strings.TrimSpace(r.Headline); h != "" { + wrap(h) + } + if d := strings.TrimSpace(r.Detail); d != "" { + wrap(d) + } + if len(r.Candidates) > 0 { + add("candidates, in search units:") + for _, c := range r.Candidates[:min(len(r.Candidates), replayCandidateRows)] { + add(" " + padTo(c.Move.String(), 4) + " " + replayScorePhrase(c)) + } + } + if st := r.Stats; st != nil { + wrap(fmt.Sprintf("completed work: depth %d, %d nodes, %s", + st.Depth, st.Nodes, replaySeconds(st.Elapsed))) + stop := "stopped: " + replayStopPhrase(st.StopReason) + if !replayReproducible(st.StopReason) { + stop += ", so not reproducible" + } + wrap(stop) + if st.Depth == 0 && st.StopReason != "immediate" { + wrap("no iteration finished, so the candidates are the move ordering's and unscored") + } + } + wrap(r.Policy.Summary()) + return out +} + +// replayAnalysisHeader is the block's first line: what it is, and the policy +// badge. On a panel with no room for both the badge is kept, because it is the +// part that qualifies everything under it. +func replayAnalysisHeader(badge string, width int) string { + if full := "analysis · " + badge; ansi.StringWidth(full) <= width { + return full + } + return truncateText(badge, width) +} + +// replayScorePhrase says what a candidate's score is. An unscored candidate +// gets no number: its score is zero because nothing measured it, and a zero on +// screen would read as a measurement. +func replayScorePhrase(c bot.AnalysisCandidate) string { + switch c.Bound { + case bot.BoundExact: + return fmt.Sprintf("%+d exact", c.Score) + case bot.BoundUpper: + return fmt.Sprintf("at most %+d", c.Score) + case bot.BoundLower: + return fmt.Sprintf("at least %+d", c.Score) + case bot.BoundUnscored: + return "unscored" + } + // A bound this screen does not know says nothing it can put a number to. + return replayLabel(string(c.Bound)) +} + +// replayStopPhrase explains why the search stopped, in the words the analyze +// command uses for the same reasons. +func replayStopPhrase(reason string) string { + switch reason { + case "depth": + return "every allowed iteration finished" + case "nodes": + return "the node ceiling was reached" + case "immediate": + return "a winning hole was taken without searching" + case "decided": + return "a forced line inside the selective search, not a proof" + case "time": + return "the search-time guard was reached" + case "canceled": + return "the search was interrupted" + } + return replayLabel(reason) +} + +// replayReproducible reports whether the completed work would be the same on +// another run. A search the clock or an interruption ended is whatever this +// machine had finished by then; one that ended on its own terms is not. +func replayReproducible(reason string) bool { + switch reason { + case "nodes", "depth", "immediate", "decided": + return true + } + return false +} + +// replaySeconds renders a duration to a tenth of a second, which is as finely +// as a reader can use it. +func replaySeconds(d time.Duration) string { + return fmt.Sprintf("%.1fs", d.Seconds()) +} diff --git a/internal/app/replay_analysis_test.go b/internal/app/replay_analysis_test.go new file mode 100644 index 0000000..2bfdd0e --- /dev/null +++ b/internal/app/replay_analysis_test.go @@ -0,0 +1,977 @@ +package app + +import ( + "context" + "errors" + "fmt" + "io/fs" + "maps" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/BAKocska/twixtui/internal/bot" + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" + "github.com/BAKocska/twixtui/internal/ui" +) + +// rpaHarness drives a replay the way Bubble Tea does: keys go in through +// Update, every command that comes back runs on a goroutine of its own, and +// what it produces is fed back in. A batch is taken apart as the runtime takes +// it apart, so the search and its indicator run side by side. +type rpaHarness struct { + t *testing.T + s *ReplayScreen + msgs chan tea.Msg + // answered counts the analysis outcomes delivered to the screen, whatever + // the screen then made of them, so a test can wait for a late one to have + // arrived before asserting that it was ignored. + answered int + // left counts the times the screen asked to be left. + left int +} + +func rpaOpen(t *testing.T, d Deps, sv gamestore.Saved, run replayAnalyser) *rpaHarness { + t.Helper() + s := rpOpen(t, d, sv) + s.analyser = run + h := &rpaHarness{t: t, s: s, msgs: make(chan tea.Msg, 64)} + h.feed(tea.WindowSizeMsg{Width: 120, Height: 40}) + return h +} + +func (h *rpaHarness) dispatch(cmd tea.Cmd) { + if cmd == nil { + return + } + go func() { + msg := cmd() + if batch, ok := msg.(tea.BatchMsg); ok { + for _, c := range batch { + h.dispatch(c) + } + return + } + if msg == nil { + return + } + select { + case h.msgs <- msg: + case <-time.After(5 * time.Second): + } + }() +} + +func (h *rpaHarness) feed(msg tea.Msg) { + h.t.Helper() + switch msg.(type) { + case DoneMsg: + h.left++ + return + case replayAnalysisDoneMsg: + h.answered++ + } + _, cmd := h.s.Update(msg) + h.dispatch(cmd) +} + +func (h *rpaHarness) press(key string) { + h.t.Helper() + msg := tutorialKeyMsg(key) + if got := msg.String(); got != key { + h.t.Fatalf("the test cannot press %q: it builds as %q", key, got) + } + h.feed(msg) +} + +// waitFor delivers what the commands produce until cond holds. +func (h *rpaHarness) waitFor(what string, cond func() bool) { + h.t.Helper() + deadline := time.After(10 * time.Second) + for !cond() { + select { + case msg := <-h.msgs: + h.feed(msg) + case <-deadline: + h.t.Fatalf("timed out waiting for %s at step %d\n%s", what, h.s.step(), h.block()) + } + } +} + +// outcome waits for the analysis outcome the screen's commands produce and +// hands it back undelivered, dropping everything else they produce on the way. +// The program delivers a message to whichever screen is up when it arrives, so +// a test can give a closed screen's answer to the screen that replaced it. +func (h *rpaHarness) outcome() replayAnalysisDoneMsg { + h.t.Helper() + deadline := time.After(10 * time.Second) + for { + select { + case msg := <-h.msgs: + if m, ok := msg.(replayAnalysisDoneMsg); ok { + return m + } + case <-deadline: + h.t.Fatal("the search never answered") + } + } +} + +// block is the analysis block as a wide panel draws it, so that nothing in it +// is wrapped and a line can be read as a whole. +func (h *rpaHarness) block() string { + return strings.Join(h.s.analysisLines(200, 200), "\n") +} + +// frame draws the screen, which is also what puts the marks on the board. +func (h *rpaHarness) frame() string { return h.s.View().Content } + +// rpaCall is one request the stand-in engine received. +type rpaCall struct { + ctx context.Context + pos *game.Game + digest string + // progress is handed to the analysis's observer from the search's own + // goroutine, which is where the engine calls it from. + progress chan bot.AnalysisProgress + answer chan rpaAnswer +} + +type rpaAnswer struct { + result bot.AnalysisResult + err error +} + +// rpaEngine stands in for bot.Analyze. Each request is announced and then held +// until the test answers it, so whether the screen has moved on by the time a +// search finishes is the test's decision rather than the scheduler's. +type rpaEngine struct{ calls chan *rpaCall } + +func newRPAEngine() *rpaEngine { return &rpaEngine{calls: make(chan *rpaCall, 8)} } + +func (e *rpaEngine) analyse(ctx context.Context, g *game.Game, opts bot.AnalysisOptions) (bot.AnalysisResult, error) { + call := &rpaCall{ + ctx: ctx, pos: g, digest: game.PositionDigest(g), + progress: make(chan bot.AnalysisProgress, 1), + answer: make(chan rpaAnswer, 1), + } + e.calls <- call + for { + select { + case p := <-call.progress: + if opts.OnComplete != nil { + opts.OnComplete(p) + } + case a := <-call.answer: + return a.result, a.err + case <-time.After(10 * time.Second): + return bot.AnalysisResult{}, errors.New("the test never answered") + } + } +} + +func (e *rpaEngine) next(t *testing.T) *rpaCall { + t.Helper() + select { + case c := <-e.calls: + return c + case <-time.After(5 * time.Second): + t.Fatal("the engine was never asked") + } + return nil +} + +// The holes the fixture answer names. They are interior holes of the six-hole +// board rpConnectionRecord is played on, and empty at every entry the tests +// analyse. +var ( + rpaMove = game.Point{Col: 2, Row: 3} + rpaUpper = game.Point{Col: 3, Row: 1} + rpaNone = game.Point{Col: 1, Row: 4} + rpaLower = game.Point{Col: 4, Row: 2} + rpaFifth = game.Point{Col: 4, Row: 3} + rpaAlsoRef = game.Point{Col: 3, Row: 3} +) + +// rpaFixture is an answer shaped like one the engine gives for a position with +// room to play: one candidate of every kind of bound, and one more than the +// panel lists. +func rpaFixture() bot.AnalysisResult { + move := rpaMove + return bot.AnalysisResult{ + Policy: bot.PlacementOnlyPolicy(), + Recommended: &move, + Candidates: []bot.AnalysisCandidate{ + {Move: rpaMove, Score: 120, Bound: bot.BoundExact}, + {Move: rpaUpper, Score: 80, Bound: bot.BoundUpper}, + {Move: rpaNone, Bound: bot.BoundUnscored}, + {Move: rpaLower, Score: -15, Bound: bot.BoundLower}, + {Move: rpaFifth, Score: 40, Bound: bot.BoundExact}, + }, + Reason: "advance", + Headline: "the headline the engine wrote", + Detail: "the detail the engine wrote", + Highlight: []game.Point{rpaMove, rpaAlsoRef}, + Stats: &bot.SearchStats{Nodes: 4321, Evaluations: 9000, Depth: 3, Elapsed: 1500 * time.Millisecond, StopReason: "time"}, + } +} + +// rpaAt opens rpConnectionRecord on the stand-in engine and goes to entry by +// its number, the way a player does. +func rpaAt(t *testing.T, entry int) (*rpaHarness, *rpaEngine) { + t.Helper() + eng := newRPAEngine() + h := rpaOpen(t, shellTestDeps(t), rpConnectionRecord(t), eng.analyse) + rpJump(t, h.s, strconv.Itoa(entry)) + if h.s.step() != entry { + t.Fatalf("the jump reached step %d, want %d", h.s.step(), entry) + } + return h, eng +} + +// TestReplayAnalysisReadsTheEntryNotThePly is the analysis's half of numbering +// the record by entry: rpConnectionRecord has draw offers between its moves, so +// the position after n entries is not the position after n moves, and two +// neighbouring entries can differ only in the offer standing. The position the +// engine is handed has to be the one on screen, down to the offer. +func TestReplayAnalysisReadsTheEntryNotThePly(t *testing.T) { + record, err := game.DecodeRecord(rpConnectionRecord(t).Record) + if err != nil { + t.Fatal(err) + } + labels := recordLabels(record.Moves, 17) + for _, entry := range []int{4, 5, 9, 13} { + t.Run(strconv.Itoa(entry), func(t *testing.T) { + want, err := game.ReplayTranscript(record.Ruleset, strings.Join(labels[:entry], "; ")) + if err != nil { + t.Fatal(err) + } + if want.Ply() == entry { + t.Fatalf("entry %d is also ply %d, so it cannot tell the two apart", entry, want.Ply()) + } + h, eng := rpaAt(t, entry) + h.press("?") + call := eng.next(t) + if call.digest != game.PositionDigest(want) { + t.Fatalf("the engine was asked about position %s, the position after %d entries is %s", + call.digest, entry, game.PositionDigest(want)) + } + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + if frame := h.frame(); !strings.Contains(frame, "engine's choice") { + t.Fatalf("the analysis of entry %d is not on screen:\n%s", entry, frame) + } + }) + } +} + +// TestReplayAnalysisIsShownOnlyOnTheEntryItRead holds a result to the position +// it was computed for: on the board and in the panel at that entry, and nowhere +// once the player has moved — not even on coming back, since what was put away +// is gone rather than hidden. +func TestReplayAnalysisIsShownOnlyOnTheEntryItRead(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + eng.next(t).answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + + frame := h.frame() + if !strings.Contains(frame, "engine's choice") { + t.Fatalf("the analysis is not in the panel:\n%s", frame) + } + // The recommended hole first, then what the explanation refers to, with the + // hole the engine named twice marked once. + if want := []game.Point{rpaMove, rpaAlsoRef}; !slices.Equal(h.s.board.Highlights, want) { + t.Fatalf("the board marks %v, want %v", h.s.board.Highlights, want) + } + + h.press("l") + frame = h.frame() + if strings.Contains(frame, "engine's choice") || h.block() != "" { + t.Fatalf("step %d shows the analysis of step 9:\n%s", h.s.step(), frame) + } + if marks := h.s.board.Highlights; len(marks) != 0 { + t.Fatalf("step %d marks %v, the holes of an analysis of step 9", h.s.step(), marks) + } + + h.press("h") + if h.s.step() != 9 { + t.Fatalf("stepping back reached step %d", h.s.step()) + } + frame = h.frame() + if strings.Contains(frame, "engine's choice") || len(h.s.board.Highlights) != 0 { + t.Fatalf("an analysis put away by moving came back with the position:\n%s", frame) + } +} + +// TestReplayAnalysisOvertakenByASeekIsDropped is the stale result: the search +// is still running when the player moves, and finishes anyway. Every way of +// moving has to cancel it at once, and what it then answers has to be dropped +// — here, and on the entry it was about, which the player can go straight back +// to before the answer arrives. +func TestReplayAnalysisOvertakenByASeekIsDropped(t *testing.T) { + for _, c := range []struct { + name string + move func(h *rpaHarness) + }{ + {"l", func(h *rpaHarness) { h.press("l") }}, + {"h", func(h *rpaHarness) { h.press("h") }}, + {"j", func(h *rpaHarness) { h.press("j") }}, + {"k", func(h *rpaHarness) { h.press("k") }}, + {"g", func(h *rpaHarness) { h.press("g") }}, + {"G", func(h *rpaHarness) { h.press("G") }}, + {"entry number", func(h *rpaHarness) { rpJump(h.t, h.s, "3") }}, + } { + t.Run(c.name, func(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + call := eng.next(t) + c.move(h) + if h.s.step() == 9 { + t.Fatal("the key did not move the replay") + } + if call.ctx.Err() == nil { + t.Fatal("moving through the record left the search running") + } + if h.s.analysis.running { + t.Fatal("the screen is still waiting on a search for a position it has left") + } + rpJump(t, h.s, "9") + + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the overtaken answer", func() bool { return h.answered == 1 }) + frame := h.frame() + if strings.Contains(frame, "engine's choice") || h.block() != "" || len(h.s.board.Highlights) != 0 { + t.Fatalf("an answer the player had moved past was shown:\n%s", frame) + } + }) + } +} + +// TestLeavingTheReplayCancelsTheAnalysis is the promise every search on a +// screen gets: nothing keeps working for a review nobody is looking at, however +// the player goes. +func TestLeavingTheReplayCancelsTheAnalysis(t *testing.T) { + for _, key := range []string{"q", "esc"} { + t.Run(key, func(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + call := eng.next(t) + h.press(key) + if call.ctx.Err() == nil { + t.Fatalf("leaving with %q left the search running", key) + } + h.waitFor("the screen to be left", func() bool { return h.left == 1 }) + + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the late answer", func() bool { return h.answered == 1 }) + if h.s.analysis.done || h.block() != "" { + t.Fatalf("a screen that has been left took in its search's answer:\n%s", h.block()) + } + }) + } + // The control form of the quit key never reaches the screen: the shell + // answers it and lets every screen finish on the way out. + t.Run("ctrl+c", func(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + call := eng.next(t) + sh := NewShell(h.s.deps, h.s) + if _, cmd := sh.Update(tutorialKeyMsg("ctrl+c")); cmd == nil { + t.Fatal("ctrl+c did not end the program") + } + if call.ctx.Err() == nil { + t.Fatal("ending the program left the search running") + } + call.answer <- rpaAnswer{result: rpaFixture()} + }) +} + +// TestAskingAgainCancelsTheRunningAnalysis covers the key's other meaning while +// a search runs: it stops the search, says so, and ignores what the search +// answers. Before that, the work the search has finished is on screen as +// finished work, taken from the search's own goroutine without touching the +// screen from there. +func TestAskingAgainCancelsTheRunningAnalysis(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + call := eng.next(t) + if !strings.Contains(h.block(), "? cancels") { + t.Fatalf("a running analysis does not say how to stop it:\n%s", h.block()) + } + + call.progress <- bot.AnalysisProgress{ + Recommended: rpaMove, + Stats: bot.SearchStats{Nodes: 1234, Depth: 3, Elapsed: 800 * time.Millisecond}, + } + h.waitFor("the finished iteration", func() bool { return strings.Contains(h.block(), "depth 3") }) + if block := h.block(); !strings.Contains(block, "completed so far") || !strings.Contains(block, "1234 nodes") { + t.Fatalf("the finished iteration is not reported as completed work:\n%s", block) + } + h.frame() + if len(h.s.board.Highlights) != 0 { + t.Fatalf("a search still running marks %v on the board", h.s.board.Highlights) + } + + h.press("?") + if call.ctx.Err() == nil { + t.Fatal("the second ? left the search running") + } + if block := h.block(); !strings.Contains(block, "canceled") || strings.Contains(block, "depth 3") { + t.Fatalf("the panel does not say the analysis was canceled:\n%s", block) + } + + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the canceled search's answer", func() bool { return h.answered == 1 }) + if frame := h.frame(); strings.Contains(frame, "engine's choice") || len(h.s.board.Highlights) != 0 { + t.Fatalf("a canceled search's answer was shown:\n%s", frame) + } + + // Asking once more is a new search, not the old one resumed. + h.press("?") + again := eng.next(t) + if again.ctx.Err() != nil { + t.Fatal("the new search started out canceled") + } + again.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the new answer", func() bool { return h.answered == 2 }) + if !strings.Contains(h.block(), "engine's choice") { + t.Fatalf("the search asked for after a cancel was not shown:\n%s", h.block()) + } +} + +// rpaRow finds the candidate row for p in a block: among the lines under the +// candidates heading, the one whose first word is the hole's name. The line +// naming the engine's choice starts with a hole too, and is not a row. +func rpaRow(t *testing.T, block string, p game.Point) (string, bool) { + t.Helper() + lines := strings.Split(block, "\n") + for i, line := range lines { + if !strings.HasPrefix(line, "candidates") { + continue + } + for _, row := range lines[i+1:] { + if fields := strings.Fields(row); len(fields) > 0 && fields[0] == p.String() { + return strings.Join(fields[1:], " "), true + } + } + } + return "", false +} + +// TestReplayAnalysisSaysWhatEachScoreIs is the honesty of the numbers. A score +// the search measured is shown as one; a ceiling is shown as a ceiling, not as a +// value to compare with the measured one; and a candidate nothing scored shows +// no number at all, because its zero is the absence of a measurement. +func TestReplayAnalysisSaysWhatEachScoreIs(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + eng.next(t).answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + block := h.block() + + for _, c := range []struct { + p game.Point + want, never string + }{ + {rpaMove, "+120 exact", "at most"}, + {rpaUpper, "at most +80", "exact"}, + {rpaLower, "at least -15", "exact"}, + } { + row, ok := rpaRow(t, block, c.p) + if !ok { + t.Fatalf("no row for %s:\n%s", c.p, block) + } + if !strings.Contains(row, c.want) || strings.Contains(row, c.never) { + t.Errorf("%s reads %q, want %q and never %q", c.p, row, c.want, c.never) + } + } + row, ok := rpaRow(t, block, rpaNone) + if !ok { + t.Fatalf("no row for the unscored candidate %s:\n%s", rpaNone, block) + } + if !strings.Contains(row, "unscored") || strings.ContainsAny(row, "0123456789") { + t.Errorf("the unscored candidate reads %q, which puts a number to nothing measured", row) + } + if _, ok := rpaRow(t, block, rpaFifth); ok { + t.Errorf("the panel lists a fifth candidate:\n%s", block) + } + + // The move is the engine's choice under a bounded placement-only search, + // and the work behind it is there to be weighed. + for _, want := range []string{ + rpaMove.String() + " is the engine's choice", "not a proven best move", "placement-only", + "the headline the engine wrote", "the detail the engine wrote", + "depth 3", "4321 nodes", "not reproducible", + } { + if !strings.Contains(block, want) { + t.Errorf("the analysis does not say %q:\n%s", want, block) + } + } + if strings.Contains(strings.ReplaceAll(block, "not a proven best move", ""), "best move") { + t.Errorf("the analysis calls a move the best one:\n%s", block) + } +} + +// TestReplayAnalysisMarksOnlyUnrepeatableWorkAsSuch keeps the reproducibility +// note on the stops that earn it. A search the clock or an interruption ended +// is whatever this machine had finished; one that ended on its own terms is +// the same search on any machine, and calling it unrepeatable would be as +// wrong as the reverse. +func TestReplayAnalysisMarksOnlyUnrepeatableWorkAsSuch(t *testing.T) { + for _, c := range []struct { + stop string + repeatable bool + }{ + {"time", false}, {"canceled", false}, + {"depth", true}, {"nodes", true}, {"decided", true}, {"immediate", true}, + } { + t.Run(c.stop, func(t *testing.T) { + r := rpaFixture() + r.Stats.StopReason = c.stop + a := replayAnalysis{job: &replayAnalysisJob{}, done: true, result: r} + block := strings.Join(a.lines(200), "\n") + if marked := strings.Contains(block, "not reproducible"); marked == c.repeatable { + t.Errorf("a search that stopped on %q is marked not reproducible=%v:\n%s", c.stop, marked, block) + } + }) + } +} + +// TestReplayAnalysisOfAFinishedPositionAdvisesNothing asks the real engine about +// the last entry of finished games. There is no turn left to advise, so there +// is no move, no candidate and no mark of the engine's; the chain the game was +// won with stays marked where it was. +func TestReplayAnalysisOfAFinishedPositionAdvisesNothing(t *testing.T) { + resigned, _ := rpSpecialRecord(t, "h:resign") + for _, c := range []struct { + name string + sv gamestore.Saved + ended string + }{ + {"connection", rpConnectionRecord(t), "vertical won by completing a chain"}, + {"resignation", resigned, "vertical won by resignation"}, + } { + t.Run(c.name, func(t *testing.T) { + h := rpaOpen(t, shellTestDeps(t), c.sv, nil) + if h.s.step() != h.s.entries() { + t.Fatal("the review did not open at the final entry") + } + h.press("?") + h.waitFor("the engine's answer", func() bool { return h.answered == 1 }) + if h.s.analysis.err != nil { + t.Fatalf("the engine refused a finished position: %v", h.s.analysis.err) + } + block := h.block() + if !strings.Contains(block, c.ended) || !strings.Contains(block, "no move to advise") { + t.Errorf("the analysis does not say the game is over:\n%s", block) + } + if strings.Contains(block, "engine's choice") || strings.Contains(block, "candidates") { + t.Errorf("a finished position was given a move:\n%s", block) + } + h.frame() + if !slices.Equal(h.s.board.Highlights, h.s.winning) { + t.Errorf("the board marks %v at the final entry, want the winning chain %v", h.s.board.Highlights, h.s.winning) + } + }) + } +} + +// TestReplayAnalysisReadsACopy hands the engine's position back to the test and +// changes it there. A screen that gave the engine the position it shows would +// now be showing whatever the search left it in; the one on screen has to be +// untouched, and the record still walks the way a fresh replay does. +func TestReplayAnalysisReadsACopy(t *testing.T) { + h, eng := rpaAt(t, 9) + shown := h.s.current() + before := game.PositionDigest(shown) + h.press("?") + call := eng.next(t) + if call.pos == shown { + t.Fatal("the engine was handed the position on screen rather than a copy of it") + } + if err := call.pos.UndoLastMove(); err != nil { + t.Fatal(err) + } + if got := game.PositionDigest(h.s.current()); got != before { + t.Fatalf("changing the analysed position changed the one on screen: %s, was %s", got, before) + } + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + + record, err := game.DecodeRecord(rpConnectionRecord(t).Record) + if err != nil { + t.Fatal(err) + } + h.press("l") + want, err := game.ReplayTranscript(record.Ruleset, strings.Join(recordLabels(record.Moves, 17)[:10], "; ")) + if err != nil { + t.Fatal(err) + } + rpSamePosition(t, 10, h.s.current(), want) +} + +// rpaFiles lists everything under dir with its size and modification time, so +// two listings differ if anything was created, removed or written. +func rpaFiles(t *testing.T, dir string) map[string]string { + t.Helper() + out := map[string]string{} + err := filepath.WalkDir(dir, func(path string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + info, err := e.Info() + if err != nil { + return err + } + out[path] = fmt.Sprintf("dir=%t size=%d mod=%d", e.IsDir(), info.Size(), info.ModTime().UnixNano()) + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} + +// TestReplayAnalysisWithTheRealEngine runs bot.Analyze itself under a work +// bound, with the machine's hint preference turned off. A review is not a game +// played with or without advice: the analysis is asked for here, answers with a +// move the rules allow on the position on screen, leaves that position as it +// was, and writes nothing. +func TestReplayAnalysisWithTheRealEngine(t *testing.T) { + d := shellTestDeps(t) + off := false + if err := (gameDefaults{Hints: &off}).save(d.ConfigDir); err != nil { + t.Fatal(err) + } + h := rpaOpen(t, d, rpConnectionRecord(t), func(ctx context.Context, g *game.Game, o bot.AnalysisOptions) (bot.AnalysisResult, error) { + // A node bound with the clock lifted out of its way is a search that + // ends on its own terms, and so takes the same time on any machine. + o.Limits = bot.Limits{Nodes: 400, Time: time.Minute} + return bot.Analyze(ctx, g, o) + }) + rpJump(t, h.s, "9") + pos := h.s.current() + before := game.PositionDigest(pos) + files := rpaFiles(t, d.ConfigDir) + + h.press("?") + h.waitFor("the engine's answer", func() bool { return h.answered == 1 }) + a := h.s.analysis + if a.err != nil || !a.shown(9) { + t.Fatalf("the analysis did not land on step 9: %v\n%s", a.err, h.block()) + } + if a.result.Recommended == nil { + t.Fatal("the engine recommended nothing for a position with room to play") + } + if err := pos.CanPlace(pos.Turn(), *a.result.Recommended); err != nil { + t.Errorf("the engine recommended %s, which the position refuses: %v", *a.result.Recommended, err) + } + if got := game.PositionDigest(h.s.current()); got != before { + t.Errorf("the analysis moved the position on screen: %s, was %s", got, before) + } + block := h.block() + for _, want := range []string{"placement-only", "is the engine's choice", "not a proven best move", "completed work"} { + if !strings.Contains(block, want) { + t.Errorf("the analysis does not say %q:\n%s", want, block) + } + } + if st := a.result.Stats; st == nil || st.StopReason != "nodes" && st.StopReason != "depth" && st.StopReason != "decided" && st.StopReason != "immediate" { + t.Errorf("a work-bound search stopped on %+v", st) + } else if strings.Contains(block, "not reproducible") { + t.Errorf("a search that stopped on %q is called unrepeatable:\n%s", st.StopReason, block) + } + h.frame() + if len(h.s.board.Highlights) == 0 || h.s.board.Highlights[0] != *a.result.Recommended { + t.Errorf("the board marks %v, which does not start with the move %s", h.s.board.Highlights, *a.result.Recommended) + } + if after := rpaFiles(t, d.ConfigDir); !maps.Equal(files, after) { + t.Errorf("the analysis wrote to the configuration directory:\nbefore %v\nafter %v", files, after) + } +} + +// TestReplayFooterOffersTheAnalysisKey holds the footer and the key together: +// the footer names ? and pressing it reads the entry on screen. While the entry +// input is open the keyboard is the input's, so ? is text it refuses rather +// than an analysis started behind the number being typed. +func TestReplayFooterOffersTheAnalysisKey(t *testing.T) { + h, eng := rpaAt(t, 9) + if keys := rpFooterKeys(t, h.s.status(200)); !slices.Contains(keys, "?") { + t.Fatalf("the footer does not name ?: %v", keys) + } + + h.press(":") + h.press("?") + if h.s.analysis.running || h.s.analysis.job != nil { + t.Fatal("? typed into the entry input started an analysis") + } + if h.s.jump.problem == "" { + t.Error("the entry input took ? without refusing it") + } + h.press("esc") + + h.press("?") + if !h.s.analysis.running || !h.s.analysis.on(9) { + t.Fatal("? did not start an analysis of the entry on screen") + } + eng.next(t).answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + + // With the answer on screen the same key puts it away, marks and all. + h.press("?") + if frame := h.frame(); strings.Contains(frame, "engine's choice") || len(h.s.board.Highlights) != 0 { + t.Fatalf("a second ? did not put the analysis away:\n%s", frame) + } +} + +// rpaOnScreen draws the screen and finds the analysis on it: status on the +// bottom row, and panel in the rows above it wherever the arrangement has a +// panel. Each phrase is one the other place never uses, so neither can be read +// off the other's rows. +func rpaOnScreen(t *testing.T, h *rpaHarness, arr ui.Arrangement, status, panel string) { + t.Helper() + frame := h.frame() + shellAssertFits(t, "replay with an analysis", frame, arr.Width, arr.Height) + lines := strings.Split(frame, "\n") + if bottom := lines[len(lines)-1]; !strings.Contains(bottom, status) { + t.Fatalf("at %dx%d the bottom row %q does not say %q:\n%s", arr.Width, arr.Height, bottom, status, frame) + } + if arr.Panel == ui.PanelNone { + return + } + if above := strings.Join(lines[:len(lines)-1], "\n"); !strings.Contains(above, panel) { + t.Fatalf("at %dx%d the panel does not say %q:\n%s", arr.Width, arr.Height, panel, frame) + } +} + +// TestReplayAnalysisIsOnScreenAtEverySize asks for an analysis in every +// terminal a review has to work in, and follows it to each way it can end. The +// bottom row carries it at every size, because at the smallest there is no +// panel and the bottom row is the whole of the interface. Wherever there is a +// panel, the panel carries it too, however few rows it has: the seven-row panel +// under the board at 40x20 once gave every row the entry list left over to the +// record's details, and showed nothing at all after ? — not the running search, +// not how to stop it, not what it found. +func TestReplayAnalysisIsOnScreenAtEverySize(t *testing.T) { + sizes := append([][2]int{{40, 20}}, shellSizes...) + // The premise, on the six-hole board rpConnectionRecord is played on: one + // of the sizes has no panel at all, and 40x20 puts its panel under the + // board, where rows are scarce, rather than beside it. + panelless := false + for _, size := range sizes { + panelless = panelless || ui.Arrange(size[0], size[1], 6).Panel == ui.PanelNone + } + if !panelless || ui.Arrange(40, 20, 6).Panel != ui.PanelBottom { + t.Fatal("the sizes no longer include a terminal with no panel and one with a short panel under the board") + } + + for _, c := range []struct { + name string + entry int + // end is how the search ends: with a move, with the game already over + // at the entry, refused, or stopped by the player. + end func(h *rpaHarness, call *rpaCall) + // status is what the bottom row says once it has ended, and panel what + // the panel says. + status, panel string + }{ + {"choice", 9, func(_ *rpaHarness, call *rpaCall) { + call.answer <- rpaAnswer{result: rpaFixture()} + }, rpaMove.String() + " placement-only", "engine's choice"}, + {"game over", 17, func(h *rpaHarness, call *rpaCall) { + call.answer <- rpaAnswer{result: bot.AnalysisResult{Policy: bot.PlacementOnlyPolicy(), Result: h.s.cursor.result}} + }, "game over", "the game is over here"}, + {"error", 9, func(_ *rpaHarness, call *rpaCall) { + call.answer <- rpaAnswer{err: errors.New("the search broke")} + }, "analysis failed", "could not analyse"}, + {"canceled", 9, func(h *rpaHarness, call *rpaCall) { + h.press("?") + call.answer <- rpaAnswer{result: rpaFixture()} + }, "analysis canceled", "canceled; ? starts it again"}, + } { + t.Run(c.name, func(t *testing.T) { + for _, size := range sizes { + w, ht := size[0], size[1] + t.Run(fmt.Sprintf("%dx%d", w, ht), func(t *testing.T) { + h, eng := rpaAt(t, c.entry) + h.feed(tea.WindowSizeMsg{Width: w, Height: ht}) + arr := ui.Arrange(w, ht, h.s.current().Size()) + h.press("?") + call := eng.next(t) + rpaOnScreen(t, h, arr, "analysing", "? cancels") + + c.end(h, call) + h.waitFor("the search to end", func() bool { return h.answered == 1 }) + rpaOnScreen(t, h, arr, c.status, c.panel) + }) + } + }) + } +} + +// TestReplayAnalysisTakesOnlyTheAnswerItIsWaitingFor holds two searches at +// once. The player asks, moves on or stops the search, and asks again; the +// first search answers while the second is still running. That answer is for +// a search the screen is no longer waiting on, and taking it would do three +// wrong things at once: cancel the search that is running, stop waiting for +// it, and show a reading of another position — or an earlier reading of this +// one — as its result. A replay closed and opened again is the same case: the +// old screen's search answers into the new one, which is waiting on a search +// of the very same entry. Only the second search's own answer is shown. +func TestReplayAnalysisTakesOnlyTheAnswerItIsWaitingFor(t *testing.T) { + // The second search answers with a different hole, so what is on screen at + // the end says which search it came from. + second := rpaFixture() + upper := rpaUpper + second.Recommended = &upper + second.Highlight = []game.Point{rpaUpper} + + // waiting is the screen still running the second search, untouched, after + // the first one's answer has been delivered to it. + waiting := func(t *testing.T, h *rpaHarness, current *rpaCall) { + t.Helper() + if !h.s.analysis.running || h.s.analysis.done { + t.Fatalf("an answer for another search ended the one running:\n%s", h.block()) + } + if current.ctx.Err() != nil { + t.Fatal("an answer for another search canceled the one running") + } + if frame := h.frame(); strings.Contains(frame, "engine's choice") || len(h.s.board.Highlights) != 0 { + t.Fatalf("an answer for another search was shown:\n%s", frame) + } + } + // shows is the second search's answer on screen, at the entry it read. + shows := func(t *testing.T, h *rpaHarness, entry int) { + t.Helper() + if !h.s.analysis.shown(entry) { + t.Fatalf("the second search's answer is not shown at step %d:\n%s", entry, h.block()) + } + if !strings.Contains(h.block(), rpaUpper.String()+" is the engine's choice") { + t.Fatalf("the screen shows another search's answer:\n%s", h.block()) + } + h.frame() + if want := []game.Point{rpaUpper}; !slices.Equal(h.s.board.Highlights, want) { + t.Fatalf("the board marks %v, want the second search's %v", h.s.board.Highlights, want) + } + } + + for _, c := range []struct { + name string + // again asks for the second search while the first is unanswered, and + // entry is where the second search reads. + again func(h *rpaHarness) + entry int + }{ + {"after moving on", func(h *rpaHarness) { h.press("l"); h.press("?") }, 10}, + {"after stopping it", func(h *rpaHarness) { h.press("?"); h.press("?") }, 9}, + } { + t.Run(c.name, func(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + first := eng.next(t) + c.again(h) + current := eng.next(t) + if h.s.step() != c.entry || !h.s.analysis.on(c.entry) || !h.s.analysis.running { + t.Fatalf("the second search is not running at step %d", c.entry) + } + + first.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the first search's answer", func() bool { return h.answered == 1 }) + waiting(t, h, current) + + current.answer <- rpaAnswer{result: second} + h.waitFor("the second search's answer", func() bool { return h.answered == 2 }) + shows(t, h, c.entry) + }) + } + + t.Run("in a replay opened again", func(t *testing.T) { + old, eng := rpaAt(t, 9) + old.press("?") + first := eng.next(t) + old.press("q") + if first.ctx.Err() == nil { + t.Fatal("leaving the replay left its search running") + } + + h := rpaOpen(t, old.s.deps, rpConnectionRecord(t), eng.analyse) + rpJump(t, h.s, "9") + h.press("?") + current := eng.next(t) + + // The old screen's search answers after all, and the program hands + // what it answered to the screen that is up now. + first.answer <- rpaAnswer{result: rpaFixture()} + h.feed(old.outcome()) + if h.answered != 1 { + t.Fatal("the old screen's answer was not delivered to the new one") + } + waiting(t, h, current) + + current.answer <- rpaAnswer{result: second} + h.waitFor("the second search's answer", func() bool { return h.answered == 2 }) + shows(t, h, 9) + }) +} + +// TestReplayAnalysisTicksOnlyWhileItsSearchRuns is the running indicator's +// chain. A tick for the search the screen is running asks for the next one; a +// tick for a search that has finished, been stopped with ?, been moved past or +// left, or been overtaken by a newer one asks for nothing. A chain that went on +// after its search would tick for as long as the program ran, and there would +// be one more such chain for every analysis the player had ever asked for. +func TestReplayAnalysisTicksOnlyWhileItsSearchRuns(t *testing.T) { + // tick delivers a tick for job and returns what the screen asks for next. + tick := func(h *rpaHarness, job *replayAnalysisJob) tea.Cmd { + h.t.Helper() + _, cmd := h.s.Update(replayAnalysisTickMsg{job: job, at: job.started.Add(time.Second)}) + return cmd + } + for _, c := range []struct { + name string + // after is what happens once the first search is running. + after func(h *rpaHarness, eng *rpaEngine, call *rpaCall) + }{ + {"finished", func(h *rpaHarness, _ *rpaEngine, call *rpaCall) { + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the answer", func() bool { return h.answered == 1 }) + }}, + {"stopped with ?", func(h *rpaHarness, _ *rpaEngine, _ *rpaCall) { h.press("?") }}, + {"moved past", func(h *rpaHarness, _ *rpaEngine, _ *rpaCall) { h.press("l") }}, + {"left", func(h *rpaHarness, _ *rpaEngine, _ *rpaCall) { h.press("q") }}, + {"overtaken", func(h *rpaHarness, eng *rpaEngine, _ *rpaCall) { + h.press("?") + h.press("?") + next := eng.next(h.t) + if tick(h, h.s.analysis.job) == nil { + h.t.Fatal("a tick for the newer search did not ask for the next one") + } + next.answer <- rpaAnswer{result: rpaFixture()} + }}, + } { + t.Run(c.name, func(t *testing.T) { + h, eng := rpaAt(t, 9) + h.press("?") + call := eng.next(t) + job := h.s.analysis.job + if tick(h, job) == nil { + t.Fatal("a tick for the search that is running did not ask for the next one") + } + + c.after(h, eng, call) + if tick(h, job) != nil { + t.Fatalf("a tick for a search that has been %s asked for another", c.name) + } + // The stand-in holds a search until it is answered. One answered + // already has taken its answer off the channel, so this never + // waits. + call.answer <- rpaAnswer{result: rpaFixture()} + }) + } +} diff --git a/internal/app/replay_test.go b/internal/app/replay_test.go index 2cdbbc0..b8b668a 100644 --- a/internal/app/replay_test.go +++ b/internal/app/replay_test.go @@ -83,7 +83,7 @@ func rpScreen(t *testing.T, d Deps, sv gamestore.Saved, w, h int) *ReplayScreen } // rpKeys is the alphabet a probe presses: everything km binds on the board, the -// plain special keys, the one this screen adds for itself, and a spread of +// plain special keys, the ones this screen adds for itself, and a spread of // letters and digits that nothing is expected to answer. func rpKeys(t *testing.T, km ui.Keymap) []string { t.Helper() @@ -104,7 +104,7 @@ func rpKeys(t *testing.T, km ui.Keymap) []string { add(k) } } - for _, k := range []string{"left", "right", "up", "down", "enter", "space", "tab", "esc", ":"} { + for _, k := range []string{"left", "right", "up", "down", "enter", "space", "tab", "esc", ":", "?"} { add(k) } for r := 'a'; r <= 'z'; r++ { diff --git a/internal/cli/game.go b/internal/cli/game.go index 875c43b..e50980e 100644 --- a/internal/cli/game.go +++ b/internal/cli/game.go @@ -167,7 +167,9 @@ Opens at the final entry with a scrolling entry list. Use h/l (or left/right) to step, k/j (or up/down) to move five entries, and g/G for the ends. Press : to enter an entry number: 0 is the initial position, enter jumps and escape cancels. Draw offers count as entries, not moves. A winning connection -is highlighted only at the final entry. Review never changes the saved record.`, +is highlighted only at the final entry. Press ? to analyse the entry on screen +under the placement-only policy; moving on or pressing ? again cancels it. +Review never changes the saved record.`, Args: exactArgs(1), ValidArgsFunction: opts.gameIDCompletions, RunE: func(cmd *cobra.Command, args []string) error { diff --git a/internal/e2e/replay_analysis_test.go b/internal/e2e/replay_analysis_test.go new file mode 100644 index 0000000..03b419e --- /dev/null +++ b/internal/e2e/replay_analysis_test.go @@ -0,0 +1,194 @@ +package e2e + +import ( + "fmt" + "io/fs" + "maps" + "os" + "path/filepath" + "regexp" + "strings" + "testing" + "time" + + "github.com/BAKocska/twixtui/internal/game" + "github.com/BAKocska/twixtui/internal/gamestore" +) + +// raeCandidateRow is one of the analysis block's candidate rows on the six-hole +// board the scenario reviews: a hole, then what its score is. Only these rows +// put a bound word straight after a hole name, so a match is the block and +// nothing else on screen. +var raeCandidateRow = regexp.MustCompile(`\b[A-F][1-6]\s+(?:[+-]\d+ exact|at most [+-]\d+|at least [+-]\d+|unscored)\b`) + +// TestReplayAnalysisFromTheMenu drives RM-01.c in a real terminal against the +// compiled program: a finished game is opened from Watch a finished game, the +// entry input reaches the middle of it, ? reads that position with the real +// engine, and the next step puts the reading away. +// +// The machine's hint preference is off. Advice during a game is that game's +// setting; a review is a different act, asked for with its own key, and the +// preference must not reach it. Nothing is written while the analysis runs: +// the configuration directory is listed before and after, and the stored +// record is compared byte for byte at the end. +func TestReplayAnalysisFromTheMenu(t *testing.T) { + t.Parallel() + cfg := t.TempDir() + saved, record := raeSeed(t, cfg) + + tm := sessionIn(t, cfg, 120, 50) + tm.MustWaitFor("skip", 20*time.Second) + tm.SendKeys("q") + menu := tm.MustWaitFor("Watch a finished game", 20*time.Second) + if !tm.Alive() { + t.Fatalf("the program exited instead of showing the menu:\n%s", menu) + } + + // Down to the watch entry one step at a time, each step proved by the frame + // changing; the entry's own explanation says the highlight has arrived. + screen := tm.WaitSettled(10 * time.Second) + for range 2 { + tm.SendKeys("j") + screen = tm.WaitChanged(screen, 10*time.Second) + } + if !strings.Contains(screen, "Step through a finished") { + t.Fatalf("two steps down did not reach the watch entry:\n%s", screen) + } + tm.SendKeys("Enter") + tm.MustWaitFor("Tester vs max bot", 20*time.Second) + tm.SendKeys("Enter") + end := tm.MustWaitFor("step 7 of 7", 20*time.Second) + if status := lbStatusLine(end); !strings.Contains(status, "? analyse") { + t.Fatalf("the replay's status line %q does not offer the analysis key:\n%s", status, end) + } + + // The middle of the game, reached by its entry number. + tm.SendKeys(":") + tm.WaitChanged(end, 10*time.Second) + tm.SendKeys("4", "Enter") + tm.MustWaitFor("step 4 of 7", 10*time.Second) + middle := tm.WaitSettled(10 * time.Second) + // The control: before ? there is no reading on screen, so the one that + // appears is the key's doing. + if strings.Contains(middle, "engine's choice") || raeCandidateRow.MatchString(middle) { + t.Fatalf("an analysis is on screen before one was asked for:\n%s", middle) + } + files := raeFiles(t, cfg) + + tm.SendKeys("?") + tm.MustWaitFor("engine's choice", 30*time.Second) + read := tm.WaitSettled(10 * time.Second) + if !tm.Alive() { + t.Fatalf("the program died while analysing:\n%s", read) + } + for _, want := range []string{"step 4 of 7", "placement-only", "not a proven", "completed work"} { + if !strings.Contains(read, want) { + t.Fatalf("the analysis does not show %q:\n%s", want, read) + } + } + if rows := raeCandidateRow.FindAllString(read, -1); len(rows) == 0 || len(rows) > 4 { + t.Fatalf("the analysis lists %d candidate rows, want one to four:\n%s", len(rows), read) + } + tm.AssertFits() + + // The next entry is a different position, and the reading goes with the + // one it was about. + tm.SendKeys("l") + tm.MustWaitFor("step 5 of 7", 10*time.Second) + next := tm.WaitSettled(10 * time.Second) + if strings.Contains(next, "engine's choice") || raeCandidateRow.MatchString(next) { + t.Fatalf("the analysis of step 4 is still on screen at step 5:\n%s", next) + } + if after := raeFiles(t, cfg); !maps.Equal(files, after) { + t.Fatalf("analysing a replay wrote to the configuration directory:\nbefore %v\nafter %v", files, after) + } + + tm.SendKeys("q") + back := tm.MustWaitFor("Watch a finished game", 20*time.Second) + if strings.Contains(back, "step 5 of 7") { + t.Fatalf("q did not leave the replay:\n%s", back) + } + tm.SendKeys("C-c") + code, exited := tm.WaitExit(20 * time.Second) + if !exited || code != 0 { + t.Fatalf("the program did not exit cleanly: exited=%v status=%d", exited, code) + } + + store, err := gamestore.Open(cfg) + if err != nil { + t.Fatal(err) + } + after, err := store.Get(saved.ID) + if err != nil { + t.Fatal(err) + } + if after.Record != record.Encode() { + t.Fatal("analysing a replay changed the stored record") + } +} + +// raeSeed stores one finished game and turns the machine's hint preference +// off. Both go through the files the program itself reads, so the fixture is +// what a real machine holds. +func raeSeed(t *testing.T, cfg string) (gamestore.Saved, game.Record) { + t.Helper() + rs := game.Std + rs.Size = 6 + g := game.MustNew(rs) + for _, move := range []string{"B1", "F2", "C3", "F3", "D5", "F4", "B6"} { + if err := g.PlayNotation(move); err != nil { + t.Fatalf("playing %s: %v", move, err) + } + } + if !g.Result().Over() || g.Entries() != 7 { + t.Fatalf("the fixture game is %d entries and over=%v, want a finished seven-entry game", + g.Entries(), g.Result().Over()) + } + record, err := g.Record() + if err != nil { + t.Fatal(err) + } + store, err := gamestore.Open(cfg) + if err != nil { + t.Fatal(err) + } + saved := gamestore.Saved{ + ID: gamestore.NewID(), + Kind: gamestore.VersusBot, + Created: time.Date(2026, 2, 2, 9, 0, 0, 0, time.UTC), + Player: "Tester", + Side: "vertical", + Opponent: "bot:max", + Record: record.Encode(), + Finished: true, + } + if err := store.Put(saved); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(cfg, "defaults.json"), []byte("{\"hints\": false}\n"), 0o600); err != nil { + t.Fatal(err) + } + return saved, record +} + +// raeFiles lists everything under dir with its size and modification time, so +// two listings differ if anything was created, removed or written. +func raeFiles(t *testing.T, dir string) map[string]string { + t.Helper() + out := map[string]string{} + err := filepath.WalkDir(dir, func(path string, e fs.DirEntry, err error) error { + if err != nil { + return err + } + info, err := e.Info() + if err != nil { + return err + } + out[path] = fmt.Sprintf("dir=%t size=%d mod=%d", e.IsDir(), info.Size(), info.ModTime().UnixNano()) + return nil + }) + if err != nil { + t.Fatal(err) + } + return out +} From f8208e147532273a5e1e5703307e304b67f8e40a Mon Sep 17 00:00:00 2001 From: BAK Date: Mon, 28 Sep 2026 15:01:03 +0200 Subject: [PATCH 2/5] docs: describe analysis in the replay viewer --- CHANGELOG.md | 12 ++++++++++++ docs/MANUAL.md | 50 ++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 58 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1c1069..d97abd3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,18 @@ project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +### Added + +- `?` in the saved-game replay analyses the entry on screen in the background: + the placement-only badge, the recommended hole as the engine's choice under a + bounded search (never a proven best move), its explanation, up to four + candidates with exact/upper/lower/unscored scores, and the completed work with + its stop reason. Time and cancellation stops are marked not reproducible, and + a finished position gets no recommendation. Any seek or leaving cancels the + search and discards its result, `?` again cancels or dismisses, the analysed + position is a copy, and nothing is written. It works regardless of hint + settings, for finished and imported games alike. + ## [0.7.0] - 2026-09-12 ### Added diff --git a/docs/MANUAL.md b/docs/MANUAL.md index b48c0aa..c49665b 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -325,7 +325,7 @@ none of those. | `1`-`8` | Only in link mode: toggle the link in that direction. | | `esc` | Leave link mode. | | `a` | Abort the turn: the board goes back to how it stood when your turn began. | -| `?` | In a bot game: the move the bot would play, and why. | +| `?` | In a bot game: the move the bot would play, and why. In a saved-game replay: the engine's reading of the entry on screen (see [Reviewing saved games](#reviewing-saved-games)). | | `s` | Take the swap option, while it is on offer. | | `d` | Offer a draw, or accept the one on offer. | | `r` | Resign. | @@ -861,6 +861,7 @@ shows both the entry counter and the number of moves played. | `k` / `up`, `j` / `down` | Back or forward five entries. | | `g` / `G` | Initial position / final entry. | | `:` | Type an entry number; `enter` jumps and `esc` cancels the input. | +| `?` | Analyse the entry on screen; while that analysis runs, cancel it; once it is shown, put it away. | | `q` / `esc` | Leave the viewer when not editing the entry number. | | `ctrl+c` | End the program. | @@ -879,14 +880,55 @@ Replay validates the whole record before opening and retains one mutable board, not a board snapshot per entry. Small backward steps use undo; longer backward seeks rebuild the requested prefix to avoid repeatedly scanning draw-offer history. Reviewing never changes the stored record or ratings. Notes and -variations are not part of this viewer; engine analysis is available through the -separate `analyze` commands below, not as an interactive replay action. +variations are not part of this viewer. + +`?` asks the engine about the position at the selected entry, in the +background: the keys keep working, and the panel shows a running indicator and, +once a search iteration has finished, the depth and nodes of that completed +work. The analysis is the same one `twixtui analyze` runs with its default +two-second guard (see [Position analysis](#position-analysis)), and the panel +reports it in the same terms, most important first, so a short panel keeps the +badge and the choice and drops the end of the block. The badge and the choice, +or the running indicator, are given rows before the record's own details, so a +panel with only a few rows to spare still shows them. The bottom line says +where the analysis stands as well — `analysing` and the time so far, the chosen +hole with its `placement-only` badge and `not proven`, or that it was canceled, +failed or has no move to advise — and on a terminal too small for a panel it is +the only place the analysis appears. The block reads, in order: + +- the `placement-only` policy badge, and the recommended hole as **the engine's + choice under a bounded search, not a proven best move**; +- the engine's own headline and detail for that choice; +- up to four candidates with their scores in search units, each marked `exact`, + `at most`/`at least` for a bound, or `unscored` with no number at all; +- the completed work — depth, nodes, elapsed time — and why the search stopped. + A search stopped by the time guard or an interruption is marked not + reproducible. + +The recommended hole and the holes the explanation refers to are marked on the +board, only while the entry they were read from is on screen. Any movement — +stepping, jumping five, the ends, or a typed entry number — cancels a search +still running and discards a result already shown, and so does leaving the +viewer; a result that arrives after that is dropped, so an analysis is never +shown against a position it was not computed for. Pressing `?` again stops a +running search (the panel says it was canceled) or puts a shown result away. +A finished position, such as the final entry of a won game, gets no +recommendation: the panel says the game is over at that entry. + +Replay analysis is an explicit review action. It works on finished and imported +games alike, whether or not hints were offered when the game was played and +whatever the machine's hint setting is, analyses a copy of the position, and +writes nothing to disk. +It is not run in the background while stepping; results are not kept between +seeks. ## Position analysis Analyse a saved game, a record file (or standard input), or a position written in the game's notation. No profile is required, and analysis does not write games, -ratings, profiles or configuration. +ratings, profiles or configuration. The same analysis, under the default +two-second guard, is available interactively with `?` in the replay viewer (see +[Reviewing saved games](#reviewing-saved-games)). ``` twixtui analyze position --size 12 --moves 'B1; L2; C3' --nodes 10000 From 8a0ae69f59bfa5997f364fe6195e0f7dfc028608 Mon Sep 17 00:00:00 2001 From: BAK Date: Mon, 28 Sep 2026 15:23:09 +0200 Subject: [PATCH 3/5] fix(replay): keep the analysis badge whole on the narrowest status line A four-character hole filled the 20-column status line exactly once the caveat was cut, and the layout then dropped the badge as a cut word. The status fragment is now built from whole items: the caveat goes first, and the hole and badge stay together wherever they fit. --- CHANGELOG.md | 4 +- docs/MANUAL.md | 5 +- internal/app/replay.go | 11 ++-- internal/app/replay_analysis.go | 53 ++++++++++++------- internal/app/replay_analysis_test.go | 76 ++++++++++++++++++++++++++++ 5 files changed, 124 insertions(+), 25 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d97abd3..84ef175 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +17,9 @@ project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). a finished position gets no recommendation. Any seek or leaving cancels the search and discards its result, `?` again cancels or dismisses, the analysed position is a copy, and nothing is written. It works regardless of hint - settings, for finished and imported games alike. + settings, for finished and imported games alike. The bottom line carries the + analysis at every size; a narrow one gives up `not proven` before the badge, + keeping the hole and its placement-only badge whole. ## [0.7.0] - 2026-09-12 diff --git a/docs/MANUAL.md b/docs/MANUAL.md index c49665b..a1459c3 100644 --- a/docs/MANUAL.md +++ b/docs/MANUAL.md @@ -894,7 +894,10 @@ panel with only a few rows to spare still shows them. The bottom line says where the analysis stands as well — `analysing` and the time so far, the chosen hole with its `placement-only` badge and `not proven`, or that it was canceled, failed or has no move to advise — and on a terminal too small for a panel it is -the only place the analysis appears. The block reads, in order: +the only place the analysis appears. A bottom line too narrow for all of the +choice gives up `not proven` first and keeps the hole and its badge whole, even +for a four-character hole such as `AA10` at twenty columns. The block reads, in +order: - the `placement-only` policy badge, and the recommended hole as **the engine's choice under a bounded search, not a proven best move**; diff --git a/internal/app/replay.go b/internal/app/replay.go index 3f4c890..da08576 100644 --- a/internal/app/replay.go +++ b/internal/app/replay.go @@ -477,11 +477,12 @@ func (s *ReplayScreen) status(width int) string { fieldWidth := max(3, width-ansi.StringWidth(note)-1) parts = append(parts, note+" "+s.jump.edit.render(shellStyles(s.deps), fieldWidth)) } - // A part wider than the row is shortened here, with a mark, rather than - // clipped at the edge of the frame: the frame pulls a marked cut back to a - // whole word, and an unmarked one ends wherever the edge fell. - if a := s.analysisStatus(); a != "" { - parts = append(parts, truncateText(a, width)) + // The analysis arrives fitted to the row: brief gives up whole items before + // it cuts anything, and marks what it does cut, which the frame pulls back + // to a whole word. A part left wider than the row would be clipped at the + // edge of the frame instead, unmarked, wherever the edge fell. + if a := s.analysisStatus(width); a != "" { + parts = append(parts, a) } parts = append(parts, counter) if s.jump.open { diff --git a/internal/app/replay_analysis.go b/internal/app/replay_analysis.go index 021145c..10165b3 100644 --- a/internal/app/replay_analysis.go +++ b/internal/app/replay_analysis.go @@ -241,14 +241,14 @@ func (s *ReplayScreen) analysisLead(width int) int { return len(s.analysis.lead(width)) } -// analysisStatus is the analysis's part of the status line, and empty when no -// analysis belongs to the entry on screen. A terminal with no room for a panel -// has nowhere else to show it. -func (s *ReplayScreen) analysisStatus() string { - if !s.analysis.on(s.step()) { +// analysisStatus is the analysis's part of a status line width columns wide, +// and empty when no analysis belongs to the entry on screen. A terminal with +// no room for a panel has nowhere else to show it. +func (s *ReplayScreen) analysisStatus(width int) string { + if width <= 0 || !s.analysis.on(s.step()) { return "" } - return s.analysis.brief() + return s.analysis.brief(width) } // indicator is a running search in the fewest words: that it runs, and for @@ -258,26 +258,43 @@ func (a *replayAnalysis) indicator() string { gsSpinnerFrames[a.spinner%len(gsSpinnerFrames)], replaySeconds(a.elapsed)) } -// brief is the analysis in the few words a status line has room for. It keeps -// the qualification the panel spells out: a hole comes with its policy badge -// and with "not proven", the caveat as an item of its own after the pair, so a -// line cut short gives up the caveat before the badge — the same pair a game's -// status line keeps for a hint. -func (a *replayAnalysis) brief() string { +// brief is the analysis in the few words a status line width columns wide has +// room for. It keeps the qualification the panel spells out: a hole comes with +// its policy badge and with "not proven", the caveat as an item of its own +// after the pair — the same pair a game's status line keeps for a hint. +// +// A recommendation is fitted by giving up whole items before anything is cut: +// the caveat goes first, and the badge only when the hole alone is all that +// fits. The frame pulls a cut back to the last whole word before it, and a cut +// that fills the row exactly has no scrap of the separator in front of its +// mark to show where the pair ended: at twenty columns a four-character hole, +// AA10 on a wide board, came out as "AA10 placement-only…" and then as +// "AA10…", without the badge, though the pair fits with a column to spare. +// Every other state is one phrase with nothing in it to give up first, and is +// shortened with a mark. +func (a *replayAnalysis) brief(width int) string { r := a.result + var state string switch { case a.running: - return a.indicator() + state = a.indicator() case a.canceled: - return "analysis canceled" + state = "analysis canceled" case a.err != nil: - return "analysis failed" + state = "analysis failed" case r.Result.Over(): - return "game over: no move to advise" + state = "game over: no move to advise" case r.Recommended == nil: - return "engine returned no move" + state = "engine returned no move" + default: + hole := r.Recommended.String() + pair := hole + " " + r.Policy.Label() + if ansi.StringWidth(pair) > width { + return truncateText(hole, width) + } + return hintLine(width, pair, "not proven") } - return fmt.Sprintf("%s %s · not proven", *r.Recommended, r.Policy.Label()) + return truncateText(state, width) } // lead is the beginning of the block: the badge, and one sentence saying where diff --git a/internal/app/replay_analysis_test.go b/internal/app/replay_analysis_test.go index 2bfdd0e..71fcb38 100644 --- a/internal/app/replay_analysis_test.go +++ b/internal/app/replay_analysis_test.go @@ -14,6 +14,7 @@ import ( "time" tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" "github.com/BAKocska/twixtui/internal/bot" "github.com/BAKocska/twixtui/internal/game" @@ -815,6 +816,81 @@ func TestReplayAnalysisIsOnScreenAtEverySize(t *testing.T) { } } +// TestReplayAnalysisStatusKeepsTheBadgeBesideALongHole puts the longest name a +// hole can have — four characters, a column past Z on a row past 9 — on the +// bottom row at every size a review has to work in. The row gives up "not +// proven" before the badge, and the badge only when the hole alone is all that +// fits, so wherever the hole and its badge fit both are there whole, and +// nothing on the row is a piece of either. At 20x8 the row once read "AA10…": +// the brief was cut to exactly the width, the frame pulled the cut back to the +// last whole word, and the badge went with it, though "AA10 placement-only" is +// nineteen columns. +func TestReplayAnalysisStatusKeepsTheBadgeBesideALongHole(t *testing.T) { + rs := game.Std + rs.Size = 30 + hole := game.Point{Col: 26, Row: 9} + name := hole.String() + if len(name) != 4 || hole.Col >= rs.Size || hole.Row >= rs.Size { + t.Fatalf("%s is not a four-character hole of a %d-hole board", name, rs.Size) + } + if !slices.Contains(shellSizes, [2]int{20, 8}) { + t.Fatal("the sizes no longer include 20x8, where a cut brief filled the row exactly") + } + g := game.MustNew(rs) + for _, move := range []string{"D4", "F5"} { + if err := g.PlayNotation(move); err != nil { + t.Fatalf("playing %s: %v", move, err) + } + } + record, err := g.Record() + if err != nil { + t.Fatal(err) + } + sv := gamestore.Saved{ + ID: "replay-wide", Kind: gamestore.Imported, Player: "Vertical", + Opponent: "Horizontal", Side: "vertical", Record: record.Encode(), + } + pair := name + " placement-only" + whole := pair + " · not proven" + + for _, size := range shellSizes { + w, ht := size[0], size[1] + t.Run(fmt.Sprintf("%dx%d", w, ht), func(t *testing.T) { + eng := newRPAEngine() + h := rpaOpen(t, shellTestDeps(t), sv, eng.analyse) + h.feed(tea.WindowSizeMsg{Width: w, Height: ht}) + h.press("?") + move := hole + eng.next(t).answer <- rpaAnswer{result: bot.AnalysisResult{ + Policy: bot.PlacementOnlyPolicy(), + Recommended: &move, + Candidates: []bot.AnalysisCandidate{{Move: move, Score: 120, Bound: bot.BoundExact}}, + Headline: "the headline the engine wrote", + Highlight: []game.Point{move}, + Stats: &bot.SearchStats{Nodes: 4321, Depth: 3, Elapsed: 1500 * time.Millisecond, StopReason: "time"}, + }} + h.waitFor("the analysis", func() bool { return h.answered == 1 }) + + frame := h.frame() + shellAssertFits(t, "replay with a four-character hole", frame, w, ht) + lines := strings.Split(frame, "\n") + bottom := lines[len(lines)-1] + if !strings.Contains(bottom, name) { + t.Fatalf("at %dx%d the bottom row %q lost the hole", w, ht, bottom) + } + if ansi.StringWidth(pair) <= w && !strings.Contains(bottom, pair) { + t.Fatalf("at %dx%d the bottom row %q lost the badge, though %q fits", w, ht, bottom, pair) + } + if ansi.StringWidth(whole) <= w && !strings.Contains(bottom, whole) { + t.Fatalf("at %dx%d the bottom row %q gave up the caveat, though %q fits", w, ht, bottom, whole) + } + if strings.Contains(bottom, ellipsis) { + t.Fatalf("at %dx%d the bottom row %q was cut rather than giving up whole items", w, ht, bottom) + } + }) + } +} + // TestReplayAnalysisTakesOnlyTheAnswerItIsWaitingFor holds two searches at // once. The player asks, moves on or stops the search, and asks again; the // first search answers while the second is still running. That answer is for From d9fab78de48d266ff54ebaf63a1fa2c3c00085ff Mon Sep 17 00:00:00 2001 From: BAK Date: Mon, 28 Sep 2026 15:58:33 +0200 Subject: [PATCH 4/5] test(e2e): assert departures on settled frames A positive marker from the next screen can be captured while the previous screen's rows are still being repainted, which made a macOS runner see the replay footer under the menu. The negative checks now read the frame once it has settled. --- internal/e2e/progress_test.go | 9 +++++++-- internal/e2e/replay_analysis_test.go | 10 ++++++++-- internal/e2e/study_test.go | 25 ++++++++++++++++--------- 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/internal/e2e/progress_test.go b/internal/e2e/progress_test.go index bb18b0b..938d33e 100644 --- a/internal/e2e/progress_test.go +++ b/internal/e2e/progress_test.go @@ -106,7 +106,11 @@ func TestPlayNowCutsAMaxSearchShort(t *testing.T) { case shown == 0: t.Logf("no completed depth showed within %s; the move was announced as %q", maxBudget*2/5, found[0]) } - after := tm.MustWaitFor("vertical to move", 10*time.Second) + // The frame the turn line first appears in can be one the terminal has + // only part of, with the thinking line still on the rows the repaint has + // not reached, so the engine is looked for once the screen has settled. + tm.MustWaitFor("vertical to move", 10*time.Second) + after := tm.WaitSettled(10 * time.Second) if strings.Contains(after, "is thinking") { t.Fatalf("the engine is still thinking after its move was played:\n%s", after) } @@ -116,7 +120,8 @@ func TestPlayNowCutsAMaxSearchShort(t *testing.T) { // arrive as one alt-modified key, which is why the move was waited for // first. tm.SendKeys("i") - stats := tm.MustWaitFor("nodes", 10*time.Second) + tm.MustWaitFor("nodes", 10*time.Second) + stats := tm.WaitSettled(10 * time.Second) var line string for _, l := range strings.Split(stats, "\n") { if strings.Contains(l, "nodes") { diff --git a/internal/e2e/replay_analysis_test.go b/internal/e2e/replay_analysis_test.go index 03b419e..15e810f 100644 --- a/internal/e2e/replay_analysis_test.go +++ b/internal/e2e/replay_analysis_test.go @@ -57,7 +57,12 @@ func TestReplayAnalysisFromTheMenu(t *testing.T) { tm.SendKeys("Enter") tm.MustWaitFor("Tester vs max bot", 20*time.Second) tm.SendKeys("Enter") - end := tm.MustWaitFor("step 7 of 7", 20*time.Second) + // The frame a marker first appears in can be one the terminal has only + // part of: the rows the repaint has not reached yet still hold the screen + // before it. A marker says the new screen has begun, and what else is on it + // is read once the screen has settled. + tm.MustWaitFor("step 7 of 7", 20*time.Second) + end := tm.WaitSettled(10 * time.Second) if status := lbStatusLine(end); !strings.Contains(status, "? analyse") { t.Fatalf("the replay's status line %q does not offer the analysis key:\n%s", status, end) } @@ -104,7 +109,8 @@ func TestReplayAnalysisFromTheMenu(t *testing.T) { } tm.SendKeys("q") - back := tm.MustWaitFor("Watch a finished game", 20*time.Second) + tm.MustWaitFor("Watch a finished game", 20*time.Second) + back := tm.WaitSettled(10 * time.Second) if strings.Contains(back, "step 5 of 7") { t.Fatalf("q did not leave the replay:\n%s", back) } diff --git a/internal/e2e/study_test.go b/internal/e2e/study_test.go index 108acd2..47180aa 100644 --- a/internal/e2e/study_test.go +++ b/internal/e2e/study_test.go @@ -53,7 +53,12 @@ func TestStudyNoteSurvivesLeavingAndResizing(t *testing.T) { t.Fatalf("two steps down did not reach Watch a finished game:\n%s", screen) } tm.SendKeys("Enter") - chooser := tm.MustWaitFor("Tester vs Rival", 20*time.Second) + // The frame a marker first appears in can be one the terminal has only + // part of: the rows the repaint has not reached yet still hold the screen + // before it. A marker says the new screen has begun, and what else is or is + // not on it is read once the screen has settled. + tm.MustWaitFor("Tester vs Rival", 20*time.Second) + chooser := tm.WaitSettled(10 * time.Second) if strings.Contains(chooser, "step 17 of 17") { t.Fatalf("the watch list was skipped:\n%s", chooser) } @@ -76,17 +81,20 @@ func TestStudyNoteSurvivesLeavingAndResizing(t *testing.T) { tm.SendKeys("e") tm.MustWaitFor("note on entry 4", 10*time.Second) tm.SendText(snNote) - typed := tm.MustWaitFor(snNote, 10*time.Second) + tm.MustWaitFor(snNote, 10*time.Second) + typed := tm.WaitSettled(10 * time.Second) if !strings.Contains(typed, "step 4 of 17") || !tm.Alive() { t.Fatalf("typing the note moved or left the review:\n%s", typed) } tm.SendKeys("Enter") - noted := tm.MustWaitFor("note: "+snNote, 10*time.Second) + tm.MustWaitFor("note: "+snNote, 10*time.Second) + noted := tm.WaitSettled(10 * time.Second) if strings.Contains(noted, "note on entry 4") { t.Fatalf("the note input is still open after saving:\n%s", noted) } tm.SendKeys("m") - marked := tm.MustWaitFor("bookmarked", 10*time.Second) + tm.MustWaitFor("bookmarked", 10*time.Second) + marked := tm.WaitSettled(10 * time.Second) row := regexp.MustCompile(`>\s*4\s+\*#\s+h:draw\?`) if !row.MatchString(marked) { t.Fatalf("the list does not mark entry 4 with its bookmark and note:\n%s", marked) @@ -98,19 +106,18 @@ func TestStudyNoteSurvivesLeavingAndResizing(t *testing.T) { // Leaving a screen opened from the menu drops the menu's open form, so // escape lands on the front list with Watch still highlighted, and the // list of finished games is chosen again from there. - tm.WaitSettled(10 * time.Second) tm.SendKeys("Escape") - menu := tm.MustWaitFor("> Watch a finished game", 10*time.Second) + tm.MustWaitFor("> Watch a finished game", 10*time.Second) + menu := tm.WaitSettled(10 * time.Second) if strings.Contains(menu, "step 4 of 17") { t.Fatalf("escape did not leave the review:\n%s", menu) } - tm.WaitSettled(10 * time.Second) tm.SendKeys("Enter") - chooser = tm.MustWaitFor("Tester vs Rival", 20*time.Second) + tm.MustWaitFor("Tester vs Rival", 20*time.Second) + chooser = tm.WaitSettled(10 * time.Second) if strings.Contains(chooser, "step 17 of 17") { t.Fatalf("the watch list was skipped on the way back:\n%s", chooser) } - tm.WaitSettled(10 * time.Second) tm.SendKeys("Enter") tm.MustWaitFor("step 17 of 17", 20*time.Second) reopened := tm.WaitSettled(10 * time.Second) From 3317f2768f70635ee15db82eafbdea8fdf857304 Mon Sep 17 00:00:00 2001 From: BAK Date: Mon, 28 Sep 2026 15:58:33 +0200 Subject: [PATCH 5/5] docs: describe notes, replay analysis and play now on the front pages --- README.md | 4 ++-- web/index.html | 20 ++++++++++++-------- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 008ee27..91ac67b 100644 --- a/README.md +++ b/README.md @@ -91,12 +91,12 @@ twixtui help # every command, with what | | | | --- | --- | -| [Play a bot](docs/MANUAL.md#playing-a-bot) | Four effort tiers: `beginner`, `intermediate`, a clock-bounded `pro`, and `max`, the largest effort on offer. Hints use `max`'s placement-only search under a two-second guard: advice, not a proof of best play. | +| [Play a bot](docs/MANUAL.md#playing-a-bot) | Four effort tiers: `beginner`, `intermediate`, a clock-bounded `pro`, and `max`, the largest effort on offer. Hints use `max`'s placement-only search under a two-second guard: advice, not a proof of best play. While the bot thinks, its completed depth is shown and `esc` makes it play now. | | [Hotseat](docs/MANUAL.md#hotseat) | Two players, one terminal, alternating turns. | | [Remote play](docs/MANUAL.md#remote-play) | Direct, through a relay you or your opponent runs, or by correspondence with no live connection at all. | | [Learn it](docs/MANUAL.md#the-tutorial) | Seven lessons taught by playing them, and a five-step introduction on [first run](docs/MANUAL.md#the-first-run). | | [Profiles & standings](docs/MANUAL.md#profiles) | Local names with no passwords, selectable [standings and player histories](docs/MANUAL.md#the-leaderboard), and verified links back to saved-game replays. | -| [Review a game](docs/MANUAL.md#reviewing-saved-games) | A numbered entry list, `:` to jump to an entry, and the winning chain highlighted at the final position. Read-only, including imported records. | +| [Review a game](docs/MANUAL.md#reviewing-saved-games) | A numbered entry list, `:` to jump to an entry, the winning chain at the final position, `?` for a bounded engine reading of the entry on screen, and bookmarks and one-line notes (`m`, `e`) kept beside the game. Records, including imported ones, are never changed. | | [Analyse a position](docs/MANUAL.md#position-analysis) | Read-only analysis of a saved game, record or move list, with time/node budgets, explicit score bounds, and text or JSON output. | | [Honest rulesets](docs/MANUAL.md#rulesets) | `std`, `pp` and `classic` make each historical disagreement an explicit setting; boards from 6×6 to 48×48. | | [Themes & cover art](docs/MANUAL.md#themes) | Four colour schemes, and the [1962 box lid](docs/MANUAL.md#the-cover) drawn beside the menu in character cells. | diff --git a/web/index.html b/web/index.html index 64a9915..b7f5c55 100644 --- a/web/index.html +++ b/web/index.html @@ -102,7 +102,9 @@

A bot at four efforts

it marks the move and explains its placement-only search, keeping offered links and searching neither link edits nor swaps. Route estimates are heuristic advice, not a proof of - a draw, an impossible win or the best legal move. + a draw, an impossible win or the best legal move. While the bot + thinks you see the depth it has completed, and + esc makes it play now.

  • @@ -131,15 +133,17 @@

    Review a saved game

    Follow the numbered entry list, press : to jump directly to an entry, and see the winning chain at the final position. Draw offers have their own entries; entry zero is - the opening board. Imported games are reviewable without - changing their records or ratings. + the opening board. Bookmark an entry with m and + write a one-line note on it with e; notes are kept + beside the game, never in its record. Imported games are + reviewable without changing their records or ratings.

    - For an engine reading, use twixtui analyze on a - saved game, record or move list. Time or node budgets keep the - search bounded; text and JSON output distinguish measured scores, - upper bounds and unscored fallbacks. This is placement-only - advice, not a proof of the best legal move. + For an engine reading, press ? on the entry on + screen, or use twixtui analyze on a saved game, + record or move list. Both are bounded searches that distinguish + measured scores, upper bounds and unscored fallbacks; this is + placement-only advice, not a proof of the best legal move.