Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Deliver buffered bridge frames before reporting disconnects, preventing lost pairing and hello replies, and let bridge readers exit without an error consumer. Thanks @SebTardif! (#9)
- Stop speech queues and cancel active system TTS when the bridge disconnects or the node exits. Thanks @SebTardif! (#7)
- Forward only final speech transcripts to quick actions, voice events, and agent requests. Thanks @SebTardif! (#12)
- Treat leading dashes in spoken text as words instead of espeak options. Thanks @SebTardif! (#11)
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ With `-stt-engine brabble`, only final utterances are routed or sent to the brid
SIGINT and SIGTERM interrupt reconnect backoff immediately, including when the bridge is unavailable.
They also cancel bridge dialing and pairing/hello waits in `run` and `pair`, closing the connection before exit.

Bridge replies already received are processed before a disconnect is reported, including pairing and hello replies sent immediately before the bridge closes the connection.

Spoken text is passed after `--` so leading dashes are treated as words. Custom `-tts-system-command` wrappers must preserve the option separator when forwarding arguments to espeak-ng.

## systemd example
Expand Down
38 changes: 19 additions & 19 deletions cmd/clawgo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ type BridgeClient struct {
mu sync.Mutex
logf func(string, ...any)
done chan struct{}
errs chan error
frames chan map[string]any
readErr error // Read only after frames closes.
eventMu sync.RWMutex
eventHandler func(string, string)
closeOnce sync.Once
Expand Down Expand Up @@ -495,14 +495,13 @@ func runNode(cfg NodeConfig) error {
mdnsCleanup()
}
return nil
case err := <-client.errs:
if err != nil {
client.logf("bridge error: %v", err)
case frame, ok := <-client.frames:
if !ok {
client.logf("bridge error: %v", client.readErr)
connCancel()
client.Close()
goto reconnect
}
connCancel()
client.Close()
goto reconnect
case frame := <-client.frames:
if frame == nil {
continue
}
Expand Down Expand Up @@ -552,7 +551,6 @@ func connectBridge(ctx context.Context, addr string) (*BridgeClient, error) {
conn: conn,
logf: func(format string, args ...any) { fmt.Fprintf(os.Stderr, format+"\n", args...) },
done: make(chan struct{}),
errs: make(chan error, 1),
frames: make(chan map[string]any, 16),
}
go client.readLoop()
Expand Down Expand Up @@ -600,6 +598,8 @@ func (c *BridgeClient) dispatchEvent(evt, payload string) {
}

func (c *BridgeClient) readLoop() {
defer close(c.frames)
c.readErr = io.EOF
scanner := bufio.NewScanner(c.conn)
scanner.Buffer(make([]byte, 0, 64*1024), 8*1024*1024)
for scanner.Scan() {
Expand All @@ -618,11 +618,9 @@ func (c *BridgeClient) readLoop() {
return
}
}
if err := scanner.Err(); err != nil && !errors.Is(err, io.EOF) {
c.errs <- err
return
if err := scanner.Err(); err != nil {
c.readErr = err
}
c.errs <- io.EOF
}

func sendPairRequest(c *BridgeClient, cfg NodeConfig, state *NodeState) error {
Expand Down Expand Up @@ -684,9 +682,10 @@ func waitForPair(ctx context.Context, c *BridgeClient) (string, error) {
return "", ctx.Err()
case <-deadline:
return "", errors.New("pairing timeout")
case err := <-c.errs:
return "", err
case frame := <-c.frames:
case frame, ok := <-c.frames:
if !ok {
return "", c.readErr
}
if frame == nil {
continue
}
Expand All @@ -712,9 +711,10 @@ func waitForHello(ctx context.Context, c *BridgeClient) error {
return ctx.Err()
case <-deadline:
return errors.New("hello timeout")
case err := <-c.errs:
return err
case frame := <-c.frames:
case frame, ok := <-c.frames:
if !ok {
return c.readErr
}
if frame == nil {
continue
}
Expand Down
133 changes: 133 additions & 0 deletions cmd/clawgo/readloop_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package main

import (
"context"
"encoding/json"
"io"
"net"
"testing"
"time"
)

func readLoopFixture(t *testing.T) (*BridgeClient, net.Conn, <-chan struct{}) {
t.Helper()
conn, peer := net.Pipe()
c := &BridgeClient{
conn: conn,
logf: func(string, ...any) {},
done: make(chan struct{}),
frames: make(chan map[string]any, 16),
}
finished := make(chan struct{})
go func() {
c.readLoop()
close(finished)
}()
t.Cleanup(func() {
c.Close()
_ = peer.Close()
select {
case <-finished:
case <-time.After(2 * time.Second):
t.Error("bridge reader did not stop")
}
})
return c, peer, finished
}

func TestBridgeHandshakeBeforeEOF(t *testing.T) {
for _, kind := range []string{"pair", "hello"} {
t.Run(kind, func(t *testing.T) {
for i := 0; i < 32; i++ {
c, peer, finished := readLoopFixture(t)
frame := map[string]any{"type": kind + "-ok", "token": "synthetic-token"}
if err := json.NewEncoder(peer).Encode(frame); err != nil {
t.Fatal(err)
}
_ = peer.Close()
select {
case <-finished:
case <-time.After(2 * time.Second):
t.Fatal("bridge reader did not finish after EOF")
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
if kind == "pair" {
token, err := waitForPair(ctx, c)
cancel()
if err != nil || token != "synthetic-token" {
t.Fatalf("iteration %d: pair = %q, %v; want token before EOF", i, token, err)
}
} else {
err := waitForHello(ctx, c)
cancel()
if err != nil {
t.Fatalf("iteration %d: hello = %v; want hello-ok before EOF", i, err)
}
}
}
})
}
}

func TestBridgeReaderStopsWithoutConsumer(t *testing.T) {
for _, frames := range []int{0, 17} {
c, peer, finished := readLoopFixture(t)
writerDone := make(chan struct{})
go func() {
defer close(writerDone)
for i := 0; i < frames; i++ {
if _, err := io.WriteString(peer, "{\"type\":\"event\"}\n"); err != nil {
return
}
}
}()
select {
case <-writerDone:
case <-time.After(2 * time.Second):
t.Fatal("could not fill frame buffer")
}
c.Close()
select {
case <-finished:
case <-time.After(2 * time.Second):
t.Fatal("reader blocked after consumer left")
}
}
}

func TestBridgeWaitReportsEOF(t *testing.T) {
c, peer, _ := readLoopFixture(t)
_ = peer.Close()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if _, err := waitForPair(ctx, c); err != io.EOF {
t.Fatalf("pair error = %v, want EOF", err)
}
if err := waitForHello(ctx, c); err != io.EOF {
t.Fatalf("hello error = %v, want EOF", err)
}
}

type failedReadConn struct {
net.Conn
err error
}

func (c failedReadConn) Read([]byte) (int, error) { return 0, c.err }

func TestBridgeReaderPreservesReadError(t *testing.T) {
want := io.ErrUnexpectedEOF
c := &BridgeClient{
conn: failedReadConn{err: want},
frames: make(chan map[string]any, 1),
}
c.readLoop()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
if _, err := waitForPair(ctx, c); err != want {
t.Fatalf("pair error = %v, want %v", err, want)
}
if err := waitForHello(ctx, c); err != want {
t.Fatalf("hello error = %v, want %v", err, want)
}
}
1 change: 0 additions & 1 deletion cmd/clawgo/wait_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,6 @@ func TestConnectBridgeCancellationClosesConnection(t *testing.T) {
func testBridgeClient() *BridgeClient {
return &BridgeClient{
logf: func(string, ...any) {},
errs: make(chan error),
frames: make(chan map[string]any),
}
}
Expand Down
Loading