diff --git a/.github/scripts/test-windows.ps1 b/.github/scripts/test-windows.ps1 index 3af846b..d8ee57d 100644 --- a/.github/scripts/test-windows.ps1 +++ b/.github/scripts/test-windows.ps1 @@ -75,6 +75,7 @@ $required = @( 'TestAnalyzeRefusalsDoNotWriteState', 'TestAnalyzeDoesNotRedirectAnUnreadableExactGame', 'TestPlayNowCutsAMaxSearchShort', + 'TestReplayAnalysisFromTheMenu', 'TestStudyNoteSurvivesLeavingAndResizing' ) $missing = @($required | Where-Object { -not $passes.ContainsKey($_) }) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81ce96d..448c0f5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -23,6 +23,17 @@ project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). move: completed depth, nodes and time in all, and stop reason. A status line too narrow for all of them gives up whole items, the stop reason before the time and the nodes, and always keeps the move and its completed depth. +- `?` 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. 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. - Study notes and bookmarks in the replay viewer: `m` bookmarks the selected entry and `e` writes a one-line note on it, shown in the panel and marked in the entry list with `*` and `#`. They are kept per game, record digest and 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/docs/MANUAL.md b/docs/MANUAL.md index 7893f10..0848b1e 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. Otherwise, while a bot is searching for its move: play now, with the search it has finished. | | `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)). | | `i` | In a bot game: the figures of the search behind the bot's last move. Offered once the bot has moved, and not while it is searching. | | `s` | Take the swap option, while it is on offer. | | `d` | Offer a draw, or accept the one on offer. | @@ -349,9 +349,10 @@ reopening the saved game. `ctrl+c` still ends the whole program, even when The replay viewer reuses the movement keys above for stepping through a record and adds keys of its own, listed under [Reviewing saved games](#reviewing-saved-games): -`:` jumps to an entry, `m` bookmarks the selected entry and `e` writes a note on -it. While a note is being written every printable key is text, and the key -bound to `enter` above is the one that saves it. +`:` jumps to an entry, `m` bookmarks the selected entry, `e` writes a note on +it and `?` analyses it (the `?` row above). While a note is being written every +printable key is text, `?` included, and the key bound to `enter` above is the +one that saves it. ## Playing a bot @@ -901,6 +902,7 @@ shows both the entry counter and the number of moves played. | `:` | Type an entry number; `enter` jumps and `esc` cancels the input. | | `m` | Bookmark the selected entry, or take its bookmark off. Saved at once. | | `e` | Write or edit the selected entry's note; `enter` saves and `esc` cancels without saving. | +| `?` | 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 or a note. | | `ctrl+c` | End the program. | @@ -919,8 +921,53 @@ 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. Variations -are not part of this viewer; engine analysis is available through the -separate `analyze` commands below, not as an interactive replay action. +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; only the notes come +before them — an open note input, a refusal, or the first lines of the selected +entry's bookmark and note (see [Notes and bookmarks](#notes-and-bookmarks)). 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 — after any refusal from +the notes and before the entry counter and the keys, and on a terminal too +small for a panel it is 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**; +- 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: an analysis is not kept in the notes. +It is not run in the background while stepping; results are not kept between +seeks. #### Notes and bookmarks @@ -935,9 +982,9 @@ marked entries a column of their own once any exist: `*` for a bookmark and `#` for a note, as characters rather than colours. A note is one line of at most 8 KiB of UTF-8; a longer paste is refused whole rather than cut, and line breaks in a paste become spaces. While the note input is open every printable -key is text, so `q`, `h` or `:` are typed rather than acted on. Text read from -the file is drawn inert: control characters and escape sequences are shown as -plain text or dropped, never obeyed, and a note written with line breaks by +key is text, so `q`, `h`, `:` or `?` are typed rather than acted on. Text read +from the file is drawn inert: control characters and escape sequences are shown +as plain text or dropped, never obeyed, and a note written with line breaks by another program keeps them unless you edit them away. Notes are attached to the record's digest as well as to the game ID, and the @@ -966,7 +1013,9 @@ damaged file, and the file is left as it was. 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 diff --git a/internal/app/replay.go b/internal/app/replay.go index 671a194..486e43f 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 // notes are the player's notes and bookmarks on this game's entries, and // the note input while one is being written. See replay_study.go. notes replayNotes @@ -201,7 +206,8 @@ var replayKeys = []replayKey{ {ui.ActEdgeBottom, nil, "ends", func(s *ReplayScreen) tea.Cmd { s.seek(s.entries()); return nil }}, {ui.ActNone, []string{"m"}, "mark", func(s *ReplayScreen) tea.Cmd { s.toggleBookmark(); return nil }}, {ui.ActNone, []string{"e"}, "note", func(s *ReplayScreen) tea.Cmd { s.openNoteEditor(); 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 @@ -275,6 +281,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) { @@ -299,6 +309,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 } @@ -388,6 +402,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 @@ -431,6 +449,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) @@ -452,19 +476,20 @@ 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 an open input is drawn here as well as there, and what is wrong with a -// number, or what the notes refused, comes before the counter and the keys, -// which are what a narrow line gives up first. +// so an open input and the analysis are drawn here as well as there, and what +// is wrong with a number, or what the notes refused, comes before the analysis, +// the counter and the keys, which a narrow line gives up from the end. 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) + parts := make([]string, 0, len(s.hints)+4) hints := s.hints switch { case s.jump.open: @@ -482,6 +507,13 @@ func (s *ReplayScreen) status(width int) string { if note := s.studyStatus(); note != "" { parts = append(parts, truncateText(note, 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) return hintLine(width, append(parts, hints...)...) } @@ -494,7 +526,10 @@ func (s *ReplayScreen) status(width int) string { // every row on titles and results would leave a review with nothing to review. // The study block comes next: it is built for every row the list leaves it and // sets aside the rows it needs, so an open note input or a refusal is drawn -// whole wherever there is room for it, and the prose has what is left. +// whole wherever there is room for it. An analysis the player has asked for is +// promised its lead after that, 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. The prose has what is left. func (s *ReplayScreen) panel(width, height int) []string { if width <= 0 || height <= 0 { return nil @@ -504,14 +539,38 @@ func (s *ReplayScreen) panel(width, height int) []string { out = append(out, clampLines(s.jump.lines(shellStyles(s.deps), width), height)...) list := s.listShare(height) study := s.studyLines(width, s.studyRoom(width, height)) - if room := height - len(out) - list - s.studyReserve(width, study); room > 1 { + kept := s.studyReserve(width, study) + // 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 - kept - reserve; room > 1 { out = append(out, clampLines(s.describe(width), room-1)...) out = append(out, "") } if room := height - len(out) - list; room > 1 && len(study) > 0 { - out = append(out, cutRows(study, room-1, width)...) + // The block is drawn in every row it set aside, even where that leaves + // the analysis's lead none: an open note input sets aside all of its + // rows, and they are the studyRoom a stale note's save is judged on + // (storedOnScreen), so an input drawn in fewer would let a save replace + // a note the player never saw whole. Rows the prose left beyond both + // reserves go to the block, and what it does not use to the analysis. + out = append(out, cutRows(study, max(room-reserve, kept)-1, width)...) 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..10165b3 --- /dev/null +++ b/internal/app/replay_analysis.go @@ -0,0 +1,453 @@ +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 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(width) +} + +// 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 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: + state = a.indicator() + case a.canceled: + state = "analysis canceled" + case a.err != nil: + state = "analysis failed" + case r.Result.Over(): + state = "game over: no move to advise" + case r.Recommended == nil: + 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 truncateText(state, width) +} + +// 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..71fcb38 --- /dev/null +++ b/internal/app/replay_analysis_test.go @@ -0,0 +1,1053 @@ +package app + +import ( + "context" + "errors" + "fmt" + "io/fs" + "maps" + "path/filepath" + "slices" + "strconv" + "strings" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "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) + }) + } + }) + } +} + +// 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 +// 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_compose_test.go b/internal/app/replay_compose_test.go new file mode 100644 index 0000000..d71574b --- /dev/null +++ b/internal/app/replay_compose_test.go @@ -0,0 +1,331 @@ +package app + +import ( + "bytes" + "slices" + "strconv" + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + "github.com/charmbracelet/x/ansi" + + "github.com/BAKocska/twixtui/internal/study" + "github.com/BAKocska/twixtui/internal/ui" +) + +// These are the seams between the replay's notes and its analysis: two +// features that each hold the status line, the panel's spare rows and the +// keyboard, written apart and composed in one screen. Each feature's own tests +// run with the other one idle; these run both at once. + +// rpcEntry is the entry the fixtures keep a note, a bookmark and an analysis on, +// and rpcNote the note. Its words appear nowhere else on a replay's screen, so +// finding them is finding the note. +const ( + rpcEntry = 9 + rpcNote = "knot-at-nine" +) + +// rpcAt opens rpConnectionRecord with a study store, a note and a bookmark +// already stored on rpcEntry, and the stand-in engine, and goes to rpcEntry by +// its number. +func rpcAt(t *testing.T) (*rpaHarness, *rpaEngine, Deps, study.Target) { + t.Helper() + d := snDeps(t) + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + if _, err := study.Open(d.ConfigDir).Set(target, 0, study.Mark{Entry: rpcEntry, Bookmark: true, Note: rpcNote}); err != nil { + t.Fatal(err) + } + eng := newRPAEngine() + h := rpaOpen(t, d, sv, eng.analyse) + rpJump(t, h.s, strconv.Itoa(rpcEntry)) + if h.s.step() != rpcEntry { + t.Fatalf("the jump reached step %d, want %d", h.s.step(), rpcEntry) + } + return h, eng, d, target +} + +// rpcAnalysed asks for an analysis of the entry on screen and has the stand-in +// engine answer it with rpaFixture. +func rpcAnalysed(t *testing.T, h *rpaHarness, eng *rpaEngine) { + t.Helper() + h.press("?") + eng.next(t).answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.s.analysis.done }) + if !h.s.analysis.shown(h.s.step()) { + t.Fatalf("the analysis of step %d is not shown:\n%s", h.s.step(), h.block()) + } +} + +// rpcPanel is the panel as View lays it out for the size the screen was last +// given, and nil where that size has no panel. +func rpcPanel(s *ReplayScreen) (ui.Arrangement, []string) { + arr := ui.Arrange(s.width, s.height, s.current().Size()) + if arr.TooSmall || arr.Panel == ui.PanelNone { + return arr, nil + } + return arr, s.panel(arr.PanelW, arr.PanelH) +} + +// rpcBottom is the frame's last row, the status line. +func rpcBottom(frame string) string { + lines := strings.Split(frame, "\n") + return lines[len(lines)-1] +} + +// TestReplayComposeNotesAndAnalysisShareEveryFrame puts a note, a bookmark and +// a finished analysis on one entry and draws it at every size a review has to +// work in. The frame fits; the entry list keeps its promised rows and the row +// under review, with its marks, is drawn; the status line carries the analysis +// at every size, which at the smallest, with no panel, is the only place it +// is; and wherever the panel is beside the board it has room for the bookmark, +// the note and the analysis's choice all at once. +func TestReplayComposeNotesAndAnalysisShareEveryFrame(t *testing.T) { + h, eng, _, _ := rpcAt(t) + rpcAnalysed(t, h, eng) + pair := rpaMove.String() + " placement-only" + + var panelless, beside int + for _, size := range shellSizes { + w, ht := size[0], size[1] + h.feed(tea.WindowSizeMsg{Width: w, Height: ht}) + frame := h.frame() + shellAssertFits(t, "replay with a note and an analysis", frame, w, ht) + if bottom := rpcBottom(frame); !strings.Contains(bottom, pair) { + t.Errorf("at %dx%d the bottom row %q does not carry the analysis %q", w, ht, bottom, pair) + } + + arr, panel := rpcPanel(h.s) + if panel == nil { + panelless++ + continue + } + all := strings.Join(panel, "\n") + if len(panel) > arr.PanelH { + t.Errorf("at %dx%d the %d-row panel produced %d lines:\n%s", w, ht, arr.PanelH, len(panel), all) + } + for _, l := range panel { + if lw := ansi.StringWidth(l); lw > arr.PanelW { + t.Errorf("at %dx%d the %d-cell panel has a line %d cells wide: %q", w, ht, arr.PanelW, lw, l) + } + } + rows := snRows(t, panel, 2) + if want := min(arr.PanelH/2, h.s.entries()+1); len(rows) < want { + t.Errorf("at %dx%d the panel shows %d entry rows, want at least %d:\n%s", w, ht, len(rows), want, all) + } + var marked []string + for _, l := range panel { + if r := snRows(t, []string{l}, 2); len(r) == 1 && r[0].marked { + if r[0].number != rpcEntry || !r[0].bookmark || !r[0].noted { + t.Errorf("at %dx%d the row under review is %+v, want entry %d with its bookmark and note", w, ht, r[0], rpcEntry) + } + marked = append(marked, l) + } + } + if len(marked) != 1 { + t.Errorf("at %dx%d the list marks %d rows, want exactly one:\n%s", w, ht, len(marked), all) + continue + } + if !strings.Contains(frame, marked[0]) { + t.Errorf("at %dx%d the panel builds the row under review %q and the frame does not draw it:\n%s", w, ht, marked[0], frame) + } + if arr.Panel == ui.PanelSide { + beside++ + for _, want := range []string{bookmarkGlyph + " bookmarked", rpcNote, "engine's choice"} { + if !strings.Contains(all, want) { + t.Errorf("at %dx%d the panel beside the board lost %q:\n%s", w, ht, want, all) + } + } + } + } + if panelless == 0 || beside == 0 { + t.Fatalf("the sizes gave %d frames without a panel and %d with one beside the board; both kinds are needed", panelless, beside) + } +} + +// TestReplayComposeNoteInputOwnsTheAnalysisKey types the analysis key into an +// open note, with the other keys a review answers around it. While the input +// is open every one of them is text: nothing is analysed, marked, left or +// moved, and escape leaves the stored note as it was. Outside the input the +// same key does start an analysis, so the press inside it was taken by the +// input rather than ignored by the screen. +func TestReplayComposeNoteInputOwnsTheAnalysisKey(t *testing.T) { + h, eng, d, target := rpcAt(t) + h.press("e") + if !h.s.notes.editor.open { + t.Fatalf("e did not open the note input:\n%s", h.frame()) + } + h.s.Update(tutorialKeyMsg("ctrl+u")) + const typed = "?mq:h" + snType(t, h.s, typed) + if got := h.s.notes.editor.edit.value(); got != typed { + t.Fatalf("the note input holds %q after %q was typed into it", got, typed) + } + if h.s.analysis.job != nil || h.s.analysis.running { + t.Fatal("a ? typed into the note started an analysis") + } + + h.press("esc") + if h.s.notes.editor.open { + t.Fatal("esc did not close the note input") + } + snAssertMarks(t, snLoad(t, d, target), study.Mark{Entry: rpcEntry, Bookmark: true, Note: rpcNote}) + + h.press("?") + eng.next(t).answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the analysis", func() bool { return h.s.analysis.done }) + if !h.s.analysis.shown(rpcEntry) { + t.Fatalf("? outside the note input did not analyse the entry:\n%s", h.block()) + } +} + +// TestReplayComposeSeekCancelsTheAnalysisAndFollowsTheNotes moves on from an +// entry with a note, a bookmark and a search still running. The search is +// cancelled and nothing of it is left on screen, and the study block follows +// the review: the next entry has no note and no bookmark, so none is shown, +// while the list still marks the entry that has them. Coming back shows the +// note again, and not the analysis, which moving put away for good. +func TestReplayComposeSeekCancelsTheAnalysisAndFollowsTheNotes(t *testing.T) { + h, eng, _, _ := rpcAt(t) + h.press("?") + call := eng.next(t) + h.press("l") + if h.s.step() != rpcEntry+1 { + t.Fatalf("l reached step %d, want %d", h.s.step(), rpcEntry+1) + } + if call.ctx.Err() == nil { + t.Fatal("moving on left the search of the entry before running") + } + if h.s.analysis.job != nil { + t.Fatal("the screen still holds an analysis of the entry it left") + } + + _, panel := rpcPanel(h.s) + all := strings.Join(panel, "\n") + for _, gone := range []string{rpcNote, "bookmarked", "analysing", "? cancels"} { + if strings.Contains(all, gone) { + t.Errorf("at step %d the panel still shows %q:\n%s", h.s.step(), gone, all) + } + } + if bottom := rpcBottom(h.frame()); strings.Contains(bottom, "analysing") { + t.Errorf("at step %d the bottom row still reports the search: %q", h.s.step(), bottom) + } + rows := snRows(t, panel, 2) + row := func(n int) snRow { + t.Helper() + i := slices.IndexFunc(rows, func(r snRow) bool { return r.number == n }) + if i < 0 { + t.Fatalf("the list has no row for entry %d:\n%s", n, all) + } + return rows[i] + } + if here := row(rpcEntry + 1); !here.marked || here.bookmark || here.noted { + t.Errorf("the row under review is %+v, want entry %d marked and without a bookmark or a note", here, rpcEntry+1) + } + if there := row(rpcEntry); there.marked || !there.bookmark || !there.noted { + t.Errorf("the row of entry %d is %+v, want it unmarked with its bookmark and note", rpcEntry, there) + } + + call.answer <- rpaAnswer{result: rpaFixture()} + h.waitFor("the overtaken answer", func() bool { return h.answered == 1 }) + h.press("h") + if h.s.step() != rpcEntry { + t.Fatalf("h reached step %d, want %d", h.s.step(), rpcEntry) + } + frame := h.frame() + _, panel = rpcPanel(h.s) + all = strings.Join(panel, "\n") + if !strings.Contains(all, rpcNote) || !strings.Contains(all, "bookmarked") { + t.Errorf("back at step %d the panel lost the entry's note or bookmark:\n%s", rpcEntry, all) + } + if strings.Contains(frame, "engine's choice") || len(h.s.board.Highlights) != 0 { + t.Errorf("back at step %d the analysis put away by moving came back:\n%s", rpcEntry, frame) + } +} + +// TestReplayComposeStaleNoteBesideAnAnalysisIsReplacedOnlyWhenShownWhole is the +// refused save of the notes with an analysis of the same entry on screen, whose +// lead also asks the panel for rows. A second confirm is a choice between two +// versions only while the other window's note is in the frame whole, so at +// each size either every word of it is drawn and confirming again replaces it, +// or some word is not and confirming again leaves the file byte for byte as it +// was and the input holding what was typed. The sizes are the note test's: +// no panel, a panel too short for the note, and panels narrow enough to wrap +// it onto many rows. At least one of the sizes that show the note whole has to +// draw the analysis in the same panel, or the two never competed. +func TestReplayComposeStaleNoteBesideAnAnalysisIsReplacedOnlyWhenShownWhole(t *testing.T) { + const ( + entry = 4 + theirs = "theirs-1 theirs-2 theirs-3 theirs-4 theirs-5 theirs-6 theirs-7" + ) + sv := rpConnectionRecord(t) + target := snTarget(t, sv) + // unseen is the first word of the other note the frame does not show, or + // nothing when it shows all of them. + unseen := func(frame string) string { + for _, word := range strings.Fields(theirs) { + if !strings.Contains(frame, word) { + return word + } + } + return "" + } + var shown, hidden, alongside int + for _, size := range append(slices.Clone(shellSizes), [2]int{24, 30}, [2]int{20, 40}) { + w, ht := size[0], size[1] + d := snDeps(t) + path := snFile(d, sv.ID) + eng := newRPAEngine() + h := rpaOpen(t, d, sv, eng.analyse) + h.feed(tea.WindowSizeMsg{Width: w, Height: ht}) + rpJump(t, h.s, strconv.Itoa(entry)) + rpcAnalysed(t, h, eng) + if _, err := study.Open(d.ConfigDir).Set(target, 0, study.Mark{Entry: entry, Note: theirs}); err != nil { + t.Fatal(err) + } + stored := snBytes(t, path) + + h.press("e") + snType(t, h.s, "mine") + h.press("enter") + if !h.s.notes.editor.open { + t.Fatalf("at %dx%d a save refused as stale closed the note input", w, ht) + } + if !h.s.analysis.shown(entry) { + t.Fatalf("at %dx%d the note input put the analysis away", w, ht) + } + frame := h.frame() + shellAssertFits(t, "a stale note beside an analysis", frame, w, ht) + missing := unseen(frame) + _, panel := rpcPanel(h.s) + analysed := strings.Contains(strings.Join(panel, "\n"), "placement-only") + + h.press("enter") + if missing != "" { + hidden++ + if after := snBytes(t, path); !bytes.Equal(after, stored) { + t.Errorf("at %dx%d %q of the other note is not on screen, and a second save replaced it:\n%s", w, ht, missing, frame) + continue + } + if !h.s.notes.editor.open || h.s.notes.editor.edit.value() != "mine" { + t.Errorf("at %dx%d the refused save did not leave the input open holding what was typed", w, ht) + } + continue + } + shown++ + if analysed { + alongside++ + } + if h.s.notes.editor.open { + t.Errorf("at %dx%d the other note is on screen whole and the second save was refused:\n%s", w, ht, h.frame()) + continue + } + snAssertMarks(t, snLoad(t, d, target), study.Mark{Entry: entry, Note: "mine"}) + } + if shown == 0 || hidden == 0 || alongside == 0 { + t.Fatalf("the other note was on screen whole at %d sizes, %d of them beside the analysis, and not at %d; the test needs all three", + shown, alongside, hidden) + } +} diff --git a/internal/app/replay_study.go b/internal/app/replay_study.go index ca56bfc..cad52b3 100644 --- a/internal/app/replay_study.go +++ b/internal/app/replay_study.go @@ -314,9 +314,9 @@ func (s *ReplayScreen) studyReserve(width int, block []string) int { // studyRoom is how many rows the study block may take in a panel width cells // wide and height rows tall: every row above the entry list's promised share, // less the entry input's and the blank line that closes the block. The block -// is given its rows before the record's prose is given any, so these are the -// rows it is drawn in whenever it needs all of them, which is what lets a save -// be judged on whether they hold the stored note. +// is given its rows before the analysis's lead or the record's prose is given +// any, so these are the rows it is drawn in whenever it needs all of them, +// which is what lets a save be judged on whether they hold the stored note. func (s *ReplayScreen) studyRoom(width, height int) int { return height - len(s.jump.lines(shellStyles(s.deps), width)) - s.listShare(height) - 1 } 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 d2fcc1f..d8fd3da 100644 --- a/internal/cli/game.go +++ b/internal/cli/game.go @@ -169,7 +169,9 @@ 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. On a finished game, m bookmarks the entry on screen and e writes a note on it; notes are kept beside the game in -the configuration directory. Review never changes the saved record.`, +the configuration directory. 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/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 new file mode 100644 index 0000000..15e810f --- /dev/null +++ b/internal/e2e/replay_analysis_test.go @@ -0,0 +1,200 @@ +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") + // 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) + } + + // 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") + 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) + } + 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 +} 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) 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 @@
esc makes it play now.
: 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.