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.
This commit is contained in:
Storm Dragon committed 2026-11-19 12:29:46 -05:00
1 parent 58d8f6bee1
commit ffc5107112
20 files changed
+569 -52

No files matched your search

+1 -1
View File
@@ -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 connected device itself and needs libusb 1.0 at runtime, which is loaded only
when DECtalk USB is selected. 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 profile model and editor. A sibling Go workspace can use local common-module
changes during development. changes during development.
See [profile verification](docs/testing/voice-profiles.md). See [profile verification](docs/testing/voice-profiles.md).
+14 -1
View File
@@ -1,6 +1,6 @@
# Primary voice profiles # 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. the released dependency; a sibling workspace remains useful for development.
Run shared tests with `GOWORK=off go test -race ./...` in screenreader-common. Run shared tests with `GOWORK=off go test -race ./...` in screenreader-common.
In Cthulhu, run `GOWORK=off go test ./internal/config ./internal/preferences 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. the currently configured primary voice keeps working after preset removal.
No running desktop reader needs to be restarted for the private checks. 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.
+1 -1
View File
@@ -3,7 +3,7 @@ module git.stormux.org/storm/cthulhu
go 1.27.2 go 1.27.2
require ( 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/godbus/dbus/v5 v5.1.0
github.com/gorilla/websocket v1.5.3 github.com/gorilla/websocket v1.5.3
github.com/pelletier/go-toml/v2 v2.4.3 github.com/pelletier/go-toml/v2 v2.4.3
+2 -2
View File
@@ -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.9.0 h1:eKyDKOhiE+xNsSPK9hjIm34g2hly7UeWRp6BXslvRDo=
git.stormux.org/storm/screenreader-common v0.8.0/go.mod h1:2LW1ooP+4sYH2ewpgutyUIzJPy2IlgfYFxNPS2L3Ul4= 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 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg= github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
+44
View File
@@ -119,6 +119,50 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti
return nil 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 // reopenHardware moves a hardware device to new settings (synthesizer or baud
// rate). The transport locks the device, so the current owner is released // 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 // before the new one opens; if the new settings cannot open it, the previous
+64 -22
View File
@@ -7,6 +7,7 @@ package app
import ( import (
"context" "context"
"errors" "errors"
"fmt"
"reflect" "reflect"
"sync" "sync"
"unicode" "unicode"
@@ -46,28 +47,7 @@ func (speaker *echoSpeaker) UpdateConfiguration(ctx context.Context, settings co
} }
return result return result
} }
voiceSettings := map[string]speech.Settings{"default": speechSettingsFromConfig(settings)} voiceSettings := echoVoiceSettings(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)
}
for _, kind := range []string{"default", "echo", "uppercase", "uppercase-echo", "hyperlink", "system"} { for _, kind := range []string{"default", "echo", "uppercase", "uppercase-echo", "hyperlink", "system"} {
values, exists := voiceSettings[kind] values, exists := voiceSettings[kind]
if !exists { if !exists {
@@ -101,6 +81,68 @@ func (speaker *echoSpeaker) UpdateConfiguration(ctx context.Context, settings co
_ = closeClients(retired) _ = closeClients(retired)
return nil 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 { func (speaker *echoSpeaker) client(kind string) *speech.Client {
if client := speaker.voices[kind]; client != nil { if client := speaker.voices[kind]; client != nil {
return client return client
+2 -2
View File
@@ -46,7 +46,7 @@ func TestAppliedInterruptionKeysPreserveQueuedSpeechAndSayAll(t *testing.T) {
live.Store(settings) live.Store(settings)
preferences := &preferencesWorker{settings: settings, live: live, speechWorker: speech} preferences := &preferencesWorker{settings: settings, live: live, speechWorker: speech}
settings.SpeechInterruption.Mode = input.InterruptCommonKeys 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) t.Fatal(err)
} }
deliver := func(name string) { 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") t.Fatal("common interruption key did not cancel Say All and pending output")
} }
settings.SpeechInterruption = input.InterruptionSettings{Mode: input.InterruptCustomKeys, Keys: []string{"F8"}} 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) t.Fatal(err)
} }
speech.Enqueue(speechRequest{Text: "Custom mode announcement"}) speech.Enqueue(speechRequest{Text: "Custom mode announcement"})
+2 -1
View File
@@ -74,12 +74,13 @@ func (worker *preferencesWorker) switchApplication(ctx context.Context, applicat
settings, err := worker.applicationSettings(application) settings, err := worker.applicationSettings(application)
if err == nil { if err == nil {
settings = worker.sessionKeyboard(settings) settings = worker.sessionKeyboard(settings)
err = worker.applyRuntime(ctx, settings) err = worker.applyRuntime(ctx, settings, speechChangeAutomatic)
} }
if err != nil { if err != nil {
worker.logger.Error("switch application settings", "application", application, "error", err) worker.logger.Error("switch application settings", "application", application, "error", err)
return return
} }
worker.logger.Debug("switched application settings", "application", application, "previous_application", worker.activeApp)
worker.activeApp = application worker.activeApp = application
if worker.live != nil { if worker.live != nil {
worker.live.application.Store(&application) worker.live.application.Store(&application)
+20 -5
View File
@@ -74,7 +74,7 @@ func (worker *preferencesWorker) applyNext(ctx context.Context, next config.Sett
if save && !worker.response("", false).CanSave { 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) 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) return worker.response(err.Error(), false)
} }
if worker.editingActive { if worker.editingActive {
@@ -126,7 +126,16 @@ func (worker *preferencesWorker) applyNext(ctx context.Context, next config.Sett
return response 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) keyboardChanged := next.KeyboardLayout != worker.settings.KeyboardLayout || !reflect.DeepEqual(next.CthulhuModifierKeys, worker.settings.CthulhuModifierKeys)
bindingsChanged := keyboardChanged || !reflect.DeepEqual(next.KeyBindings, worker.settings.KeyBindings) bindingsChanged := keyboardChanged || !reflect.DeepEqual(next.KeyBindings, worker.settings.KeyBindings)
bindingsCommitted := false bindingsCommitted := false
@@ -166,13 +175,13 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S
if speechApplied && !bindingsCommitted { if speechApplied && !bindingsCommitted {
restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
defer cancel() 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) worker.logger.Error("restore speech after failed preferences apply", "error", err)
} }
} }
}() }()
if next.EnableSpeech && (speechChanged || !worker.settings.EnableSpeech) { 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) return errors.New(message)
} }
speechApplied = true speechApplied = true
@@ -217,12 +226,18 @@ func (worker *preferencesWorker) applyKeyboard(ctx context.Context, settings con
return worker.bindings.SetKeyBindings(ctx, settings.KeyBindings) 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 var err error
if worker.updater == nil { if worker.updater == nil {
return "Speech is disabled or this backend cannot change settings." 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 { if updater, ok := worker.updater.(interface {
UpdateConfiguration(context.Context, config.Settings) error UpdateConfiguration(context.Context, config.Settings) error
}); ok { }); ok {
+46
View File
@@ -9,6 +9,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"strings" "strings"
"time"
"git.stormux.org/storm/cthulhu/internal/config" "git.stormux.org/storm/cthulhu/internal/config"
"git.stormux.org/storm/cthulhu/internal/preferences" "git.stormux.org/storm/cthulhu/internal/preferences"
@@ -139,10 +140,55 @@ func (worker *preferencesWorker) restorePreview(ctx context.Context) preferences
return response 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 { func (worker *preferencesWorker) updateSpeech(ctx context.Context, next config.Settings) error {
if worker.updater == nil { if worker.updater == nil {
return errors.New("speech is disabled or this backend cannot change settings") 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 { if updater, ok := worker.updater.(interface {
UpdateConfiguration(context.Context, config.Settings) error UpdateConfiguration(context.Context, config.Settings) error
}); ok { }); ok {
+1 -1
View File
@@ -168,7 +168,7 @@ func (worker *speechWorker) SetSecureInputActive(active bool) {
worker.secure = active worker.secure = active
if active { if active {
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
worker.interruptLocked() worker.interruptLocked("secure input")
} }
} }
+5 -2
View File
@@ -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 // 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) { func (worker *speechWorker) logDelivery(ctx context.Context, request speechRequest, text string, readAllIndex int) {
if !worker.logger.Enabled(ctx, slog.LevelDebug) { if !worker.logger.Enabled(ctx, slog.LevelDebug) {
return return
@@ -262,7 +265,7 @@ func (worker *speechWorker) logDelivery(ctx context.Context, request speechReque
} }
worker.logger.DebugContext(ctx, "delivering accessible presentation", worker.logger.DebugContext(ctx, "delivering accessible presentation",
"role", request.Role, "cause", request.Cause, "utterance", text, "role", request.Role, "cause", request.Cause, "utterance", text,
"append", true, "interrupt_previous", false, "generation", request.deliveryGeneration,
"character", request.Character, "custom_echo", request.CustomEcho, "character", request.Character, "custom_echo", request.CustomEcho,
"read_all_index", readAllIndex) "read_all_index", readAllIndex)
} }
+2 -2
View File
@@ -31,7 +31,7 @@ func TestPreferencesEnableAndDisableSpeechDuringSession(t *testing.T) {
worker.speechWorker = speechWorker worker.speechWorker = speechWorker
enabled := settings enabled := settings
enabled.EnableSpeech = true 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) t.Fatal(err)
} }
if updates != 1 { if updates != 1 {
@@ -45,7 +45,7 @@ func TestPreferencesEnableAndDisableSpeechDuringSession(t *testing.T) {
if got := <-speaker.spoken; got != "enabled" { if got := <-speaker.spoken; got != "enabled" {
t.Fatalf("spoken text = %q", got) 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) t.Fatal(err)
} }
if updates != 1 { if updates != 1 {
+11 -6
View File
@@ -44,11 +44,13 @@ func (worker *speechWorker) SetEnabled(enabled bool) {
worker.enabled = enabled worker.enabled = enabled
if !enabled { if !enabled {
worker.startupUntil = time.Time{} 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() worker.retireRemoteSpeechLocked()
if worker.hintCancel != nil { if worker.hintCancel != nil {
worker.hintCancel() worker.hintCancel()
@@ -68,11 +70,14 @@ func (worker *speechWorker) interruptLocked() {
worker.readAllCancel = nil worker.readAllCancel = nil
} }
if time.Now().Before(worker.startupUntil) { if time.Now().Before(worker.startupUntil) {
worker.logger.Debug("kept startup speech despite interruption", "reason", reason)
return return
} }
if !worker.running { if !worker.running {
return return
} }
worker.logger.Debug("speech interrupted", "reason", reason, "dropped_pending", len(worker.pending),
"retired_generation", worker.generation)
completeSpeechRequests(worker.pending, context.Canceled) completeSpeechRequests(worker.pending, context.Canceled)
worker.pending = nil worker.pending = nil
worker.generation++ worker.generation++
@@ -90,7 +95,7 @@ func (worker *speechWorker) BeginReadAll(ctx context.Context, timestamp uint32)
defer worker.mutex.Unlock() defer worker.mutex.Unlock()
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
if !worker.hasUninterruptibleLocked() { if !worker.hasUninterruptibleLocked() {
worker.interruptLocked() worker.interruptLocked("read all started")
} else if worker.readAllCancel != nil { } else if worker.readAllCancel != nil {
worker.readAllCancel() worker.readAllCancel()
} }
@@ -139,7 +144,7 @@ func (worker *speechWorker) interruptForInputLocked(event input.Event) bool {
return false return false
} }
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
worker.interruptLocked() worker.interruptLocked("key press")
return true return true
} }
@@ -157,7 +162,7 @@ func (worker *speechWorker) ProtectCommand(timestamp uint32) {
} }
if !worker.hasUninterruptibleLocked() { if !worker.hasUninterruptibleLocked() {
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
worker.interruptLocked() worker.interruptLocked("command")
} }
} }
@@ -177,7 +182,7 @@ func (worker *speechWorker) InterruptForUser() {
return return
} }
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
worker.interruptLocked() worker.interruptLocked("user action")
} }
func (worker *speechWorker) cancelActiveSpeech(ctx context.Context) { func (worker *speechWorker) cancelActiveSpeech(ctx context.Context) {
+1 -1
View File
@@ -36,7 +36,7 @@ func (worker *speechWorker) cycleSpeechMode() speechMode {
defer worker.mutex.Unlock() defer worker.mutex.Unlock()
worker.mode = (worker.mode + 1) % 3 worker.mode = (worker.mode + 1) % 3
worker.startupUntil = time.Time{} worker.startupUntil = time.Time{}
worker.interruptLocked() worker.interruptLocked("speech mode changed")
worker.logger.Debug("speech mode changed", "mode", worker.mode.announcement()) worker.logger.Debug("speech mode changed", "mode", worker.mode.announcement())
return worker.mode return worker.mode
} }
+320
View File
@@ -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")
}
}
+22 -2
View File
@@ -374,14 +374,34 @@ func TestSpeechDeliveryDiagnosticsIncludeUtteranceAndPolicy(t *testing.T) {
logText := output.String() logText := output.String()
for _, expected := range []string{ for _, expected := range []string{
`"cause":"object:text-changed:insert"`, `"cause":"object:text-changed:insert"`,
`"append":true`, `"generation":0`,
`"interrupt_previous":false`,
`"utterance":"Terminal output with Café and 猫."`, `"utterance":"Terminal output with Café and 猫."`,
} { } {
if !strings.Contains(logText, expected) { if !strings.Contains(logText, expected) {
t.Fatalf("diagnostics %q do not contain %q", 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) { func TestNormalSpeechDeliveryDiagnosticsOmitUtterance(t *testing.T) {
+3 -3
View File
@@ -465,7 +465,7 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) {
} }
next := worker.settings next := worker.settings
next.EnableSpeech = false 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) t.Fatal(err)
} }
count := len(recorder.values) count := len(recorder.values)
@@ -476,14 +476,14 @@ func TestReaderExtensionApplicationOverlayAndDisabledSpeech(t *testing.T) {
t.Fatal("override enabled or connected disabled speech") t.Fatal("override enabled or connected disabled speech")
} }
next.EnableSpeech = true 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) t.Fatal(err)
} }
if len(recorder.values) != count+1 || *recorder.values[len(recorder.values)-1].DefaultVoice.Rate != 83 { if len(recorder.values) != count+1 || *recorder.values[len(recorder.values)-1].DefaultVoice.Rate != 83 {
t.Fatal("reenabling did not apply pending override") t.Fatal("reenabling did not apply pending override")
} }
next.EnableSpeech = false 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) t.Fatal(err)
} }
count = len(recorder.values) count = len(recorder.values)
+3
View File
@@ -16,6 +16,9 @@ var DefaultSocketAddress = sd.DefaultSocketAddress
var Discover = sd.Discover var Discover = sd.Discover
var ReadDefaults = sd.ReadDefaults 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 New(socket string) *Client { return NewWithSettings(socket, Settings{}) }
func NewWithSettings(socket string, settings Settings) *Client { func NewWithSettings(socket string, settings Settings) *Client {
settings.ClientName = "cthulhu" settings.ClientName = "cthulhu"
+5
View File
@@ -12,6 +12,11 @@ from native_test_session import run_private_session
requiredTests = { requiredTests = {
"TestConfiguredSpeakerRetuneKeepsQueuedSpeech",
"TestApplicationSwitchRetunesAndExplicitChangeReconnects",
"TestEchoSpeakerRetuneRejectsChangedVoiceKinds",
"TestAutomaticSpeechFailureRestoresAllVoices",
"TestAutomaticSpeechCancellationRestoresAllVoices",
"TestSpeechWorkerRadioSelectionDoesNotCancelLabel", "TestSpeechWorkerRadioSelectionDoesNotCancelLabel",
"TestPrivateWineReviewUpdatesPreserveQueuedTitleSpeech", "TestPrivateWineReviewUpdatesPreserveQueuedTitleSpeech",
"TestPrivateWineTitleSurvivesReviewFocusBurst", "TestPrivateWineTitleSurvivesReviewFocusBurst",