Agent review pass.

This commit is contained in:
hjozwiak committed 2026-11-24 11:12:17 -05:00
1 parent e9b2e9508b
commit 64ee749a8e
105 files changed
+2078 -300

No files matched your search

+1 -1
View File
@@ -44,7 +44,7 @@ feature needs its headers.
- `go build -o build/cthulhu ./cmd/cthulhu`: build the reader.
- `go build -tags brlapi -o build/cthulhu-braille ./cmd/cthulhu-braille`: build the Braille helper.
- `go build -tags duckdb -o build/cthulhu ./cmd/cthulhu`: build the reader with `--debug-db` DuckDB debug-log support (needs duckdb headers at build time only; libduckdb is dlopen'ed at runtime and is an optional package dependency; test with `go test -tags duckdb ./internal/logging/ ./cmd/cthulhu/`).
- `go build -tags duckdb -o build/cthulhu ./cmd/cthulhu`: build the reader with `--debug-db` DuckDB debug-log support (needs duckdb headers at build time only; libduckdb is dlopen'ed at runtime and is an optional package dependency; test with `go test -tags duckdb ./internal/logging/ ./cmd/cthulhu/`). Packaged builds exclude `--debug-db`; build with `-tags duckdb` and the DuckDB headers to enable it.
- `go build -o build/cthulhu-input-helper ./cmd/cthulhu-input-helper`: build the remote input helper; install it beside the reader for incoming keyboard control.
- `go test ./... -count=1`: run default tests; native cases may skip.
- `go test -tags brlapi ./... -count=1`: run packaging checks.
+2 -2
View File
@@ -375,8 +375,8 @@ Add `--append` to preserve earlier sessions, for example
`cthulhu --debug-file /tmp/cthulhu.log --append`.
`--append` requires `--debug-file` or `--debug-db`. A log can still grow during a long session.
Builds compiled with `-tags duckdb` (needs the DuckDB headers at build time;
the `cthulhu-git` Arch package does not build it) also accept
Packaged builds exclude `--debug-db`; build with `-tags duckdb` and the
DuckDB headers to enable it. Builds compiled that way also accept
`--debug-db PATH`, which writes the same redacted debug records to a DuckDB
database instead of, or in addition to, the NDJSON file. This is an optional
developer feature; normal builds, tests and the lint gate do not need DuckDB.
+26 -3
View File
@@ -97,9 +97,33 @@ if [[ -z $goCommand ]]; then
loongarch64) archiveArch=loong64 ;;
*) fail "No Go bootstrap archive configured for $(uname -m). Install Go 1.21 or newer."
esac
# Pinned SHA-256 digests of the official archives for the go.mod Go
# release. Never fetch a digest from the archive's own origin: a mirror
# that can replace the archive could replace its .sha256 file too.
# Update this table whenever the go directive in go.mod changes.
case "$requiredVersion:$archiveArch" in
1.27.2:amd64) expectedChecksum=ecbadb99091a3f46e31f5f934b068b1864eafa7995211b39eaddf76996045fe5 ;;
1.27.2:arm64) expectedChecksum=94f3e30b8e374bc285e7dadc11e0865726b9bc6e85b841ccceaabc0214c6b7c8 ;;
1.27.2:armv6l) expectedChecksum=e25a174051d8675f87ac720aedcd25bf89ac652c4b82f26aa47919524725ed95 ;;
1.27.2:386) expectedChecksum=93dae4b7f463ed1e9c65e05561ce9fc5f7cd5c4ffca5e336248d48f3a2eab5fc ;;
1.27.2:ppc64le) expectedChecksum=059d5f01b1607a724ea5ae87c5589041a51c577a6f3f20099e49d00f31c803fa ;;
1.27.2:riscv64) expectedChecksum=420f3b8dac8b5a9d11f51e12b496ac27f02ab31cbe495067e355ed43b9fe3aa1 ;;
1.27.2:s390x) expectedChecksum=dfd01d1e08e4dbece2cd91e259953f87b858752037fd151da2f674c4fa09aeef ;;
1.27.2:loong64) expectedChecksum=b49a3b2f090934ca588c7a897d64bc12f844348a2cd35e301d8f4f50eaf3bfdb ;;
*) fail "No pinned SHA-256 for Go $requiredVersion on Linux/$archiveArch. Install Go $requiredVersion or newer, or add its official digest to build-cthulhu.sh."
esac
toolchainDir="${XDG_CACHE_HOME:-$HOME/.cache}/cthulhu/toolchains/go${requiredVersion}.linux-${archiveArch}"
goCommand="$toolchainDir/go/bin/go"
if [[ ! -x $goCommand ]]; then
digestFile="$toolchainDir/.archive.sha256"
if [[ -x $goCommand ]]; then
# A cached toolchain is trusted only if a previous verified download
# recorded the pinned digest for it.
cachedChecksum=""
if [[ -f $digestFile ]]; then
IFS= read -r cachedChecksum < "$digestFile" || true
fi
[[ $cachedChecksum == "$expectedChecksum" ]] || fail "Cached Go toolchain at $toolchainDir is unverified. Remove it and rerun to download a verified copy."
else
for dependency in curl tar sha256sum; do
command -v "$dependency" >/dev/null || fail "Install $dependency to bootstrap Go, or install Go $requiredVersion or newer."
done
@@ -109,8 +133,6 @@ if [[ -z $goCommand ]]; then
archiveURL="https://dl.google.com/go/go${requiredVersion}.linux-${archiveArch}.tar.gz"
echo "Downloading Go $requiredVersion for Linux/$archiveArch..."
curlFlags=(--fail --location --silent --show-error --proto '=https' --proto-redir '=https')
expectedChecksum=$(curl "${curlFlags[@]}" "$archiveURL.sha256")
[[ $expectedChecksum =~ ^[[:xdigit:]]{64}$ ]] || fail "Invalid Go archive checksum."
curl "${curlFlags[@]}" --output "$downloadDir/go.tar.gz" "$archiveURL"
printf '%s %s\n' "$expectedChecksum" "$downloadDir/go.tar.gz" | sha256sum --check --status || fail "Go archive checksum mismatch."
tar -xzf "$downloadDir/go.tar.gz" -C "$downloadDir"
@@ -120,6 +142,7 @@ if [[ -z $goCommand ]]; then
mkdir -p -- "$toolchainDir"
mv -T -- "$downloadDir/go" "$toolchainDir/go" || [[ -x $goCommand ]]
fi
printf '%s\n' "$expectedChecksum" > "$digestFile"
fi
unset GOROOT
fi
+20 -7
View File
@@ -7,12 +7,11 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"
"git.stormux.org/storm/cthulhu/internal/platform/xorg"
"git.stormux.org/storm/cthulhu/internal/remoteinput"
@@ -27,10 +26,10 @@ func main() {
}
func run() error {
flags := flag.NewFlagSet("cthulhu-input-helper", flag.ContinueOnError)
flags.SetOutput(io.Discard)
epoch := flags.Uint64("epoch", 0, "private input epoch")
if flags.Parse(os.Args[1:]) != nil || flags.NArg() != 0 || *epoch == 0 {
// The helper takes no arguments: the lease epoch arrives as the
// first frame over the private control pipe, never in argv where
// /proc/<pid>/cmdline would expose it to every local process.
if len(os.Args) != 1 {
return remoteinput.ErrProtocol
}
control, err := remoteinput.AdoptPipe(os.Stdin, false)
@@ -50,7 +49,21 @@ func run() error {
return err
}
defer lifetime.Close()
// Consume the epoch before installing signal handling or opening
// any native target: until then no keys can be held, so a signal
// may simply terminate the process, and a missing or malformed
// Hello fails within one watchdog instead of blocking forever.
if err := control.SetReadDeadline(time.Now().Add(remoteinput.Watchdog)); err != nil {
return remoteinput.ErrProtocol
}
epoch, err := remoteinput.ReadEpoch(control)
if err != nil {
return err
}
if err := control.SetReadDeadline(time.Time{}); err != nil {
return remoteinput.ErrProtocol
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
defer stop()
return xorg.ServeRemoteKeyHelper(ctx, *epoch, control, lifetime, output)
return xorg.ServeRemoteKeyHelper(ctx, epoch, control, lifetime, output)
}
+29 -4
View File
@@ -293,14 +293,39 @@ func run(ctx context.Context, arguments []string, stdout, stderr io.Writer) (res
return err
}
// resolvedDestination returns the cleaned absolute path with the parent
// directory (and a final symlink, even a dangling one) resolved, so aliases
// compare equal even when the target does not exist yet. Resolution errors
// fall back to the cleaned absolute path.
func resolvedDestination(path string, depth int) string {
absolute, err := filepath.Abs(path)
if err != nil {
return filepath.Clean(path)
}
directory, err := filepath.EvalSymlinks(filepath.Dir(absolute))
if err != nil {
return absolute
}
resolved := filepath.Join(directory, filepath.Base(absolute))
if depth < 40 {
if info, err := os.Lstat(resolved); err == nil && info.Mode()&os.ModeSymlink != 0 {
if target, err := os.Readlink(resolved); err == nil {
if !filepath.IsAbs(target) {
target = filepath.Join(directory, target)
}
return resolvedDestination(target, depth+1)
}
}
}
return resolved
}
// sameDestination reports whether two sink paths name the same file, via
// cleaned absolute paths or, when both exist, file identity (symlink and
// resolved absolute paths or, when both exist, file identity (symlink and
// ./ aliases). Sharing one file between the NDJSON and DuckDB sinks would
// corrupt both.
func sameDestination(a, b string) bool {
absA, errA := filepath.Abs(a)
absB, errB := filepath.Abs(b)
if errA == nil && errB == nil && absA == absB {
if resolvedDestination(a, 0) == resolvedDestination(b, 0) {
return true
}
infoA, errA := os.Stat(a)
+13 -1
View File
@@ -311,11 +311,23 @@ func TestAppendRequiresDebugSink(t *testing.T) {
}
func TestDebugFileAndDBSameFileRejected(t *testing.T) {
shared := filepath.Join(t.TempDir(), "debug.out")
directory := t.TempDir()
shared := filepath.Join(directory, "debug.out")
alias := filepath.Dir(shared) + string(filepath.Separator) + "." + string(filepath.Separator) + "debug.out"
// A dangling symlink and a symlinked parent must alias the absent target.
dangling := filepath.Join(directory, "debug-link")
if err := os.Symlink(shared, dangling); err != nil {
t.Fatal(err)
}
linkedDirectory := filepath.Join(directory, "linked")
if err := os.Symlink(directory, linkedDirectory); err != nil {
t.Fatal(err)
}
for _, arguments := range [][]string{
{"--debug-file", shared, "--debug-db", shared},
{"--debug-file", shared, "--debug-db", alias},
{"--debug-file", dangling, "--debug-db", shared},
{"--debug-file", filepath.Join(linkedDirectory, "debug.out"), "--debug-db", shared},
} {
var output bytes.Buffer
err := run(context.Background(), arguments, &output, &output)
@@ -0,0 +1,44 @@
pkgbase = cthulhu-git
pkgdesc = Desktop-agnostic screen reader with speech, Braille, and Tentacle support
pkgver = 2026.10.31.r588.g9680b58
pkgrel = 3
url = https://git.stormux.org/storm/cthulhu
arch = x86_64
arch = aarch64
arch = armv7h
license = GPL-3.0-or-later
makedepends = git
makedepends = go
makedepends = pkgconf
depends = glibc
depends = at-spi2-core
depends = glib2
depends = gdk-pixbuf2
depends = gtk3
depends = speech-dispatcher
depends = gstreamer
depends = gst-plugins-base
depends = gst-plugins-good
depends = brltty
depends = liblouis
depends = libx11
depends = libxres
depends = libxtst
depends = libxi
depends = libxfixes
depends = libxkbcommon
depends = xclip
depends = dbus
optdepends = git: Discover and update Tentacle repositories
optdepends = libusb: DECtalk USB hardware speech
optdepends = tesseract: OCR engine for text recognition
optdepends = tesseract-data-eng: English OCR language data
provides = cthulhu=2026.10.31.r588.g9680b58
conflicts = cthulhu
options = !debug
options = !lto
source = cthulhu::git+https://git.stormux.org/storm/cthulhu.git#branch=master
sha512sums = SKIP
optdepends_x86_64 = wine-access: Wine, Proton, NVDA Controller, and Tolk integration
pkgname = cthulhu-git
@@ -81,6 +81,8 @@ build() {
export CGO_LDFLAGS="${LDFLAGS}"
export GOPATH="${srcdir}/go"
export GOCACHE="${GOCACHE:-${srcdir}/go-build}"
export GOWORK=off
export GOTOOLCHAIN=local
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
go build -o build/cthulhu ./cmd/cthulhu
@@ -76,6 +76,8 @@ build() {
export CGO_LDFLAGS="${LDFLAGS}"
export GOPATH="${srcdir}/go"
export GOCACHE="${GOCACHE:-${srcdir}/go-build}"
export GOWORK=off
export GOTOOLCHAIN=local
export GOFLAGS="-buildmode=pie -trimpath -ldflags=-linkmode=external -mod=readonly -modcacherw"
go build -o build/cthulhu ./cmd/cthulhu
@@ -1,14 +0,0 @@
diff --git a/internal/wine/manager_test.go b/internal/wine/manager_test.go
index 438fe26..0a5a0bb 100644
--- a/internal/wine/manager_test.go
+++ b/internal/wine/manager_test.go
@@ -226,7 +226,8 @@ func TestManagerLaunchesAndStopsHelperForActivePrefix(t *testing.T) {
t.Setenv("CTHULHU_TEST_WINE_OUTPUT", output)
t.Setenv("DBUS_SESSION_BUS_ADDRESS", "unix:path=/reader-bus")
helper := filepath.Join(root, "helper")
- script := "#!/bin/sh\nprintf '%s\\n' \"$WINEPREFIX\" \"$CTHULHU_WINE_ACCESS_MANAGED\" \"$DBUS_SESSION_BUS_ADDRESS\" \"$DISPLAY\" > \"$CTHULHU_TEST_WINE_OUTPUT\"\nexec sleep 30\n"
+ // Publish the complete environment atomically; printf can issue multiple writes.
+ script := "#!/bin/sh\nprintf '%s\\n' \"$WINEPREFIX\" \"$CTHULHU_WINE_ACCESS_MANAGED\" \"$DBUS_SESSION_BUS_ADDRESS\" \"$DISPLAY\" > \"$CTHULHU_TEST_WINE_OUTPUT.tmp\"\nmv \"$CTHULHU_TEST_WINE_OUTPUT.tmp\" \"$CTHULHU_TEST_WINE_OUTPUT\"\nexec sleep 30\n"
if err := os.WriteFile(helper, []byte(script), 0700); err != nil {
t.Fatal(err)
}
@@ -1,43 +0,0 @@
diff --git a/internal/app/tentacle_interaction_test.go b/internal/app/tentacle_interaction_test.go
index db03ab2..52307f0 100644
--- a/internal/app/tentacle_interaction_test.go
+++ b/internal/app/tentacle_interaction_test.go
@@ -32,7 +32,9 @@ func TestTentacleInteractionPeer(t *testing.T) {
return sdk.Interaction{Form: &sdk.Form{Title: "Wormhole menu", Elements: []sdk.Element{{ID: "code", Label: "Wormhole code", Kind: sdk.Entry, Required: true, MaxLength: 256}}}, Next: next}, nil
}
submit := func(_ context.Context, raw json.RawMessage) (any, error) {
- os.WriteFile(marker, raw, 0600)
+ if err := write_tentacle_fixture_marker(marker, raw); err != nil {
+ return nil, err
+ }
return sdk.Interaction{Presentation: sdk.Presentation{Speech: "Submitted", Braille: "Submitted"}}, nil
}
commands := []sdk.Command{
diff --git a/internal/app/tentacles_test.go b/internal/app/tentacles_test.go
index 8b862fd..36ee001 100644
--- a/internal/app/tentacles_test.go
+++ b/internal/app/tentacles_test.go
@@ -19,6 +19,14 @@ import (
sdk "git.stormux.org/storm/cthulhu/sdk/go/tentacle"
)
+// Publish complete fixture data before readers can observe the marker.
+func write_tentacle_fixture_marker(markerPath string, data []byte) error {
+ if err := os.WriteFile(markerPath+".tmp", data, 0600); err != nil {
+ return err
+ }
+ return os.Rename(markerPath+".tmp", markerPath)
+}
+
// Subprocess fixture: no reader backend, network, or desktop access.
func TestTentacleReaderPeer(t *testing.T) {
if len(os.Args) < 3 || os.Args[len(os.Args)-2] != "reader-peer" {
@@ -41,7 +49,7 @@ func TestTentacleReaderPeer(t *testing.T) {
os.Exit(3)
}
group, _ := os.ReadFile("/proc/self/cgroup")
- if err := os.WriteFile(marker, group, 0600); err != nil {
+ if err := write_tentacle_fixture_marker(marker, group); err != nil {
return nil, err
}
if filepath.Base(marker) == "present-delay" {
+1 -1
View File
@@ -10,7 +10,7 @@ carries one `braille` object whose `op` selects its form:
| --- | --- | --- |
| `size` | controlled child to host | `width` 0–4,096: the controller's display; 0 stops export |
| `gesture` | controlled child to host; host to controller child | `gesture` `pan-left`, `pan-right` or `route`, with `index` for route |
| `cells` | host to controlled child; controller child to host | `cells`: 1–4,096 final dot values 0–255, never text |
| `cells` | host to controlled child; controller child to host | `cells`: final dot values 0–255, never text; 1–2,000 in a child request (8192-byte call bound), 1–4,096 in a host event |
| `geometry` | controller child to host (no width); host reply event with `width` | 0 means no local display |
The request reply acknowledges admission into a 16-item reader mailbox; a full
-1
View File
@@ -42,7 +42,6 @@ and reader-settings grants, plus independent remote grants:
| `keyboard-capture` | Controller consumes and forwards its local keyboard. |
| `keyboard-inject` | Controlled reader accepts remote key transitions. |
| `braille-stream` | Exchange display cells and supported Braille gestures. |
| `clipboard-exchange` | Explicit send and separately consented receive. |
`commands`, `session-events` and `remote-access` are API names, not capability
strings in 1.1. The installer checks manifest/catalog agreement and persists
+2 -1
View File
@@ -28,7 +28,8 @@ independently of control buffering, so a queued or incomplete key record cannot
postpone ownership cancellation until the control stream drains. Cancellation
is checked before every queued effect and after native calls return.
The helper requires `--epoch` with a nonzero uint64. That epoch is bookkeeping,
The helper takes no arguments. The reader launcher delivers a nonzero epoch
as the first frame over the private control pipe. That epoch is bookkeeping,
not consent or a secret. A future reader launcher must bind it to the original
approved controlled lease, check `keyboard-inject` and policy at delivery, and
keep all three pipes away from the network Tentacle. Possession of an inherited
+1 -1
View File
@@ -1,6 +1,6 @@
# Shared reader core acceptance
Both readers pin `screenreader-common` v0.4.0 for date/time formatting,
Both readers pin `screenreader-common` v0.9.0 for date/time formatting,
language-based voice selection, progress/tone synthesis, phonetic words, and
hardware protocol encoding. Standalone builds use that published module; the
sibling workspace remains available for local development. Verify standalone
+1 -1
View File
@@ -1,6 +1,6 @@
# Shared Speech Dispatcher acceptance
Both readers pin `screenreader-common` v0.4.0, which supplies the shared
Both readers pin `screenreader-common` v0.9.0, which supplies the shared
`speechdispatcher` package. Standalone builds use the published module;
the sibling Go workspace can also be used for local development.
+4 -3
View File
@@ -21,9 +21,10 @@ operational only; this contract remains normative if they differ.
## Established facts (verified live, 2026-11-01)
- Cthulhu sends one `--exclude-hook-program <name>` argument per entry in
the profile's `wine.excluded-hook-programs` setting, plus
`--no-dialog-reader` when a listed program (or the global
`wine.controller-only` setting) makes the prefix controller-only.
the profile's `wine.excluded-hook-programs` setting. Listing a program
never by itself adds `--no-dialog-reader`; that wholesale flag is sent
only for the global `wine.controller-only` setting, the environment
override, or a helper that did not confirm the exclusions it was sent.
- The wine-access helper enforces exclusions itself: a listed program's
thread never receives the native menu/input hooks, and its windows get
no dialog reading, from the helper's first foreground poll. Controller
+1 -1
View File
@@ -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...)
+43 -8
View File
@@ -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)
+79
View File
@@ -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 = &currentRate
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)
}
}
+17 -3
View File
@@ -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,11 +332,20 @@ 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)) {
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)
return
+5
View File
@@ -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
+5
View File
@@ -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) {
+16 -2
View File
@@ -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)
}
+5
View File
@@ -26,6 +26,7 @@ type tentacleStartupCall struct {
type tentacleRetiredPackage struct {
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 {
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)
+57
View File
@@ -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})
+4 -2
View File
@@ -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)
}
}
-32
View File
@@ -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) {
@@ -126,7 +95,6 @@ func remoteConsentForm(id, role string, grants []string) commonui.Form {
"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",
}
for _, grant := range grants {
+6 -6
View File
@@ -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)
+1
View File
@@ -85,4 +85,5 @@ func (pending *pendingPresentation) coalesceTerminalRepaint(event atspi.Event) {
return
}
pending.event = event
pending.deleted = false
}
+48
View File
@@ -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")
}
}
})
}
}
+1 -1
View File
@@ -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
}
+7
View File
@@ -381,6 +381,13 @@ func (adapter *Adapter) markProviderHung(busName string, at time.Time) {
if adapter.hungBuses == nil {
adapter.hungBuses = make(map[string]time.Time)
}
// Sweep expired entries on every mark so the map only ever holds buses
// hung within one cooldown window instead of growing without bound.
for bus, since := range adapter.hungBuses {
if at.Sub(since) > providerHungCooldown {
delete(adapter.hungBuses, bus)
}
}
adapter.hungBuses[busName] = at
}
+1 -1
View File
@@ -422,7 +422,7 @@ func (adapter *Adapter) readNativeDocumentCaret(ctx context.Context, position Ob
case DocumentCaretWord:
granularity = C.AtspiTextGranularity(C.ATSPI_TEXT_GRANULARITY_WORD)
}
rangeText := C.atspi_text_get_string_at_offset(text, C.gint(offset), granularity, &nativeErr)
rangeText := C.cthulhu_text_get_string_at_offset(text, C.gint(offset), granularity, &nativeErr)
if nativeErr != nil {
err := adapter.documentObjectError(position.ID(), nativeError("read document text", nativeErr))
C.g_error_free(nativeErr)
+6
View File
@@ -412,6 +412,12 @@ func cthulhuAtspiTreeCaptureCallback(userData unsafe.Pointer) {
request := <-adapter.treeRequests
captureDiagnosticsFrom(request.ctx).beginStage("callback-setup", request.reviewFocus, "")
adapter.applySecureReset()
// A deferred selection waits on a DEFAULT_IDLE source, which repeated
// G_PRIORITY_HIGH captures can overtake indefinitely. Flush it here so
// the selection that preceded this capture is presented first. The
// foreground tick needs no flush: it is a short 50ms timeout at default
// priority, so the idle source still runs between ticks.
C.cthulhu_flush_selection(adapter.callbackData)
if request.ctx.Err() != nil {
request.result <- treeCaptureResult{err: request.ctx.Err()}
return
+10 -4
View File
@@ -80,7 +80,12 @@ func (tree *AccessibleTree) DocumentLineAtOffset(ctx context.Context, reference
if node.Hidden {
continue
}
contributed := false
// Presentation indexes SourceContexts by content index, so every
// emitted range needs its own entry even when one node contributes
// several ranges to the same visual row. Fetch the owner's ancestry
// once per node, but append it once per range.
var ancestry []Snapshot
fetched := false
for _, textRange := range node.Text.Ranges {
if !boundsAreOnSameLine(caretRange.Bounds, textRange.Bounds) {
continue
@@ -88,11 +93,12 @@ func (tree *AccessibleTree) DocumentLineAtOffset(ctx context.Context, reference
if textRange.Text == "" {
continue
}
if !contributed {
if !fetched {
owner, _ := tree.DocumentContext(node.Reference)
line.SourceContexts = append(line.SourceContexts, owner.Ancestors)
contributed = true
ancestry = owner.Ancestors
fetched = true
}
line.SourceContexts = append(line.SourceContexts, ancestry)
line.Contents = append(line.Contents, DocumentContent{
Reference: node.Reference,
Snapshot: node.Snapshot,
+11 -3
View File
@@ -184,9 +184,17 @@ func TestDocumentLineAssemblesSameVisualRow(t *testing.T) {
}
nodes[index].Text = text
}
lineNode(3, "/heading", "heading", "Before", Rectangle{X: 0, Y: 100, Width: 50, Height: 20}, true)
lineNode(3, "/heading", "heading", "Before more", Rectangle{X: 0, Y: 100, Width: 100, Height: 20}, true)
lineNode(5, "/link", "link", "link text", Rectangle{X: 100, Y: 100, Width: 80, Height: 20}, true)
lineNode(6, "/other", "paragraph", "Other row", Rectangle{X: 0, Y: 200, Width: 80, Height: 20}, false)
// The heading contributes a second range to the same visual row. Each
// emitted range needs its own SourceContexts entry, or presentation
// (which indexes contexts by content index) attributes the link's
// ancestry to this fragment and runs past the end for the last one.
nodes[3].Text.Ranges = []TextRange{
{Start: 0, End: 6, Text: "Before", Bounds: Rectangle{X: 0, Y: 100, Width: 50, Height: 20}},
{Start: 7, End: 11, Text: "more", Bounds: Rectangle{X: 50, Y: 100, Width: 50, Height: 20}},
}
tree, err := NewAccessibleTree(testID("/root"), nodes)
if err != nil {
t.Fatal(err)
@@ -203,7 +211,7 @@ func TestDocumentLineAssemblesSameVisualRow(t *testing.T) {
for _, content := range line.Contents {
contents = append(contents, content.Text)
}
if !reflect.DeepEqual(contents, []string{"Before", "link text"}) {
if !reflect.DeepEqual(contents, []string{"Before", "more", "link text"}) {
t.Fatalf("line contents = %q", contents)
}
if line.Document.ID() != testID("/doc") {
@@ -219,7 +227,7 @@ func TestDocumentLineAssemblesSameVisualRow(t *testing.T) {
}
// The first fragment is outside the caret object's ancestry. Keep its
// original ancestry even though line.Context belongs to the caret.
if line.SourceContexts[0][1].ID() != testID("/doc") || line.SourceContexts[1][1].ID() != testID("/inner") {
if line.SourceContexts[0][1].ID() != testID("/doc") || line.SourceContexts[2][1].ID() != testID("/inner") {
t.Fatal("neighbor ancestry was replaced by caret ancestry")
}
}
+16
View File
@@ -42,6 +42,19 @@ type VirtualResponse struct {
// panning and routing maps, so remote cells match local behaviour apart from
// the explicit uncontracted table and static cursor. It exits on EOF.
func RunVirtual(ctx context.Context, input io.Reader, output io.Writer) error {
// A blocked Scan cannot observe ctx; closing a closable input (the
// helper's stdin) on cancellation unblocks it, as RunClient does.
if closer, ok := input.(io.Closer); ok {
done := make(chan struct{})
defer close(done)
go func() {
select {
case <-ctx.Done():
_ = closer.Close()
case <-done:
}
}()
}
scanner := bufio.NewScanner(input)
scanner.Buffer(make([]byte, 4096), 65536)
encoder := json.NewEncoder(output)
@@ -115,5 +128,8 @@ func RunVirtual(ctx context.Context, input io.Reader, output io.Writer) error {
return err
}
}
if ctx.Err() != nil {
return nil
}
return scanner.Err()
}
+29
View File
@@ -0,0 +1,29 @@
// Copyright (c) 2026 Storm Dragon
// Authors: Storm Dragon, Angus Kola
// SPDX-License-Identifier: GPL-3.0-or-later
package braille
import (
"context"
"io"
"testing"
"time"
)
func TestRunVirtualCancelUnblocksIdleInput(t *testing.T) {
reader, writer := io.Pipe()
defer writer.Close()
ctx, cancel := context.WithCancel(context.Background())
done := make(chan error, 1)
go func() { done <- RunVirtual(ctx, reader, io.Discard) }()
cancel()
select {
case err := <-done:
if err != nil {
t.Fatalf("cancelled RunVirtual: %v", err)
}
case <-time.After(5 * time.Second):
t.Fatal("RunVirtual did not return after cancellation on blocked input")
}
}
+20 -8
View File
@@ -64,7 +64,9 @@ func decodeDocument(contents []byte) (writableDocument, Settings, error) {
return writableDocument{}, Settings{}, fmt.Errorf("parse settings schema %d: %w", CurrentSchemaVersion, err)
}
if document.SchemaVersion < speechScaleSchemaVersion {
migrateSpeechScale(&document)
if err := migrateSpeechScale(&document); err != nil {
return writableDocument{}, Settings{}, err
}
}
settings, err := effectiveSettings(document)
if err != nil {
@@ -74,8 +76,9 @@ func decodeDocument(contents []byte) (writableDocument, Settings, error) {
}
// Schema 2 differs only in its legacy voice scale. The migrated document is
// written as the current schema on the next save.
func migrateSpeechScale(document *writableDocument) {
// written as the current schema on the next save. A legacy value outside
// its scale rejects the load, leaving the file untouched.
func migrateSpeechScale(document *writableDocument) error {
applicationProfiles := make(map[string]bool)
for _, name := range document.Applications {
applicationProfiles[name] = true
@@ -86,12 +89,20 @@ func migrateSpeechScale(document *writableDocument) {
if factory == nil && applicationProfiles[name] {
factory = globalFactory
}
for _, voice := range []**Voice{&profile.Speech.DefaultVoice, &profile.Speech.UppercaseVoice, &profile.Speech.HyperlinkVoice, &profile.Speech.SystemVoice, &profile.KeyEcho.EchoVoice} {
voices := []**Voice{&profile.Speech.DefaultVoice, &profile.Speech.UppercaseVoice, &profile.Speech.HyperlinkVoice, &profile.Speech.SystemVoice, &profile.KeyEcho.EchoVoice}
for index, voice := range voices {
if *voice != nil {
converted := voiceFromLegacy(**voice)
// Echo always uses Speech Dispatcher, including with serial output.
if voice != &profile.KeyEcho.EchoVoice && factory != nil && *factory == "hardwarefactory" {
converted = hardwareVoiceFromLegacy(**voice)
var converted Voice
var err error
// Echo always uses Speech Dispatcher, including with serial output,
// so it keeps the wider 0..100 / 0..10 legacy limits.
if index < len(voices)-1 && factory != nil && *factory == "hardwarefactory" {
converted, err = hardwareVoiceFromLegacy(**voice)
} else {
converted, err = voiceFromLegacy(**voice)
}
if err != nil {
return fmt.Errorf("profile %q: %w", name, err)
}
*voice = &converted
}
@@ -99,6 +110,7 @@ func migrateSpeechScale(document *writableDocument) {
document.Profiles[name] = profile
}
document.SchemaVersion = CurrentSchemaVersion
return nil
}
func effectiveSettings(document writableDocument) (Settings, error) {
+28 -5
View File
@@ -18,6 +18,8 @@
package config
import (
"math"
"git.stormux.org/storm/screenreader-common/datetime"
)
@@ -266,7 +268,7 @@ func applyLegacyEcho(settings *Settings, values rawSettings) {
settings.UseCustomEchoForSentence = *values.UseCustomEchoForSentence
}
if values.EchoVoice != nil {
mergeVoice(&settings.EchoVoice, voiceFromLegacy(*values.EchoVoice))
mergeVoice(&settings.EchoVoice, convertLegacyVoice(*values.EchoVoice, false))
}
if len(values.EchoSpeechServerInfo) > 1 {
settings.EchoSpeechServer = values.EchoSpeechServerInfo[1]
@@ -314,12 +316,33 @@ func applyLegacyEcho(settings *Settings, values rawSettings) {
func applyLegacyDefaultVoice(settings *Settings, values rawSettings) {
if voice, exists := values.Voices["default"]; exists {
converted := voiceFromLegacy(voice)
if settings.SpeechServerFactory == "hardwarefactory" {
converted = hardwareVoiceFromLegacy(voice)
mergeVoice(&settings.DefaultVoice, convertLegacyVoice(voice, settings.SpeechServerFactory == "hardwarefactory"))
}
mergeVoice(&settings.DefaultVoice, converted)
}
// convertLegacyVoice converts a Python legacy voice, rejecting values
// outside the legacy scale instead of clamping them. apply has no error
// path, so a rejected value is marked non-finite and the caller's
// validation of the imported settings fails the load.
func convertLegacyVoice(voice Voice, hardware bool) Voice {
var converted Voice
var err error
if hardware {
converted, err = hardwareVoiceFromLegacy(voice)
} else {
converted, err = voiceFromLegacy(voice)
}
if err == nil {
return converted
}
converted = cloneVoice(voice)
for _, field := range voiceFields(&converted) {
if *field != nil {
invalid := math.NaN()
*field = &invalid
}
}
return converted
}
func mergeVoice(target *Voice, source Voice) {
+27 -6
View File
@@ -33,10 +33,34 @@ import (
// Validate checks the complete configuration without touching the filesystem.
func Validate(settings Settings) error { return validate(settings) }
// wineExclusionUnitLimit bounds the UTF-16 exclusion list handed to the
// Wine helper, NUL terminators included.
const wineExclusionUnitLimit = 32766
// WineExclusionUnits counts a program name in UTF-16 code units plus its
// NUL terminator, matching the aggregate limit validation enforces.
func WineExclusionUnits(name string) int {
return len(utf16.Encode([]rune(name))) + 1
}
// WineExclusionsTooLong returns the first entry whose addition reaches the
// aggregate UTF-16 limit, or false when the whole list fits.
func WineExclusionsTooLong(programs []string) (string, bool) {
units := 0
for _, name := range programs {
units += WineExclusionUnits(name)
if units >= wineExclusionUnitLimit {
return name, true
}
}
return "", false
}
// ValidWineProgramName reports whether an exclusion is an executable basename
// accepted by settings, preferences, and the helper launch boundary.
// accepted by settings, preferences, and the helper launch boundary. The
// 255 cap counts UTF-16 code units, as the helper boundary does.
func ValidWineProgramName(name string) bool {
return name != "" && len(name) <= 255 && strings.TrimSpace(name) == name &&
return name != "" && WineExclusionUnits(name)-1 <= 255 && strings.TrimSpace(name) == name &&
!strings.ContainsAny(name, `/\`) &&
!strings.ContainsFunc(name, func(character rune) bool { return character < ' ' })
}
@@ -48,15 +72,12 @@ func validate(settings Settings) error {
if len(settings.Wine.ExcludedPrograms) > 256 {
return errors.New("too many Wine hook exclusions")
}
exclusionUnits := 0
for _, name := range settings.Wine.ExcludedPrograms {
exclusionUnits += len(utf16.Encode([]rune(name))) + 1
if !ValidWineProgramName(name) {
return errors.New("Wine hook exclusions must be executable basenames")
}
}
if exclusionUnits >= 32766 {
if _, tooLong := WineExclusionsTooLong(settings.Wine.ExcludedPrograms); tooLong {
return errors.New("Wine hook exclusion list is too long")
}
if err := settings.SpeechInterruption.Validate(); err != nil {
+20 -6
View File
@@ -5,6 +5,7 @@
package config
import (
"fmt"
"math"
"git.stormux.org/storm/screenreader-common/hardware"
@@ -37,20 +38,30 @@ func voiceFields(voice *Voice) [3]**float64 {
return [3]**float64{&voice.Rate, &voice.AveragePitch, &voice.Gain}
}
func voiceFromLegacy(voice Voice) Voice {
// voiceFromLegacy converts a legacy 0..100 / 0..10 voice to the -100..100
// scale. Finite values outside the legacy scale are rejected rather than
// clamped, so a corrupt schema-2 or Python settings file fails to load
// instead of silently changing the voice. Non-finite values stay invalid
// so validation still rejects them. SpeechFromLegacy retains clamping for
// the remote API, which must tolerate out-of-range requests.
func voiceFromLegacy(voice Voice) (Voice, error) {
voice = cloneVoice(voice)
for field, value := range voiceFields(&voice) {
// Non-finite values stay invalid so validation still rejects them.
if *value != nil && !math.IsNaN(**value) && !math.IsInf(**value, 0) {
maximum := legacyVoiceScales[field].maximum
if **value < 0 || **value > maximum {
return Voice{}, fmt.Errorf("legacy voice %s %g is outside 0 through %g", []string{"rate", "average-pitch", "gain"}[field], **value, maximum)
}
converted := SpeechFromLegacy(field, **value)
*value = &converted
}
}
return voice
return voice, nil
}
// Serial synthesizers used a different legacy conversion from SSIP.
func hardwareVoiceFromLegacy(voice Voice) Voice {
// Serial synthesizers used a different legacy conversion from SSIP, with
// rate 0..99 and pitch/gain 0..9. The same rejection rule applies.
func hardwareVoiceFromLegacy(voice Voice) (Voice, error) {
voice = cloneVoice(voice)
for field, value := range voiceFields(&voice) {
if *value != nil && !math.IsNaN(**value) && !math.IsInf(**value, 0) {
@@ -58,11 +69,14 @@ func hardwareVoiceFromLegacy(voice Voice) Voice {
if field == VoiceRate {
maximum = 99
}
if **value < 0 || **value > maximum {
return Voice{}, fmt.Errorf("legacy hardware voice %s %g is outside 0 through %g", []string{"rate", "average-pitch", "gain"}[field], **value, maximum)
}
converted := math.Round(hardware.LegacyValue(**value, maximum))
*value = &converted
}
}
return voice
return voice, nil
}
// RoundSpeechValues keeps speech controls and persisted voices at whole
+35
View File
@@ -275,3 +275,38 @@ average-pitch = 4.5
t.Fatal(reloaded.DefaultVoice, err)
}
}
func TestSchemaTwoOutOfRangeVoicesRejected(t *testing.T) {
for name, voice := range map[string]string{
"rate above legacy scale": "rate = 150.0",
"gain below legacy scale": "gain = -3.0",
} {
t.Run(name, func(t *testing.T) {
contents := "schema-version = 2\nactive-profile = \"default\"\n[profiles.default.speech.default-voice]\n" + voice + "\n"
path := writeConfig(t, contents)
store, err := NewStore(path)
if err != nil {
t.Fatal(err)
}
if _, err := store.Load(); err == nil {
t.Fatal("out-of-range legacy voice was clamped and accepted")
}
saved, err := os.ReadFile(path)
if err != nil || string(saved) != contents {
t.Fatalf("rejected load rewrote the settings file: %v", err)
}
})
}
// Hardware voices use the narrower 0..99 / 0..9 legacy scale.
contents := "schema-version = 2\nactive-profile = \"default\"\n[profiles.default.speech]\nserver-factory = \"hardwarefactory\"\noutput-module = \"doubletalk\"\nhardware-device = \"/dev/fixture-synth\"\n[profiles.default.speech.default-voice]\nrate = 100.0\n"
if _, err := Load(writeConfig(t, contents)); err == nil {
t.Fatal("hardware rate 100 accepted on the 0..99 legacy scale")
}
}
func TestLegacyPythonOutOfRangeVoiceRejected(t *testing.T) {
path := writeConfig(t, "[general.voices.default]\nrate = 150.0\n")
if _, err := Load(path); err == nil {
t.Fatal("out-of-range Python legacy voice was clamped and accepted")
}
}
+21
View File
@@ -52,3 +52,24 @@ func TestWineSettingsRejectEmbeddedControlCharacters(t *testing.T) {
})
}
}
func TestWineProgramNameCapCountsUTF16Units(t *testing.T) {
settings := DefaultSettings()
// 100 three-byte runes plus ".exe": 104 UTF-16 units, 304 bytes.
name := ""
for range 100 {
name += "€"
}
name += ".exe"
if len(name) != 304 || WineExclusionUnits(name)-1 != 104 {
t.Fatalf("fixture name is %d bytes / %d UTF-16 units", len(name), WineExclusionUnits(name)-1)
}
settings.Wine.ExcludedPrograms = []string{name}
if err := Validate(settings); err != nil {
t.Fatalf("multibyte name within UTF-16 cap rejected: %v", err)
}
settings.Wine.ExcludedPrograms = []string{name + name + name}
if err := Validate(settings); err == nil {
t.Fatal("name beyond 255 UTF-16 units accepted")
}
}
+97 -8
View File
@@ -67,6 +67,13 @@ type keyboardOwner struct {
uiSession uint64
grabbed bool
grabKnown bool
// grabUnsupported latches when the compositor reports the exclusive
// grab methods as unknown/unsupported: learn and internal UI then
// degrade instead of retrying an impossible GrabKeyboard forever.
grabUnsupported bool
// syncFailureReported bounds transient-sync logging to once per
// failure episode; a successful configure re-arms it.
syncFailureReported bool
started time.Time
sequence uint32
generation uint64
@@ -80,7 +87,7 @@ func (owner *keyboardOwner) call(ctx context.Context, method string, arguments .
func (owner *keyboardOwner) requestedPolicy() keyboardPolicy {
keyboard := owner.keyboard
if !keyboard.enabled.Load() || keyboard.secure.Load() {
if !keyboard.enabled.Load() || keyboard.secure.Load() || owner.grabUnsupported {
owner.learning = false
keyboard.learn.Store(false)
if owner.uiSession != 0 {
@@ -119,13 +126,80 @@ func (owner *keyboardOwner) retireSecureGeneration() {
owner.keyboard.active.Store(false)
}
// isGrabUnsupported reports whether a D-Bus error means the compositor
// does not implement the exclusive GrabKeyboard/UngrabKeyboard pair at
// all, as opposed to a transient failure worth retrying.
func isGrabUnsupported(err error) bool {
name := ""
var valueError dbus.Error
var pointerError *dbus.Error
switch {
case errors.As(err, &valueError):
name = valueError.Name
case errors.As(err, &pointerError) && pointerError != nil:
name = pointerError.Name
}
switch name {
case "org.freedesktop.DBus.Error.UnknownMethod",
"org.freedesktop.DBus.Error.UnknownInterface",
"org.freedesktop.DBus.Error.UnknownObject",
"org.freedesktop.DBus.Error.NotSupported":
return true
}
return false
}
// noteSyncFailure keeps one failed policy/secure synchronization from
// killing the backend. The applied grab state is marked unknown so the
// next loop tick forces the compositor back to the desired state,
// exclusively-held learn/UI sessions that this sync could not apply
// are dropped (and announced through their existing command events),
// and the failure is logged once until a configure succeeds again.
// It never reports on the failures channel: that stays reserved for
// terminal backend loss.
func (owner *keyboardOwner) noteSyncFailure(ctx context.Context, err error) {
if err == nil || ctx.Err() != nil {
return
}
owner.grabKnown = false
if owner.learning {
owner.learning = false
owner.keyboard.learn.Store(false)
select {
case owner.keyboard.commands <- input.CommandEvent{Command: input.ToggleLearnMode}:
default:
}
}
if owner.uiSession != 0 {
session := owner.uiSession
owner.dismissInternalUi()
select {
case owner.keyboard.commands <- input.CommandEvent{Command: input.InternalUIDismiss, UISession: session}:
default:
}
}
if !owner.syncFailureReported {
owner.syncFailureReported = true
owner.keyboard.logger.Warn("Wayland keyboard policy synchronization failed; retrying", "error", err)
}
}
func (owner *keyboardOwner) configure(ctx context.Context, configuration keyboardConfiguration, policy keyboardPolicy) error {
symbols, grabs, bindings := makeGrabs(configuration, policy)
if err := owner.call(ctx, "SetKeyGrabs", symbols, grabs); err != nil {
// The compositor may have applied the new grabs before the
// reply was lost. Force the whole policy, grab transition
// included, to be re-asserted by the next synchronization.
owner.grabKnown = false
return err
}
grabKeyboard := policy.enabled && !policy.secure && (policy.learn || policy.ui)
if !owner.grabKnown || grabKeyboard != owner.grabbed {
if owner.grabUnsupported {
// The compositor has no exclusive grab to apply or release;
// exclusive sessions are refused or dropped by the callers
// that would need one, and ordinary grabs above still apply.
owner.grabbed, owner.grabKnown = false, true
} else if !owner.grabKnown || grabKeyboard != owner.grabbed {
method := "UngrabKeyboard"
if grabKeyboard {
method = "GrabKeyboard"
@@ -136,12 +210,17 @@ func (owner *keyboardOwner) configure(ctx context.Context, configuration keyboar
// policy sync forces the compositor back to the desired state
// instead of trusting a diff against stale policy.
owner.grabKnown = false
if isGrabUnsupported(err) {
owner.grabUnsupported = true
owner.grabbed = false
}
return err
}
owner.grabbed = grabKeyboard
owner.grabKnown = true
}
owner.configuration, owner.policy, owner.bindings = configuration, policy, bindings
owner.syncFailureReported = false
if owner.router == nil {
owner.router = input.NewCommandRouter(symbols, bindings)
} else {
@@ -257,11 +336,14 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error
if policy.secure {
method = "UnwatchKeyboard"
}
// A transient watch/configure failure must not kill the
// reader. Applied policy stays at the previous secure
// state, so this branch retries on the next tick; key
// signals are discarded while secure either way.
if err := owner.call(ctx, method); err != nil {
return err
}
if err := owner.configure(ctx, owner.configuration, policy); err != nil {
return err
owner.noteSyncFailure(ctx, err)
} else if err := owner.configure(ctx, owner.configuration, policy); err != nil {
owner.noteSyncFailure(ctx, err)
}
}
// A close request revokes the session identity promptly, even if
@@ -272,7 +354,11 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error
owner.dismissInternalUi()
policy = owner.requestedPolicy()
}
if !stopping && len(owner.held) == 0 {
// While a secure transition is still unapplied, no other
// configure this tick may adopt its policy and thereby lose
// the pending Watch/Unwatch retry.
secureTransitionPending := policy.secure != owner.policy.secure
if !stopping && !secureTransitionPending && len(owner.held) == 0 {
if pendingUI != nil {
update := pendingUI
pendingUI = nil
@@ -311,8 +397,11 @@ func (owner *keyboardOwner) loop(ctx context.Context, queue *signalQueue) error
}
update.result <- err
} else if policy != owner.policy || !owner.grabKnown {
// Transient grab/configure failures (including one
// 750ms D-Bus timeout) are reconciled next tick via
// grabKnown=false instead of terminating the reader.
if err := owner.configure(ctx, owner.configuration, policy); err != nil {
return err
owner.noteSyncFailure(ctx, err)
}
}
}
+202
View File
@@ -7,6 +7,7 @@ package wayland
import (
"context"
"errors"
"fmt"
"os"
"sync"
"testing"
@@ -33,6 +34,8 @@ type FakeKeyboardMonitor struct {
rejectNext bool
rejectWatch bool
failGrabNext bool
failUngrabNext bool
grabUnsupported bool
grabDelay time.Duration
grabStarted chan struct{}
grabCalls int
@@ -67,6 +70,10 @@ func (monitor *FakeKeyboardMonitor) UnwatchKeyboard() *dbus.Error {
func (monitor *FakeKeyboardMonitor) GrabKeyboard() *dbus.Error {
monitor.mutex.Lock()
monitor.grabCalls++
if monitor.grabUnsupported {
monitor.mutex.Unlock()
return dbus.NewError("org.freedesktop.DBus.Error.UnknownMethod", []any{"no GrabKeyboard"})
}
failApplied, delay, started := monitor.failGrabNext, monitor.grabDelay, monitor.grabStarted
monitor.failGrabNext = false
monitor.mutex.Unlock()
@@ -92,8 +99,16 @@ func (monitor *FakeKeyboardMonitor) UngrabKeyboard() *dbus.Error {
monitor.mutex.Lock()
defer monitor.mutex.Unlock()
monitor.ungrabCalls++
if monitor.grabUnsupported {
return dbus.NewError("org.freedesktop.DBus.Error.UnknownMethod", []any{"no UngrabKeyboard"})
}
failApplied := monitor.failUngrabNext
monitor.failUngrabNext = false
monitor.state.grabbed = false
monitor.publish()
if failApplied {
return dbus.NewError("org.freedesktop.DBus.Error.Timeout", []any{"ungrab applied but timed out"})
}
return nil
}
func (monitor *FakeKeyboardMonitor) SetKeyGrabs(modifiers []uint32, grabs []keyGrab) *dbus.Error {
@@ -121,6 +136,18 @@ func (monitor *FakeKeyboardMonitor) failNextGrab() {
monitor.failGrabNext = true
}
func (monitor *FakeKeyboardMonitor) failNextUngrab() {
monitor.mutex.Lock()
defer monitor.mutex.Unlock()
monitor.failUngrabNext = true
}
func (monitor *FakeKeyboardMonitor) setGrabUnsupported(unsupported bool) {
monitor.mutex.Lock()
defer monitor.mutex.Unlock()
monitor.grabUnsupported = unsupported
}
func (monitor *FakeKeyboardMonitor) delayNextGrab(delay time.Duration) <-chan struct{} {
started := make(chan struct{}, 1)
monitor.mutex.Lock()
@@ -770,3 +797,178 @@ func TestNativeInternalUIRecoversAmbiguousGrabFailure(t *testing.T) {
t.Fatal(err)
}
}
func TestGrabUnsupportedClassification(t *testing.T) {
for _, err := range []error{
dbus.Error{Name: "org.freedesktop.DBus.Error.UnknownMethod"},
&dbus.Error{Name: "org.freedesktop.DBus.Error.UnknownInterface"},
fmt.Errorf("grab: %w", dbus.Error{Name: "org.freedesktop.DBus.Error.NotSupported"}),
} {
if !isGrabUnsupported(err) {
t.Fatalf("%v not classified as an unsupported grab", err)
}
}
for _, err := range []error{
nil,
errors.New("timeout"),
dbus.Error{Name: "org.freedesktop.DBus.Error.Timeout"},
dbus.Error{Name: "org.freedesktop.DBus.Error.AccessDenied"},
} {
if isGrabUnsupported(err) {
t.Fatalf("%v misclassified as an unsupported grab", err)
}
}
}
func TestNoteSyncFailureDropsExclusiveSessionsOnce(t *testing.T) {
keyboard := New([]string{"Insert"}, input.DesktopKeyboardLayout, nil)
keyboard.learn.Store(true)
keyboard.uiSession.Store(9)
owner := &keyboardOwner{keyboard: keyboard, learning: true, uiSession: 9, grabKnown: true}
owner.noteSyncFailure(context.Background(), errors.New("grab timed out"))
if owner.grabKnown || owner.learning || owner.uiSession != 0 || keyboard.LearnModeActive() || keyboard.InternalUIActive() {
t.Fatal("sync failure did not mark the grab unknown and drop exclusive sessions")
}
if !owner.syncFailureReported {
t.Fatal("sync failure was not marked as reported")
}
if event := <-keyboard.commands; event.Command != input.ToggleLearnMode || event.LearnModeStarted {
t.Fatalf("learn drop announcement = %+v", event)
}
if event := <-keyboard.commands; event.Command != input.InternalUIDismiss || event.UISession != 9 {
t.Fatalf("internal UI drop announcement = %+v", event)
}
owner.noteSyncFailure(context.Background(), errors.New("grab timed out again"))
if len(keyboard.commands) != 0 {
t.Fatal("repeated sync failure announced dropped sessions twice")
}
cancelled, cancel := context.WithCancel(context.Background())
cancel()
stopped := &keyboardOwner{keyboard: keyboard, learning: true, grabKnown: true}
stopped.noteSyncFailure(cancelled, errors.New("grab timed out"))
if !stopped.grabKnown || !stopped.learning || len(keyboard.commands) != 0 {
t.Fatal("sync failure was reported while the backend was stopping")
}
}
func TestNativeKeyboardSurvivesGrabFailureDuringLearnExitAndSecureEntry(t *testing.T) {
monitor := startMonitor(t)
keyboard := startKeyboard(t, monitor)
assertAlive := func() {
t.Helper()
select {
case err := <-keyboard.Failures():
t.Fatalf("transient grab failure terminated the backend: %v", err)
default:
}
select {
case <-keyboard.done:
t.Fatal("transient grab failure stopped the keyboard owner")
default:
}
}
enterLearn := func() {
t.Helper()
monitor.key(t, 0xff63, 118, 0, false)
monitor.key(t, 'h', 43, 0, false)
if !awaitCommand(t, keyboard, input.ToggleLearnMode).LearnModeStarted {
t.Fatal("learn did not begin")
}
monitor.key(t, 'h', 43, 0, true)
monitor.key(t, 0xff63, 118, 0, true)
waitSnapshot(t, monitor, func(state MonitorSnapshot) bool { return state.grabbed })
}
// Learn exit: the ungrab is applied by the compositor but its
// reply times out. The backend must reconcile with a second
// ungrab instead of terminating the reader.
enterLearn()
_, _, ungrabsBefore, _ := monitor.grabState()
monitor.failNextUngrab()
monitor.key(t, 0xff1b, 9, 0, false)
if awaitCommand(t, keyboard, input.ToggleLearnMode).LearnModeStarted {
t.Fatal("Escape entered learn mode")
}
monitor.key(t, 0xff1b, 9, 0, true)
waitFor(t, func() bool {
grabbed, _, ungrabCalls, _ := monitor.grabState()
return !grabbed && ungrabCalls >= ungrabsBefore+2
}, "failed learn-exit ungrab was not reconciled by a retry")
assertAlive()
monitor.key(t, 'q', 24, 0, false)
monitor.key(t, 'q', 24, 0, true)
awaitInput(t, keyboard, "q")
awaitInput(t, keyboard, "q")
// Secure entry from learn mode: the same ambiguous ungrab now
// happens on the watch/secure transition path.
enterLearn()
_, _, ungrabsBefore, _ = monitor.grabState()
monitor.failNextUngrab()
keyboard.SetSecureInputActive(true)
waitFor(t, func() bool {
grabbed, _, ungrabCalls, keyGrabs := monitor.grabState()
monitor.mutex.Lock()
watching := monitor.state.watching
monitor.mutex.Unlock()
return !watching && !grabbed && keyGrabs == 0 && ungrabCalls >= ungrabsBefore+2
}, "failed secure-entry ungrab was not reconciled by a retry")
assertAlive()
if keyboard.LearnModeActive() {
t.Fatal("secure entry retained learn mode")
}
keyboard.SetSecureInputActive(false)
waitFor(t, func() bool {
monitor.mutex.Lock()
defer monitor.mutex.Unlock()
return monitor.state.watching && !monitor.state.grabbed && len(monitor.state.modifiers) == 3
}, "keyboard did not resume after secure-entry grab failure")
assertAlive()
monitor.key(t, 'q', 24, 0, false)
monitor.key(t, 'q', 24, 0, true)
awaitInput(t, keyboard, "q")
awaitInput(t, keyboard, "q")
}
func TestNativeKeyboardDegradesWhenExclusiveGrabUnsupported(t *testing.T) {
monitor := startMonitor(t)
keyboard := startKeyboard(t, monitor)
monitor.setGrabUnsupported(true)
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
if session, err := keyboard.BeginInternalUI(ctx); err == nil || session != 0 {
t.Fatalf("unsupported grab begin = session %d, %v", session, err)
}
_, grabCalls, _, _ := monitor.grabState()
if session, err := keyboard.BeginInternalUI(ctx); err == nil || session != 0 {
t.Fatalf("unsupported grab retry = session %d, %v", session, err)
}
monitor.key(t, 0xff63, 118, 0, false)
monitor.key(t, 0xffe1, 50, 1, false)
monitor.key(t, 'A', 38, 1, false)
if opened := awaitCommand(t, keyboard, input.ShowActions); opened.UISession != 0 {
t.Fatalf("ShowActions on an unsupported grab = %+v, want session-zero degradation", opened)
}
monitor.key(t, 'A', 38, 1, true)
monitor.key(t, 0xffe1, 50, 0, true)
monitor.key(t, 0xff63, 118, 0, true)
monitor.key(t, 0xff63, 118, 0, false)
monitor.key(t, 'h', 43, 0, false)
if event := awaitCommand(t, keyboard, input.ToggleLearnMode); event.LearnModeStarted || keyboard.LearnModeActive() {
t.Fatalf("learn mode began without an exclusive grab: %+v", event)
}
monitor.key(t, 'h', 43, 0, true)
monitor.key(t, 0xff63, 118, 0, true)
if grabbed, afterGrabCalls, _, _ := monitor.grabState(); grabbed || afterGrabCalls != grabCalls {
t.Fatalf("unsupported grab was retried or applied: grabbed=%v calls %d -> %d", grabbed, grabCalls, afterGrabCalls)
}
select {
case err := <-keyboard.Failures():
t.Fatalf("unsupported grab terminated the backend: %v", err)
default:
}
monitor.key(t, 'q', 24, 0, false)
monitor.key(t, 'q', 24, 0, true)
awaitInput(t, keyboard, "q")
awaitInput(t, keyboard, "q")
}
+5 -1
View File
@@ -289,11 +289,15 @@ func (owner *keyboardOwner) handleKey(key keyEvent) error {
owner.learning = false
keyboard.learn.Store(false)
}
} else if command == input.ToggleLearnMode {
} else if command == input.ToggleLearnMode && !owner.grabUnsupported {
owner.learning = true
keyboard.learn.Store(true)
keyboard.learnEcho.Store(true)
}
// With no exclusive grab, learn mode cannot keep keys away from
// applications, so it is not entered above: the ToggleLearnMode
// event below still dispatches with LearnModeStarted=false,
// mirroring ShowActions' session-zero degradation.
if command != "" && !repeated {
uiSession := uint64(0)
if command == input.ShowActions && !key.released {
+4 -1
View File
@@ -82,7 +82,10 @@ func (keyboard *Keyboard) updateInternalUi(ctx context.Context, closeSession uin
// beginInternalUi runs on the owner goroutine. The compositor grab is
// applied before the session is acknowledged, mirroring the Xorg owner.
func (owner *keyboardOwner) beginInternalUi(ctx context.Context) (uint64, error) {
if !owner.policy.enabled || owner.policy.secure || !owner.keyboard.enabled.Load() || owner.keyboard.secure.Load() || owner.learning || owner.uiSession != 0 {
// Without a compositor exclusive grab an internal UI could not
// capture keys away from applications; fail like any other
// unavailable capture (ShowActions then degrades to session zero).
if owner.grabUnsupported || !owner.policy.enabled || owner.policy.secure || !owner.keyboard.enabled.Load() || owner.keyboard.secure.Load() || owner.learning || owner.uiSession != 0 {
return 0, errors.New("internal UI input unavailable")
}
policy := owner.policy
@@ -163,6 +163,57 @@ func TestNativeCommandBypass(t *testing.T) {
t.Fatal("missing Caps Lock unlock")
}
}
// A secure-input reset must not restore full routing while
// bypass keeps only the bypass-toggle native grab: a non-toggle
// command chord after secure input clears is replayed to the
// application, not dispatched owner-side.
listener.SetSecureInputActive(true)
wait(func() bool { return !listener.commandsApplied.Load() })
listener.SetSecureInputActive(false)
wait(func() bool { return listener.CommandGrabsEnabled() && listener.CommandBypassEnabled() })
key("keydown", modifier, "key", "s", "keyup", modifier)
key("key", "F12")
postSecure := map[string]int{}
for postSecure["F12"] < 2 {
select {
case line := <-seen:
for _, name := range []string{"s", "F12"} {
if strings.Contains(strings.ToLower(line), strings.ToLower(", "+name+")")) {
postSecure[name]++
}
}
case <-ctx.Done():
t.Fatalf("post-secure application events = %v: %v", postSecure, ctx.Err())
}
}
if postSecure["s"] != 2 {
t.Fatalf("post-secure bypass chord did not reach the application: %v", postSecure)
}
select {
case event := <-listener.Commands():
t.Fatalf("command escaped bypass after secure input: %s", event.Command)
default:
}
if modifier == "Caps_Lock" {
// The replayed chord toggled Caps Lock on again; restore it.
drainLocks:
for {
select {
case <-listener.LockStates():
default:
break drainLocks
}
}
key("key", "Caps_Lock")
for unlocked := false; !unlocked; {
select {
case state := <-listener.LockStates():
unlocked = !state.Locked
case <-ctx.Done():
t.Fatal("Caps Lock did not unlock after secure input")
}
}
}
key("keydown", modifier, "key", "z", "keyup", modifier)
next(input.ToggleCommandBypass)
listener.SetCommandBypass(false)
+24 -4
View File
@@ -11,13 +11,14 @@
// Xorg marks XTEST devices with a non-deletable, read-only property. Device
// names and the core send_event flag are not provenance. Unknown/non-device
// sources stay ineligible; no timing match against XRecord is involved.
static int local_source(CommandDevice *device, int source) {
if (source <= 0 || source == device->localKeyboard) return 0;
// The caller holds the X11 read guard (acquisition already does; the
// local_source wrapper below takes it for per-event checks).
static int local_source_for_master(CommandDevice *device, int source, int master) {
if (source <= 0 || source == master) return 0;
int count = 0, allowed = 0;
cthulhu_x11_begin_read(device->display);
XIDeviceInfo *info = XIQueryDevice(device->display, source, &count);
if (info && count == 1 && info->use == XISlaveKeyboard && info->enabled &&
info->attachment == device->localKeyboard) {
info->attachment == master) {
Atom type = None;
int format = 0;
unsigned long items = 0, remaining = 0;
@@ -49,6 +50,12 @@ static int local_source(CommandDevice *device, int source) {
if (data) XFree(data);
}
if (info) XIFreeDeviceInfo(info);
return allowed;
}
static int local_source(CommandDevice *device, int source) {
cthulhu_x11_begin_read(device->display);
int allowed = local_source_for_master(device, source, device->localKeyboard);
if (cthulhu_x11_end_read(device->display)) allowed = 0;
return allowed;
}
@@ -65,6 +72,19 @@ static int acquire_local_keyboard_unchecked(CommandDevice *device) {
keyboard = info->attachment;
if (info) XIFreeDeviceInfo(info);
if (!keyboard) return -1;
// BeginLocalUI must fail on a master no eligible slave can feed, rather
// than grab a keyboard whose every event next_local_key would discard.
// The read guard is already held here, so use the unchecked check; a
// slave vanishing mid-enumeration fails the whole acquisition safely.
int slaveCount = 0, eligible = 0;
XIDeviceInfo *slaves = XIQueryDevice(device->display, XIAllDevices, &slaveCount);
if (slaves) {
for (int i = 0; i < slaveCount && !eligible; i++)
if (slaves[i].use == XISlaveKeyboard)
eligible = local_source_for_master(device, slaves[i].deviceid, keyboard);
XIFreeDeviceInfo(slaves);
}
if (!eligible) return -1;
// A key held before the dialog cannot submit it on repeat or provide an
// inherited modifier. The caller may retry after releasing that chord.
char held[32];
+14
View File
@@ -743,6 +743,20 @@ void release_command_keyboard(CommandDevice *device) {
release_local_keyboard(device);
XUngrabKeyboard(device->display,CurrentTime); XFlush(device->display); device->active=0;
}
int discard_pending_key_events(CommandDevice *device, CommandKey *keys, int capacity) {
// Pull every event the server has already generated under the grab into
// the local queue first, so typeahead cannot surface after the drain.
XSync(device->display,False);
int count=0;
XEvent event;
while (count<capacity && XCheckMaskEvent(device->display,KeyPressMask|KeyReleaseMask,&event)) {
keys[count].pressed=(event.type==KeyPress);
keys[count].code=(int)event.xkey.keycode;
keys[count].timestamp=event.xkey.time;
count++;
}
return count;
}
int replay_command_keys(CommandDevice *device, CommandKey *keys, int count) {
pthread_mutex_lock(&error_mutex);
XSync(device->display,False);
+4
View File
@@ -69,6 +69,10 @@ int next_local_key(CommandDevice *device, XEvent *event);
void release_local_keyboard(CommandDevice *device);
void reset_internal_compose(CommandDevice *device);
void release_command_keyboard(CommandDevice *device);
// Remove up to capacity already-queued core key events, reporting each as a
// minimal CommandKey (code/pressed/timestamp) so the owner can reconcile its
// held-key accounting. Non-key events stay queued. Returns the count removed.
int discard_pending_key_events(CommandDevice *device, CommandKey *keys, int capacity);
int replay_command_keys(CommandDevice *device, CommandKey *keys, int count);
void close_commands(CommandDevice *device);
int cthulhu_ocr_click(unsigned long foreground, int x, int y, int root_width, int root_height);
+1
View File
@@ -68,6 +68,7 @@ func (listener *CommandListener) Start(ctx context.Context) error {
defer listener.ocrApplied.Store(false)
defer listener.commandsApplied.Store(false)
defer listener.bypassApplied.Store(false)
defer listener.remoteSession.Store(0)
listener.commandsApplied.Store(true)
layout := listener.layout
modifiers := append([]string(nil), listener.modifiers...)
@@ -51,6 +51,10 @@ func (listener *CommandListener) runCommandLoop(workerContext context.Context, d
}
func (owner *commandOwner) run() {
// Every exit path (context shutdown, native failure, queue overflow)
// must close an active capture: release owned keys and deliver Ended
// rather than leaving RemoteCaptureActive stuck after the owner dies.
defer owner.endRemoteCapture("local")
owner.publishFocus()
owner.globalBindings = resolvedBindings(owner.layout, false, owner.overrides)
owner.router = input.NewCommandRouter(owner.symbols, owner.contextBindings())
@@ -231,7 +235,7 @@ func (owner *commandOwner) resetForSecureInput() {
if err := configureContextBindings(owner.device, owner.layout, owner.modifiers, owner.overrides, false, false); err != nil {
owner.listener.failures <- err
}
owner.router = input.NewCommandRouter(owner.symbols, resolvedBindings(owner.layout, false, owner.overrides))
owner.router = input.NewCommandRouter(owner.symbols, owner.contextBindings())
}
}
+29
View File
@@ -183,6 +183,10 @@ func (owner *commandOwner) endRemoteCapture(reason string) {
close(capture.events)
owner.remote = nil
owner.listener.remoteSession.Store(0)
// Keys typed under the capture grab may still sit in the Xlib queue.
// Drop them now: left queued, they would be read as a fresh local chord
// and replayed into the focused window after the grab releases.
owner.discardPendingRemoteKeys()
if len(owner.held) == 0 {
C.release_command_keyboard(owner.device)
owner.listener.grabActive.Store(owner.learnMode || owner.uiSession != 0)
@@ -191,6 +195,31 @@ func (owner *commandOwner) endRemoteCapture(reason string) {
}
}
// discardPendingRemoteKeys removes queued key events natively and folds them
// into held-key accounting: a discarded press whose release has not arrived
// stays held (keeping the grab until that release is swallowed), and a
// discarded release retires its press. Idempotent via endRemoteCapture's
// ending guard; it runs at most once per capture.
func (owner *commandOwner) discardPendingRemoteKeys() {
var pending [64]C.CommandKey
for {
count := int(C.discard_pending_key_events(owner.device, &pending[0], C.int(len(pending))))
if count <= 0 {
return
}
for _, key := range pending[:count] {
if key.pressed != 0 {
owner.held[int(key.code)] = true
} else {
delete(owner.held, int(key.code))
}
}
if count < len(pending) {
return
}
}
}
// sendRemote never blocks the X thread. Running into the reserve ends
// capture; the reserve still holds the release plan and end marker.
func (owner *commandOwner) sendRemote(event input.RemoteCaptureEvent) bool {
@@ -57,9 +57,32 @@ func TestNativeLocalUIRejectsInjectedApproval(t *testing.T) {
}
key("keyup", "Return")
id, err := listener.BeginLocalUI(ctx)
if err != nil {
// The private Xvfb server has no device-backed slave keyboard, only
// XTEST: BeginLocalUI must fail before grabbing a master no eligible
// slave can feed, leaving no session. Ordinary forms still work.
if listener.InternalUISession() != 0 {
t.Fatal("failed local capture left a session active")
}
ordinary, err := listener.BeginInternalUI(ctx)
if err != nil {
t.Fatal(err)
}
key("key", "Return")
select {
case event := <-listener.Commands():
if event.Command != input.InternalUIKey || event.UISession != ordinary {
t.Fatal(event)
}
case <-ctx.Done():
t.Fatal("ordinary form stopped receiving keys")
}
if err := listener.EndInternalUI(ctx, ordinary); err != nil {
t.Fatal(err)
}
t.Log("no eligible slave keyboard on this server; local capture refused before grabbing")
return
}
// XTEST has send_event=False. Neither navigation, approval, secret entry,
// clipboard shortcuts nor Escape may enter this local-only form.
key("key", "Tab", "space", "Return", "a", "ctrl+v", "Insert+space", "Insert+shift+a", "Escape")
@@ -263,4 +263,39 @@ func TestNativeRemoteCaptureForwardsBypassesAndEscapes(t *testing.T) {
t.Fatalf("captured key %s reached the local application", leaked)
}
}
// Shutdown with a capture active and a key held must still end the
// capture: the owned key is released, Ended is delivered, the stream
// closes, and RemoteCaptureActive does not stick. Ending again through
// a fresh owner path must stay harmless.
third, events, err := listener.BeginRemoteCapture(ctx, "tentacle/remote-1/")
if err != nil || third == second {
t.Fatal("shutdown capture refused", err)
}
run("keydown", "Control_L")
control = expect("Control_L", true, true)
if err := listener.Stop(context.Background()); err != nil {
t.Fatal(err)
}
if expect("", false, false) != control {
t.Fatal("shutdown did not release the owned modifier")
}
if event := next(); event.Ended != "local" {
t.Fatalf("shutdown end event = %+v", event)
}
select {
case event, ok := <-events:
if ok {
t.Fatalf("capture stream stayed open after shutdown: %+v", event)
}
case <-ctx.Done():
t.Fatal("capture stream did not close after shutdown")
}
if listener.RemoteCaptureActive() {
t.Fatal("remote capture still active after shutdown")
}
if err := listener.Stop(context.Background()); err != nil {
t.Fatal("second stop failed", err)
}
run("keyup", "Control_L")
}
@@ -141,7 +141,7 @@ func startNativeHelper(t *testing.T) *nativeHelper {
defer lifeWrite.Close()
f := &nativeHelper{probe: probe, shift: shift, control: controlCode,
writerDone: make(chan struct{}), helperDone: make(chan struct{})}
f.helper = exec.Command(path, "--epoch", "7")
f.helper = exec.Command(path)
f.helper.Stdin = keyRead
f.helper.ExtraFiles = []*os.File{lifeRead}
f.helper.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
@@ -217,6 +217,8 @@ func startNativeHelper(t *testing.T) *nativeHelper {
if err != nil || writerGroup == helperGroup || helperGroup != f.helper.Process.Pid {
t.Fatal("input helper was not isolated from its writer process group")
}
// The epoch travels as the first frame over the control pipe, never argv.
f.send(t, remoteinput.Operation{Kind: remoteinput.Hello, Epoch: 7})
// Deferred closes now remove every supervisor copy of both write ends.
return f
}
+4
View File
@@ -17,6 +17,10 @@ enum {
PREFS_TENTACLE_INSTALL = 19,
PREFS_TENTACLE_SETTINGS = 20,
PREFS_TENTACLE_UPDATE = 21,
PREFS_PROFILE_ADD = 30,
PREFS_PROFILE_EDIT = 31,
PREFS_PROFILE_REMOVE = 32,
PREFS_PROFILE_USE = 33,
};
int prefs_init(const char *xml);
void prefs_set_application(const char *name);
+3 -1
View File
@@ -23,12 +23,14 @@ void prefs_profiles_init(void) {
// Focus the internal combo button so Tab and Shift+Tab leave it normally.
gtk_widget_set_can_focus(profileCombo, FALSE);
atk_object_set_name(gtk_widget_get_accessible(profileCombo), "Voice Profiles");
g_object_set_data_full(G_OBJECT(profileCombo), "profile-label", g_strdup("Voice Profiles"), g_free);
g_signal_connect(profileCombo, "changed", G_CALLBACK(profile_combo_changed), NULL);
gtk_box_pack_start(GTK_BOX(profilePage), profileCombo, FALSE, FALSE, 0);
GtkWidget **buttons[] = {&profileAdd, &profileEdit, &profileRemove, &profileUse};
const char *labels[] = {"Add Voice Profile", "Edit Voice Profile", "Remove Voice Profile", "Use Voice Profile"};
for (unsigned i = 0; i < G_N_ELEMENTS(buttons); i++) {
*buttons[i] = gtk_button_new_with_label(labels[i]);
g_signal_connect(*buttons[i], "clicked", G_CALLBACK(profile_action), GINT_TO_POINTER(30 + i));
g_signal_connect(*buttons[i], "clicked", G_CALLBACK(profile_action), GINT_TO_POINTER(PREFS_PROFILE_ADD + (int)i));
gtk_box_pack_start(GTK_BOX(profilePage), *buttons[i], FALSE, FALSE, 0);
}
gtk_notebook_append_page(GTK_NOTEBOOK(prefs_widget("notebook")), profilePage, gtk_label_new("Voice Profiles"));
@@ -67,7 +67,6 @@ func remotePermissions(grants []string) string {
{"keyboard-capture", "capture local keyboard input for the controlled computer"},
{"keyboard-inject", "accept keyboard input from the remote controller"},
{"braille-stream", "exchange remote braille cells and supported display gestures"},
{"clipboard-exchange", "send clipboard text explicitly and receive text with session permission"},
}
var requested []string
for _, item := range descriptions {
@@ -54,9 +54,9 @@ func TestTentacleInstallConfirmationDescribesInteractionAndSettings(t *testing.T
func TestRemoteGrantConfirmationExplainsDirectionAndConsent(t *testing.T) {
entry := tentacle.Entry{RemoteGrants: []string{"output-observe"}}
manifest := tentacle.Manifest{Capabilities: []string{"output-observe", "keyboard-inject", "remote-present", "keyboard-capture", "braille-stream", "clipboard-exchange"}}
manifest := tentacle.Manifest{Capabilities: []string{"output-observe", "keyboard-inject", "remote-present", "keyboard-capture", "braille-stream"}}
for _, message := range []string{tentacleInstallConfirmation(entry, manifest, "Install"), tentacleUpdateConfirmation(entry, tentacle.AvailableUpdate{}, manifest)} {
for _, want := range []string{"share local reader output", "accept keyboard input from the remote controller", "capture local keyboard input", "present output received", "Each session requires local approval", "receive text with session permission", "Installation does not start a connection"} {
for _, want := range []string{"share local reader output", "accept keyboard input from the remote controller", "capture local keyboard input", "present output received", "Each session requires local approval", "Installation does not start a connection"} {
if !strings.Contains(message, want) {
t.Fatalf("missing %q in %s", want, message)
}
+1 -1
View File
@@ -177,7 +177,7 @@ func Run(ctx context.Context, input io.Reader, output io.Writer) error {
session.refreshSpeechVoices()
session.refreshKeyBindingLayout()
action := C.prefs_action()
if action >= 30 && action <= 33 && !busy && session.wineEditable {
if action >= C.PREFS_PROFILE_ADD && action <= C.PREFS_PROFILE_USE && !busy && session.wineEditable {
session.profileAction(int(action))
continue
}
+3 -3
View File
@@ -31,12 +31,12 @@ func (session *uiSession) populateProfiles(index int) {
func (session *uiSession) profileAction(action int) {
index := int(C.prefs_profiles_selected())
if action == 32 {
if action == int(C.PREFS_PROFILE_REMOVE) {
session.profiles = session.profiles.Remove(index)
session.populateProfiles(index)
return
}
if action == 33 {
if action == int(C.PREFS_PROFILE_USE) {
if index < 0 || index >= len(session.profiles.Profiles) {
return
}
@@ -71,7 +71,7 @@ func (session *uiSession) profileAction(action int) {
if p.BaudRate == 0 {
p.BaudRate = 9600
}
if action == 31 {
if action == int(C.PREFS_PROFILE_EDIT) {
if index < 0 || index >= len(session.profiles.Profiles) {
return
}
+4 -1
View File
@@ -36,12 +36,15 @@ func validateWinePrograms(programs []string) error {
return fmt.Errorf("Wine program entry %d is blank. Type an executable name such as Game.exe, or delete the entry.", index+1)
case strings.ContainsAny(name, `/\`):
return fmt.Errorf("Wine program \"%s\" is a path. Type only the executable name, such as Game.exe, or delete the entry.", name)
case len(name) > 255:
case config.WineExclusionUnits(name)-1 > 255:
return fmt.Errorf("Wine program \"%s\" is too long. Executable names may be at most 255 characters; fix or delete the entry.", name)
case !config.ValidWineProgramName(name):
return fmt.Errorf("Wine program \"%s\" is not a valid executable name. Remove the surrounding spaces or control characters, or delete the entry.", name)
}
}
if offending, tooLong := config.WineExclusionsTooLong(programs); tooLong {
return fmt.Errorf("Wine program \"%s\" makes the exclusion list too long. Shorten or delete an entry.", offending)
}
return nil
}
+20
View File
@@ -115,3 +115,23 @@ func TestWineValuesRejectEmbeddedControlCharacters(t *testing.T) {
})
}
}
func TestWineProgramsAggregateLimitAndMultibyteNames(t *testing.T) {
multibyte := strings.Repeat("€", 100) + ".exe"
if err := validateWinePrograms([]string{multibyte}); err != nil {
t.Fatalf("multibyte name within UTF-16 cap rejected: %v", err)
}
entry := strings.Repeat("a", 251) + ".exe"
programs := make([]string, 129)
for index := range programs {
programs[index] = fmt.Sprintf("%03d%s", index, entry[3:])
}
err := validateWinePrograms(programs)
if err == nil || !strings.Contains(err.Error(), "too long") {
t.Fatalf("aggregate UTF-16 limit not enforced: %v", err)
}
// Entry 128 (0-based 127) is the first to reach 32766 units.
if !strings.Contains(err.Error(), programs[127]) {
t.Fatalf("aggregate error %q does not name offending entry %q", err, programs[127])
}
}
+2 -2
View File
@@ -114,7 +114,7 @@ func ContextEnabled(kind string, reading config.ReadingSettings) bool {
}
switch kind {
case "article":
return true
return reading.SpeakContextLandmark
case "blockquote":
return reading.SpeakContextBlockquote
case "list":
@@ -138,7 +138,7 @@ func SayAllContextEnabled(kind string, reading config.ReadingSettings) bool {
}
switch kind {
case "article":
return true
return reading.SayAllContextLandmark
case "blockquote":
return reading.SayAllContextBlockquote
case "list":
+12
View File
@@ -109,6 +109,7 @@ func TestEachNavigationContextHasItsOwnPreference(t *testing.T) {
{atspi.Snapshot{Role: "panel"}, "panel", func(r *config.ReadingSettings) { r.SpeakContextPanel = false }},
{atspi.Snapshot{Role: "section", XMLRoles: "navigation"}, "landmark", func(r *config.ReadingSettings) { r.SpeakContextLandmark = false }},
{atspi.Snapshot{Role: "form"}, "form", func(r *config.ReadingSettings) { r.SpeakContextNonLandmarkForm = false }},
{atspi.Snapshot{Role: "article", Name: "Story"}, "article", func(r *config.ReadingSettings) { r.SpeakContextLandmark = false }},
} {
reading := config.DefaultSettings().Reading
if ContextType(tc.snapshot) != tc.kind || !ContextEnabled(tc.kind, reading) {
@@ -123,3 +124,14 @@ func TestEachNavigationContextHasItsOwnPreference(t *testing.T) {
t.Fatal("layout table announced")
}
}
func TestArticleSayAllContextFollowsLandmarkPreference(t *testing.T) {
reading := config.DefaultSettings().Reading
if !SayAllContextEnabled("article", reading) {
t.Fatal("named article context missing in Say All")
}
reading.SayAllContextLandmark = false
if SayAllContextEnabled("article", reading) {
t.Fatal("disabled landmark preference still announced article in Say All")
}
}
+36 -3
View File
@@ -10,6 +10,7 @@ package remoteinput
import (
"encoding/binary"
"errors"
"io"
"git.stormux.org/storm/cthulhu/internal/input"
)
@@ -23,6 +24,11 @@ const (
Down byte = 2
Up byte = 3
Close byte = 4
// Hello is the first fixed control frame. It carries the lease epoch
// over the private pipe itself, never in argv (world-readable via
// /proc/<pid>/cmdline). Possession of the pipe is the authentication;
// the epoch only binds subsequent frames to one approved lease.
Hello byte = 5
Ready byte = 1
Accepted byte = 2
@@ -46,16 +52,22 @@ type Operation struct {
}
func EncodeOperation(operation Operation) ([]byte, error) {
if operation.Epoch == 0 || operation.Sequence == 0 || len(operation.Name) > 32 {
if operation.Epoch == 0 || len(operation.Name) > 32 {
return nil, ErrProtocol
}
switch operation.Kind {
case Hello:
// Sequence zero is reserved for the opening epoch frame, mirroring
// Ready; regular operations still start at sequence one.
if operation.Sequence != 0 || operation.Name != "" {
return nil, ErrProtocol
}
case Down, Up:
if !input.ValidRemoteKeyName(operation.Name) {
if operation.Sequence == 0 || !input.ValidRemoteKeyName(operation.Name) {
return nil, ErrProtocol
}
case Heartbeat, Close:
if operation.Name != "" {
if operation.Sequence == 0 || operation.Name != "" {
return nil, ErrProtocol
}
default:
@@ -69,6 +81,27 @@ func EncodeOperation(operation Operation) ([]byte, error) {
return frame, nil
}
// ReadEpoch consumes the mandatory first fixed frame from a control pipe
// and returns its lease epoch. A helper must call it before Run (and
// before opening any native target): Ready is only sent by Run for the
// epoch obtained here. Anything other than one well-formed Hello frame
// is a protocol failure. Run itself rejects a later Hello, whose
// sequence zero can never follow the first regular operation.
func ReadEpoch(control io.Reader) (uint64, error) {
if control == nil {
return 0, ErrProtocol
}
frame := make([]byte, OperationSize)
if _, err := io.ReadFull(control, frame); err != nil {
return 0, ErrProtocol
}
operation, err := DecodeOperation(frame)
if err != nil || operation.Kind != Hello {
return 0, ErrProtocol
}
return operation.Epoch, nil
}
func DecodeOperation(frame []byte) (Operation, error) {
if len(frame) != OperationSize || frame[0] != Version || frame[3] != 0 || frame[2] > 32 {
return Operation{}, ErrProtocol
+40
View File
@@ -5,6 +5,7 @@
package remoteinput
import (
"bytes"
"encoding/binary"
"errors"
"testing"
@@ -12,6 +13,7 @@ import (
func TestHelperOperationCodec(t *testing.T) {
for _, operation := range []Operation{
{Kind: Hello, Epoch: 7},
{Kind: Down, Epoch: 7, Sequence: 1, Name: "Control_R"},
{Kind: Up, Epoch: 7, Sequence: 2, Name: "KP_Enter"},
{Kind: Heartbeat, Epoch: 7, Sequence: ^uint64(0)},
@@ -28,9 +30,12 @@ func TestHelperOperationCodec(t *testing.T) {
}
for _, operation := range []Operation{
{Kind: 0, Epoch: 7, Sequence: 1}, {Kind: Heartbeat, Sequence: 1},
{Kind: Hello}, {Kind: Hello, Epoch: 7, Sequence: 1},
{Kind: Hello, Epoch: 7, Name: "a"},
{Kind: Heartbeat, Epoch: 7}, {Kind: Down, Epoch: 7, Sequence: 1},
{Kind: Up, Epoch: 7, Sequence: 1, Name: "private unknown"},
{Kind: Down, Epoch: 7, Sequence: 1, Name: "a\x00"},
{Kind: Down, Epoch: 7, Name: "a"},
{Kind: Heartbeat, Epoch: 7, Sequence: 1, Name: "a"},
{Kind: Close, Epoch: 7, Sequence: 1, Name: "a"},
} {
@@ -53,6 +58,41 @@ func TestHelperOperationCodec(t *testing.T) {
}
}
func TestReadEpochConsumesOnlyHelloFrame(t *testing.T) {
hello, err := EncodeOperation(Operation{Kind: Hello, Epoch: 41})
if err != nil {
t.Fatal(err)
}
down, err := EncodeOperation(Operation{Kind: Down, Epoch: 41, Sequence: 1, Name: "a"})
if err != nil {
t.Fatal(err)
}
reader := bytes.NewReader(append(append([]byte(nil), hello...), down...))
epoch, err := ReadEpoch(reader)
if err != nil || epoch != 41 {
t.Fatalf("ReadEpoch = %d, %v", epoch, err)
}
if reader.Len() != OperationSize {
t.Fatal("ReadEpoch consumed beyond the first fixed frame")
}
// The next frame stays strictly bound to the adopted epoch.
frame := make([]byte, OperationSize)
if _, err := reader.Read(frame); err != nil {
t.Fatal(err)
}
if operation, err := DecodeOperation(frame); err != nil || operation.Epoch != epoch || operation.Sequence != 1 {
t.Fatal("first regular operation lost its epoch or sequence", err)
}
for _, bad := range [][]byte{nil, hello[:OperationSize-1], down} {
if _, err := ReadEpoch(bytes.NewReader(bad)); !errors.Is(err, ErrProtocol) {
t.Fatal("missing, partial or non-Hello epoch frame accepted", err)
}
}
if _, err := ReadEpoch(nil); !errors.Is(err, ErrProtocol) {
t.Fatal("missing control pipe accepted", err)
}
}
func TestHelperAckCodec(t *testing.T) {
for _, ack := range []Ack{
{Kind: Ready, Epoch: 7}, {Kind: Accepted, Epoch: 7, Sequence: 1},
+2
View File
@@ -41,6 +41,8 @@ type ackWrite struct {
// Stream Close must interrupt blocked reads/writes; AdoptPipe supplies that
// property for inherited Go file descriptors. The caller supplies one fixed
// nonzero epoch and must not launch a replacement until cleanup is confirmed.
// A helper process obtains that epoch from ReadEpoch's opening Hello frame
// on the control pipe, never from argv; every later frame must still match it.
func Run(ctx context.Context, epoch uint64, control, lifetime io.ReadCloser, output io.WriteCloser, target Target) error {
return run(ctx, epoch, control, lifetime, output, target, Watchdog)
}
+5 -1
View File
@@ -182,7 +182,7 @@ func TestHelperRunnerOrderedClose(t *testing.T) {
}
func TestHelperRunnerRejectsStaleAndMalformed(t *testing.T) {
for _, failure := range []string{"epoch", "replay", "partial", "reserved", "lifetime-data"} {
for _, failure := range []string{"epoch", "replay", "partial", "reserved", "lifetime-data", "late-hello"} {
t.Run(failure, func(t *testing.T) {
f := startHelper(t, time.Second)
f.ack(t)
@@ -211,6 +211,10 @@ func TestHelperRunnerRejectsStaleAndMalformed(t *testing.T) {
if _, err := f.life.Write([]byte{1}); err != nil {
t.Fatal(err)
}
case "late-hello":
// A Hello is only the opening ReadEpoch frame; Run must
// never rebind the epoch mid-stream.
f.send(t, Operation{Kind: Hello, Epoch: 8})
}
if ack := f.ack(t); ack.Kind != Closed || ack.Reason != ReasonProtocol || ack.CleanupFailed {
t.Fatal("invalid input did not retire with cleanup", ack)
+21 -5
View File
@@ -12,7 +12,6 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"sync"
"syscall"
"time"
@@ -34,15 +33,17 @@ type Supervisor struct {
mu sync.Mutex
active bool
uncertain bool
command func(uint64) *exec.Cmd
command func() *exec.Cmd
}
func NewSupervisor(executable string) (*Supervisor, error) {
if !filepath.IsAbs(executable) {
return nil, ErrUnavailable
}
return &Supervisor{command: func(epoch uint64) *exec.Cmd {
return exec.Command(executable, "--epoch", strconv.FormatUint(epoch, 10))
// No arguments at all: the epoch travels as the first frame over the
// private control pipe, never in world-readable argv.
return &Supervisor{command: func() *exec.Cmd {
return exec.Command(executable)
}}, nil
}
@@ -173,7 +174,7 @@ func (supervisor *Supervisor) serve(ctx context.Context, epoch uint64, client *C
if err != nil {
return ErrUnavailable
}
cmd := supervisor.command(epoch)
cmd := supervisor.command()
cmd.Stdin, cmd.Stdout, cmd.Stderr = controlRead, outputWrite, io.Discard
cmd.ExtraFiles = []*os.File{lifetimeRead}
// No CommandContext/Pdeathsig: writer death must allow native retirement.
@@ -287,6 +288,21 @@ func (supervisor *Supervisor) serve(ctx context.Context, epoch uint64, client *C
return Ack{}, ErrUnavailable
}
}
// Deliver the epoch as the first fixed frame over the control pipe
// before expecting Ready; the helper adopts it via ReadEpoch. The
// sequence-zero Hello never counts toward sent/accepted operations.
hello, helloErr := EncodeOperation(Operation{Kind: Hello, Epoch: epoch})
if helloErr == nil {
if helloErr = control.SetWriteDeadline(time.Now().Add(operationTimeout)); helloErr == nil {
helloErr = writeAll(control, hello)
}
}
if helloErr != nil {
if cleanup := retire(); cleanup != nil {
return cleanup
}
return ErrUnavailable
}
ready, err := readAck()
if err != nil || ready != (Ack{Kind: Ready, Epoch: epoch}) {
// An ACK consumed here cannot be reinterpreted as a valid terminal.
+25 -5
View File
@@ -11,7 +11,6 @@ import (
"os"
"os/exec"
"path/filepath"
"strconv"
"syscall"
"testing"
"time"
@@ -43,7 +42,6 @@ func TestSupervisorProcess(t *testing.T) {
if mode == "" {
return
}
epoch, _ := strconv.ParseUint(os.Getenv("CTHULHU_SUPERVISOR_EPOCH"), 10, 64)
control, err := AdoptPipe(os.Stdin, false)
if err != nil {
os.Exit(2)
@@ -56,6 +54,12 @@ func TestSupervisorProcess(t *testing.T) {
if err != nil {
os.Exit(2)
}
// The epoch only arrives as the first control-pipe frame; neither
// argv nor the environment carries it.
epoch, err := ReadEpoch(control)
if err != nil {
os.Exit(2)
}
if mode == "no-ready" || mode == "bad-ready" {
if mode == "bad-ready" {
frame, _ := EncodeAck(Ack{Kind: Ready, Epoch: epoch + 1})
@@ -107,10 +111,9 @@ func TestSupervisorProcess(t *testing.T) {
func testSupervisor(t *testing.T, mode string) (*Supervisor, func() *exec.Cmd) {
t.Helper()
var command *exec.Cmd
supervisor := &Supervisor{command: func(epoch uint64) *exec.Cmd {
supervisor := &Supervisor{command: func() *exec.Cmd {
cmd := exec.Command(os.Args[0], "-test.run=^TestSupervisorProcess$")
cmd.Env = append(os.Environ(), "CTHULHU_SUPERVISOR_TEST="+mode,
"CTHULHU_SUPERVISOR_EPOCH="+strconv.FormatUint(epoch, 10))
cmd.Env = append(os.Environ(), "CTHULHU_SUPERVISOR_TEST="+mode)
t.Cleanup(func() {
if cmd.Process != nil {
cmd.Process.Kill()
@@ -230,6 +233,23 @@ pending:
}
}
func TestSupervisorCommandOmitsEpochFromArgv(t *testing.T) {
executable := filepath.Join(t.TempDir(), "helper")
supervisor, err := NewSupervisor(executable)
if err != nil {
t.Fatal(err)
}
command := supervisor.command()
if len(command.Args) != 1 || command.Args[0] != executable {
t.Fatalf("helper argv = %v, want only the executable (epoch must travel over the control pipe)", command.Args)
}
for _, argument := range command.Args {
if argument == "--epoch" {
t.Fatal("epoch flag present in helper argv")
}
}
}
func TestSupervisorLaunchValidationAndFailure(t *testing.T) {
if _, err := NewSupervisor("relative-helper"); !errors.Is(err, ErrUnavailable) {
t.Fatal("relative executable accepted", err)
+13 -1
View File
@@ -79,6 +79,10 @@ type documentPlace struct {
// child's index and count under that generation-checked parent.
parent, parentPrevious, parentNext atspi.ObjectReference
parentChildIndex, parentChildCount int
// parentChildRole is the saved child's role under that parent. Generic
// replacement recovery must match it, so a slot cannot transfer the
// place to an unrelated kind of object.
parentChildRole string
// Bounded surviving ancestry is a navigation fallback, never an action target.
recoveryParents []atspi.ObjectReference
}
@@ -131,7 +135,15 @@ func (cursor *DocumentCursor) captureAnchor(focus atspi.ObjectID) (atspi.ObjectI
if len(cursor.places) == 0 {
return atspi.ObjectID{}, false
}
document := cursor.places[len(cursor.places)-1].document.ID()
place := cursor.places[len(cursor.places)-1]
document := place.document.ID()
// Only the saved place's own focus or object being reported dead means
// the page destroyed the anchor. Any other same-bus focus (for example
// focus that legitimately left the document) must not pull a recapture
// back into the saved document.
if focus != place.focus.ID() && focus != place.object.ID() {
return atspi.ObjectID{}, false
}
if !document.Valid() || document.BusName != focus.BusName || document == focus {
return atspi.ObjectID{}, false
}
+9 -2
View File
@@ -120,7 +120,10 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare
}
indices := cursor.caretRanges
if len(indices) == 0 {
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, 0, len(doc.Nodes)-1); err != nil {
// No captured range exists to read live, so staleness here is the
// only signal that text appeared after capture. Strict validation
// runs once and forces one recapture instead of reporting empty.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, 0, len(doc.Nodes)-1); err != nil {
return DocumentCaretMove{}, err
}
return DocumentCaretMove{Position: documentPosition(doc, *place)}, nil
@@ -162,7 +165,11 @@ func (cursor *DocumentCursor) MoveCaret(ctx context.Context, reader DocumentCare
if command == CaretPreviousCharacter || command == CaretPreviousWord || command == CaretPreviousLine || command == CaretDocumentStart {
boundary = 0
}
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, current, boundary); err != nil {
// Strict here, unlike the live-read paths above: this check exists
// precisely to catch insertions past the boundary, which tolerant
// validation would wave through. It runs once at the boundary, so
// ticking pages cannot turn it into a recapture loop.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, current, boundary); err != nil {
return DocumentCaretMove{}, err
}
}
+34
View File
@@ -633,3 +633,37 @@ func TestDocumentCaretContinuesFromStructuralLinkedHeading(t *testing.T) {
t.Fatalf("Up after linked heading = %+v, %v", line, err)
}
}
// Text inserted past the caret boundary after capture (signalled by text
// invalidation of a node that had no captured caret range) must report
// staleness at the boundary instead of silently reporting "end of
// document" forever. The live-read move itself stays tolerant.
func TestDocumentCaretBoundaryReportsInsertionPastBoundary(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{webID("/text"): "Only line"}
cursor := newCaretTextCursor(t, reader)
if move, err := cursor.MoveCaret(ctx, reader, CaretNextLine); err != nil || move.Moved {
t.Fatalf("clean boundary = %+v, %v; want unmoved without error", move, err)
}
cursor.tree.InvalidateText(webID("/next"))
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("boundary after insertion = %+v, %v; want stale text error for recapture", move, err)
}
}
// The same applies when the captured document has no caret ranges at all:
// text appearing after capture must not keep reporting an empty document.
func TestDocumentCaretEmptyRangesReportInsertedText(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{}
cursor := newCaretTextCursor(t, reader)
if move, err := cursor.MoveCaret(ctx, reader, CaretNextLine); err != nil || move.Moved {
t.Fatalf("clean empty document = %+v, %v; want unmoved without error", move, err)
}
cursor.tree.InvalidateText(webID("/next"))
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("empty document after insertion = %+v, %v; want stale text error for recapture", move, err)
}
}
+20 -7
View File
@@ -21,11 +21,13 @@ func rememberTextParent(doc atspi.DocumentSnapshot, place *documentPlace) {
place.parent = atspi.ObjectReference{}
place.parentPrevious, place.parentNext = atspi.ObjectReference{}, atspi.ObjectReference{}
place.parentChildIndex, place.parentChildCount = 0, 0
place.parentChildRole = ""
place.recoveryParents = nil
node, ok := doc.Node(place.object.ID())
if !ok || node.Reference != place.object {
return
}
place.parentChildRole = node.Snapshot.Role
plainText := replacementTextLeaf(node)
firstParent := true
for parentID := node.Parent; parentID.Valid(); {
@@ -201,14 +203,18 @@ func replacementChildNode(doc atspi.DocumentSnapshot, saved documentPlace) (atsp
byID[node.Reference.ID()] = node
}
parent, ok := doc.Node(saved.parent.ID())
if !ok || parent.Reference != saved.parent || len(parent.Children) == 0 ||
// The document root itself is never a bounded recovery parent: its
// children are the whole page, so an index there identifies nothing.
if !ok || parent.Reference != saved.parent || parent.Reference == saved.document ||
atspi.IsWebDocumentRole(parent.Snapshot.Role) || len(parent.Children) == 0 ||
parent.Hidden || parent.ParentEditable || parent.Snapshot.Editable ||
parent.Snapshot.Focusable || parent.Snapshot.SupportsClick {
return atspi.DocumentNode{}, "", false
}
usable := func(child *atspi.DocumentNode) bool {
return child != nil && !child.Hidden && !child.ParentEditable && !child.Snapshot.Editable &&
child.Snapshot.Role != "password text"
child.Snapshot.Role != "password text" &&
saved.parentChildRole != "" && child.Snapshot.Role == saved.parentChildRole
}
for index, id := range parent.Children {
var previous, next atspi.ObjectReference
@@ -226,20 +232,27 @@ func replacementChildNode(doc atspi.DocumentSnapshot, saved documentPlace) (atsp
}
next = sibling.Reference
}
if child := byID[id]; previous == saved.parentPrevious && next == saved.parentNext && usable(child) {
// Boundary evidence needs at least one saved boundary: with neither
// sibling retained (a sole child) every sole child would match.
if child := byID[id]; (saved.parentPrevious.Valid() || saved.parentNext.Valid()) &&
previous == saved.parentPrevious && next == saved.parentNext && usable(child) {
return *child, "replaced-child", true
}
}
siblingsRetired := true
// The index path needs positive evidence of recreation: at least one
// saved sibling, and every saved sibling actually retired. A sole child
// has no siblings to retire, so its index alone proves nothing.
savedSiblings, retiredSiblings := 0, 0
for _, sibling := range []atspi.ObjectReference{saved.parentPrevious, saved.parentNext} {
if !sibling.Valid() {
continue
}
if node, ok := byID[sibling.ID()]; ok && node.Reference == sibling {
siblingsRetired = false
savedSiblings++
if node, ok := byID[sibling.ID()]; !ok || node.Reference != sibling {
retiredSiblings++
}
}
if siblingsRetired && saved.parentChildCount > 0 && len(parent.Children) == saved.parentChildCount &&
if savedSiblings > 0 && retiredSiblings == savedSiblings && saved.parentChildCount > 0 && len(parent.Children) == saved.parentChildCount &&
saved.parentChildIndex >= 0 && saved.parentChildIndex < len(parent.Children) {
if child := byID[parent.Children[saved.parentChildIndex]]; usable(child) {
return *child, "replaced-child-index", true
@@ -305,3 +305,85 @@ func TestDocumentRecoveryUsesSurvivingContainerWithoutTransferringOffset(t *test
})
}
}
// Generic child-slot recovery needs positive evidence of recreation. A
// sole child has no sibling that retired (and a role-changed child is a
// different kind of object), so the place must fall back to the surviving
// container instead of transferring onto the unrelated replacement.
func TestDocumentCaretDoesNotRecoverUnrelatedChildByIndex(t *testing.T) {
ctx := context.Background()
reader := caretTextReader{}
node := func(path, role, name string, children ...atspi.ObjectID) atspi.TreeNode {
snapshot := atspi.Snapshot{BusName: webID(path).BusName, Path: path, Role: role, Name: name}
if role == "button" {
snapshot.Focusable = true
}
return atspi.TreeNode{Snapshot: snapshot, Children: children}
}
for _, test := range []struct {
name string
generation func(suffix string) []atspi.TreeNode
landOn string
notOn string
}{
{
name: "sole child",
generation: func(suffix string) []atspi.TreeNode {
return []atspi.TreeNode{
node("/doc", "document web", "", webID("/section")),
node("/section", "section", "", webID("/only"+suffix)),
node("/only"+suffix, "button", "Buy"),
}
},
landOn: "/onlya", notOn: "/onlyb",
},
{
name: "role change",
generation: func(suffix string) []atspi.TreeNode {
middle := node("/b2"+suffix, "button", "Buy two")
if suffix == "b" {
middle = node("/b2b", "check box", "Buy two")
}
return []atspi.TreeNode{
node("/doc", "document web", "", webID("/section")),
node("/section", "section", "", webID("/b1"+suffix), webID("/b2"+suffix), webID("/b3"+suffix)),
node("/b1"+suffix, "button", "Buy one"), middle, node("/b3"+suffix, "button", "Buy three"),
}
},
landOn: "/b2a", notOn: "/b2b",
},
} {
t.Run(test.name, func(t *testing.T) {
tree, err := atspi.NewAccessibleTree(webID("/doc"), test.generation("a"))
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
if _, err := cursor.SyncFocus(ctx, webID("/doc")); err != nil {
t.Fatal(err)
}
for {
move, err := cursor.MoveCaret(ctx, reader, CaretNextLine)
if err != nil || !move.Moved {
t.Fatalf("move onto %s = %+v, %v", test.landOn, move, err)
}
if move.Position.Object.ID() == webID(test.landOn) {
break
}
}
if err := tree.Replace(webID("/doc"), test.generation("b")); err != nil {
t.Fatal(err)
}
position, recovery, err := cursor.syncFocus(ctx, webID("/doc"))
if err != nil {
t.Fatal(err)
}
if recovery == "replaced-child" || recovery == "replaced-child-index" || position.Object.ID() == webID(test.notOn) {
t.Fatalf("recovery = %q onto %v; place transferred to unrelated child %s", recovery, position.Object.ID(), test.notOn)
}
if position.Object.ID() != webID("/section") {
t.Fatalf("recovery = %q onto %v, want surviving container /section", recovery, position.Object.ID())
}
})
}
}
+4 -1
View File
@@ -25,7 +25,10 @@ func (cursor *DocumentCursor) moveTable(ctx context.Context, doc atspi.DocumentS
}
table := doc.Nodes[tableIndex]
tableEnd := doc.SubtreeEnd(tableIndex)
if err := cursor.tree.ValidateDocumentCaretRange(ctx, doc, tableIndex, tableEnd); err != nil {
// Table moves consume only captured snapshot coordinates and cell
// order; nothing is read live. Strict validation must therefore force
// a recapture when the table changed since capture.
if err := cursor.tree.ValidateDocumentRange(ctx, doc, tableIndex, tableEnd); err != nil {
return DocumentCaretMove{}, err
}
var current atspi.DocumentNode
+36
View File
@@ -177,3 +177,39 @@ func TestTableNavigationSkipsHolesAndKeepsLocalDependencies(t *testing.T) {
t.Fatal("failed move changed table position")
}
}
// Table moves consume only captured snapshot data, so a cell whose text
// was invalidated after capture must force a stale error (and recapture)
// instead of navigating the old coordinates.
func TestTableNavigationReportsTextInvalidatedTable(t *testing.T) {
node := func(path, role string, children ...string) atspi.TreeNode {
s := atspi.NewSnapshot(path, path, role, "", "")
s.BusName = webID(path).BusName
n := atspi.TreeNode{Snapshot: s}
for _, child := range children {
n.Children = append(n.Children, webID(child))
}
return n
}
table := node("/table", "table", "/a", "/b")
table.Snapshot.TableRowCount, table.Snapshot.TableColumnCount = 1, 2
a, b := node("/a", "table cell"), node("/b", "table cell")
for _, cell := range []*atspi.TreeNode{&a, &b} {
cell.Snapshot.TablePositionKnown = true
cell.Snapshot.TableRowSpan, cell.Snapshot.TableColumnSpan = 1, 1
}
b.Snapshot.TableColumnIndex = 1
tree, err := atspi.NewAccessibleTree(webID("/doc"), []atspi.TreeNode{node("/doc", "document web", "/table"), table, a, b})
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
if _, err := cursor.SyncFocus(context.Background(), webID("/a")); err != nil {
t.Fatal(err)
}
tree.InvalidateText(webID("/b"))
move, err := cursor.MoveCaret(context.Background(), caretTextReader{}, TableRight)
if !errors.Is(err, atspi.ErrStaleText) || move.Moved {
t.Fatalf("text-invalidated table move = %+v, %v; want stale text error for recapture", move, err)
}
}
+12 -4
View File
@@ -211,6 +211,11 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
result.Err = ErrNoCurrent
return result, cursor
}
// Completed steps live outside the move closure, keyed by cursor: a
// recapture-retry of the same cursor resumes only the remaining steps
// from its already-advanced place, while a trial on a different
// retained cursor still starts its own count from zero.
completedSteps := make(map[*DocumentCursor]int)
move := func() (moveErr error) {
attempt := DocumentAttempt{Focus: result.DocumentFocus, Before: cursor.diagnosticState(), Stage: "focus"}
defer func() { result.recordDocumentAttempt(cursor, attempt, moveErr) }()
@@ -224,11 +229,14 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
return err
}
attempt.Stage = "move"
moved := false
for range repeat {
for completedSteps[cursor] < repeat {
move, err := cursor.Move(ctx, target, level, backwards)
if err != nil {
if moved {
// A capture-worthy failure after some steps must surface
// so the recapture below can resume the remaining ones;
// masking it would silently drop those keypresses. Other
// failures keep the partial progress already made.
if completedSteps[cursor] > 0 && !documentNeedsCapture(err) {
return nil
}
return err
@@ -239,7 +247,7 @@ func (worker *Worker) moveDocumentRepeated(ctx context.Context, cursor *Document
if !move.Moved {
break
}
moved = true
completedSteps[cursor]++
}
return nil
}
+111
View File
@@ -1322,3 +1322,114 @@ func TestDocumentWorkerUsesSeparateCaptureDeadline(t *testing.T) {
t.Fatalf("capture was not canceled: %v", call.ctx.Err())
}
}
// refreshingTreeCapturer recaptures by replacing the same tree with fresh
// nodes under the same identities, like a production capture that
// refreshes the retained tree in place.
type refreshingTreeCapturer struct {
tree *atspi.AccessibleTree
nodes func() []atspi.TreeNode
captures int
placements []atspi.ObjectID
}
func (capturer *refreshingTreeCapturer) CaptureDocument(_ context.Context, _ atspi.ObjectID) (*atspi.AccessibleTree, error) {
capturer.captures++
if err := capturer.tree.Replace(webID("/doc"), capturer.nodes()); err != nil {
return nil, err
}
return capturer.tree, nil
}
func (capturer *refreshingTreeCapturer) CaptureDocumentText(ctx context.Context, focus atspi.ObjectID) (*atspi.AccessibleTree, error) {
return capturer.CaptureDocument(ctx, focus)
}
func (capturer *refreshingTreeCapturer) CaptureReviewWindow(ctx context.Context, focus atspi.ObjectID) (*atspi.AccessibleTree, error) {
return capturer.CaptureDocument(ctx, focus)
}
func (capturer *refreshingTreeCapturer) CaptureDesktop(context.Context) (*atspi.AccessibleTree, error) {
return nil, atspi.ErrObjectNotFound
}
func (capturer *refreshingTreeCapturer) SetDocumentPosition(_ context.Context, position atspi.ObjectReference, _ atspi.ObjectID) error {
capturer.placements = append(capturer.placements, position.ID())
return nil
}
// Three coalesced heading presses where the second step goes stale must
// recapture and resume the remaining steps from the first heading,
// landing on the third instead of silently dropping two presses.
func TestWorkerCoalescedMoveResumesRemainingStepsAfterRecapture(t *testing.T) {
nodes := func() []atspi.TreeNode {
node := func(path, role string, children ...string) atspi.TreeNode {
snapshot := atspi.NewSnapshot(path, path, role, "", "")
snapshot.BusName = webID(path).BusName
if role == "heading" {
snapshot.HeadingLevel = 2
}
result := atspi.TreeNode{Snapshot: snapshot}
for _, child := range children {
result.Children = append(result.Children, webID(child))
}
return result
}
return []atspi.TreeNode{
node("/doc", "document web", "/h1", "/mid", "/h2", "/h3"),
node("/h1", "heading"), node("/mid", "paragraph"), node("/h2", "heading"), node("/h3", "heading"),
}
}
tree, err := atspi.NewAccessibleTree(webID("/doc"), nodes())
if err != nil {
t.Fatal(err)
}
cursor, _ := NewDocumentCursor(tree)
ctx := context.Background()
if _, err := cursor.SyncFocus(ctx, webID("/doc")); err != nil {
t.Fatal(err)
}
// The paragraph between the first and second headings goes stale after
// capture: step one commits, step two must demand a recapture.
tree.InvalidateText(webID("/mid"))
capturer := &refreshingTreeCapturer{tree: tree, nodes: nodes}
worker, err := NewWorker(capturer, time.Second)
if err != nil {
t.Fatal(err)
}
worker.SyncFocus(webID("/doc"))
result, _ := worker.moveDocumentRepeated(ctx, cursor, DocumentHeading, 0, false, 0, 0, 3)
if result.Err != nil || !result.Moved || result.DocumentPosition.Object.ID() != webID("/h3") {
t.Fatalf("coalesced move = %+v, want third heading /h3 after recapture", result)
}
if capturer.captures != 1 {
t.Fatalf("captures = %d, want exactly one recapture", capturer.captures)
}
}
// The saved-document capture fallback is only for a dead anchor that is
// the saved place's own focus or object. Focus that legitimately left
// the document (same bus, unrelated object) must not use it.
func TestCaptureAnchorRequiresSavedPlaceIdentity(t *testing.T) {
_, cursor := webCursor(t)
ctx := context.Background()
if _, err := cursor.SyncFocus(ctx, webID("/first")); err != nil {
t.Fatal(err)
}
if anchor, ok := cursor.captureAnchor(webID("/first")); !ok || anchor != webID("/doc") {
t.Fatalf("dead saved focus anchor = %v, %v; want /doc", anchor, ok)
}
if _, ok := cursor.captureAnchor(webID("/chrome")); ok {
t.Fatal("capture anchor fired for focus that legitimately left the document")
}
move, err := cursor.Move(ctx, DocumentHeading, 0, false)
if err != nil || move.Position.Object.ID() != webID("/second") {
t.Fatalf("heading move = %+v, %v", move, err)
}
if anchor, ok := cursor.captureAnchor(webID("/second")); !ok || anchor != webID("/doc") {
t.Fatalf("dead saved object anchor = %v, %v; want /doc", anchor, ok)
}
if _, ok := cursor.captureAnchor(webID("/link")); ok {
t.Fatal("capture anchor fired for an unrelated same-bus object")
}
}
+2 -2
View File
@@ -22,7 +22,7 @@ func TestRemoteBrailleSDKDirectionsAndEvents(t *testing.T) {
for _, language := range []string{"go", "python"} {
t.Run(language, func(t *testing.T) {
manager := testManager(t, DefaultLimits(), nil)
session := startSessionSDK(t, manager, language, "braille", "braille-stream")
session := startSessionSDK(t, manager, language, "braille")
lease := speechFixtureLease(t, session, "controlled", []string{"output-observe", "braille-stream"})
size := tentaclewire.RemoteBraille{Op: "size", Width: 40}
if _, code := remoteCall(t, session, "remote.braille", brailleRequest(lease, 1, size)); code != -32601 {
@@ -95,7 +95,7 @@ func TestRemoteBrailleSDKDirectionsAndEvents(t *testing.T) {
func TestRemoteBrailleSDKGrantAndSaturation(t *testing.T) {
manager := testManager(t, DefaultLimits(), nil)
session := startSessionSDK(t, manager, "go", "braille", "braille-stream")
session := startSessionSDK(t, manager, "go", "braille")
deliveries := session.EnableRemoteBraille()
lease := speechFixtureLease(t, session, "controlled", []string{"output-observe"})
size := tentaclewire.RemoteBraille{Op: "size", Width: 40}
+2 -2
View File
@@ -81,7 +81,7 @@ func sessionSDKProgram(t *testing.T, language string) []string {
func startSessionSDK(t *testing.T, manager *Manager, language, id string, extraGrants ...string) *Session {
t.Helper()
grants := append([]string{"output-observe", "remote-present", "clipboard-exchange"}, extraGrants...)
grants := append([]string{"output-observe", "remote-present", "braille-stream"}, extraGrants...)
session, err := manager.Start(t.Context(), Spec{ID: id, Program: sessionSDKProgram(t, language), SessionEvents: true, RemoteGrants: grants})
if err != nil {
t.Fatal(err)
@@ -212,7 +212,7 @@ func TestSessionSDKLifecycleConformance(t *testing.T) {
if err != nil {
t.Fatal(err)
}
if _, err := session.RemoteContext(lease, "clipboard-exchange"); !errors.Is(err, ErrPermission) {
if _, err := session.RemoteContext(lease, "braille-stream"); !errors.Is(err, ErrPermission) {
t.Fatal("install grant became session grant")
}
if _, code := remoteCall(t, session, "remote.key", map[string]any{}); code != -32602 {
+18 -4
View File
@@ -8,6 +8,12 @@ import "encoding/json"
const (
RemoteBrailleMaxCells = 4096
// RemoteBrailleRequestMaxCells bounds a child-to-host "cells" request.
// Child calls cap params at 8192 bytes; worst case (32-byte lease,
// 20-digit epoch and sequence, every cell 255) is 140 + 4*n bytes, so
// 2000 cells encode to 8140 bytes. Host-to-child cells ride the 64KiB
// event frame instead: 4096 cells worst-case encode to ~16.5KiB.
RemoteBrailleRequestMaxCells = 2000
RemoteBrailleQueueSize = 16
)
@@ -19,7 +25,9 @@ const (
// - "gesture" (controlled child to host, or host to controller child):
// Gesture is "pan-left", "pan-right" or "route"; Index is the route cell.
// - "cells" (controller child to host, or host to controlled child): final
// dot cells, 1 to 4,096 values of 0 to 255, never text to translate.
// dot cells, values of 0 to 255, never text to translate; at most
// RemoteBrailleRequestMaxCells in a request, RemoteBrailleMaxCells in
// a host-to-child event.
// - "geometry" (controller child to host asks; host to controller child
// answers with Width, zero meaning no local display).
type RemoteBraille struct {
@@ -35,8 +43,8 @@ type RemoteBrailleRequest struct {
Braille RemoteBraille `json:"braille"`
}
func validCells(cells []int) bool {
if len(cells) == 0 || len(cells) > RemoteBrailleMaxCells {
func validCells(cells []int, max int) bool {
if len(cells) == 0 || len(cells) > max {
return false
}
for _, cell := range cells {
@@ -64,7 +72,7 @@ func ValidRemoteBraille(value RemoteBraille) bool {
}
return false
case "cells":
return validCells(value.Cells) && value.Width == 0 && value.Gesture == "" && value.Index == 0
return validCells(value.Cells, RemoteBrailleMaxCells) && value.Width == 0 && value.Gesture == "" && value.Index == 0
}
return false
}
@@ -74,6 +82,9 @@ func ValidRemoteBrailleFor(role string, request bool, value RemoteBraille) bool
if !ValidRemoteBraille(value) {
return false
}
if request && value.Op == "cells" && !validCells(value.Cells, RemoteBrailleRequestMaxCells) {
return false
}
switch {
case role == "controlled" && request:
return value.Op == "size" || value.Op == "gesture"
@@ -88,6 +99,9 @@ func ValidRemoteBrailleFor(role string, request bool, value RemoteBraille) bool
}
func ValidRemoteBrailleRequest(request RemoteBrailleRequest) bool {
if request.Braille.Op == "cells" && !validCells(request.Braille.Cells, RemoteBrailleRequestMaxCells) {
return false
}
return len(request.Lease) == 32 && request.Epoch != 0 && request.Sequence != 0 && ValidRemoteBraille(request.Braille)
}
@@ -6,6 +6,8 @@ package tentaclewire
import (
"encoding/json"
"math"
"strings"
"testing"
)
@@ -42,3 +44,51 @@ func TestRemoteBrailleDirections(t *testing.T) {
}
}
}
func cellsOf(n int) []int {
cells := make([]int, n)
for i := range cells {
cells[i] = 255
}
return cells
}
func TestRemoteBrailleRequestCellsFitCallBound(t *testing.T) {
atCap := RemoteBraille{Op: "cells", Cells: cellsOf(RemoteBrailleRequestMaxCells)}
overCap := RemoteBraille{Op: "cells", Cells: cellsOf(RemoteBrailleRequestMaxCells + 1)}
atMax := RemoteBraille{Op: "cells", Cells: cellsOf(RemoteBrailleMaxCells)}
overMax := RemoteBraille{Op: "cells", Cells: cellsOf(RemoteBrailleMaxCells + 1)}
// Request direction (child call, 8192-byte params bound).
if !ValidRemoteBrailleFor("controller", true, atCap) || ValidRemoteBrailleFor("controller", true, overCap) {
t.Fatal("request-direction cells cap not enforced at boundary")
}
request := RemoteBrailleRequest{
RemoteOperation: RemoteOperation{Lease: strings.Repeat("a", 32), Epoch: math.MaxUint64, Sequence: math.MaxUint64},
Braille: atCap,
}
if !ValidRemoteBrailleRequest(request) {
t.Fatal("request at cap rejected")
}
data, err := json.Marshal(request)
if err != nil || len(data) > 8192 {
t.Fatalf("worst-case request at cap = %d bytes, err %v", len(data), err)
}
request.Braille = overCap
if ValidRemoteBrailleRequest(request) {
t.Fatal("request over cap accepted")
}
if raw, _ := json.Marshal(request); json.Unmarshal(raw, &RemoteBrailleRequest{}) == nil {
t.Fatal("over-cap request decoded")
}
// Event direction (host frame, 64KiB bound) keeps the larger cap.
if !ValidRemoteBrailleFor("controlled", false, atMax) || !ValidRemoteBraille(atMax) {
t.Fatal("event-direction cells at max rejected")
}
if ValidRemoteBraille(overMax) || ValidRemoteBrailleFor("controlled", false, overMax) {
t.Fatal("cells over max accepted")
}
event, err := json.Marshal(SessionEvent{Sequence: math.MaxUint64, Kind: "remote.braille", Lease: strings.Repeat("a", 32), Epoch: math.MaxUint64, Braille: &atMax})
if err != nil || len(event) > 64*1024 {
t.Fatalf("worst-case event at max = %d bytes, err %v", len(event), err)
}
}
@@ -65,7 +65,7 @@ func TestRemoteOptionalGrantsValidation(t *testing.T) {
optional []string
valid bool
}{
{[]string{"keyboard-capture", "clipboard-exchange", "braille-stream"}, true},
{[]string{"keyboard-capture", "braille-stream"}, true}, {[]string{"clipboard-exchange"}, false},
{[]string{"keyboard-inject"}, false}, {[]string{"remote-present"}, false},
{[]string{"braille-stream", "braille-stream"}, false}, {[]string{"unknown"}, false},
} {
+11 -2
View File
@@ -10,15 +10,21 @@ const (
SessionQueueBytes = 256 * 1024
)
// legacyClipboardGrant was grantable before any clipboard dispatch existed.
// It is no longer in RemoteGrants, so negotiation and session role grants
// reject it, but ValidRemoteGrants still parses it so registries persisted
// with it load (validateSpec) instead of hard-failing; such grants are inert.
const legacyClipboardGrant = "clipboard-exchange"
// RemoteGrants are independent install-time permissions, never session consent.
func RemoteGrants() []string {
return []string{"output-observe", "remote-present", "keyboard-capture", "keyboard-inject", "braille-stream", "clipboard-exchange"}
return []string{"output-observe", "remote-present", "keyboard-capture", "keyboard-inject", "braille-stream"}
}
func ValidRemoteGrants(grants []string) bool {
seen := map[string]bool{}
for _, grant := range grants {
if seen[grant] || !slices.Contains(RemoteGrants(), grant) {
if seen[grant] || !(slices.Contains(RemoteGrants(), grant) || grant == legacyClipboardGrant) {
return false
}
seen[grant] = true
@@ -90,6 +96,9 @@ func ValidRoleGrants(role string, grants []string) bool {
return false
}
for _, grant := range grants {
if grant == legacyClipboardGrant {
return false
}
if role == "controller" && (grant == "output-observe" || grant == "keyboard-inject") || role == "controlled" && (grant == "remote-present" || grant == "keyboard-capture") {
return false
}
+22
View File
@@ -24,6 +24,7 @@ func TestSessionNegotiationRequiresIndependentGrants(t *testing.T) {
{"missing prerequisite", 1, []string{"session-events", "commands", "interaction"}, []string{"interaction"}, false},
{"legacy capability in 1.1", 1, []string{"session-events", "commands"}, []string{"commands"}, false},
{"future version", 2, []string{"session-events", "commands"}, nil, false},
{"clipboard-exchange not grantable", 1, []string{"session-events", "commands", "remote-access"}, []string{"clipboard-exchange"}, false},
}
for _, item := range cases {
t.Run(item.name, func(t *testing.T) {
@@ -34,6 +35,27 @@ func TestSessionNegotiationRequiresIndependentGrants(t *testing.T) {
}
}
func TestClipboardExchangeGrantIsParseToleratedButNotGrantable(t *testing.T) {
for _, grant := range RemoteGrants() {
if grant == "clipboard-exchange" {
t.Fatal("clipboard-exchange still in grant vocabulary")
}
}
// A registry persisted before removal must still load (validateSpec).
if !ValidRemoteGrants([]string{"braille-stream", "clipboard-exchange"}) {
t.Fatal("persisted clipboard-exchange grant no longer parses")
}
if ValidRemoteGrants([]string{"clipboard-exchange", "clipboard-exchange"}) {
t.Fatal("duplicate legacy grant accepted")
}
// But it can no longer be granted for a session, in either role.
for _, role := range []string{"controller", "controlled"} {
if ValidRoleGrants(role, []string{"braille-stream", "clipboard-exchange"}) {
t.Fatalf("clipboard-exchange grantable for %s", role)
}
}
}
func TestRemoteRevocationIdentifiesExactlyOneActionOrLease(t *testing.T) {
token := "0123456789abcdef0123456789abcdef"
for _, item := range []struct {
+3 -2
View File
@@ -126,8 +126,9 @@ func TestHelperReadinessBypassesDiagnosticBackpressure(t *testing.T) {
t.Fatalf("readiness publications before logging = %d, want 1", readyCount)
}
manager := New(nil)
if !manager.restartRunningHelper(child, prefix{}, Settings{}) || !manager.helperUnconfirmed("helper") {
t.Fatal("lost exclusion mismatch fallback under diagnostic backpressure")
manager.helper = "helper"
if !manager.restartRunningHelper(child, prefix{}, Settings{}) || !manager.helperUnconfirmed() {
t.Fatal("unconfirmed exclusions did not restart the helper wholesale")
}
output.finish()
output.logRecords(slog.New(slog.DiscardHandler))
+25 -5
View File
@@ -84,28 +84,48 @@ func (set *helperSet) publish(root string) (string, error) {
if err := os.MkdirAll(root, 0700); err != nil {
return "", err
}
stage := filepath.Join(root, set.digest)
if _, err := os.Stat(stage); os.IsNotExist(err) {
// A damaged or tampered set is never overwritten in place: a running
// process may still have its sidecar mapped. Repair by publishing the
// same verified bytes under the next suffixed directory; later launches
// scan the same sequence and reuse the first set that verifies.
for attempt := range 128 {
name := set.digest
if attempt > 0 {
name = fmt.Sprintf("%s-repair-%d", set.digest, attempt)
}
stage := filepath.Join(root, name)
if _, err := os.Stat(stage); err == nil {
if err := set.verify(stage); err == nil {
return stage, nil
}
continue
} else if !os.IsNotExist(err) {
return "", err
}
temporary, err := os.MkdirTemp(root, ".stage-")
if err != nil {
return "", err
}
defer func() { _ = os.RemoveAll(temporary) }()
for _, file := range set.files {
if err := os.WriteFile(filepath.Join(temporary, file.name), file.data, file.mode); err != nil {
_ = os.RemoveAll(temporary)
return "", err
}
}
if err := os.Rename(temporary, stage); err != nil {
_ = os.RemoveAll(temporary)
if info, statErr := os.Stat(stage); statErr != nil || !info.IsDir() {
return "", err
}
}
// Another publisher won the race; re-evaluate its set.
continue
}
if err := set.verify(stage); err != nil {
return "", err
continue
}
return stage, nil
}
return "", fmt.Errorf("no intact staged Wine helper set could be published")
}
func (set *helperSet) verify(stage string) error {
+10 -8
View File
@@ -67,25 +67,27 @@ type Manager struct {
// yields empty settings.
SettingsSource func() Settings
// unconfirmed remembers helper binaries whose ready record did not
// confirm the exclusions sent, keyed by launched executable path.
// confirm the exclusions sent, keyed by the installed helper path
// (manager.helper), never the launched path: one binary may launch
// directly or from a staged digest directory depending on the prefix.
// Later spawns of such a binary go wholesale directly.
unconfirmedMu sync.Mutex
unconfirmed map[string]bool
}
func (manager *Manager) helperUnconfirmed(helper string) bool {
func (manager *Manager) helperUnconfirmed() bool {
manager.unconfirmedMu.Lock()
defer manager.unconfirmedMu.Unlock()
return manager.unconfirmed[helper]
return manager.unconfirmed[manager.helper]
}
func (manager *Manager) markUnconfirmed(helper string) {
func (manager *Manager) markUnconfirmed() {
manager.unconfirmedMu.Lock()
defer manager.unconfirmedMu.Unlock()
if manager.unconfirmed == nil {
manager.unconfirmed = make(map[string]bool)
}
manager.unconfirmed[helper] = true
manager.unconfirmed[manager.helper] = true
}
func New(logger *slog.Logger) *Manager {
@@ -241,11 +243,11 @@ func (manager *Manager) restartRunningHelper(child *process, source prefix, sett
if child.controllerOnly {
return false
}
if wholesaleControllerOnly(settings) || manager.helperUnconfirmed(child.launchedHelper) {
if wholesaleControllerOnly(settings) || manager.helperUnconfirmed() {
return true
}
if child.readySeen.Load() && int(child.readyExclusions.Load()) != len(child.exclusions) {
manager.markUnconfirmed(child.launchedHelper)
manager.markUnconfirmed()
manager.logger.Warn("Wine accessibility helper did not confirm hook exclusions; restarting without dialog reading",
"sent", len(child.exclusions), "reported", child.readyExclusions.Load())
return true
@@ -274,7 +276,7 @@ func (manager *Manager) launch(child *process, source prefix, now time.Time, set
return err
}
controllerOnly := child.controllerOnly || wholesaleControllerOnly(settings) ||
manager.helperUnconfirmed(helper)
manager.helperUnconfirmed()
arguments := helperArguments(controllerOnly, settings)
cmd := exec.Command(helper, arguments...)
diagnostics := newHelperDiagnostics()
+46
View File
@@ -354,3 +354,49 @@ func TestManagerStopsHelperWhenOnlyWineServicesRemain(t *testing.T) {
t.Fatal("Wine service restarted the helper")
}
}
func TestUnconfirmedHelperMemorySpansStagedAndUnstagedLaunches(t *testing.T) {
root := t.TempDir()
t.Setenv("XDG_STATE_HOME", filepath.Join(root, "state"))
helper := filepath.Join(root, "installed", "wine-access.exe")
writeHelperFile(t, helper, "#!/bin/sh\nexec sleep 30\n")
for _, name := range []string{"wine-access.exe.so", "wine-access-menu.dll", "wine-access-menu32.dll", "wine-access-menu-host32.exe"} {
writeHelperFile(t, filepath.Join(filepath.Dir(helper), name), name)
}
manager := &Manager{helper: helper, logger: slog.New(slog.DiscardHandler)}
settings := Settings{ExcludedPrograms: []string{"game.exe"}}
// First launch is staged (pressure-vessel) and does not confirm its
// exclusions, so the installed binary is remembered as unconfirmed.
staged := &process{}
source := prefix{path: root, environment: map[string]string{"PRESSURE_VESSEL_RUNTIME": "runtime"}}
if err := manager.launch(staged, source, time.Now(), settings); err != nil {
t.Fatal(err)
}
defer stop(staged)
if staged.launchedHelper == helper {
t.Fatal("pressure-vessel launch was not staged")
}
if staged.controllerOnly {
t.Fatal("first launch went wholesale before any mismatch")
}
staged.readySeen.Store(true)
staged.readyExclusions.Store(0)
if !manager.restartRunningHelper(staged, source, settings) {
t.Fatal("unconfirmed staged helper did not restart wholesale")
}
// The same installed binary launched unstaged must go wholesale
// directly, not get a fresh non-wholesale start.
unstaged := &process{}
if err := manager.launch(unstaged, prefix{path: root}, time.Now(), settings); err != nil {
t.Fatal(err)
}
defer stop(unstaged)
if unstaged.launchedHelper != helper {
t.Fatalf("unstaged launch used %q, want installed %q", unstaged.launchedHelper, helper)
}
if !unstaged.controllerOnly {
t.Fatal("unconfirmed memory did not carry from staged to unstaged launch")
}
}
+16 -3
View File
@@ -70,8 +70,21 @@ func TestContainerHelperPublishesImmutableCompleteSets(t *testing.T) {
t.Fatal("old sidecar overwritten")
}
writeHelperFile(t, updated+".so", "tampered")
if _, err := stageHelper(helper, environment); err == nil {
t.Fatal("accepted modified staging")
repaired, err := stageHelper(helper, environment)
if err != nil {
t.Fatalf("damaged staged set was not repaired: %v", err)
}
if repaired == updated {
t.Fatal("repair reused the damaged set")
}
if data, _ := os.ReadFile(repaired + ".so"); string(data) != "new sidecar" {
t.Fatalf("repaired sidecar = %q", data)
}
if data, _ := os.ReadFile(updated + ".so"); string(data) != "tampered" {
t.Fatal("damaged set overwritten in place")
}
if again, err := stageHelper(helper, environment); err != nil || again != repaired {
t.Fatalf("later launch = %q, %v; want repaired %q", again, err, repaired)
}
if err := os.Remove(helper + ".so"); err != nil {
t.Fatal(err)
@@ -115,7 +128,7 @@ func TestHelperArgumentsValidateProgramNames(t *testing.T) {
settings := Settings{ExcludedPrograms: []string{
"Game.exe", "Another Game.exe", "Café.exe", "game.EXE",
"Game\t.exe", "Game\x01.exe", "Game\x1f.exe", `C:\Game.exe`,
strings.Repeat("é", 126) + ".exe",
strings.Repeat("é", 252) + ".exe",
}}
want := []string{
"--exclude-hook-program", "another game.exe",
+8
View File
@@ -9,6 +9,14 @@ import "git.stormux.org/storm/cthulhu/internal/tentaclewire"
type RemoteBraille = tentaclewire.RemoteBraille
type RemoteBrailleRequest = tentaclewire.RemoteBrailleRequest
// RemoteBrailleRequestMaxCells bounds a child-to-host cells request so its
// worst-case JSON fits the 8192-byte call bound; host-to-child events may
// carry up to RemoteBrailleMaxCells.
const (
RemoteBrailleMaxCells = tentaclewire.RemoteBrailleMaxCells
RemoteBrailleRequestMaxCells = tentaclewire.RemoteBrailleRequestMaxCells
)
func ValidRemoteBraille(value RemoteBraille) bool { return tentaclewire.ValidRemoteBraille(value) }
func ValidRemoteBrailleRequest(request RemoteBrailleRequest) bool {
Loaded 100 of 105 files, more files were not shown because too many files have changed in this diff. Show more