Agent review pass.
This commit is contained in:
1 parent
e9b2e9508b
commit
64ee749a8e
105 files changed
+2098
-320
No files matched your search
@@ -148,7 +148,7 @@ func (worker *brailleWorker) enqueueSecureFrameLocked(frame braille.Frame, base
|
||||
if base || restoresBase {
|
||||
worker.baseFrame.ID = frame.ID
|
||||
}
|
||||
if base {
|
||||
if base || restoresBase {
|
||||
worker.exportLocked(frame, frame.ID)
|
||||
}
|
||||
frame.Routes = append([]braille.TextRoute(nil), frame.Routes...)
|
||||
|
||||
@@ -36,6 +36,12 @@ type configuredSpeaker struct {
|
||||
socket string
|
||||
settings config.Settings
|
||||
closed bool
|
||||
// stranded records that a hardware reopen released the old device
|
||||
// and both the candidate and the restore failed, leaving no active
|
||||
// voice. Preferences rollback uses it to retry the previous
|
||||
// configuration; ordinary failed updates keep the old voice and
|
||||
// must not be re-applied (that would cancel live speech).
|
||||
stranded bool
|
||||
}
|
||||
|
||||
func newConfiguredSpeaker(socket string, settings config.Settings) *configuredSpeaker {
|
||||
@@ -109,6 +115,7 @@ func (speaker *configuredSpeaker) UpdateConfiguration(ctx context.Context, setti
|
||||
}
|
||||
}
|
||||
speaker.active = candidate
|
||||
speaker.stranded = false
|
||||
speaker.mu.Unlock()
|
||||
speaker.retireRemoteVoice(settings)
|
||||
// The new backend is committed. A retired connection's cleanup error must
|
||||
@@ -191,6 +198,9 @@ func (speaker *configuredSpeaker) reopenHardware(ctx context.Context, old *hardw
|
||||
next = &hardwareSpeaker{device: old.device, baud: old.baud, synth: old.synth, settings: old.settings}
|
||||
old.mu.RUnlock()
|
||||
if err := next.Connect(context.Background()); err != nil {
|
||||
speaker.mu.Lock()
|
||||
speaker.stranded = true
|
||||
speaker.mu.Unlock()
|
||||
return errors.Join(connectErr, err)
|
||||
}
|
||||
}
|
||||
@@ -201,6 +211,7 @@ func (speaker *configuredSpeaker) reopenHardware(ctx context.Context, old *hardw
|
||||
return errors.New("speech configuration was canceled")
|
||||
}
|
||||
speaker.active = next
|
||||
speaker.stranded = false
|
||||
speaker.mu.Unlock()
|
||||
if connectErr != nil {
|
||||
return connectErr
|
||||
@@ -209,6 +220,15 @@ func (speaker *configuredSpeaker) reopenHardware(ctx context.Context, old *hardw
|
||||
return nil
|
||||
}
|
||||
|
||||
// speechStranded reports whether the last hardware reopen left no
|
||||
// active voice (see the stranded field). Preferences rollback retries
|
||||
// the previous configuration only in that case.
|
||||
func (speaker *configuredSpeaker) speechStranded() bool {
|
||||
speaker.mu.RLock()
|
||||
defer speaker.mu.RUnlock()
|
||||
return speaker.stranded && !speaker.closed
|
||||
}
|
||||
|
||||
func (speaker *configuredSpeaker) voice() (configuredVoice, error) {
|
||||
speaker.mu.RLock()
|
||||
defer speaker.mu.RUnlock()
|
||||
@@ -361,10 +381,19 @@ func (speaker *hardwareSpeaker) SpeakVoice(ctx context.Context, text, kind strin
|
||||
}
|
||||
return speaker.speak(ctx, text, false, kind)
|
||||
}
|
||||
func (speaker *hardwareSpeaker) speak(ctx context.Context, text string, echo bool, kind string) error {
|
||||
speaker.mu.RLock()
|
||||
defer speaker.mu.RUnlock()
|
||||
settings := speaker.settings
|
||||
|
||||
// Unset hardware voice fields fall back to the old-scale mids (rate 50 of
|
||||
// 0..99, pitch/volume 5 of 0..9) converted with the hardware legacy
|
||||
// formula config migration uses, hardware.LegacyValue: rate
|
||||
// round(200*50/99-100) = 1, pitch/volume round(200*5/9-100) = 11 on the
|
||||
// -100..100 scale hardware.Parameters expects.
|
||||
const (
|
||||
hardwareDefaultRate = 1.0
|
||||
hardwareDefaultPitch = 11.0
|
||||
hardwareDefaultVolume = 11.0
|
||||
)
|
||||
|
||||
func hardwareVoiceFor(settings config.Settings, echo bool, kind string) speech.HardwareVoice {
|
||||
voice := config.EffectiveVoice(settings, "default")
|
||||
if echo && settings.UseCustomEchoVoice {
|
||||
if value := settings.EchoVoice.Rate; value != nil {
|
||||
@@ -382,18 +411,24 @@ func (speaker *hardwareSpeaker) speak(ctx context.Context, text string, echo boo
|
||||
// Hardware has a single serial engine; echo uses that same synth with its
|
||||
// custom numeric voice settings. Restore the default values each utterance.
|
||||
if voice.Rate == nil {
|
||||
value := 50.0
|
||||
value := hardwareDefaultRate
|
||||
voice.Rate = &value
|
||||
}
|
||||
if voice.AveragePitch == nil {
|
||||
value := 5.0
|
||||
value := hardwareDefaultPitch
|
||||
voice.AveragePitch = &value
|
||||
}
|
||||
if voice.Gain == nil {
|
||||
value := 5.0
|
||||
value := hardwareDefaultVolume
|
||||
voice.Gain = &value
|
||||
}
|
||||
return speaker.client.Speak(ctx, text, speech.HardwareVoice{Rate: voice.Rate, Pitch: voice.AveragePitch, Volume: voice.Gain})
|
||||
return speech.HardwareVoice{Rate: voice.Rate, Pitch: voice.AveragePitch, Volume: voice.Gain}
|
||||
}
|
||||
|
||||
func (speaker *hardwareSpeaker) speak(ctx context.Context, text string, echo bool, kind string) error {
|
||||
speaker.mu.RLock()
|
||||
defer speaker.mu.RUnlock()
|
||||
return speaker.client.Speak(ctx, text, hardwareVoiceFor(speaker.settings, echo, kind))
|
||||
}
|
||||
func (speaker *hardwareSpeaker) SpeakAndWait(ctx context.Context, text string, began func()) error {
|
||||
return speaker.SpeakVoiceAndWait(ctx, text, "default", began)
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"testing"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/config"
|
||||
)
|
||||
|
||||
func TestHardwareVoiceDefaultsUseNewScale(t *testing.T) {
|
||||
settings := config.DefaultSettings()
|
||||
settings.DefaultVoice = config.Voice{}
|
||||
voice := hardwareVoiceFor(settings, false, "default")
|
||||
for _, check := range []struct {
|
||||
name string
|
||||
got *float64
|
||||
want float64
|
||||
}{
|
||||
{"rate", voice.Rate, 1},
|
||||
{"pitch", voice.Pitch, 11},
|
||||
{"volume", voice.Volume, 11},
|
||||
} {
|
||||
if check.got == nil || *check.got != check.want {
|
||||
t.Fatalf("unset hardware %s = %v, want %g", check.name, check.got, check.want)
|
||||
}
|
||||
}
|
||||
rate, pitch, gain := -20.0, 30.0, 40.0
|
||||
settings.DefaultVoice = config.Voice{Rate: &rate, AveragePitch: &pitch, Gain: &gain}
|
||||
voice = hardwareVoiceFor(settings, false, "default")
|
||||
if *voice.Rate != rate || *voice.Pitch != pitch || *voice.Volume != gain {
|
||||
t.Fatalf("explicit hardware voice changed: %+v", voice)
|
||||
}
|
||||
}
|
||||
|
||||
type failingFirstSpeechUpdater struct {
|
||||
calls []config.Settings
|
||||
stranded bool
|
||||
}
|
||||
|
||||
func (updater *failingFirstSpeechUpdater) speechStranded() bool { return updater.stranded }
|
||||
|
||||
func (updater *failingFirstSpeechUpdater) UpdateConfiguration(_ context.Context, settings config.Settings) error {
|
||||
updater.calls = append(updater.calls, settings)
|
||||
if len(updater.calls) == 1 {
|
||||
// The candidate and reopenHardware's own restore both failed,
|
||||
// leaving no active voice.
|
||||
updater.stranded = true
|
||||
return errors.New("hardware candidate and restore failed")
|
||||
}
|
||||
updater.stranded = false
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestApplyRuntimeRestoresSpeechAfterFailedSwap(t *testing.T) {
|
||||
current := config.DefaultSettings()
|
||||
currentRate := 10.0
|
||||
current.DefaultVoice.Rate = ¤tRate
|
||||
updater := &failingFirstSpeechUpdater{}
|
||||
worker := newPreferencesWorker(slog.New(slog.DiscardHandler), current, updater)
|
||||
next := current
|
||||
nextRate := 80.0
|
||||
next.DefaultVoice = config.Voice{Rate: &nextRate, AveragePitch: current.DefaultVoice.AveragePitch, Gain: current.DefaultVoice.Gain, Family: current.DefaultVoice.Family}
|
||||
if err := worker.applyRuntime(context.Background(), next, speechChangeExplicit); err == nil {
|
||||
t.Fatal("failed speech swap was accepted")
|
||||
}
|
||||
if len(updater.calls) != 2 {
|
||||
t.Fatalf("speech updates = %d, want candidate plus restore attempt", len(updater.calls))
|
||||
}
|
||||
restored := updater.calls[1]
|
||||
if restored.DefaultVoice.Rate == nil || *restored.DefaultVoice.Rate != currentRate {
|
||||
t.Fatalf("restore used %+v, want previous rate %g", restored.DefaultVoice, currentRate)
|
||||
}
|
||||
}
|
||||
@@ -265,7 +265,12 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) {
|
||||
if state.pending.terminalRepaint.event.Type == "" {
|
||||
return
|
||||
}
|
||||
deleted := state.pending.terminalRepaint.deleted
|
||||
pending, _ := state.pending.terminalRepaint.take()
|
||||
if deleted {
|
||||
logger.Debug("dropped deleted terminal repaint", "role", pending.Source.Role)
|
||||
return
|
||||
}
|
||||
if isTrivialTerminalRepaint(pending) {
|
||||
logger.Debug("dropped trivial terminal repaint fragment", "role", pending.Source.Role)
|
||||
return
|
||||
@@ -327,10 +332,19 @@ func (handler *accessibilityEventHandler) handle(event atspi.Event) {
|
||||
return
|
||||
}
|
||||
if event.Type == atspi.TextDeletedEvent && event.Source.Role == "terminal" {
|
||||
if state.pending.terminalRepaint.event.Type != "" &&
|
||||
!shouldIgnoreTerminalScrollback(event) &&
|
||||
(isUserTerminalDeletion(event, intent) || !terminalReplacementOverlap(state.pending.terminalRepaint.event, event)) {
|
||||
flushTerminalRepaint()
|
||||
if state.pending.terminalRepaint.event.Type != "" && !shouldIgnoreTerminalScrollback(event) {
|
||||
if !isUserTerminalDeletion(event, intent) &&
|
||||
terminalReplacementOverlap(state.pending.terminalRepaint.event, event) {
|
||||
// The held repaint's region is being deleted. Mark it
|
||||
// deleted rather than clearing it: a replacement
|
||||
// insertion (the usual repaint pair) revives it under
|
||||
// its first deadline, while a deletion with no
|
||||
// replacement is dropped at flush instead of speaking
|
||||
// text that is already gone.
|
||||
state.pending.terminalRepaint.deleted = true
|
||||
} else {
|
||||
flushTerminalRepaint()
|
||||
}
|
||||
}
|
||||
if shouldIgnoreTerminalScrollback(event) {
|
||||
logger.Debug("skipped terminal scrollback deletion", "role", event.Source.Role)
|
||||
|
||||
@@ -344,7 +344,12 @@ func processEventsWithAttributes(
|
||||
state.pending.clear()
|
||||
continue
|
||||
}
|
||||
deleted := state.pending.terminalRepaint.deleted
|
||||
event, _ := state.pending.terminalRepaint.take()
|
||||
if deleted {
|
||||
logger.Debug("dropped deleted terminal repaint", "role", event.Source.Role)
|
||||
continue
|
||||
}
|
||||
if isTrivialTerminalRepaint(event) {
|
||||
logger.Debug("dropped trivial terminal repaint fragment", "role", event.Source.Role)
|
||||
continue
|
||||
|
||||
@@ -20,6 +20,11 @@ type pendingPresentation struct {
|
||||
intent input.Intent
|
||||
timer *time.Timer
|
||||
ready <-chan time.Time
|
||||
// deleted marks a held terminal repaint whose region a program
|
||||
// deletion removed. It stays pending (keeping its first deadline)
|
||||
// in case a replacement insertion follows; flushes drop it while
|
||||
// set. Only terminalRepaint uses it.
|
||||
deleted bool
|
||||
}
|
||||
|
||||
func (pending *pendingPresentation) schedule(event atspi.Event, intent input.Intent, delay time.Duration) {
|
||||
|
||||
@@ -135,6 +135,13 @@ const (
|
||||
speechChangeAutomatic // An application switch; queued speech finishes.
|
||||
)
|
||||
|
||||
// speechStranded reports whether the speech backend lost its only
|
||||
// voice to a failed swap and needs the previous configuration retried.
|
||||
func (worker *preferencesWorker) speechStranded() bool {
|
||||
stranded, ok := worker.updater.(interface{ speechStranded() bool })
|
||||
return ok && stranded.speechStranded()
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -170,9 +177,15 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S
|
||||
}
|
||||
}
|
||||
speechChanged := !reflect.DeepEqual(tentaclewire.SpeechFromSettings(effectiveNext), tentaclewire.SpeechFromSettings(effectiveCurrent))
|
||||
speechApplied := false
|
||||
// Roll back a committed speech swap when a later step fails, and
|
||||
// also retry the previous configuration when a failed swap stranded
|
||||
// speech with no active voice (reopenHardware releases the old
|
||||
// device before the candidate connects, and its own restore can
|
||||
// also fail). An ordinary failed swap keeps the old voice serving;
|
||||
// re-applying then would only cancel live speech.
|
||||
speechAttempted, speechApplied := false, false
|
||||
defer func() {
|
||||
if speechApplied && !bindingsCommitted {
|
||||
if (speechApplied || speechAttempted && worker.speechStranded()) && !bindingsCommitted {
|
||||
restoreCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second)
|
||||
defer cancel()
|
||||
if err := worker.changeSpeech(restoreCtx, effectiveCurrent, change); err != nil {
|
||||
@@ -181,6 +194,7 @@ func (worker *preferencesWorker) applyRuntime(ctx context.Context, next config.S
|
||||
}
|
||||
}()
|
||||
if next.EnableSpeech && (speechChanged || !worker.settings.EnableSpeech) {
|
||||
speechAttempted = true
|
||||
if message := worker.applySpeechSettings(ctx, effectiveNext, change); message != "" {
|
||||
return errors.New(message)
|
||||
}
|
||||
|
||||
@@ -24,8 +24,9 @@ type tentacleStartupCall struct {
|
||||
|
||||
// A retired package stays on disk until the session using it has joined.
|
||||
type tentacleRetiredPackage struct {
|
||||
entry tentacle.Entry
|
||||
session *tentacle.Session
|
||||
entry tentacle.Entry
|
||||
session *tentacle.Session
|
||||
reported bool
|
||||
}
|
||||
|
||||
// tentacleLifecycle owns managed state for one run, on the lifecycle goroutine.
|
||||
@@ -224,8 +225,12 @@ func (owner *tentacleLifecycle) removeRetiredPackages() {
|
||||
continue
|
||||
}
|
||||
if err := tentacle.RemovePackage(tentacle.PackageRoot(owner.runtime.registry.Path), entry); err != nil {
|
||||
owner.runtime.logger.Warn("remove tentacle package", "error", err)
|
||||
owner.runtime.report("Tentacle was removed, but its package files could not be deleted.")
|
||||
if !retired.reported {
|
||||
retired.reported = true
|
||||
owner.removedPackages[directory] = retired
|
||||
owner.runtime.logger.Warn("remove tentacle package", "error", err)
|
||||
owner.runtime.report("Tentacle was removed, but its package files could not be deleted.")
|
||||
}
|
||||
continue
|
||||
}
|
||||
delete(owner.removedPackages, directory)
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// Copyright (c) 2026 Storm Dragon
|
||||
// Authors: Storm Dragon, Angus Kola
|
||||
// SPDX-License-Identifier: GPL-3.0-or-later
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"git.stormux.org/storm/cthulhu/internal/tentacle"
|
||||
)
|
||||
|
||||
func TestRemoveRetiredPackagesReportsPersistentFailureOnce(t *testing.T) {
|
||||
directory := t.TempDir()
|
||||
registryPath := filepath.Join(directory, "registry.json")
|
||||
root := tentacle.PackageRoot(registryPath)
|
||||
if err := os.MkdirAll(root, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A regular file where a package directory is expected fails removal
|
||||
// on every attempt.
|
||||
packageDirectory := filepath.Join(root, "package-stuck")
|
||||
if err := os.WriteFile(packageDirectory, []byte("stuck"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runtime := &tentacleRuntime{
|
||||
logger: slog.New(slog.DiscardHandler),
|
||||
registry: &tentacle.Registry{Path: registryPath},
|
||||
announcements: make(chan string, 4),
|
||||
}
|
||||
entry := tentacle.Entry{ID: "stuck", PackageDirectory: packageDirectory}
|
||||
owner := &tentacleLifecycle{
|
||||
runtime: runtime,
|
||||
removedPackages: map[string]tentacleRetiredPackage{packageDirectory: {entry: entry}},
|
||||
}
|
||||
for range 3 {
|
||||
owner.removeRetiredPackages()
|
||||
}
|
||||
if _, retained := owner.removedPackages[packageDirectory]; !retained {
|
||||
t.Fatal("failed removal was not retained for retry")
|
||||
}
|
||||
reports := 0
|
||||
for {
|
||||
select {
|
||||
case <-runtime.announcements:
|
||||
reports++
|
||||
default:
|
||||
if reports != 1 {
|
||||
t.Fatalf("persistent failure reported %d times, want 1", reports)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -226,6 +226,36 @@ func TestRemoteBrailleInitialExportDuringFlashIsUnroutable(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteBrailleRoutingWorksAfterFlashRestore(t *testing.T) {
|
||||
router := peerRouteRecorder{routes: make(chan atspi.BrailleRoute, 1)}
|
||||
worker := &brailleWorker{cancel: func() {}, connected: true, wake: make(chan struct{}, 1), router: router}
|
||||
route := braille.TextRoute{Start: 0, End: 5, SourceStart: 0, TextLength: 5, BusName: ":1.2", Path: "/text", SourceText: "hello"}
|
||||
worker.EnqueueFrame(braille.Frame{Text: "hello", Cursor: -1, Routes: []braille.TextRoute{route}})
|
||||
var exported []braille.Frame
|
||||
worker.SetRemoteExport(func(frame braille.Frame) { exported = append(exported, frame) })
|
||||
if len(exported) != 1 || exported[0].ID == 0 {
|
||||
t.Fatalf("initial export = %+v", exported)
|
||||
}
|
||||
worker.FlashConfirmation("message", config.BrailleOptions{FlashMessages: true, FlashPersistent: true})
|
||||
worker.DismissConfirmation()
|
||||
if len(exported) < 2 {
|
||||
t.Fatal("restored base frame was not re-exported")
|
||||
}
|
||||
restored := exported[len(exported)-1]
|
||||
if restored.Text != "hello" || restored.ID == 0 || restored.ID == exported[0].ID || restored.ID != worker.current().ID {
|
||||
t.Fatalf("restored export = %+v, current ID %d", restored, worker.current().ID)
|
||||
}
|
||||
worker.RouteExported(t.Context(), braille.RoutingEvent{ID: restored.ID, Offset: 3})
|
||||
select {
|
||||
case routed := <-router.routes:
|
||||
if routed.Offset != 3 {
|
||||
t.Fatal("route changed", routed)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("peer route after flash restore did not reach the application")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteBrailleInitialExportSerializedWithUpdates(t *testing.T) {
|
||||
worker := &brailleWorker{cancel: func() {}, wake: make(chan struct{}, 1)}
|
||||
worker.EnqueueFrame(braille.Frame{Text: "initial", Cursor: -1})
|
||||
|
||||
@@ -120,8 +120,10 @@ func (runtime *tentacleRuntime) startRemoteCapture(ctx context.Context, session
|
||||
continue
|
||||
}
|
||||
if event.Ended != "" {
|
||||
runtime.logger.Debug("remote keyboard capture ended", "reason", event.Ended, "session", session.Identity(), "epoch", lease.Epoch)
|
||||
_ = session.PublishRemoteFocus(lease, tentaclewire.RemoteFocusLocal, event.Ended)
|
||||
endedLease := lease
|
||||
active, events, leaseDone = 0, nil, nil
|
||||
runtime.logger.Debug("remote keyboard capture ended", "reason", event.Ended, "session", session.Identity(), "epoch", endedLease.Epoch)
|
||||
_ = session.PublishRemoteFocus(endedLease, tentaclewire.RemoteFocusLocal, event.Ended)
|
||||
runtime.report("Keyboard returned to this computer.")
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -70,6 +70,14 @@ func (fake *fakeCaptureInput) emit(event input.RemoteCaptureEvent) {
|
||||
}
|
||||
}
|
||||
|
||||
// emitHeld sends an event without closing the stream, so a test can queue a
|
||||
// request between an Ended event and the owner's channel close.
|
||||
func (fake *fakeCaptureInput) emitHeld(event input.RemoteCaptureEvent) {
|
||||
fake.mu.Lock()
|
||||
defer fake.mu.Unlock()
|
||||
fake.stream <- event
|
||||
}
|
||||
|
||||
func captureNextEvent(t *testing.T, session *tentacle.Session) tentaclewire.SessionEvent {
|
||||
t.Helper()
|
||||
var event tentaclewire.SessionEvent
|
||||
@@ -203,3 +211,27 @@ func TestRemoteCaptureRequiresGrantAndOwner(t *testing.T) {
|
||||
t.Fatal("ungranted session attached capture")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemoteCaptureEndedClearsActiveBeforeStreamClose(t *testing.T) {
|
||||
session, _, fake, _ := captureFixture(t)
|
||||
lease := captureOpen(t, session)
|
||||
captureFocus(t, session, lease, 1, true)
|
||||
<-fake.begun
|
||||
captureNextEvent(t, session)
|
||||
// The owner reports the end but has not closed the stream yet.
|
||||
fake.emitHeld(input.RemoteCaptureEvent{Ended: "escape"})
|
||||
if event := captureNextEvent(t, session); event.Focus != "local" || event.Reason != "escape" {
|
||||
t.Fatal("escape not reported", event)
|
||||
}
|
||||
// A queued remote request must begin a fresh capture, not reuse the
|
||||
// ended one and falsely report remote focus.
|
||||
captureFocus(t, session, lease, 2, true)
|
||||
select {
|
||||
case <-fake.begun:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("request after Ended did not begin a new capture")
|
||||
}
|
||||
if event := captureNextEvent(t, session); event.Focus != "remote" || event.Reason != "requested" {
|
||||
t.Fatal("missing remote focus after re-capture", event)
|
||||
}
|
||||
}
|
||||
@@ -24,37 +24,6 @@ type coreForms interface {
|
||||
|
||||
const consentTab = "consent"
|
||||
|
||||
// authorizeRemote reserves a standalone core dialog. Interactive commands use
|
||||
// authorizeRemoteSession with their already-reserved slot and exact session.
|
||||
func (runtime *tentacleRuntime) authorizeRemote(ctx context.Context, id, role string, grants []string) (tentaclewire.SessionEvent, error) {
|
||||
if runtime == nil || runtime.remotePolicy == nil || !tentaclewire.ValidRoleGrants(role, grants) {
|
||||
return tentaclewire.SessionEvent{}, tentacle.ErrPermission
|
||||
}
|
||||
runtime.mutex.Lock()
|
||||
var target *tentacle.Session
|
||||
if !runtime.disabled {
|
||||
for _, session := range runtime.sessions {
|
||||
if session.TentacleID() == id {
|
||||
target = session
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
runtime.mutex.Unlock()
|
||||
if target == nil {
|
||||
return tentaclewire.SessionEvent{}, tentacle.ErrUnavailable
|
||||
}
|
||||
// Reserve the interaction before creating a ticket, so a second request
|
||||
// rejected as busy cannot invalidate the dialog already on screen.
|
||||
select {
|
||||
case runtime.interactionSlots <- struct{}{}:
|
||||
default:
|
||||
return tentaclewire.SessionEvent{}, tentacle.ErrBusy
|
||||
}
|
||||
defer func() { <-runtime.interactionSlots }()
|
||||
return runtime.authorizeRemoteSession(ctx, target, role, grants)
|
||||
}
|
||||
|
||||
// Caller owns interactionSlots. A child request may open a dialog, but only
|
||||
// local capture and the core-issued ticket can authorize the requesting session.
|
||||
func (runtime *tentacleRuntime) authorizeRemoteSession(ctx context.Context, target *tentacle.Session, role string, grants []string) (tentaclewire.SessionEvent, error) {
|
||||
@@ -122,12 +91,11 @@ func remoteConsentForm(id, role string, grants []string) commonui.Form {
|
||||
title := "Remote access for " + id + ": " + roleText + ". The relay can read session contents. Select access for this session."
|
||||
controls := []commonui.Control{{ID: "cancel", Label: "Cancel", Kind: commonui.Button, Action: "cancel", SkipValidation: true}}
|
||||
labels := map[string]string{
|
||||
"output-observe": "Share speech with the helper",
|
||||
"remote-present": "Hear the other computer",
|
||||
"keyboard-capture": "Keyboard control of the other computer. F11 returns here",
|
||||
"keyboard-inject": "Allow the helper to type here",
|
||||
"clipboard-exchange": "Clipboard text, transferred on request",
|
||||
"braille-stream": "Braille display and routing",
|
||||
"output-observe": "Share speech with the helper",
|
||||
"remote-present": "Hear the other computer",
|
||||
"keyboard-capture": "Keyboard control of the other computer. F11 returns here",
|
||||
"keyboard-inject": "Allow the helper to type here",
|
||||
"braille-stream": "Braille display and routing",
|
||||
}
|
||||
for _, grant := range grants {
|
||||
controls = append(controls, commonui.Control{ID: grant, Label: labels[grant], Kind: commonui.CheckBox})
|
||||
|
||||
@@ -77,7 +77,7 @@ func consentRuntimeFixture(t *testing.T) (*tentacleRuntime, *tentacle.Session, *
|
||||
if err := manager.UseRemotePolicy(policy); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
session, err := manager.Start(t.Context(), tentacle.Spec{ID: "consent-probe", Program: []string{executable, "-test.run=^TestRemoteManagementPeer$", "--", "remote-management-peer"}, SessionEvents: true, RemoteGrants: []string{"output-observe", "clipboard-exchange"}})
|
||||
session, err := manager.Start(t.Context(), tentacle.Spec{ID: "consent-probe", Program: []string{executable, "-test.run=^TestRemoteManagementPeer$", "--", "remote-management-peer"}, SessionEvents: true, RemoteGrants: []string{"output-observe", "braille-stream"}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -102,7 +102,7 @@ func TestRemoteConsentFormDefaultsAndRevocation(t *testing.T) {
|
||||
defer cancel()
|
||||
result := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := runtime.authorizeRemote(ctx, "consent-probe", "controlled", []string{"output-observe", "clipboard-exchange"})
|
||||
_, err := runtime.authorizeRemoteRequest(ctx, session, tentaclewire.RemoteRequest{Role: "controlled", Grants: []string{"output-observe", "braille-stream"}})
|
||||
result <- err
|
||||
}()
|
||||
var request consentFormRequest
|
||||
@@ -169,7 +169,7 @@ func TestRemoteConsentFormDefaultsAndRevocation(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := session.RemoteContext(lease, "clipboard-exchange"); err == nil {
|
||||
if _, err := session.RemoteContext(lease, "braille-stream"); err == nil {
|
||||
t.Fatal("unchecked permission granted")
|
||||
}
|
||||
gate.SetSuspended(true)
|
||||
@@ -202,7 +202,7 @@ type ordinaryOnlyForms struct{ tentacleForms }
|
||||
func TestRemoteConsentCannotFallBackToOrdinaryForms(t *testing.T) {
|
||||
runtime, session, _, _ := consentRuntimeFixture(t)
|
||||
runtime.forms = ordinaryOnlyForms{runtime.forms}
|
||||
if _, err := runtime.authorizeRemote(t.Context(), "consent-probe", "controlled", []string{"output-observe"}); err == nil {
|
||||
if _, err := runtime.authorizeRemoteSession(t.Context(), session, "controlled", []string{"output-observe"}); err == nil {
|
||||
t.Fatal("consent fell back to ordinary input")
|
||||
}
|
||||
form := tentaclewire.Form{Title: "Certificate review", Elements: []tentaclewire.Element{{ID: "cancel", Label: "Cancel", Kind: tentaclewire.Button}}}
|
||||
@@ -230,7 +230,7 @@ func TestRemoteOptionalGrantsRespectInstallationAndLocalSelection(t *testing.T)
|
||||
}
|
||||
completed := make(chan result, 1)
|
||||
go func() {
|
||||
action, err := runtime.authorizeRemoteRequest(t.Context(), session, tentaclewire.RemoteRequest{Role: "controlled", Grants: []string{"output-observe"}, OptionalGrants: []string{"clipboard-exchange", "keyboard-inject", "braille-stream"}})
|
||||
action, err := runtime.authorizeRemoteRequest(t.Context(), session, tentaclewire.RemoteRequest{Role: "controlled", Grants: []string{"output-observe"}, OptionalGrants: []string{"braille-stream", "keyboard-inject"}})
|
||||
completed <- result{action, err}
|
||||
}()
|
||||
request := nextRemoteForm(t, forms)
|
||||
@@ -243,7 +243,7 @@ func TestRemoteOptionalGrantsRespectInstallationAndLocalSelection(t *testing.T)
|
||||
}
|
||||
}
|
||||
}
|
||||
if !offered["output-observe"] || !offered["clipboard-exchange"] || offered["keyboard-inject"] || offered["braille-stream"] {
|
||||
if !offered["output-observe"] || !offered["braille-stream"] || offered["keyboard-inject"] {
|
||||
t.Fatal("uninstalled access offered", offered)
|
||||
}
|
||||
request.reply <- consentReply("output-observe", "keyboard-inject")
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
@@ -112,14 +113,19 @@ func (target keyboardOwnerTestTarget) Close() error {
|
||||
}
|
||||
|
||||
func TestRemoteKeyboardHelper(t *testing.T) {
|
||||
if len(os.Args) < 3 || os.Args[len(os.Args)-2] != "--epoch" {
|
||||
// The supervisor script re-execs this test binary with "--" and no
|
||||
// further arguments; the epoch arrives over the control pipe.
|
||||
if !slices.Contains(os.Args, "--") {
|
||||
return
|
||||
}
|
||||
epoch, _ := strconv.ParseUint(os.Args[len(os.Args)-1], 10, 64)
|
||||
control, err := remoteinput.AdoptPipe(os.Stdin, false)
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
epoch, err := remoteinput.ReadEpoch(control)
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
}
|
||||
output, err := remoteinput.AdoptPipe(os.Stdout, true)
|
||||
if err != nil {
|
||||
os.Exit(2)
|
||||
|
||||
@@ -85,4 +85,5 @@ func (pending *pendingPresentation) coalesceTerminalRepaint(event atspi.Event) {
|
||||
return
|
||||
}
|
||||
pending.event = event
|
||||
pending.deleted = false
|
||||
}
|
||||
@@ -684,3 +684,51 @@ func TestTerminalHeldRepaintPreservesOrderAndRetiresOnFocusChange(t *testing.T)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTerminalHeldRepaintRetiredByOverlappingDeletion(t *testing.T) {
|
||||
for _, next := range []string{"deletion-only", "replacement", "scrollback"} {
|
||||
t.Run(next, func(t *testing.T) {
|
||||
handler, spoken := terminalHandlerFixture(t)
|
||||
terminal := atspi.Snapshot{BusName: ":1.10", Path: "/terminal", Role: "terminal"}
|
||||
handler.handle(atspi.NewEventWithPayload(atspi.TextDeletedEvent, terminal, "Old status"))
|
||||
handler.handle(atspi.NewEventWithPayload(atspi.TextInsertedEvent, terminal, "Latest status"))
|
||||
if handler.state.pending.terminalRepaint.event.Type == "" {
|
||||
t.Fatal("repaint was not held")
|
||||
}
|
||||
deletion := atspi.NewEventWithPayload(atspi.TextDeletedEvent, terminal, "Latest status")
|
||||
if next == "scrollback" {
|
||||
// A scroll shift removes old lines before the caret line; it
|
||||
// must not retire a held repaint.
|
||||
deletion.Source.TextCaretKnown = true
|
||||
deletion.Source.BrailleLineStart = 100
|
||||
deletion.TextChangeLength = 10
|
||||
}
|
||||
handler.handle(deletion)
|
||||
switch next {
|
||||
case "scrollback":
|
||||
if handler.state.pending.terminalRepaint.event.Payload != "Latest status" {
|
||||
t.Fatal("scrollback shift retired held repaint")
|
||||
}
|
||||
case "deletion-only":
|
||||
if !handler.state.pending.terminalRepaint.deleted {
|
||||
t.Fatal("overlapping deletion did not retire held repaint")
|
||||
}
|
||||
for _, text := range *spoken {
|
||||
if text == "Latest status" {
|
||||
t.Fatal("deleted text was spoken")
|
||||
}
|
||||
}
|
||||
case "replacement":
|
||||
firstTimer := handler.state.pending.terminalRepaint.timer
|
||||
handler.handle(atspi.NewEventWithPayload(atspi.TextInsertedEvent, terminal, "Newer status"))
|
||||
pending := &handler.state.pending.terminalRepaint
|
||||
if pending.event.Payload != "Newer status" || pending.deleted {
|
||||
t.Fatalf("replacement did not revive repaint: %q deleted=%v", pending.event.Payload, pending.deleted)
|
||||
}
|
||||
if pending.timer != firstTimer {
|
||||
t.Fatal("replacement postponed the first deadline")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -417,7 +417,7 @@ func (titles *windowTitleController) flush() {
|
||||
if pending.changed && titles.repeatedWithinWindow(*pending, time.Now()) {
|
||||
if titles.logger != nil {
|
||||
titles.logger.Debug("suppressed repeated window title",
|
||||
"key", animatedWindowTitleKey(pending.text), "recent", len(titles.recent))
|
||||
"title_length", len(pending.text), "recent", len(titles.recent))
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user