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:
1 parent
58d8f6bee1
commit
ffc5107112
20 files changed
+569
-52
No files matched your search
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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"})
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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"
|
||||
|
||||
Reference in new issue
Block a user