Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
companion: serialize proxy changes and handle registration failure
Barack Sokullud80ee339ad36
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.goindex 3b0f9b5e8..8c77a418e 100644--- a/webbrain-systray/internal/app/app.go+++ b/webbrain-systray/internal/app/app.go@@ -34,11 +34,12 @@ type login struct {}type App struct {- Version string- Store *settings.Store- Proxy *core.Proxy- Local *localmodel.Manager- D1 *d1.Manager+ Version string+ Store *settings.Store+ Proxy *core.Proxy+ Local *localmodel.Manager+ D1 *d1.Manager+ restartMu sync.Mutex // serializes settings changes and their proxy restartsmu sync.Mutexcreds []core.Credential@@ -83,11 +84,17 @@ func New(version string, store *settings.Store) *App {internalKey: "wbc-local-" + settings.RandomSecret(),}a.ctx, a.cancel = context.WithCancel(context.Background())- a.Local = localmodel.NewManager(store, a.Proxy.SetLocal, a.changed)+ a.Local = localmodel.NewManager(store, a.registerLocal, a.changed)a.D1 = d1.NewManager(store, a.changed)return a}+func (a *App) registerLocal(local []core.LocalUpstream) error {+ a.restartMu.Lock()+ defer a.restartMu.Unlock()+ return a.Proxy.SetLocal(local)+}+// changed notifies panel listeners and the tray.func (a *App) changed() {a.subsMu.Lock()@@ -414,6 +421,8 @@ func (a *App) SetAccountDisabled(name string, disabled bool) error {// RotateKey issues a new client API key and restarts the proxy with it.func (a *App) RotateKey() error {+ a.restartMu.Lock()+ defer a.restartMu.Unlock()s, err := a.Store.Update(func(s *settings.Settings) { s.APIKey = settings.NewAPIKey() })if err != nil {return err@@ -451,6 +460,8 @@ func (a *App) proxyOptionsOn(s settings.Settings, local []core.LocalUpstream, po// key, or 127.0.0.1 only) and restarts the proxy on the same port, so open// panels and configured apps keep working.func (a *App) SetNetwork(on bool) error {+ a.restartMu.Lock()+ defer a.restartMu.Unlock()s, err := a.Store.Update(func(s *settings.Settings) { s.Network = on })if err != nil {return err@@ -476,6 +487,8 @@ func (a *App) SetPort(port int) error {if port < 1024 || port > 65535 {return errors.New("choose a port between 1024 and 65535")}+ a.restartMu.Lock()+ defer a.restartMu.Unlock()previous := a.Store.Get()previousPort := a.Proxy.Port()panelOpen := a.listeners() > 0diff --git a/webbrain-systray/internal/app/port_test.go b/webbrain-systray/internal/app/port_test.goindex 3be333261..b3fce8d90 100644--- a/webbrain-systray/internal/app/port_test.go+++ b/webbrain-systray/internal/app/port_test.go@@ -1,8 +1,11 @@package appimport (+ "fmt""net"+ "os""strings"+ "sync""testing""github.com/esokullu/webbrain-systray/internal/paths"@@ -43,3 +46,51 @@ func TestSetPortRestoresWorkingProxyWhenLastPortIsOccupied(t *testing.T) {t.Fatal("panel has no notice explaining the rejected port")}}++func TestConcurrentSettingsRestartsKeepProxyConfigCurrent(t *testing.T) {+ 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()+ free, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatal(err)+ }+ port := free.Addr().(*net.TCPAddr).Port+ _ = free.Close()+ operations := []func() error{func() error { return a.SetNetwork(false) }, func() error { return a.SetPort(port) }, a.RotateKey}+ var wg sync.WaitGroup+ errs := make(chan error, len(operations))+ for _, op := range operations {+ wg.Add(1)+ go func() {+ defer wg.Done()+ errs <- op()+ }()+ }+ wg.Wait()+ close(errs)+ for err := range errs {+ if err != nil {+ t.Fatal(err)+ }+ }+ data, err := os.ReadFile(paths.ProxyConfig())+ if err != nil {+ t.Fatal(err)+ }+ config := string(data)+ if !a.Proxy.Running() || !strings.Contains(config, fmt.Sprintf("port: %d", a.Proxy.Port())) ||+ !strings.Contains(config, store.Get().APIKey) {+ t.Fatalf("proxy config does not match the final port and API key (running=%v port=%d)", a.Proxy.Running(), a.Proxy.Port())+ }+}diff --git a/webbrain-systray/internal/core/proxy.go b/webbrain-systray/internal/core/proxy.goindex 309f5e6c2..17a01015a 100644--- a/webbrain-systray/internal/core/proxy.go+++ b/webbrain-systray/internal/core/proxy.go@@ -65,6 +65,7 @@ type Options struct {}type Proxy struct {+ opMu sync.Mutex // serializes start, stop, and config rewritesmu sync.Mutexopts Optionsport int@@ -171,6 +172,8 @@ func (p *Proxy) Host() string {// Start launches the service and waits until it answers HTTP requests.func (p *Proxy) Start(opts Options) error {+ p.opMu.Lock()+ defer p.opMu.Unlock()p.mu.Lock()if p.done != nil {select {@@ -266,6 +269,8 @@ func (p *Proxy) Start(opts Options) error {// Stop shuts the service down and waits for it to exit.func (p *Proxy) Stop() {+ p.opMu.Lock()+ defer p.opMu.Unlock()p.mu.Lock()cancel, done := p.cancel, p.donep.mu.Unlock()@@ -293,6 +298,8 @@ func (p *Proxy) Local() []LocalUpstream {// SetLocal rewrites the registered local upstreams; the service hot-reloads// its config file.func (p *Proxy) SetLocal(local []LocalUpstream) error {+ p.opMu.Lock()+ defer p.opMu.Unlock()p.mu.Lock()p.opts.Local = localopts, port, secret := p.opts, p.port, p.secretdiff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.goindex df18e3898..1dccef756 100644--- a/webbrain-systray/internal/localmodel/manager.go+++ b/webbrain-systray/internal/localmodel/manager.go@@ -674,13 +674,20 @@ func (m *Manager) Start() (startErr error) {Models: []core.LocalModel{{Upstream: upstream, Alias: ModelID, DisplayName: ModelName + " (local)",Vision: vision, ContextLength: plan.Context}},}}); err != nil {- logx.Printf("register local model: %v", err)+ m.registrationFailed(err)+ return}now := time.Now()m.mu.Lock()+ if m.cmd != cmd || m.stopping {+ m.mu.Unlock()+ _ = m.register(nil)+ return+ }m.startedAt = &now+ m.phase, m.step, m.err = PhaseRunning, "", ""m.mu.Unlock()- m.setPhase(PhaseRunning, "", nil)+ m.changed()return}logx.Printf("local model: not ready after 10 minutes, stopping it")@@ -692,6 +699,14 @@ func (m *Manager) Start() (startErr error) {return nil}+func (m *Manager) registrationFailed(err error) {+ logx.Printf("register local model: %v", err)+ m.mu.Lock()+ m.stopErr = fmt.Errorf("could not register the local model with the proxy: %w", err)+ m.mu.Unlock()+ m.Stop()+}+// waitForExit finishes cleanup before Stop can return and Restart can launch// another server. Keeping cmd set until then also prevents an early Start.func (m *Manager) waitForExit(cmd *exec.Cmd, exited chan struct{}) {diff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.goindex b215e0020..48cb7eeb5 100644--- a/webbrain-systray/internal/localmodel/manager_test.go+++ b/webbrain-systray/internal/localmodel/manager_test.go@@ -3,8 +3,10 @@ package localmodelimport ("crypto/sha256""encoding/hex"+ "errors""os""path/filepath"+ "strings""sync/atomic""testing""time"@@ -20,6 +22,34 @@ func TestLocalModelExitHelper(t *testing.T) {}}+func TestLocalModelWaitHelper(t *testing.T) {+ if os.Getenv("WBC_WAIT_HELPER") == "1" {+ time.Sleep(30 * time.Second)+ }+}++func TestRegistrationFailureStopsServerAndReportsError(t *testing.T) {+ executable, err := os.Executable()+ if err != nil {+ t.Fatal(err)+ }+ cmd := osutil.Command(executable, "-test.run=^TestLocalModelWaitHelper$")+ cmd.Env = append(os.Environ(), "WBC_WAIT_HELPER=1")+ if err := cmd.Start(); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { _ = cmd.Process.Kill() })+ m := NewManager(nil, func([]core.LocalUpstream) error { return nil }, nil)+ m.cmd, m.exited, m.phase = cmd, make(chan struct{}), PhaseStarting+ go m.waitForExit(cmd, m.exited)+ m.registrationFailed(errors.New("data volume full"))+ m.mu.Lock()+ defer m.mu.Unlock()+ if m.cmd != nil || m.phase != PhaseError || !strings.Contains(m.err, "data volume full") {+ t.Fatalf("registration failure left cmd=%v phase=%q error=%q", m.cmd, m.phase, m.err)+ }+}+func TestStartClaimPreventsOverlappingLaunches(t *testing.T) {t.Setenv("WBC_HOME", t.TempDir())store, err := settings.Open()