From cafb45b0a93dab29b0472250de129174b4a84160 Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Wed, 2 Dec 2026 15:31:44 -0500 Subject: [PATCH] Better handling of command history. --- docs/fenrir.1 | 64 +++++-- docs/user.md | 10 ++ docs/user.txt | 92 ++++++---- internal/app/commands.go | 5 +- internal/app/history_test.go | 101 +++++++++++ internal/input/history_test.go | 41 +++++ internal/input/router.go | 19 ++- internal/prompt/history_test.go | 29 ++++ internal/prompt/shell.go | 23 +++ internal/reader/application_override.go | 1 + internal/reader/changes.go | 23 ++- internal/reader/echo.go | 1 + internal/reader/history.go | 53 ++++++ internal/reader/history_test.go | 215 ++++++++++++++++++++++++ internal/reader/reader.go | 17 +- internal/reader/regions.go | 1 + tests/native_history.py | 103 ++++++++++++ 17 files changed, 742 insertions(+), 56 deletions(-) create mode 100644 internal/app/history_test.go create mode 100644 internal/input/history_test.go create mode 100644 internal/prompt/history_test.go create mode 100644 internal/reader/history.go create mode 100644 internal/reader/history_test.go create mode 100644 tests/native_history.py diff --git a/docs/fenrir.1 b/docs/fenrir.1 index 54514106..eebae9ab 100644 --- a/docs/fenrir.1 +++ b/docs/fenrir.1 @@ -1,4 +1,4 @@ -.\" Automatically generated by Pandoc 3.13 +.\" Automatically generated by Pandoc 3.14 .\" .TH "fenrir" "1" "" "" "Fenrir User Manual" .SH Fenrir User Manual @@ -215,6 +215,8 @@ Outside table mode, Fenrir+X places a text\-selection mark instead. .SS Speech and automatic reading .IP \(bu 2 \f[B]Control\f[R] interrupts speech. +By default, so does any other key except Shift, Alt, Super and AltGr +pressed by themselves. .IP \(bu 2 \f[B]Fenrir+F4\f[R] toggles mute. .IP \(bu 2 @@ -228,7 +230,41 @@ laptop, toggles automatic reading of new text. \f[B]Fenrir+Backspace\f[R] passes the next key through to the application. .PP +The \f[B]Keys that interrupt speech\f[R] setting in the Keyboard tab of +the Fenrir Menu chooses which keys typed into applications stop speech. +Cthulhu offers the same three choices with the same keys: +.IP \(bu 2 +\f[B]All keys interrupt\f[R], the default. +.IP \(bu 2 +\f[B]Control, Enter, Space, Escape, and arrow keys\f[R]. +Both Control keys and keypad Enter count; letters, Tab and Shift let +speech continue. +.IP \(bu 2 +\f[B]Define interruption keys\f[R]. +Activate \f[B]Record interruption keys\f[R], then press each key to +record it, including Tab, Enter, Space and Escape. +Press and release a modifier by itself to record it. +\f[B]Control+Enter\f[R] finishes and \f[B]Control+Escape\f[R] cancels; +recording replaces the previous keys. +The \f[B]Defined interruption keys\f[R] list shows the result. +Press \f[B]OK\f[R] to save. +.PP +Fenrir commands and keys pressed in the Fenrir Menu always interrupt +speech. +.PP Character echo, word echo, and cursor echo can be configured separately. +With automatic reading and cursor echo enabled in cursor tracking mode, +bare Up and Down read the whole recalled command when the application +replaces text on the same cursor row. +Similar commands are read in full even if only one character differs. +Recognized, unchanged shell prompts are omitted; unfamiliar prompts +remain part of the line so command text is not accidentally discarded. +Returning to an empty command is announced as \f[B]blank\f[R]. +Ordinary vertical navigation, application overrides, and reading\-region +filters retain their usual behavior. +Wrapped commands that move the cursor to another row use ordinary screen +reading. +.PP Punctuation levels are \f[CR]none\f[R], \f[CR]some\f[R], \f[CR]most\f[R], and \f[CR]all\f[R]. At \f[CR]some\f[R] and \f[CR]most\f[R], punctuation inside words, URLs, @@ -350,7 +386,7 @@ matching search intact. Start the application normally, then select its override. This menu does not launch programs. Choose \f[B]Default\f[R] to restore ordinary settings and clear the -current terminal's reading window and live regions. +current terminal\(cqs reading window and live regions. Overrides are never selected automatically or remembered across restarts. .PP @@ -437,8 +473,8 @@ Names are saved in lower case and may contain letters, numbers, dot, plus, underscore, and hyphen. The menu returns with the new profile selected. .PP -A new profile saves the current terminal's reading window and numbered -live regions when you confirm its name. +A new profile saves the current terminal\(cqs reading window and +numbered live regions when you confirm its name. It also saves application settings that differ from your saved ordinary settings. If there are no regions or customized settings, it is created empty and @@ -458,11 +494,11 @@ When updating a profile that is not active, current regions replace its saved regions if any are set; otherwise its saved regions are kept. Ordinary settings saves do not save regions. .PP -Saved regions load when you select the profile, including after restarting -Fenrir or importing profiles. -They keep their fixed row and column coordinates; regions outside a smaller -screen are clipped, and a single-mark region still extends to the end of -its line as the width changes. +Saved regions load when you select the profile, including after +restarting Fenrir or importing profiles. +They keep their fixed row and column coordinates; regions outside a +smaller screen are clipped, and a single\-mark region still extends to +the end of its line as the width changes. If a status bar moves to another row after resizing, redefine its region and save the profile again. .PP @@ -850,11 +886,11 @@ profile. A reading window restricts automatic reading to a rectangle. Live regions exclude changing areas from automatic speech while allowing explicit reading and progress monitoring. -Arrow-key navigation and confirmed Backspace/Delete feedback remain +Arrow\-key navigation and confirmed Backspace/Delete feedback remain available inside live regions. -Typed-character and word echo remain filtered there. -Selecting Default clears the current terminal's regions without deleting -the profile's saved definitions. +Typed\-character and word echo remain filtered there. +Selecting Default clears the current terminal\(cqs regions without +deleting the profile\(cqs saved definitions. .PP Outside table mode, place two marks with \f[B]Fenrir+X\f[R] to define opposite corners. @@ -1232,7 +1268,7 @@ opening devices \f[B]Purpose:\f[R] Write effective settings to a file and exit .RE .IP \(bu 2 -\f[B]\f[CB]\-i USER\f[B]\f[R], \f[B]\f[CB]\-\-import\-applications USER\f[B]\f[R] +\f[B]\f[CB]\-i USER\f[B], \f[CB]\-\-import\-applications USER\f[B]\f[R] .RS 2 \f[B]Purpose:\f[R] Copy USER\(cqs application profiles into this settings directory and exit diff --git a/docs/user.md b/docs/user.md index c43480dd..f9191f83 100644 --- a/docs/user.md +++ b/docs/user.md @@ -160,6 +160,16 @@ same three choices with the same keys: Fenrir commands and keys pressed in the Fenrir Menu always interrupt speech. Character echo, word echo, and cursor echo can be configured separately. +With automatic reading and cursor echo enabled in cursor tracking mode, +bare Up and Down read the whole recalled command when the application replaces +text on the same cursor row. Similar commands are read in full even if only one +character differs. Recognized, unchanged shell prompts are omitted; unfamiliar +prompts remain part of the line so command text is not accidentally discarded. +Returning to an empty command is announced as **blank**. Ordinary vertical +navigation, application overrides, and reading-region filters retain their +usual behavior. Wrapped commands that move the cursor to another row use +ordinary screen reading. + Punctuation levels are `none`, `some`, `most`, and `all`. At `some` and `most`, punctuation inside words, URLs, email addresses, and filenames is also named, without adding sentence pauses. diff --git a/docs/user.txt b/docs/user.txt index a93bee39..fff4614a 100644 --- a/docs/user.txt +++ b/docs/user.txt @@ -156,7 +156,8 @@ text-selection mark instead. Speech and automatic reading -- Control interrupts speech. +- Control interrupts speech. By default, so does any other key except + Shift, Alt, Super and AltGr pressed by themselves. - Fenrir+F4 toggles mute. - Keypad Enter on desktop temporarily silences speech. Speech can return on the next keypress or a newly recognized prompt or completion. @@ -164,7 +165,34 @@ Speech and automatic reading automatic reading of new text. - Fenrir+Backspace passes the next key through to the application. +The Keys that interrupt speech setting in the Keyboard tab of the Fenrir +Menu chooses which keys typed into applications stop speech. Cthulhu +offers the same three choices with the same keys: + +- All keys interrupt, the default. +- Control, Enter, Space, Escape, and arrow keys. Both Control keys and + keypad Enter count; letters, Tab and Shift let speech continue. +- Define interruption keys. Activate Record interruption keys, then + press each key to record it, including Tab, Enter, Space and Escape. + Press and release a modifier by itself to record it. Control+Enter + finishes and Control+Escape cancels; recording replaces the previous + keys. The Defined interruption keys list shows the result. Press OK to + save. + +Fenrir commands and keys pressed in the Fenrir Menu always interrupt +speech. + Character echo, word echo, and cursor echo can be configured separately. +With automatic reading and cursor echo enabled in cursor tracking mode, +bare Up and Down read the whole recalled command when the application +replaces text on the same cursor row. Similar commands are read in full +even if only one character differs. Recognized, unchanged shell prompts +are omitted; unfamiliar prompts remain part of the line so command text +is not accidentally discarded. Returning to an empty command is +announced as blank. Ordinary vertical navigation, application overrides, +and reading-region filters retain their usual behavior. Wrapped commands +that move the cursor to another row use ordinary screen reading. + Punctuation levels are none, some, most, and all. At some and most, punctuation inside words, URLs, email addresses, and filenames is also named, without adding sentence pauses. Apostrophes within words and @@ -250,9 +278,9 @@ search. Unmatched characters announce No matches and leave the last matching search intact. Start the application normally, then select its override. This menu does -not launch programs. Choose Default to restore ordinary settings and clear -the current terminal's reading window and live regions. Overrides are never -selected automatically or remembered across restarts. +not launch programs. Choose Default to restore ordinary settings and +clear the current terminal’s reading window and live regions. Overrides +are never selected automatically or remembered across restarts. To launch a program with its override, select its name in this list, then Tab to Copy alias to clipboard and press Enter. This copies a Bash @@ -318,11 +346,11 @@ and press Enter or activate Create. Names are saved in lower case and may contain letters, numbers, dot, plus, underscore, and hyphen. The menu returns with the new profile selected. -A new profile saves the current terminal's reading window and numbered -live regions when you confirm its name. It also saves application settings -that differ from your saved ordinary settings. If there are no regions or -customized settings, it is created empty and inherits ordinary settings -until you update it. +A new profile saves the current terminal’s reading window and numbered +live regions when you confirm its name. It also saves application +settings that differ from your saved ordinary settings. If there are no +regions or customized settings, it is created empty and inherits +ordinary settings until you update it. Update profile adds the current differences to the selected profile. Settings already in the profile are kept unless you have changed them @@ -330,17 +358,18 @@ again. Saving while the profile is active, with Fenrir+F or Fenrir+Control+S, also updates it. Saving or updating the active profile records its current reading window -and live regions, including cleared slots. Clearing regions and then saving -removes them from that profile. When updating a profile that is not active, -current regions replace its saved regions if any are set; otherwise its -saved regions are kept. Ordinary settings saves do not save regions. +and live regions, including cleared slots. Clearing regions and then +saving removes them from that profile. When updating a profile that is +not active, current regions replace its saved regions if any are set; +otherwise its saved regions are kept. Ordinary settings saves do not +save regions. -Saved regions load when you select the profile, including after restarting -Fenrir or importing profiles. They keep their fixed row and column -coordinates; regions outside a smaller screen are clipped, and a single-mark -region still extends to the end of its line as the width changes. If a -status bar moves to another row after resizing, redefine its region and -save the profile again. +Saved regions load when you select the profile, including after +restarting Fenrir or importing profiles. They keep their fixed row and +column coordinates; regions outside a smaller screen are clipped, and a +single-mark region still extends to the end of its line as the width +changes. If a status bar moves to another row after resizing, redefine +its region and save the profile again. Delete profile asks for confirmation; No has focus first. Deleting the active profile restores Default first. Built-in applications cannot be @@ -414,12 +443,12 @@ region reads: Fenrir+Shift+B lists these application assignments. Existing user regions are preserved and restored when the override ends automatically. -Selecting Default explicitly clears them. Review, Read Screen, and copying -continue to expose the actual terminal text, -including its literal X marks. Chat history is baselined on activation, -resize, buffer changes, and history paging to avoid announcing old -messages as new. Messages that appear and disappear between screen -captures cannot be recovered reliably. +Selecting Default explicitly clears them. Review, Read Screen, and +copying continue to expose the actual terminal text, including its +literal X marks. Chat history is baselined on activation, resize, buffer +changes, and history paging to avoid announcing old messages as new. +Messages that appear and disappear between screen captures cannot be +recovered reliably. The laptop shortcut for reading attributes is Fenrir+Shift+A; Fenrir+A opens Applications in both layouts. @@ -602,13 +631,12 @@ Reading windows and live regions Reading regions belong to the current terminal. They last for the reader session unless you save them in an application profile. A reading window -restricts automatic reading to a rectangle. -Live regions exclude changing areas from automatic speech while allowing -explicit reading and progress monitoring. Arrow-key navigation and -confirmed Backspace/Delete feedback remain available inside live regions. -Typed-character and word echo remain filtered there. Selecting Default -clears the current terminal's regions without deleting the profile's saved -definitions. +restricts automatic reading to a rectangle. Live regions exclude +changing areas from automatic speech while allowing explicit reading and +progress monitoring. Arrow-key navigation and confirmed Backspace/Delete +feedback remain available inside live regions. Typed-character and word +echo remain filtered there. Selecting Default clears the current +terminal’s regions without deleting the profile’s saved definitions. Outside table mode, place two marks with Fenrir+X to define opposite corners. Press Fenrir+Keypad Slash on desktop or Fenrir+Control+8 on diff --git a/internal/app/commands.go b/internal/app/commands.go index f582c18c..f5492607 100644 --- a/internal/app/commands.go +++ b/internal/app/commands.go @@ -44,7 +44,7 @@ func (a *application) handleInput(decision input.Decision) { return } diagnostic.Record("input decision", "command", decision.Command, "forward", decision.Forward, - "interrupt", decision.Interrupt, "keypress", decision.Keypress, "typing", decision.Typing, "deletion", decision.Deletion, + "interrupt", decision.Interrupt, "keypress", decision.Keypress, "typing", decision.Typing, "deletion", decision.Deletion, "history", decision.History, "ui_active", a.ui.active) interruptSpeech := a.interruptsSpeech(decision) if !decision.Interrupt && interruptSpeech { @@ -66,6 +66,9 @@ func (a *application) handleInput(decision input.Decision) { a.voice.Interrupt() } a.engine.NoteInput(decision.Forward && !a.ui.active, decision.Typing, decision.WordBoundary) + if decision.Forward && decision.History && !a.ui.active { + a.engine.NoteHistory() + } if decision.Forward && decision.Deletion && !a.ui.active { a.engine.NoteDeletion() } diff --git a/internal/app/history_test.go b/internal/app/history_test.go new file mode 100644 index 00000000..00623292 --- /dev/null +++ b/internal/app/history_test.go @@ -0,0 +1,101 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +package app + +import ( + "context" + "reflect" + "slices" + "testing" + "time" + + "git.stormux.org/storm/fenrir/internal/command" + "git.stormux.org/storm/fenrir/internal/config" + "git.stormux.org/storm/fenrir/internal/input" + "git.stormux.org/storm/fenrir/internal/screen" +) + +func TestHistoryThroughSharedRouter(t *testing.T) { + for _, key := range []uint16{input.KeyUp, input.KeyDown} { + for _, mode := range []string{"press", "repeat", "modified", "muted", "speech disabled", "automatic off", "cursor off", "menu"} { + t.Run(mode+"/"+map[uint16]string{input.KeyUp: "up", input.KeyDown: "down"}[key], func(t *testing.T) { + router, err := input.NewRouter(input.Layout{Bindings: []input.Binding{{Name: "Quit", Keys: []string{"FENRIR", "Q"}, Command: command.Quit}}}) + if err != nil { + t.Fatal(err) + } + before := "$ /ooc hello person2" + source := &fakeSource{snapshot: screen.Snapshot{Terminal: 1, Active: true, Rows: 1, Cols: 40, X: len(before), Cells: make([]rune, 40)}, events: make(chan error, 1)} + for index := range source.snapshot.Cells { + source.snapshot.Cells[index] = ' ' + } + copy(source.snapshot.Cells, []rune(before)) + keys := &fakeKeys{events: make(chan error, 1)} + voice := &fakeVoice{muted: mode == "speech disabled"} + reads, polls := 0, 0 + source.afterRead = func() { + reads++ + if reads == 2 { + keys.events <- nil + } + } + keys.poll = func(_ bool, handle func(input.Decision)) error { + polls++ + if polls == 1 { + if mode == "muted" { + handle(input.Decision{Command: command.Mute, Interrupt: true}) + } + if mode == "modified" { + handle(router.Key(0, input.KeyCtrl, 1, false, false)) + } + if mode == "menu" { + handle(input.Decision{Command: command.FenrirMenu, Interrupt: true}) + } + if mode == "repeat" { + _ = router.Key(0, key, 1, false, false) + handle(router.Key(0, key, 2, false, false)) + } else { + handle(router.Key(0, key, 1, false, false)) + } + // Real application redraws can arrive after key release. + handle(router.Key(0, key, 0, false, false)) + voice.messages = nil + source.snapshot.Cells = slices.Clone(source.snapshot.Cells) + copy(source.snapshot.Cells, []rune("$ /ooc hello person1")) + source.events <- nil + } else { + handle(input.Decision{Command: command.Quit}) + } + return nil + } + settings := config.Defaults() + settings.Reading.Automatic = mode != "automatic off" + settings.Reading.CursorEcho = mode != "cursor off" + settings.Presentation.Speech.Enabled = mode != "speech disabled" + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := run(ctx, source, keys, voice, nil, RunOptions{Settings: settings}); err != nil || reads != 2 { + t.Fatal(err, reads) + } + var want []string + switch mode { + case "press", "repeat": + want = []string{"/ooc hello person1"} + case "modified", "cursor off": + want = []string{"1"} + case "menu": + // Menu loading is asynchronous; only assert that it owns input. + for _, text := range voice.messages { + if text == "/ooc hello person1" || text == "1" { + t.Fatal("history escaped active menu", voice.messages) + } + } + return + } + if !reflect.DeepEqual(voice.messages, want) { + t.Fatal("history routing or speech policy", voice.messages, want) + } + }) + } + } +} diff --git a/internal/input/history_test.go b/internal/input/history_test.go new file mode 100644 index 00000000..cc79032b --- /dev/null +++ b/internal/input/history_test.go @@ -0,0 +1,41 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +package input + +import "testing" + +func TestHistoryMetadataOnlyForForwardedBareArrows(t *testing.T) { + for _, key := range []uint16{KeyUp, KeyDown} { + router := desktopRouter(t) + for _, value := range []int32{1, 2} { + got := router.Key(0, key, value, false, false) + if !got.Forward || !got.History || !got.Interrupt || got.Typing || got.Deletion { + t.Fatal("history press/repeat metadata", key, value, got) + } + } + if got := router.Key(0, key, 2, false, true); got.History || got.Interrupt { + t.Fatal("state sync became history", got) + } + if got := router.Key(0, key, 0, false, false); !got.Forward || got.History { + t.Fatal("history release changed", got) + } + for _, modifier := range []uint16{KeyCtrl, KeyRightCtrl, KeyAlt, KeyRightAlt, KeyShift, KeyRightShift, KeyMeta, KeyRightMeta, KeyInsert} { + router := desktopRouter(t) + router.Key(1, modifier, 1, false, false) + for _, value := range []int32{1, 2} { + if got := router.Key(0, key, value, false, false); got.History { + t.Fatal("modified arrow became history", key, modifier, value, got) + } + } + } + } + for _, key := range []uint16{KeyLeft, KeyRight, KeyEnter, KeyKP8, KeyKP2} { + for _, numLock := range []bool{false, true} { + router := desktopRouter(t) + if got := router.Key(0, key, 1, numLock, false); got.History { + t.Fatal("other input became history", key, numLock, got) + } + } + } +} diff --git a/internal/input/router.go b/internal/input/router.go index 21dce923..3c6a54bd 100644 --- a/internal/input/router.go +++ b/internal/input/router.go @@ -75,6 +75,7 @@ type Decision struct { Interrupt bool Keypress bool // a fresh physical press, excluding repeats and state repair Deletion bool // forwarded Backspace/Delete, including repeats + History bool // forwarded bare Up/Down, including repeats Typing bool // forwarded text key or repeat; the screen supplies its actual text WordBoundary bool // a forwarded Space, rather than cursor navigation Command command.ID @@ -214,7 +215,7 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re } if state.forwarded { typing := !syncEvent && r.typingKey(key, numLock) - return Decision{Code: key, Forward: true, Deletion: !syncEvent && deletionKey(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Interrupt: !syncEvent && !pureModifier(key)} + return Decision{Code: key, Forward: true, Deletion: !syncEvent && deletionKey(key, numLock), History: !syncEvent && r.historyKey(key), Typing: typing, WordBoundary: typing && key == KeySpace, Interrupt: !syncEvent && !pureModifier(key)} } commandID := state.commandID if value == 2 && repeatable(commandID) && !syncEvent { @@ -281,7 +282,21 @@ func (r *Router) key(device int, key uint16, value int32, numLock, syncEvent, re return Decision{Forward: forwarded} } typing := forwarded && r.typingKey(key, numLock) - return Decision{Code: key, Keypress: true, Deletion: forwarded && deletionKey(key, numLock), Typing: typing, WordBoundary: typing && key == KeySpace, Forward: forwarded, Command: commandID, Interrupt: commandID != "" || forwarded && (!pureModifier(key) || key == KeyCtrl || key == KeyRightCtrl)} + return Decision{Code: key, Keypress: true, Deletion: forwarded && deletionKey(key, numLock), History: forwarded && r.historyKey(key), Typing: typing, WordBoundary: typing && key == KeySpace, Forward: forwarded, Command: commandID, Interrupt: commandID != "" || forwarded && (!pureModifier(key) || key == KeyCtrl || key == KeyRightCtrl)} +} + +func (r *Router) historyKey(key uint16) bool { + if key != KeyUp && key != KeyDown { + return false + } + for _, held := range r.keys { + for code := range held { + if code != key { + return false + } + } + } + return true } func (r *Router) typingKey(key uint16, numLock bool) bool { diff --git a/internal/prompt/history_test.go b/internal/prompt/history_test.go new file mode 100644 index 00000000..cc4f057b --- /dev/null +++ b/internal/prompt/history_test.go @@ -0,0 +1,29 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +package prompt + +import "testing" + +func TestShellPrefixBeforeHistoryCommand(t *testing.T) { + for _, trial := range []struct{ text, want string }{ + {"$ echo $PATH", "$"}, + {"# echo hi", "#"}, + {"Username@host:~$ echo hi", "Username@host:~$"}, + {"[Username@host ~]$ echo hi", "[Username@host ~]$"}, + {" $ echo hi", " $"}, + {"$", "$"}, + {"> echo hi", ">"}, + {"$\techo hi", "$"}, + {"echo $PATH # comment", ""}, + {"Username@host:~$echo $PATH # comment", ""}, + {"Username@host:~$echo hi > output", ""}, + {"/ooc # hello person1", ""}, + {"echo > output", ""}, + {"<100hp 50mp> /ooc hi", ""}, + } { + if got := ShellPrefix(trial.text); got != trial.want { + t.Errorf("ShellPrefix(%q) = %q, want %q", trial.text, got, trial.want) + } + } +} diff --git a/internal/prompt/shell.go b/internal/prompt/shell.go index 134f6fb3..0bfd9797 100644 --- a/internal/prompt/shell.go +++ b/internal/prompt/shell.go @@ -6,6 +6,7 @@ package prompt import ( "regexp" "strings" + "unicode" "git.stormux.org/storm/fenrir/internal/screen" ) @@ -19,6 +20,28 @@ type ShellDetector struct { var shellPattern = regexp.MustCompile(`^(?:[$#>]|\[[^\r\n]+\]\s*[$#>]|[a-zA-Z0-9._-]+[$#>]|[a-zA-Z0-9._-]+@[^\s<>]+.*[$#>])\s*$`) +// ShellPrefix identifies the first recognized shell prompt before a command. +// Delimiters inside words (such as $PATH) cannot terminate a prompt. Unknown +// prefixes are left intact rather than guessing where the command begins. +func ShellPrefix(text string) string { + for index, char := range text { + if char != '$' && char != '#' && char != '>' { + continue + } + prefix, rest := text[:index+1], text[index+1:] + if rest != "" && !strings.HasPrefix(rest, " ") && !strings.HasPrefix(rest, "\t") { + return "" + } + if shellPattern.MatchString(strings.TrimLeftFunc(prefix, unicode.IsSpace)) { + return prefix + } + // Do not extend a rejected prefix through command text to a later + // delimiter: the shell recognizer allows spaces in custom prompts. + return "" + } + return "" +} + func (d *ShellDetector) Observe(next screen.Snapshot) bool { if !next.Active || next.Rows <= 0 || next.Cols <= 0 || len(next.Cells) != next.Rows*next.Cols { return false diff --git a/internal/reader/application_override.go b/internal/reader/application_override.go index 9befd918..8729fc12 100644 --- a/internal/reader/application_override.go +++ b/internal/reader/application_override.go @@ -54,6 +54,7 @@ func (r *Reader) CaptureTerminalSession(terminal int) SessionState { } func (r *Reader) RestoreSession(state SessionState, terminal int) { + r.historyInput = false r.automatic = state.automatic r.ConfigureTracking(state.mode) r.attributeConfigured, r.attributeMode, r.attributeResumeMode = state.attributeConfigured, state.attributeMode, state.attributeResumeMode diff --git a/internal/reader/changes.go b/internal/reader/changes.go index 5b194c9b..e483c212 100644 --- a/internal/reader/changes.go +++ b/internal/reader/changes.go @@ -26,12 +26,19 @@ import ( "git.stormux.org/storm/fenrir/internal/screen" ) -func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presentation.Message) { +func changes(previous, next screen.Snapshot, cursorEcho bool) []presentation.Message { + return changesExceptRow(previous, next, cursorEcho, -1) +} + +// Keep the original changed-row count when excluding history input. Masking +// that row first would make concurrent output look like a single-row edit and +// clip common prefixes from messages that ordinarily would be read in full. +func changesExceptRow(previous, next screen.Snapshot, cursorEcho bool, excludedRow int) (output []presentation.Message) { if slices.Equal(previous.Cells, next.Cells) { - if cursorEcho && next.Y != previous.Y { + if cursorEcho && next.Y != excludedRow && next.Y != previous.Y { return []presentation.Message{presentation.LineMessage(next, next.Y)} } - if cursorEcho && next.X != previous.X { + if cursorEcho && next.Y != excludedRow && next.X != previous.X { return []presentation.Message{presentation.CharacterMessage(next.Line(next.Y)[next.X])} } return nil @@ -39,7 +46,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta // Keep navigation over unchanged text audible even when other rows change // (mutt), but first read those changes. A dialog can finish drawing its // body while moving the cursor onto an already drawn button row. - if cursorEcho && next.Y != previous.Y && strings.TrimSpace(next.Text(next.Y)) != "" && slices.Equal(previous.Line(next.Y), next.Line(next.Y)) { + if cursorEcho && next.Y != excludedRow && next.Y != previous.Y && strings.TrimSpace(next.Text(next.Y)) != "" && slices.Equal(previous.Line(next.Y), next.Line(next.Y)) { defer func() { output = append(output, presentation.LineMessage(next, next.Y)) }() @@ -55,6 +62,9 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta } var result []presentation.Message for row := next.Rows - shift; row < next.Rows; row++ { + if row == excludedRow { + continue + } if text := next.Text(row); strings.TrimSpace(text) != "" { result = append(result, presentation.Message{Text: text}) } @@ -78,7 +88,7 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta } changedRows = kept } - if len(changedRows) == 1 && scrollStart == scrollEnd { + if len(changedRows) == 1 && changedRows[0] != excludedRow && scrollStart == scrollEnd { row := changedRows[0] before, after := previous.Line(row), next.Line(row) // A shorter replacement prompt can also move the cursor left. Only @@ -110,6 +120,9 @@ func changes(previous, next screen.Snapshot, cursorEcho bool) (output []presenta } var result []presentation.Message for _, row := range changedRows { + if row == excludedRow { + continue + } if text := next.Text(row); strings.TrimSpace(text) != "" { result = append(result, presentation.Message{Text: text}) } diff --git a/internal/reader/echo.go b/internal/reader/echo.go index 880914d8..facafaca 100644 --- a/internal/reader/echo.go +++ b/internal/reader/echo.go @@ -35,6 +35,7 @@ const echoWindow = 500 * time.Millisecond // NoteInput associates direct application input with cursor movement and echo. // It never speaks raw keys: password fields without screen echo stay silent. func (r *Reader) NoteInput(forwarded, typing, wordBoundary bool) { + r.historyInput = false r.progressDeletionAt = time.Time{} r.applicationInputAt = time.Time{} if forwarded { diff --git a/internal/reader/history.go b/internal/reader/history.go new file mode 100644 index 00000000..42a40c54 --- /dev/null +++ b/internal/reader/history.go @@ -0,0 +1,53 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +package reader + +import ( + "strings" + "time" + + "git.stormux.org/storm/fenrir/internal/i18n" + "git.stormux.org/storm/fenrir/internal/presentation" + "git.stormux.org/storm/fenrir/internal/prompt" + "git.stormux.org/storm/fenrir/internal/screen" +) + +// NoteHistory follows NoteInput for a forwarded bare Up/Down. Releases do not +// cancel it: an application can redraw after the user has released the key. +func (r *Reader) NoteHistory() { r.historyInput = true } + +func (r *Reader) historyChanged(previous, next screen.Snapshot) bool { + if !r.historyInput || r.applicationInputAt.IsZero() || time.Since(r.applicationInputAt) >= 300*time.Millisecond || + !previous.Active || !next.Active || previous.Terminal != next.Terminal || previous.Generation != next.Generation || + previous.Rows != next.Rows || previous.Cols != next.Cols || previous.Y != next.Y { + return false + } + // Some dialog applications park the cursor at the bottom right instead of + // placing it on an input field. Python excluded these from history too. + if next.X == next.Cols-1 && next.Y == next.Rows-1 { + return false + } + regions := r.regions[next.Terminal] + if !regions.allows(next.X, next.Y, next.Cols, true, true) { + return false + } + before, after := previous.Line(next.Y), next.Line(next.Y) + for col, char := range before { + if char != after[col] && regions.allows(col, next.Y, next.Cols, true, true) { + return true + } + } + return false +} + +func historyMessage(previous, next screen.Snapshot) presentation.Message { + before, after := previous.Text(next.Y), next.Text(next.Y) + if prefix := prompt.ShellPrefix(before); prefix != "" && prefix == prompt.ShellPrefix(after) { + after = strings.TrimLeft(after[len(prefix):], " \t") + } + if strings.TrimSpace(after) == "" { + return presentation.Message{Text: i18n.T("blank"), Cue: presentation.Blank} + } + return presentation.Message{Text: after} +} diff --git a/internal/reader/history_test.go b/internal/reader/history_test.go new file mode 100644 index 00000000..8a415bfb --- /dev/null +++ b/internal/reader/history_test.go @@ -0,0 +1,215 @@ +// Copyright (c) 2026 Storm Dragon +// SPDX-License-Identifier: GPL-3.0-or-later + +package reader + +import ( + "reflect" + "slices" + "testing" + "time" + + "git.stormux.org/storm/fenrir/internal/applicationoverrides" + "git.stormux.org/storm/fenrir/internal/command" + "git.stormux.org/storm/fenrir/internal/presentation" + "git.stormux.org/storm/fenrir/internal/screen" +) + +func historySnapshot(line string) screen.Snapshot { + result := screen.Snapshot{Terminal: 2, Active: true, Cols: 80, Rows: 2, Y: 1, X: len([]rune(line)), Cells: make([]rune, 160)} + for index := range result.Cells { + result.Cells[index] = ' ' + } + copy(result.Line(0), []rune("game output")) + copy(result.Line(1), []rune(line)) + return result +} + +func historyInput(r *Reader) { + r.NoteInput(true, false, false) + r.NoteHistory() +} + +func TestHistoryReadsWholeCommandAndStripsOnlyKnownUnchangedPrompts(t *testing.T) { + for _, trial := range []struct { + name, before, after, want string + }{ + {"plain", "/ooc hello person2", "/ooc hello person1", "/ooc hello person1"}, + {"dollar", "$ /ooc hello person2", "$ /ooc hello person1", "/ooc hello person1"}, + {"root", "# /ooc hello person2", "# /ooc hello person1", "/ooc hello person1"}, + {"shell", "Username@host:~$ /ooc hello person2", "Username@host:~$ /ooc hello person1", "/ooc hello person1"}, + {"brackets", "[Username@host ~]$ /ooc hello person2", "[Username@host ~]$ /ooc hello person1", "/ooc hello person1"}, + {"mud", "<100hp 50mp> /ooc hello person2", "<100hp 50mp> /ooc hello person1", "<100hp 50mp> /ooc hello person1"}, + {"literal markers", "/ooc #room costs $5 person2", "/ooc #room costs $5 person1", "/ooc #room costs $5 person1"}, + {"shell markers in command", "$ echo $PATH # comment2", "$ echo $PATH # comment1", "echo $PATH # comment1"}, + {"changed prefix", "Username@host1$ echo old", "Username@host2$ echo new", "Username@host2$ echo new"}, + {"unicode", "$ /ooc café person2", "$ /ooc café person1", "/ooc café person1"}, + {"shorter", "$ /ooc hello person2", "$ /ooc hello", "/ooc hello"}, + {"longer", "$ /ooc hello", "$ /ooc hello person1", "/ooc hello person1"}, + {"prompt only", "$ /ooc hello", "$ ", "blank"}, + {"blank", "/ooc hello", "", "blank"}, + } { + t.Run(trial.name, func(t *testing.T) { + r := New() + r.ConfigureEcho(false, false, false) + r.Update(historySnapshot(trial.before)) + historyInput(r) + next := historySnapshot(trial.after) + want := presentation.Message{Text: trial.want} + if trial.want == "blank" { + want.Cue = presentation.Blank + } + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{want}) { + t.Fatalf("got %+v, want %+v", got, want) + } + if got := r.Update(next); len(got) != 0 { + t.Fatal("unchanged recall repeated", got) + } + }) + } +} + +func TestHistoryWaitsForRecallAndPreservesConcurrentOutput(t *testing.T) { + r := New() + r.ConfigureProgress(true) + before := historySnapshot("$ echo 20%") + r.Update(before) + historyInput(r) + if got := r.Update(before); len(got) != 0 { + t.Fatal("read stale command before redraw", got) + } + background := historySnapshot("$ echo 20%") + copy(background.Line(0), []rune("new message")) + if got := r.Update(background); !reflect.DeepEqual(got, []presentation.Message{{Text: "new message"}}) { + t.Fatal("background output consumed pending recall", got) + } + next := historySnapshot("$ echo 30%") + copy(next.Line(0), []rune("newer alert")) + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{{Text: "newer alert"}, {Text: "echo 30%"}}) { + t.Fatal("lost output or repeated/diffed history", got) + } + if _, ok := r.NextProgress(time.Now().Add(time.Second)); ok { + t.Fatal("recalled percentage became a progress cue") + } + // A history key must affect only one replacement, even within its timeout. + next = historySnapshot("$ echo 40%") + copy(next.Line(0), []rune("newer alert")) + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{presentation.CharacterMessage('4')}) { + t.Fatal("history key leaked into later passive output", got) + } +} + +func TestHistoryDoesNotCaptureOtherNavigationSessionsOrModes(t *testing.T) { + for _, mode := range []string{"no key", "expired", "other input", "reader command", "vertical", "terminal", "buffer", "resize", "inactive", "bottom right", "automatic off", "cursor off", "highlight", "table", "keep review", "outside window", "live region", "override"} { + t.Run(mode, func(t *testing.T) { + r := New() + before := historySnapshot("$ /ooc person2") + r.Update(before) + historyInput(r) + next := historySnapshot("$ /ooc person1") + frame := applicationoverrides.Frame{} + switch mode { + case "no key": + r.historyInput = false + case "expired": + r.applicationInputAt = time.Now().Add(-time.Second) + case "other input": + r.NoteInput(true, false, false) + case "reader command": + r.Command(command.Time) + case "vertical": + next.Y = 0 + case "terminal": + next.Terminal++ + case "buffer": + next.Generation++ + case "resize": + next.Rows++ + next.Cells = append(next.Cells, slices.Repeat([]rune{' '}, next.Cols)...) + case "inactive": + next.Active = false + case "bottom right": + next.X = next.Cols - 1 + case "automatic off": + r.Configure(false, true) + case "cursor off": + r.Configure(true, false) + case "highlight", "table": + r.ConfigureTracking(mode) + case "keep review": + r.ConfigureReview(false, false, false, false) + r.Command(command.CurrentLine) + historyInput(r) + case "outside window": + if err := r.SetWindow(0, 0, 79, 0); err != nil { + t.Fatal(err) + } + historyInput(r) + case "live region": + r.ensureRegions().live[0] = &screen.Region{Left: 0, Top: 1, Right: 79, Bottom: 1} + case "override": + frame = applicationoverrides.Frame{Recognized: true, OwnsPresentation: true} + } + got := r.UpdateApplication(next, frame) + if slices.ContainsFunc(got, func(message presentation.Message) bool { return message.Text == "/ooc person1" }) { + t.Fatal("history bypassed navigation/session/mode policy", got) + } + if mode == "automatic off" || mode == "inactive" || mode == "outside window" || mode == "live region" || mode == "override" { + if len(got) != 0 { + t.Fatal("history bypassed silence policy", got) + } + } + }) + } +} + +func TestHistoryResumesReviewForSameLengthCommands(t *testing.T) { + r := New() + r.Update(historySnapshot("$ /ooc person2")) + r.Command(command.CurrentLine) + historyInput(r) + if got := r.Update(historySnapshot("$ /ooc person1")); !reflect.DeepEqual(got, []presentation.Message{{Text: "/ooc person1"}}) || r.review.Active() { + t.Fatal("same-position recall did not resume tracking", got, r.review.Active()) + } +} + +func TestHistoryWithScrollingOutput(t *testing.T) { + r := New() + before := fixture("first", "second", "third", "$ /ooc person2") + before.Y, before.X = 3, 14 + r.Update(before) + historyInput(r) + next := fixture("second", "third", "new message", "$ /ooc person1") + next.Y, next.X = before.Y, before.X + want := []presentation.Message{{Text: "new message"}, {Text: "/ooc person1"}} + if got := r.Update(next); !reflect.DeepEqual(got, want) { + t.Fatal("scroll replayed old output or lost recall", got, want) + } +} + +func TestHistoryIgnoresExcludedChangesOnInputRow(t *testing.T) { + for _, mode := range []string{"live region", "window"} { + t.Run(mode, func(t *testing.T) { + r := New() + before := historySnapshot("$ /ooc person2 100hp") + before.X = 14 + r.Update(before) + if mode == "live region" { + r.ensureRegions().live[0] = &screen.Region{Left: 17, Top: 1, Right: 79, Bottom: 1} + } else if err := r.SetWindow(0, 1, 16, 1); err != nil { + t.Fatal(err) + } + historyInput(r) + background := historySnapshot("$ /ooc person2 200hp") + background.X = before.X + if got := r.Update(background); len(got) != 0 { + t.Fatal("hidden status change spoke stale history", got) + } + next := historySnapshot("$ /ooc person1 200hp") + next.X = before.X + if got := r.Update(next); !reflect.DeepEqual(got, []presentation.Message{{Text: "/ooc person1"}}) { + t.Fatal("hidden change consumed recall or leaked status", got) + } + }) + } +} diff --git a/internal/reader/reader.go b/internal/reader/reader.go index 3e1391d8..f8a6017b 100644 --- a/internal/reader/reader.go +++ b/internal/reader/reader.go @@ -52,6 +52,7 @@ type Reader struct { lastCompletedWord string inputAt time.Time applicationInputAt time.Time + historyInput bool applicationActivity bool applicationActivityAt time.Time attributeConfigured, attributeResumeMode string @@ -96,15 +97,19 @@ func (r *Reader) Update(next screen.Snapshot) []presentation.Message { func (r *Reader) UpdateApplication(next screen.Snapshot, frame applicationoverrides.Frame) (output []presentation.Message) { r.completedWords = nil previous := r.screen + history := !frame.OwnsPresentation && r.historyChanged(previous, next) r.applicationActivity = next.Active && frame.Recognized && frame.OwnsPresentation && frame.Activity && r.progressEnabled // Python runs cursor-change commands only after recent direct application // input (300 ms). Reader commands and passive output must preserve review. if !r.keepReviewOnCursorChange && r.review.Active() && !r.applicationInputAt.IsZero() && time.Since(r.applicationInputAt) < 300*time.Millisecond && previous.Active && next.Active && previous.Terminal == next.Terminal && previous.Generation == next.Generation && - previous.Rows == next.Rows && previous.Cols == next.Cols && (previous.X != next.X || previous.Y != next.Y || frame.Recognized && frame.FocusChanged) { + previous.Rows == next.Rows && previous.Cols == next.Cols && (previous.X != next.X || previous.Y != next.Y || history || frame.Recognized && frame.FocusChanged) { r.review.ResumeTracking() } switched := r.review.Update(next) + if history || switched || !next.Active || previous.Y != next.Y || frame.OwnsPresentation { + r.historyInput = false + } r.screen = next path := "screen-changes" if diagnostic.Enabled() { @@ -194,7 +199,7 @@ func (r *Reader) UpdateApplication(next screen.Snapshot, frame applicationoverri } if !frame.OwnsPresentation && r.progressEnabled { deletionRow := -1 - if len(deleted) > 0 { + if len(deleted) > 0 || history { deletionRow = next.Y } r.progress.Update(regions.progressSnapshot(previous), regions.progressSnapshot(next), deletionRow) @@ -227,6 +232,13 @@ func (r *Reader) UpdateApplication(next screen.Snapshot, frame applicationoverri } readingPrevious := regions.filteredSnapshot(previous, true, true) readingNext := r.AutomaticSnapshot() + if history && r.trackingMode == "cursor" && r.cursorEcho && !r.review.Active() && regions.allows(next.X, next.Y, next.Cols, true, true) { + path = "history" + message := historyMessage(readingPrevious, readingNext) + // Exclude only the recalled row from ordinary diff speech. Concurrent + // game messages and status changes must still be announced once. + return append(changesExceptRow(readingPrevious, readingNext, false, next.Y), message) + } if r.trackingMode == "highlight" && !r.review.Active() { if output := highlights(readingPrevious, readingNext); len(output) > 0 { path = "highlight" @@ -245,6 +257,7 @@ func (r *Reader) UpdateApplication(next screen.Snapshot, frame applicationoverri // Command returns the complete feedback for one action, without retaining // presentation state for callers to retrieve after dispatch. func (r *Reader) Command(id command.ID) presentation.CommandResult { + r.historyInput = false r.applicationInputAt = time.Time{} r.progressDeletionAt = time.Time{} if result, handled := r.regionCommand(id); handled { diff --git a/internal/reader/regions.go b/internal/reader/regions.go index 7c8ac5db..a77124ff 100644 --- a/internal/reader/regions.go +++ b/internal/reader/regions.go @@ -175,6 +175,7 @@ func (s *terminalRegions) progressSnapshot(snapshot screen.Snapshot) screen.Snap } func (r *Reader) resetRegionFeedback() { + r.historyInput = false r.regionRevision++ r.progress.Reset() r.inputCount, r.inputBoundary = 0, false diff --git a/tests/native_history.py b/tests/native_history.py new file mode 100644 index 00000000..620a8bfe --- /dev/null +++ b/tests/native_history.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# Copyright (c) 2026 Storm Dragon +# SPDX-License-Identifier: GPL-3.0-or-later +"""Exercise real Bash history through Fenrir's private X11/PTY input path. + +Run: xvfb-run -a env FENRIR_PRIVATE_X11=1 python3 -B tests/native_history.py +Captures SSIP requests; does not connect to live speech or the user's reader. +""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import time + +from native_terminal import KeyboardFixture, SpeechServer, wait_for + + +def main(): + if not os.environ.get("DISPLAY") or os.environ.get("FENRIR_PRIVATE_X11") != "1": + raise SystemExit("Use xvfb-run -a env FENRIR_PRIVATE_X11=1 python3 -B tests/native_history.py") + repository = Path(__file__).resolve().parents[1] + fixture = str(repository / "tests/native_terminal.py") + binary = os.environ.get("FENRIR_TEST_BINARY", str(repository / "fenrir")) + with tempfile.TemporaryDirectory(prefix="fenrir-history-", dir="/tmp") as directory: + root = Path(directory) + (root / "home").mkdir() + (root / "keyboard").mkdir() + (root / "keyboard/custom.toml").write_bytes((repository / "config/keyboard/desktop.toml").read_bytes()) + (root / "settings.toml").write_text( + 'version=3\n[presentation.sound]\nenabled=false\n' + '[presentation.progress]\nenabled=false\n' + '[keyboard]\ncharacter_echo=false\nword_echo=false\n' + '[reading]\npunctuation_level="none"\nspellcheck=false\n' + f'[remote]\nsocket_file="{root / "remote.sock"}"\n') + history = root / "history" + history.write_text("/ooc hello person1\n/ooc hello person2\n") + shell = root / "shell" + shell.write_text( + f'#!{sys.executable}\nimport os\n' + f'os.environ.update(HISTFILE={str(history)!r}, HISTSIZE="100", ' + 'HISTCONTROL="", HISTIGNORE="", PS1="Username@host:~$ ", ' + 'INPUTRC="/dev/null", PROMPT_COMMAND="")\n' + 'os.execv("/bin/bash", ["bash", "--noprofile", "--norc", "-i"])\n') + shell.chmod(0o700) + server = SpeechServer(root / "speech.sock") + keyboard = KeyboardFixture() + environment = dict(os.environ, FENRIR_TEST_BINARY=binary, FENRIR_FIXTURE_DIR=str(root), + HOME=str(root / "home"), TMPDIR=str(root), LOGNAME="Username", USER="Username", + SPEECHD_ADDRESS="unix_socket:" + str(root / "speech.sock"), LC_ALL="C", LANGUAGE="C") + terminal = subprocess.Popen(["xterm", "-geometry", "80x25", "-e", sys.executable, + fixture, "--outer", str(root)], env=environment, cwd=root) + try: + wait_for(lambda: (root / "started").exists(), "reader startup") + state = json.loads((root / "started").read_text()) + subprocess.run(["xdotool", "windowfocus", "--sync", state["window"]], check=True) + wait_for(lambda: any("Username" in item for item in server.events), "initial Bash prompt") + + for chord, expected in [("Up", "hello person2"), ("Up", "hello person1"), + ("Down", "hello person2"), ("Down", "blank")]: + start = len(server.events) + keyboard.key(chord) + wait_for(lambda: any(expected in item for item in server.events[start:]), + f"history {chord}: {expected}; recent={server.events[-12:]}") + time.sleep(0.1) # Include any duplicate echo after the recall. + utterances = [item for item in server.events[start:] if item != "CANCEL"] + assert len(utterances) == 1, (chord, expected, utterances) + assert "Username" not in utterances[0], utterances + if expected != "blank": + assert "ooc hello person" in utterances[0], utterances + print(f"PASS: Bash {chord} reads {expected!r} once without the prompt", flush=True) + + # Raw review still includes the prompt; it must not be mistaken + # for a history key or use the stripped automatic presentation. + start = len(server.events) + keyboard.key("KP_Up") + wait_for(lambda: any("Username" in item for item in server.events[start:]), "raw prompt review") + keyboard.key("Insert+q") + wait_for(lambda: (root / "finished").exists(), "reader shutdown") + result = json.loads((root / "finished").read_text()) + assert result == {"status": 0, "restored": True, "flagsRestored": True}, result + assert not server.errors, server.errors + except BaseException: + print("SSIP:", server.events[-25:], file=sys.stderr) + for name in ("reader-errors", "timing.log"): + if (root / name).exists(): + print(name + ":", (root / name).read_text()[-6000:], file=sys.stderr) + raise + finally: + terminal.terminate() + try: + terminal.wait(timeout=3) + except subprocess.TimeoutExpired: + terminal.kill() + terminal.wait() + keyboard.close() + server.close() + + +if __name__ == "__main__": + main()