Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

companion: order panel restarts and reject model API errors

Barack Sokullu3e7386c7ac13
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.go
index 5f0c34ef3..fde848155 100644
--- a/webbrain-systray/internal/app/app.go
+++ b/webbrain-systray/internal/app/app.go
@@ -40,6 +40,8 @@ type App struct {
Local *localmodel.Manager
D1 *d1.Manager
restartMu sync.Mutex // serializes settings changes and their proxy restarts
+ queueMu sync.Mutex // orders restarts requested by the panel before they run
+ queueTail chan struct{}
mu sync.Mutex
creds []core.Credential
@@ -95,6 +97,33 @@ func (a *App) registerLocal(local []core.LocalUpstream) error {
return a.Proxy.SetLocal(local)
}
+// The panel must receive its response before a restart drops its connection.
+// Chain delayed operations in request order so rapid changes apply in order.
+func (a *App) queueRestart(label string, change func() error) {
+ a.queueMu.Lock()
+ previous := a.queueTail
+ done := make(chan struct{})
+ a.queueTail = done
+ a.queueMu.Unlock()
+ go func() {
+ defer close(done)
+ if previous != nil {
+ <-previous
+ }
+ select {
+ case <-time.After(300 * time.Millisecond):
+ case <-a.ctx.Done():
+ return
+ }
+ if a.ctx.Err() != nil {
+ return
+ }
+ if err := change(); err != nil {
+ logx.Printf("%s: %v", label, err)
+ }
+ }()
+}
+
// changed notifies panel listeners and the tray.
func (a *App) changed() {
a.subsMu.Lock()
diff --git a/webbrain-systray/internal/app/port_test.go b/webbrain-systray/internal/app/port_test.go
index b3fce8d90..0758f2d24 100644
--- a/webbrain-systray/internal/app/port_test.go
+++ b/webbrain-systray/internal/app/port_test.go
@@ -3,10 +3,15 @@ package app
import (
"fmt"
"net"
+ "net/http"
+ "net/http/httptest"
"os"
"strings"
"sync"
"testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
"github.com/esokullu/webbrain-systray/internal/paths"
"github.com/esokullu/webbrain-systray/internal/settings"
@@ -47,6 +52,57 @@ func TestSetPortRestoresWorkingProxyWhenLastPortIsOccupied(t *testing.T) {
}
}
+func TestRapidNetworkTogglesApplyInRequestOrder(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ t.Setenv("WBC_HOME", t.TempDir())
+ if err := paths.Ensure(); err != nil {
+ t.Fatal(err)
+ }
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ a := New("test", store)
+ if err := a.Start(); err != nil {
+ t.Fatal(err)
+ }
+ defer a.Shutdown()
+ e := gin.New()
+ a.routes(e)
+ send := func(network bool) chan struct{} {
+ body := fmt.Sprintf(`{"network":%t}`, network)
+ r := httptest.NewRequest(http.MethodPatch, "http://127.0.0.1:8327/companion/api/settings", strings.NewReader(body))
+ r.RemoteAddr = "127.0.0.1:50000"
+ r.Header.Set("Content-Type", "application/json")
+ r.Header.Set("X-Companion-Key", store.Get().PanelToken)
+ w := httptest.NewRecorder()
+ e.ServeHTTP(w, r)
+ if w.Code != http.StatusOK {
+ t.Fatalf("settings update returned %d: %s", w.Code, w.Body.String())
+ }
+ a.queueMu.Lock()
+ done := a.queueTail
+ a.queueMu.Unlock()
+ return done
+ }
+ onDone := send(true)
+ offDone := send(false) // arrives while the first change is still delayed
+ for _, step := range []struct {
+ done chan struct{}
+ want bool
+ host string
+ }{{onDone, true, "0.0.0.0"}, {offDone, false, "127.0.0.1"}} {
+ select {
+ case <-step.done:
+ case <-time.After(45 * time.Second):
+ t.Fatal("queued network change did not finish")
+ }
+ if store.Get().Network != step.want || a.Proxy.Host() != step.host {
+ t.Fatalf("queued network change finished with network=%v host=%q, want %v and %q", store.Get().Network, a.Proxy.Host(), step.want, step.host)
+ }
+ }
+}
+
func TestConcurrentSettingsRestartsKeepProxyConfigCurrent(t *testing.T) {
t.Setenv("WBC_HOME", t.TempDir())
if err := paths.Ensure(); err != nil {
diff --git a/webbrain-systray/internal/app/routes.go b/webbrain-systray/internal/app/routes.go
index 639aca481..0c9d6b77f 100644
--- a/webbrain-systray/internal/app/routes.go
+++ b/webbrain-systray/internal/app/routes.go
@@ -487,28 +487,34 @@ func (a *App) routes(e *gin.Engine) {
if req.Welcomed != nil {
_, _ = a.Store.Update(func(s *settings.Settings) { s.Welcomed = *req.Welcomed })
}
- if req.Network != nil && *req.Network != a.Store.Get().Network {
+ if req.Port != nil && (*req.Port < 1024 || *req.Port > 65535) {
+ fail(c, http.StatusBadRequest, errors.New("choose a port between 1024 and 65535"))
+ return
+ }
+ restart := false
+ if req.Network != nil {
on := *req.Network
- // Reply first: the proxy restarts on the new address.
- c.JSON(http.StatusOK, gin.H{"ok": true, "restart": true})
- go func() {
- time.Sleep(300 * time.Millisecond)
- if err := a.SetNetwork(on); err != nil {
- logx.Printf("network access: %v", err)
+ a.queueRestart("network access", func() error {
+ if a.Store.Get().Network == on {
+ return nil
}
- }()
- return
+ return a.SetNetwork(on)
+ })
+ restart = true
}
- if req.Port != nil && *req.Port != a.Store.Get().Port {
+ if req.Port != nil {
port := *req.Port
- // Reply first: the panel will reconnect on the new port.
- c.JSON(http.StatusOK, gin.H{"ok": true, "restart": true})
- go func() {
- time.Sleep(300 * time.Millisecond)
- if err := a.SetPort(port); err != nil {
- logx.Printf("change port: %v", err)
+ a.queueRestart("change port", func() error {
+ if a.Store.Get().Port == port {
+ return nil
}
- }()
+ return a.SetPort(port)
+ })
+ restart = true
+ }
+ if restart {
+ // Reply before queued changes restart the proxy.
+ c.JSON(http.StatusOK, gin.H{"ok": true, "restart": true})
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
@@ -523,13 +529,8 @@ func (a *App) routes(e *gin.Engine) {
}
})
api.POST("/key/rotate", func(c *gin.Context) {
+ a.queueRestart("rotate key", a.RotateKey)
c.JSON(http.StatusOK, gin.H{"ok": true})
- go func() {
- time.Sleep(300 * time.Millisecond)
- if err := a.RotateKey(); err != nil {
- logx.Printf("rotate key: %v", err)
- }
- }()
})
api.POST("/open", func(c *gin.Context) {
var req struct {
diff --git a/webbrain-systray/internal/core/mgmt.go b/webbrain-systray/internal/core/mgmt.go
index 21939ebe1..afec90822 100644
--- a/webbrain-systray/internal/core/mgmt.go
+++ b/webbrain-systray/internal/core/mgmt.go
@@ -215,6 +215,10 @@ func (m *Mgmt) Models(ctx context.Context) ([]string, error) {
return nil, err
}
defer resp.Body.Close()
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ data, _ := io.ReadAll(io.LimitReader(resp.Body, 32<<10))
+ return nil, &APIError{Status: resp.StatusCode, Body: string(data)}
+ }
var out struct {
Data []struct {
ID string `json:"id"`
diff --git a/webbrain-systray/internal/core/mgmt_test.go b/webbrain-systray/internal/core/mgmt_test.go
new file mode 100644
index 000000000..fc2a8db02
--- /dev/null
+++ b/webbrain-systray/internal/core/mgmt_test.go
@@ -0,0 +1,24 @@
+package core
+
+import (
+ "context"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestModelsRejectsHTTPErrorResponse(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusServiceUnavailable)
+ _, _ = w.Write([]byte(`{"error":"temporarily unavailable"}`))
+ }))
+ defer server.Close()
+ m := newMgmt(server.URL, "pass", "key")
+ models, err := m.Models(context.Background())
+ var apiErr *APIError
+ if models != nil || !errors.As(err, &apiErr) || apiErr.Status != http.StatusServiceUnavailable {
+ t.Fatalf("Models returned %v, %v; want HTTP 503 error", models, err)
+ }
+}