From ffc510711299cc25eb557a197200a08f0a45c86d Mon Sep 17 00:00:00 2001 From: Storm Dragon Date: Thu, 19 Nov 2026 12:29:46 -0500 Subject: [PATCH] Preserve queued speech during automatic voice changes Adopt screenreader-common v0.9.0 for in-place retuning and restore the complete effective speech configuration when retuning and fallback replacement fail. Add interruption diagnostics and require the retune and recovery regressions in the speech push gate. --- README.md | 2 +- docs/testing/voice-profiles.md | 15 +- go.mod | 2 +- go.sum | 4 +- internal/app/configured_speaker.go | 44 ++++ internal/app/echo_speaker.go | 86 +++++-- internal/app/interruption_test.go | 4 +- internal/app/preferences_application.go | 3 +- internal/app/preferences_apply.go | 25 +- internal/app/preferences_preview.go | 46 ++++ internal/app/screen_lock.go | 2 +- internal/app/speech_delivery.go | 7 +- internal/app/speech_enable_test.go | 4 +- internal/app/speech_interrupt.go | 17 +- internal/app/speech_mode.go | 2 +- internal/app/speech_retune_test.go | 320 ++++++++++++++++++++++++ internal/app/speech_worker_test.go | 24 +- internal/app/tentacle_reader_test.go | 6 +- internal/speech/speech.go | 3 + tests/check_speech.py | 5 + 20 files changed, 569 insertions(+), 52 deletions(-) create mode 100644 internal/app/speech_retune_test.go diff --git a/README.md b/README.md index f2f7c2b..02a1a21 100644 --- a/README.md +++ b/README.md @@ -695,7 +695,7 @@ drive the same synthesizer at the same time. DECtalk USB finds a single connected device itself and needs libusb 1.0 at runtime, which is loaded only when DECtalk USB is selected. -Standalone builds pin `screenreader-common v0.8.0`, which supplies the shared +Standalone builds pin `screenreader-common v0.9.0`, which supplies the shared profile model and editor. A sibling Go workspace can use local common-module changes during development. See [profile verification](docs/testing/voice-profiles.md). diff --git a/docs/testing/voice-profiles.md b/docs/testing/voice-profiles.md index 347230c..b8ad605 100644 --- a/docs/testing/voice-profiles.md +++ b/docs/testing/voice-profiles.md @@ -1,6 +1,6 @@ # Primary voice profiles -Standalone builds pin screenreader-common v0.7.0. Use `GOWORK=off` to verify +Standalone builds pin screenreader-common v0.9.0. Use `GOWORK=off` to verify the released dependency; a sibling workspace remains useful for development. Run shared tests with `GOWORK=off go test -race ./...` in screenreader-common. In Cthulhu, run `GOWORK=off go test ./internal/config ./internal/preferences @@ -43,3 +43,16 @@ Before submitting, review all three diffs and test with the intended reader: the currently configured primary voice keeps working after preset removal. No running desktop reader needs to be restarted for the private checks. + +For automatic application voice changes, queue a long announcement in an +application with its own profile, then switch to an application using the +global voice. Earlier speech should finish; later speech should use the new +voice. Test returning to a global voice without a named family, a non-default +Speech Dispatcher client configuration, and an explicit module when the server +has language-to-module routing. Explicit preference changes may cancel queued +speech. Confirm that interruption keys and custom echo voices still work. + +The push gate includes retune ordering and failed-change restoration tests. +The common module's `CTHULHU_NATIVE_SPEECH_STARTUP=1` tests compare retuned and +fresh defaults against private dummy-output daemons. These automated checks do +not establish audible speech, physical-key, Braille, or hardware acceptance. diff --git a/go.mod b/go.mod index a07cca1..0f31b2f 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module git.stormux.org/storm/cthulhu go 1.27.2 require ( - git.stormux.org/storm/screenreader-common v0.8.0 + git.stormux.org/storm/screenreader-common v0.9.0 github.com/godbus/dbus/v5 v5.1.0 github.com/gorilla/websocket v1.5.3 github.com/pelletier/go-toml/v2 v2.4.3 diff --git a/go.sum b/go.sum index 979bd03..46c474e 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -git.stormux.org/storm/screenreader-common v0.8.0 h1:vMHgI9c+qT9yOKk1A/MP98GsXZpVpzKa6rrKzRe7D+Y= -git.stormux.org/storm/screenreader-common v0.8.0/go.mod h1:2LW1ooP+4sYH2ewpgutyUIzJPy2IlgfYFxNPS2L3Ul4= +git.stormux.org/storm/screenreader-common v0.9.0 h1:eKyDKOhiE+xNsSPK9hjIm34g2hly7UeWRp6BXslvRDo= +git.stormux.org/storm/screenreader-common v0.9.0/go.mod h1:2LW1ooP+4sYH2ewpgutyUIzJPy2IlgfYFxNPS2L3Ul4= github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= diff --git a/internal/app/configured_speaker.go b/internal/app/configured_speaker.go index 8c1f5bc..edc7f0a 100644 --- a/internal/app/configured_speaker.go +++ b/internal/app/configured_speaker.go @@ -119,6 +119,50 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti return nil } +// RetuneConfiguration applies an automatic settings change, such as an +// application profile, without cancelling speech already queued. Only the +// active backend's voice parameters change; utterances queued earlier finish +// with the voice they were queued with. It returns an error, leaving speech +// untouched, when the change needs a new backend or connection set; the caller +// then decides whether UpdateConfiguration, which cancels, is acceptable. +func (speaker *configuredSpeaker) RetuneConfiguration(ctx context.Context, settings config.Settings) error { + if !speaker.update.TryLock() { + return errors.New("speech settings update already in progress") + } + defer speaker.update.Unlock() + if err := config.Validate(settings); err != nil { + return err + } + speaker.mu.RLock() + current, closed := speaker.active, speaker.closed + speaker.mu.RUnlock() + if closed { + return errors.New("speech is closed") + } + switch voice := current.(type) { + case *hardwareSpeaker: + // Serial voice parameters are sent with each utterance. + if settings.SpeechServerFactory != "hardwarefactory" || voice.device != settings.HardwareSpeechDevice || + voice.baud != settings.HardwareSpeechBaudRate || voice.synth != settings.SpeechOutputModule { + return speech.ErrRetuneNeedsReconnect + } + voice.mu.Lock() + voice.settings = settings + voice.mu.Unlock() + case *echoSpeaker: + if settings.SpeechServerFactory == "hardwarefactory" { + return speech.ErrRetuneNeedsReconnect + } + if err := voice.RetuneConfiguration(ctx, settings); err != nil { + return err + } + default: + return speech.ErrRetuneNeedsReconnect + } + speaker.retireRemoteVoice(settings) + return nil +} + // reopenHardware moves a hardware device to new settings (synthesizer or baud // rate). The transport locks the device, so the current owner is released // before the new one opens; if the new settings cannot open it, the previous diff --git a/internal/app/echo_speaker.go b/internal/app/echo_speaker.go index 87bae42..c34411f 100644 --- a/internal/app/echo_speaker.go +++ b/internal/app/echo_speaker.go @@ -7,6 +7,7 @@ package app import ( "context" "errors" + "fmt" "reflect" "sync" "unicode" @@ -46,28 +47,7 @@ func (speaker *echoSpeaker) UpdateConfiguration(ctx context.Context, settings co } return result } - voiceSettings := map[string]speech.Settings{"default": speechSettingsFromConfig(settings)} - for _, kind := range []string{"uppercase", "hyperlink", "system"} { - if kind == "hyperlink" && reflect.DeepEqual(settings.HyperlinkVoice, config.Voice{}) || kind == "system" && reflect.DeepEqual(settings.SystemVoice, config.Voice{}) { - continue - } - candidate := settings - candidate.DefaultVoice = config.EffectiveVoice(settings, kind) - voiceSettings[kind] = speechSettingsFromConfig(candidate) - } - if settings.UseCustomEchoVoice { - voiceSettings["echo"] = echoSpeechSettings(settings) - echoSettings := settings - echoSettings.DefaultVoice = config.EffectiveVoice(settings, "default") - mergeEchoVoice(&echoSettings.DefaultVoice, settings.EchoVoice) - echoSettings.DefaultVoice = config.EffectiveVoice(echoSettings, "uppercase") - if settings.UseCustomEchoSpeechServer { - echoSettings.SpeechOutputModule = settings.EchoSpeechServer - } - // Echo endpoints allow 100/10/10; use the existing clamping mapper. - echoSettings.EchoVoice = echoSettings.DefaultVoice - voiceSettings["uppercase-echo"] = echoSpeechSettings(echoSettings) - } + voiceSettings := echoVoiceSettings(settings) for _, kind := range []string{"default", "echo", "uppercase", "uppercase-echo", "hyperlink", "system"} { values, exists := voiceSettings[kind] if !exists { @@ -101,6 +81,68 @@ func (speaker *echoSpeaker) UpdateConfiguration(ctx context.Context, settings co _ = closeClients(retired) return nil } + +// RetuneConfiguration moves every connection to new settings in place. Speech +// already queued keeps the voice it was queued with and is not cancelled. +// It fails before changing anything when the new settings need a different +// set of voice connections. On any error the caller uses UpdateConfiguration, +// which replaces every connection. If that replacement also fails, the +// preferences worker restores the previous complete configuration. +func (speaker *echoSpeaker) RetuneConfiguration(ctx context.Context, settings config.Settings) error { + if !speaker.update.TryLock() { + return errors.New("speech settings update already in progress") + } + defer speaker.update.Unlock() + voiceSettings := echoVoiceSettings(settings) + speaker.mu.RLock() + defer speaker.mu.RUnlock() + if speaker.closed { + return errors.New("speech is closed") + } + if len(voiceSettings) != len(speaker.voices) { + return speech.ErrRetuneNeedsReconnect + } + for kind := range voiceSettings { + if speaker.voices[kind] == nil { + return speech.ErrRetuneNeedsReconnect + } + } + for kind, values := range voiceSettings { + if err := speaker.voices[kind].RetuneSettings(ctx, values); err != nil { + return fmt.Errorf("retune %s voice: %w", kind, err) + } + } + return nil +} + +// echoVoiceSettings maps each voice kind with its own Speech Dispatcher +// connection to that connection's settings. Kinds left out use "default". +func echoVoiceSettings(settings config.Settings) map[string]speech.Settings { + voiceSettings := map[string]speech.Settings{"default": speechSettingsFromConfig(settings)} + for _, kind := range []string{"uppercase", "hyperlink", "system"} { + if kind == "hyperlink" && reflect.DeepEqual(settings.HyperlinkVoice, config.Voice{}) || kind == "system" && reflect.DeepEqual(settings.SystemVoice, config.Voice{}) { + continue + } + candidate := settings + candidate.DefaultVoice = config.EffectiveVoice(settings, kind) + voiceSettings[kind] = speechSettingsFromConfig(candidate) + } + if settings.UseCustomEchoVoice { + voiceSettings["echo"] = echoSpeechSettings(settings) + echoSettings := settings + echoSettings.DefaultVoice = config.EffectiveVoice(settings, "default") + mergeEchoVoice(&echoSettings.DefaultVoice, settings.EchoVoice) + echoSettings.DefaultVoice = config.EffectiveVoice(echoSettings, "uppercase") + if settings.UseCustomEchoSpeechServer { + echoSettings.SpeechOutputModule = settings.EchoSpeechServer + } + // Echo endpoints allow 100/10/10; use the existing clamping mapper. + echoSettings.EchoVoice = echoSettings.DefaultVoice + voiceSettings["uppercase-echo"] = echoSpeechSettings(echoSettings) + } + return voiceSettings +} + func (speaker *echoSpeaker) client(kind string) *speech.Client { if client := speaker.voices[kind]; client != nil { return client diff --git a/internal/app/interruption_test.go b/internal/app/interruption_test.go index aade9fb..76fd6bf 100644 --- a/internal/app/interruption_test.go +++ b/internal/app/interruption_test.go @@ -46,7 +46,7 @@ func TestAppliedInterruptionKeysPreserveQueuedSpeechAndSayAll(t *testing.T) { live.Store(settings) preferences := &preferencesWorker{settings: settings, live: live, speechWorker: speech} settings.SpeechInterruption.Mode = input.InterruptCommonKeys - if err := preferences.applyRuntime(context.Background(), settings); err != nil { + if err := preferences.applyRuntime(context.Background(), settings, speechChangeExplicit); err != nil { t.Fatal(err) } deliver := func(name string) { @@ -69,7 +69,7 @@ func TestAppliedInterruptionKeysPreserveQueuedSpeechAndSayAll(t *testing.T) { t.Fatal("common interruption key did not cancel Say All and pending output") } settings.SpeechInterruption = input.InterruptionSettings{Mode: input.InterruptCustomKeys, Keys: []string{"F8"}} - if err := preferences.applyRuntime(context.Background(), settings); err != nil { + if err := preferences.applyRuntime(context.Background(), settings, speechChangeExplicit); err != nil { t.Fatal(err) } speech.Enqueue(speechRequest{Text: "Custom mode announcement"}) diff --git a/internal/app/preferences_application.go b/internal/app/preferences_application.go index 0f5002b..5cdcc79 100644 --- a/internal/app/preferences_application.go +++ b/internal/app/preferences_application.go @@ -74,12 +74,13 @@ func (worker *preferencesWorker) switchApplication(ctx context.Context, applicat settings, err := worker.applicationSettings(application) if err == nil { settings = worker.sessionKeyboard(settings) - err = worker.applyRuntime(ctx, settings) + err = worker.applyRuntime(ctx, settings, speechChangeAutomatic) } if err != nil { worker.logger.Error("switch application settings", "application", application, "error", err) return } + worker.logger.Debug("switched application settings", "application", application, "previous_application", worker.activeApp) worker.activeApp = application if worker.live != nil { worker.live.application.Store(&application) diff --git a/internal/app/preferences_apply.go b/internal/app/preferences_apply.go index 87dcd9e..d08b320 100644 --- a/internal/app/preferences_apply.go +++ b/internal/app/preferences_apply.go @@ -74,7 +74,7 @@ func (worker *preferencesWorker) applyNext(ctx context.Context, next config.Sett if save && !worker.response("", false).CanSave { return worker.response("This settings file cannot be saved by the Go preview. Use Apply for this session.", false) } - if err := worker.applyRuntime(ctx, next); err != nil { + if err := worker.applyRuntime(ctx, next, speechChangeExplicit); err != nil { return worker.response(err.Error(), false) } if worker.editingActive { @@ -126,7 +126,16 @@ func (worker *preferencesWorker) applyNext(ctx context.Context, next config.Sett return response } -func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.Settings) error { +// speechChange says whether applying new speech settings may cancel speech +// queued under the old ones. Only explicit user changes may interrupt. +type speechChange int + +const ( + speechChangeExplicit speechChange = iota // The user changed settings. + speechChangeAutomatic // An application switch; queued speech finishes. +) + +func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.Settings, change speechChange) error { keyboardChanged := next.KeyboardLayout != worker.settings.KeyboardLayout || !reflect.DeepEqual(next.CthulhuModifierKeys, worker.settings.CthulhuModifierKeys) bindingsChanged := keyboardChanged || !reflect.DeepEqual(next.KeyBindings, worker.settings.KeyBindings) bindingsCommitted := false @@ -166,13 +175,13 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S if speechApplied && !bindingsCommitted { restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) defer cancel() - if err := worker.updateSpeech(restoreCtx, effectiveCurrent); err != nil { + if err := worker.changeSpeech(restoreCtx, effectiveCurrent, change); err != nil { worker.logger.Error("restore speech after failed preferences apply", "error", err) } } }() if next.EnableSpeech && (speechChanged || !worker.settings.EnableSpeech) { - if message := worker.applySpeechSettings(ctx, effectiveNext); message != "" { + if message := worker.applySpeechSettings(ctx, effectiveNext, change); message != "" { return errors.New(message) } speechApplied = true @@ -217,12 +226,18 @@ func (worker *preferencesWorker) applyKeyboard(ctx context.Context, settings con return worker.bindings.SetKeyBindings(ctx, settings.KeyBindings) } -func (worker *preferencesWorker) applySpeechSettings(ctx context.Context, next config.Settings) string { +func (worker *preferencesWorker) applySpeechSettings(ctx context.Context, next config.Settings, change speechChange) string { var err error if worker.updater == nil { return "Speech is disabled or this backend cannot change settings." } + if change == speechChangeAutomatic { + if err := worker.retuneSpeech(ctx, next); err != nil { + return "Settings were not applied: " + err.Error() + } + return "" + } if updater, ok := worker.updater.(interface { UpdateConfiguration(context.Context, config.Settings) error }); ok { diff --git a/internal/app/preferences_preview.go b/internal/app/preferences_preview.go index a697b3e..4680ed2 100644 --- a/internal/app/preferences_preview.go +++ b/internal/app/preferences_preview.go @@ -9,6 +9,7 @@ import ( "errors" "fmt" "strings" + "time" "git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/preferences" @@ -139,10 +140,55 @@ func (worker *preferencesWorker) restorePreview(ctx context.Context) preferences return response } +func (worker *preferencesWorker) changeSpeech(ctx context.Context, next config.Settings, change speechChange) error { + if change == speechChangeAutomatic { + return worker.retuneSpeech(ctx, next) + } + return worker.updateSpeech(ctx, next) +} + +// retuneSpeech applies an automatic change without cancelling queued speech +// when the backend can change voice parameters in place. Only a change that +// needs new connections, such as another speech server or an added voice +// kind, falls back to updateSpeech, which cancels. Both outcomes are logged. +func (worker *preferencesWorker) retuneSpeech(ctx context.Context, next config.Settings) error { + retuner, ok := worker.updater.(interface { + RetuneConfiguration(context.Context, config.Settings) error + }) + if !ok { + worker.logger.Debug("speech backend cannot retune in place; reconnecting cancels queued speech") + return worker.updateSpeech(ctx, next) + } + err := retuner.RetuneConfiguration(ctx, next) + if err == nil { + worker.logger.Debug("retuned speech settings in place; queued speech continues", + "output_module", next.SpeechOutputModule) + return nil + } + worker.logger.Info("speech settings need new connections; reconnecting cancels queued speech", "reason", err) + if err := worker.updateSpeech(ctx, next); err != nil { + // Retuning can commit some voice connections before another fails. + // If replacement also fails, restore the complete previous effective + // configuration, including an active Tentacle override. The initiating + // context may already be cancelled, so cleanup needs its own deadline. + restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + defer cancel() + if restoreErr := worker.updateSpeech(restoreCtx, worker.effectiveSettings(worker.settings)); restoreErr != nil { + return errors.Join(err, fmt.Errorf("restore speech after failed automatic change: %w", restoreErr)) + } + return err + } + return nil +} + +// updateSpeech replaces the speech connections, cancelling queued speech. It +// is for explicit user changes; automatic changes use retuneSpeech. func (worker *preferencesWorker) updateSpeech(ctx context.Context, next config.Settings) error { if worker.updater == nil { return errors.New("speech is disabled or this backend cannot change settings") } + worker.logger.Debug("reconnecting speech with new settings; queued speech is cancelled", + "output_module", next.SpeechOutputModule) if updater, ok := worker.updater.(interface { UpdateConfiguration(context.Context, config.Settings) error }); ok { diff --git a/internal/app/screen_lock.go b/internal/app/screen_lock.go index 01fbddf..4acef4c 100644 --- a/internal/app/screen_lock.go +++ b/internal/app/screen_lock.go @@ -168,7 +168,7 @@ func (worker *speechWorker) SetSecureInputActive(active bool) { worker.secure = active if active { worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("secure input") } } diff --git a/internal/app/speech_delivery.go b/internal/app/speech_delivery.go index 96f9578..399f140 100644 --- a/internal/app/speech_delivery.go +++ b/internal/app/speech_delivery.go @@ -252,7 +252,10 @@ func (worker *speechWorker) transformText(text string) string { } // Log the text passed to the backend, including each Say All part rather than -// the entire queued batch. A delivery record is an attempt, not audible proof. +// the entire queued batch. A delivery record is an attempt, not audible proof: +// delivery itself never cancels earlier speech, so a later "speech interrupted" +// record or a speech settings reconnection is what stops queued text. +// The generation matches the one an interruption record reports retiring. func (worker *speechWorker) logDelivery(ctx context.Context, request speechRequest, text string, readAllIndex int) { if !worker.logger.Enabled(ctx, slog.LevelDebug) { return @@ -262,7 +265,7 @@ func (worker *speechWorker) logDelivery(ctx context.Context, request speechReque } worker.logger.DebugContext(ctx, "delivering accessible presentation", "role", request.Role, "cause", request.Cause, "utterance", text, - "append", true, "interrupt_previous", false, + "generation", request.deliveryGeneration, "character", request.Character, "custom_echo", request.CustomEcho, "read_all_index", readAllIndex) } diff --git a/internal/app/speech_enable_test.go b/internal/app/speech_enable_test.go index 4c9d460..50fc4f5 100644 --- a/internal/app/speech_enable_test.go +++ b/internal/app/speech_enable_test.go @@ -31,7 +31,7 @@ func TestPreferencesEnableAndDisableSpeechDuringSession(t *testing.T) { worker.speechWorker = speechWorker enabled := settings enabled.EnableSpeech = true - if err := worker.applyRuntime(context.Background(), enabled); err != nil { + if err := worker.applyRuntime(context.Background(), enabled, speechChangeExplicit); err != nil { t.Fatal(err) } if updates != 1 { @@ -45,7 +45,7 @@ func TestPreferencesEnableAndDisableSpeechDuringSession(t *testing.T) { if got := <-speaker.spoken; got != "enabled" { t.Fatalf("spoken text = %q", got) } - if err := worker.applyRuntime(context.Background(), settings); err != nil { + if err := worker.applyRuntime(context.Background(), settings, speechChangeExplicit); err != nil { t.Fatal(err) } if updates != 1 { diff --git a/internal/app/speech_interrupt.go b/internal/app/speech_interrupt.go index a87e51c..6614c77 100644 --- a/internal/app/speech_interrupt.go +++ b/internal/app/speech_interrupt.go @@ -44,11 +44,13 @@ func (worker *speechWorker) SetEnabled(enabled bool) { worker.enabled = enabled if !enabled { worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("speech disabled") } } -func (worker *speechWorker) interruptLocked() { +// interruptLocked cancels pending and active speech. The reason names the +// user action or mode change responsible, so every cancellation is logged. +func (worker *speechWorker) interruptLocked(reason string) { worker.retireRemoteSpeechLocked() if worker.hintCancel != nil { worker.hintCancel() @@ -68,11 +70,14 @@ func (worker *speechWorker) interruptLocked() { worker.readAllCancel = nil } if time.Now().Before(worker.startupUntil) { + worker.logger.Debug("kept startup speech despite interruption", "reason", reason) return } if !worker.running { return } + worker.logger.Debug("speech interrupted", "reason", reason, "dropped_pending", len(worker.pending), + "retired_generation", worker.generation) completeSpeechRequests(worker.pending, context.Canceled) worker.pending = nil worker.generation++ @@ -90,7 +95,7 @@ func (worker *speechWorker) BeginReadAll(ctx context.Context, timestamp uint32) defer worker.mutex.Unlock() worker.startupUntil = time.Time{} if !worker.hasUninterruptibleLocked() { - worker.interruptLocked() + worker.interruptLocked("read all started") } else if worker.readAllCancel != nil { worker.readAllCancel() } @@ -139,7 +144,7 @@ func (worker *speechWorker) interruptForInputLocked(event input.Event) bool { return false } worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("key press") return true } @@ -157,7 +162,7 @@ func (worker *speechWorker) ProtectCommand(timestamp uint32) { } if !worker.hasUninterruptibleLocked() { worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("command") } } @@ -177,7 +182,7 @@ func (worker *speechWorker) InterruptForUser() { return } worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("user action") } func (worker *speechWorker) cancelActiveSpeech(ctx context.Context) { diff --git a/internal/app/speech_mode.go b/internal/app/speech_mode.go index c32ae02..fa11702 100644 --- a/internal/app/speech_mode.go +++ b/internal/app/speech_mode.go @@ -36,7 +36,7 @@ func (worker *speechWorker) cycleSpeechMode() speechMode { defer worker.mutex.Unlock() worker.mode = (worker.mode + 1) % 3 worker.startupUntil = time.Time{} - worker.interruptLocked() + worker.interruptLocked("speech mode changed") worker.logger.Debug("speech mode changed", "mode", worker.mode.announcement()) return worker.mode } diff --git a/internal/app/speech_retune_test.go b/internal/app/speech_retune_test.go new file mode 100644 index 0000000..e5fc501 --- /dev/null +++ b/internal/app/speech_retune_test.go @@ -0,0 +1,320 @@ +// Copyright (c) 2026 Storm Dragon +// Authors: Storm Dragon, Angus Kola +// SPDX-License-Identifier: GPL-3.0-or-later + +package app + +import ( + "bufio" + "context" + "errors" + "fmt" + "log/slog" + "net" + "path/filepath" + "strings" + "sync" + "testing" + "time" + + "git.stormux.org/storm/cthulhu/internal/config" + "git.stormux.org/storm/cthulhu/internal/speech" +) + +// retuneServer records each connection's commands and reports server defaults. +type retuneServer struct { + mu sync.Mutex + commands map[int][]string +} + +func newRetuneServer(t *testing.T) (string, *retuneServer) { + t.Helper() + return newRetuneServerWithHook(t, nil) +} + +func newRetuneServerWithHook(t *testing.T, hook func(string) string) (string, *retuneServer) { + t.Helper() + path := filepath.Join(t.TempDir(), "speech.sock") + listener, err := net.Listen("unix", path) + if err != nil { + t.Fatal(err) + } + server := &retuneServer{commands: make(map[int][]string)} + var handlers sync.WaitGroup + var connections []net.Conn + var connectionsMutex sync.Mutex + accepted := make(chan struct{}) + go func() { + defer close(accepted) + for id := 1; ; id++ { + conn, err := listener.Accept() + if err != nil { + return + } + connectionsMutex.Lock() + connections = append(connections, conn) + connectionsMutex.Unlock() + handlers.Add(1) + go func(id int) { + defer handlers.Done() + defer conn.Close() + reader := bufio.NewReader(conn) + for { + line, err := reader.ReadString('\n') + if err != nil { + return + } + command := strings.TrimSpace(line) + server.mu.Lock() + server.commands[id] = append(server.commands[id], command) + server.mu.Unlock() + response := "200 OK\r\n" + switch command { + case "HISTORY GET CLIENT_ID": + response = fmt.Sprintf("245-%d\r\n245 OK\r\n", id) + case "GET RATE": + response = "251-50\r\n251 OK GET RETURNED\r\n" + case "GET LANGUAGE": + response = "251-en\r\n251 OK GET RETURNED\r\n" + case "GET VOICE_TYPE": + response = "251-MALE1\r\n251 OK GET RETURNED\r\n" + case "SPEAK": + for { + text, err := reader.ReadString('\n') + if err != nil { + return + } + if text == ".\r\n" { + break + } + } + response = "230 OK\r\n200 QUEUED\r\n" + } + if hook != nil { + if override := hook(command); override != "" { + response = override + } + } + if _, err := conn.Write([]byte(response)); err != nil { + return + } + } + }(id) + } + }() + t.Cleanup(func() { + listener.Close() + <-accepted + connectionsMutex.Lock() + for _, conn := range connections { + conn.Close() + } + connectionsMutex.Unlock() + handlers.Wait() + }) + return path, server +} + +func (server *retuneServer) snapshot() map[int][]string { + server.mu.Lock() + defer server.mu.Unlock() + copied := make(map[int][]string, len(server.commands)) + for id, commands := range server.commands { + copied[id] = append([]string(nil), commands...) + } + return copied +} + +// An application profile with its own voice family switches back to a global +// voice without one. Speech queued before the switch must not be cancelled. +func TestConfiguredSpeakerRetuneKeepsQueuedSpeech(t *testing.T) { + path, server := newRetuneServer(t) + rate, pitch, gain := 82.0, 0.0, 40.0 + application := config.DefaultSettings() + application.SpeechOutputModule = "rhvoice" + application.DefaultVoice = config.Voice{Rate: &rate, AveragePitch: &pitch, Gain: &gain, + Family: &config.VoiceFamily{Name: "Lyubov", Lang: "en"}} + global := application + globalRate := 80.0 + global.DefaultVoice = config.Voice{Rate: &globalRate, AveragePitch: &pitch, Gain: &gain} + + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + speaker := newConfiguredSpeaker(path, application) + if err := speaker.Connect(ctx); err != nil { + t.Fatal(err) + } + defer speaker.Close(context.Background()) + if err := speaker.Speak(ctx, "New Tab - Brave"); err != nil { + t.Fatal(err) + } + before := len(server.snapshot()) + if err := speaker.RetuneConfiguration(ctx, global); err != nil { + t.Fatal(err) + } + if err := speaker.Speak(ctx, "Address and search bar"); err != nil { + t.Fatal(err) + } + + commands := server.snapshot() + for id, history := range commands { + for _, command := range history { + if strings.HasPrefix(command, "CANCEL") { + t.Errorf("connection %d received %s during an automatic switch", id, command) + } + } + } + // Connections opened by the retune may only read server defaults; speech + // stays on its original connection. + for id := before + 1; id <= len(commands); id++ { + for _, command := range commands[id] { + if !strings.HasPrefix(command, "GET ") && command != "SET SELF CLIENT_NAME cthulhu:cthulhu:main" { + t.Fatalf("retune connection %d sent %q; only default probes may connect", id, command) + } + } + } + speaking := strings.Join(commands[1], "|") + if !strings.Contains(speaking, "SPEAK|SET SELF PUNCTUATION") { + t.Fatalf("retune did not follow the queued utterance on the speaking connection: %s", speaking) + } + for _, command := range []string{"SET SELF RATE 80", "SET SELF VOICE_TYPE MALE1", "SET SELF LANGUAGE en|SET SELF OUTPUT_MODULE rhvoice"} { + if !strings.Contains(speaking, command) { + t.Fatalf("speaking connection missing %q: %s", command, speaking) + } + } + if !strings.HasSuffix(speaking, "SET SELF VOICE_TYPE MALE1|SPEAK") { + t.Fatalf("later speech did not use the retuned voice: %s", speaking) + } +} + +type recordingSpeechUpdater struct { + calls []string + retuneErr error +} + +func (updater *recordingSpeechUpdater) UpdateSettings(context.Context, speech.Settings) error { + updater.calls = append(updater.calls, "update-settings") + return nil +} + +func (updater *recordingSpeechUpdater) UpdateConfiguration(context.Context, config.Settings) error { + updater.calls = append(updater.calls, "reconnect") + return nil +} + +func (updater *recordingSpeechUpdater) RetuneConfiguration(context.Context, config.Settings) error { + updater.calls = append(updater.calls, "retune") + return updater.retuneErr +} + +func TestApplicationSwitchRetunesAndExplicitChangeReconnects(t *testing.T) { + for _, test := range []struct { + name string + change speechChange + retuneErr error + want string + }{ + {"application switch", speechChangeAutomatic, nil, "retune"}, + {"application switch needing new connections", speechChangeAutomatic, speech.ErrRetuneNeedsReconnect, "retune,reconnect"}, + {"explicit preferences change", speechChangeExplicit, nil, "reconnect"}, + } { + t.Run(test.name, func(t *testing.T) { + settings := config.DefaultSettings() + updater := &recordingSpeechUpdater{retuneErr: test.retuneErr} + worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, updater) + next := settings + rate := 30.0 + next.DefaultVoice.Rate = &rate + if err := worker.applyRuntime(context.Background(), next, test.change); err != nil { + t.Fatal(err) + } + if got := strings.Join(updater.calls, ","); got != test.want { + t.Fatalf("speech backend calls = %s, want %s", got, test.want) + } + }) + } +} + +func TestEchoSpeakerRetuneRejectsChangedVoiceKinds(t *testing.T) { + path, _ := newRetuneServer(t) + settings := config.DefaultSettings() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + speaker := newEchoSpeaker(path, settings) + if err := speaker.Connect(ctx); err != nil { + t.Fatal(err) + } + defer speaker.Close(context.Background()) + next := settings + rate := 20.0 + next.SystemVoice = config.Voice{Rate: &rate} + if err := speaker.RetuneConfiguration(ctx, next); !errors.Is(err, speech.ErrRetuneNeedsReconnect) { + t.Fatalf("adding a system voice returned %v, want ErrRetuneNeedsReconnect", err) + } +} + +func TestAutomaticSpeechFailureRestoresAllVoices(t *testing.T) { + testAutomaticSpeechRestoration(t, false) +} + +func TestAutomaticSpeechCancellationRestoresAllVoices(t *testing.T) { + testAutomaticSpeechRestoration(t, true) +} + +func testAutomaticSpeechRestoration(t *testing.T, cancelOnReject bool) { + t.Helper() + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + var mu sync.Mutex + candidateRates := 0 + path, server := newRetuneServerWithHook(t, func(command string) string { + mu.Lock() + defer mu.Unlock() + if command == "SET SELF RATE 30" { + candidateRates++ + if candidateRates > 1 { + if cancelOnReject { + cancel() + } + return "500 REJECTED\r\n" + } + } + return "" + }) + oldRate := 10.0 + settings := config.DefaultSettings() + settings.DefaultVoice.Rate = &oldRate + speaker := newConfiguredSpeaker(path, settings) + if err := speaker.Connect(ctx); err != nil { + t.Fatal(err) + } + defer speaker.Close(context.Background()) + worker := newPreferencesWorker(slog.New(slog.DiscardHandler), settings, speaker) + next := settings + newRate := 30.0 + next.DefaultVoice.Rate = &newRate + if err := worker.applyRuntime(ctx, next, speechChangeAutomatic); err == nil { + t.Fatal("expected rejected automatic change") + } + recoveredCtx, recoveredCancel := context.WithTimeout(t.Context(), 3*time.Second) + defer recoveredCancel() + for _, kind := range []string{"default", "uppercase"} { + if err := speaker.SpeakVoice(recoveredCtx, "after failed change", kind); err != nil { + t.Fatal(err) + } + } + for id, history := range server.snapshot() { + lastRate := "" + for _, command := range history { + if strings.HasPrefix(command, "SET SELF RATE ") { + lastRate = strings.TrimPrefix(command, "SET SELF RATE ") + } + if command == "SPEAK" && lastRate != "10" { + t.Errorf("connection %d speaks at rate %s after rejected change; worker stores rate %.0f", id, lastRate, *worker.settings.DefaultVoice.Rate) + } + } + } + if candidateRates < 2 || !cancelOnReject && candidateRates < 3 { + t.Fatal("fixture did not exercise partial retune and failed replacement") + } +} diff --git a/internal/app/speech_worker_test.go b/internal/app/speech_worker_test.go index f8d080a..a474578 100644 --- a/internal/app/speech_worker_test.go +++ b/internal/app/speech_worker_test.go @@ -374,14 +374,34 @@ func TestSpeechDeliveryDiagnosticsIncludeUtteranceAndPolicy(t *testing.T) { logText := output.String() for _, expected := range []string{ `"cause":"object:text-changed:insert"`, - `"append":true`, - `"interrupt_previous":false`, + `"generation":0`, `"utterance":"Terminal output with Café and 猫."`, } { if !strings.Contains(logText, expected) { t.Fatalf("diagnostics %q do not contain %q", logText, expected) } } + // Delivery never interrupts; constant policy fields misled diagnosis. + if strings.Contains(logText, `"interrupt_previous"`) { + t.Fatalf("diagnostics %q report a fixed interruption policy", logText) + } +} + +func TestSpeechInterruptionDiagnosticsNameReason(t *testing.T) { + var output bytes.Buffer + logger := logging.New(&output, logging.Options{Level: slog.LevelDebug}) + worker := newSpeechWorker(logger, &orderedSpeaker{}) + worker.mutex.Lock() + worker.running = true + worker.pending = []speechRequest{{Text: "queued"}} + worker.interruptLocked("key press") + worker.mutex.Unlock() + logText := output.String() + for _, expected := range []string{`"speech interrupted"`, `"reason":"key press"`, `"dropped_pending":1`, `"retired_generation":0`} { + if !strings.Contains(logText, expected) { + t.Fatalf("diagnostics %q do not contain %q", logText, expected) + } + } } func TestNormalSpeechDeliveryDiagnosticsOmitUtterance(t *testing.T) { diff --git a/internal/app/tentacle_reader_test.go b/internal/app/tentacle_reader_test.go index 7540f53..1a9300f 100644 --- a/internal/app/tentacle_reader_test.go +++ b/internal/app/tentacle_reader_test.go @@ -465,7 +465,7 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { } next := worker.settings next.EnableSpeech = false - if err := worker.applyRuntime(t.Context(), next); err != nil { + if err := worker.applyRuntime(t.Context(), next, speechChangeExplicit); err != nil { t.Fatal(err) } count := len(recorder.values) @@ -476,14 +476,14 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) { t.Fatal("override enabled or connected disabled speech") } next.EnableSpeech = true - if err := worker.applyRuntime(t.Context(), next); err != nil { + if err := worker.applyRuntime(t.Context(), next, speechChangeExplicit); err != nil { t.Fatal(err) } if len(recorder.values) != count+1 || *recorder.values[len(recorder.values)-1].DefaultVoice.Rate != 83 { t.Fatal("reenabling did not apply pending override") } next.EnableSpeech = false - if err := worker.applyRuntime(t.Context(), next); err != nil { + if err := worker.applyRuntime(t.Context(), next, speechChangeExplicit); err != nil { t.Fatal(err) } count = len(recorder.values) diff --git a/internal/speech/speech.go b/internal/speech/speech.go index 2260703..780ec73 100644 --- a/internal/speech/speech.go +++ b/internal/speech/speech.go @@ -16,6 +16,9 @@ var DefaultSocketAddress = sd.DefaultSocketAddress var Discover = sd.Discover var ReadDefaults = sd.ReadDefaults +// ErrRetuneNeedsReconnect reports settings that only a fresh connection can apply. +var ErrRetuneNeedsReconnect = sd.ErrRetuneNeedsReconnect + func New(socket string) *Client { return NewWithSettings(socket, Settings{}) } func NewWithSettings(socket string, settings Settings) *Client { settings.ClientName = "cthulhu" diff --git a/tests/check_speech.py b/tests/check_speech.py index 7b00dae..e6b7fec 100755 --- a/tests/check_speech.py +++ b/tests/check_speech.py @@ -12,6 +12,11 @@ from native_test_session import run_private_session requiredTests = { + "TestConfiguredSpeakerRetuneKeepsQueuedSpeech", + "TestApplicationSwitchRetunesAndExplicitChangeReconnects", + "TestEchoSpeakerRetuneRejectsChangedVoiceKinds", + "TestAutomaticSpeechFailureRestoresAllVoices", + "TestAutomaticSpeechCancellationRestoresAllVoices", "TestSpeechWorkerRadioSelectionDoesNotCancelLabel", "TestPrivateWineReviewUpdatesPreserveQueuedTitleSpeech", "TestPrivateWineTitleSurvivesReviewFocusBurst",