Skip to content

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

companion: honor explicit stop and clean up on shutdown

Barack Sokullu560d1c675c8c
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.go
index 7f5225967..daadf07da 100644
--- a/webbrain-systray/internal/app/app.go
+++ b/webbrain-systray/internal/app/app.go
@@ -199,7 +199,11 @@ func (a *App) Start() error {
// Shutdown stops child servers and the proxy.
func (a *App) Shutdown() {
a.cancel()
- a.Local.Stop()
+ a.Local.BeginShutdown()
+ a.D1.BeginShutdown()
+ if err := a.Local.StopExplicit(); err != nil {
+ logx.Printf("stop local model during shutdown: %v", err)
+ }
a.D1.Unload()
a.Proxy.Stop()
}
diff --git a/webbrain-systray/internal/app/routes.go b/webbrain-systray/internal/app/routes.go
index 2c3bcaceb..697413cf4 100644
--- a/webbrain-systray/internal/app/routes.go
+++ b/webbrain-systray/internal/app/routes.go
@@ -357,14 +357,17 @@ func (a *App) routes(e *gin.Engine) {
})
api.POST("/local/cancel", func(c *gin.Context) { a.Local.Cancel(); c.JSON(http.StatusOK, gin.H{"ok": true}) })
api.POST("/local/start", func(c *gin.Context) {
- if err := a.Local.Start(); err != nil {
+ if err := a.Local.StartExplicit(); err != nil {
fail(c, http.StatusConflict, err)
return
}
c.JSON(http.StatusOK, gin.H{"ok": true})
})
api.POST("/local/stop", func(c *gin.Context) {
- go a.Local.Stop()
+ if err := a.Local.StopExplicit(); err != nil {
+ fail(c, http.StatusConflict, err)
+ return
+ }
c.JSON(http.StatusOK, gin.H{"ok": true})
})
api.POST("/local/remove", func(c *gin.Context) {
diff --git a/webbrain-systray/internal/d1/manager.go b/webbrain-systray/internal/d1/manager.go
index 6619bf460..4b50b66e7 100644
--- a/webbrain-systray/internal/d1/manager.go
+++ b/webbrain-systray/internal/d1/manager.go
@@ -133,6 +133,7 @@ type Manager struct {
cancel context.CancelFunc
installDone chan struct{}
removing bool
+ closing bool
eng *engine
evalMu sync.Mutex
verified download.Verifier
@@ -272,6 +273,10 @@ func (m *Manager) Install() error {
return errors.New("ONNX Runtime " + ortVersion + " has no build for this platform")
}
m.mu.Lock()
+ if m.closing {
+ m.mu.Unlock()
+ return errors.New("the companion is shutting down")
+ }
if m.removing || m.phase == PhaseDownloading || m.phase == PhaseInstalling || m.phase == PhaseLoading {
m.mu.Unlock()
return errors.New("already installing")
@@ -319,6 +324,21 @@ func (m *Manager) Cancel() {
}
}
+// BeginShutdown cancels installation and waits for its worker to release
+// downloads and any newly loaded sessions before Unload runs.
+func (m *Manager) BeginShutdown() {
+ m.mu.Lock()
+ m.closing = true
+ cancel, done := m.cancel, m.installDone
+ m.mu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+ if done != nil {
+ <-done
+ }
+}
+
func (m *Manager) install(ctx context.Context, asset ortAsset) error {
type item struct {
label, url, dest string
@@ -402,6 +422,12 @@ func (m *Manager) Load() error {
// load requires evalMu so sessions cannot be replaced or released during use.
func (m *Manager) load() error {
+ m.mu.Lock()
+ closing := m.closing
+ m.mu.Unlock()
+ if closing {
+ return errors.New("the companion is shutting down")
+ }
if !m.Installed() {
return ErrNotReady
}
diff --git a/webbrain-systray/internal/d1/manager_files_test.go b/webbrain-systray/internal/d1/manager_files_test.go
index 7875665cd..761702d9d 100644
--- a/webbrain-systray/internal/d1/manager_files_test.go
+++ b/webbrain-systray/internal/d1/manager_files_test.go
@@ -72,6 +72,40 @@ func TestRemoveWaitsForCanceledInstall(t *testing.T) {
}
}
+func TestShutdownWaitsForDecisionInstaller(t *testing.T) {
+ m := NewManager(nil, nil)
+ installDone, canceled := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() {
+ select {
+ case <-installDone:
+ default:
+ close(installDone)
+ }
+ })
+ m.installDone, m.cancel = installDone, func() { close(canceled) }
+ shutdownDone := make(chan struct{})
+ go func() { m.BeginShutdown(); close(shutdownDone) }()
+ select {
+ case <-canceled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("shutdown did not cancel installation")
+ }
+ if err := m.Load(); err == nil {
+ t.Fatal("decision model loaded during shutdown")
+ }
+ select {
+ case <-shutdownDone:
+ t.Fatal("shutdown returned before installation finished")
+ case <-time.After(25 * time.Millisecond):
+ }
+ close(installDone)
+ select {
+ case <-shutdownDone:
+ case <-time.After(5 * time.Second):
+ t.Fatal("shutdown did not finish after installation stopped")
+ }
+}
+
func TestValidFileRejectsSameSizeCorruption(t *testing.T) {
path := filepath.Join(t.TempDir(), "model.data")
good := []byte("pinned model contents")
diff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.go
index ed36b0815..4bf7d860d 100644
--- a/webbrain-systray/internal/localmodel/manager.go
+++ b/webbrain-systray/internal/localmodel/manager.go
@@ -70,21 +70,23 @@ type Manager struct {
register func([]core.LocalUpstream) error
onChange func()
- phase string
- step string
- progress *download.Progress
- err string
- port int
- startedAt *time.Time
- plan Plan
- cancel context.CancelFunc
- installDone chan struct{}
- removing bool
- cmd *exec.Cmd
- starting chan struct{} // closed after Start either publishes cmd or fails
- exited chan struct{}
- stopping bool
- stopErr error // why the server was stopped, when it was not the user
+ phase string
+ step string
+ progress *download.Progress
+ err string
+ port int
+ startedAt *time.Time
+ plan Plan
+ cancel context.CancelFunc
+ installDone chan struct{}
+ removing bool
+ closing bool
+ stopRequested bool
+ cmd *exec.Cmd
+ starting chan struct{} // closed after Start either publishes cmd or fails
+ exited chan struct{}
+ stopping bool
+ stopErr error // why the server was stopped, when it was not the user
}
func NewManager(store *settings.Store, register func([]core.LocalUpstream) error, onChange func()) *Manager {
@@ -517,6 +519,8 @@ type item struct {
// Install downloads everything the selected format needs, then starts it.
func (m *Manager) Install(format string) error {
+ m.restartMu.Lock()
+ defer m.restartMu.Unlock()
info := sysinfo.Get()
if format == "" {
format = m.format(info)
@@ -525,6 +529,10 @@ func (m *Manager) Install(format string) error {
return errors.New("MLX needs a Mac with Apple Silicon")
}
m.mu.Lock()
+ if m.closing {
+ m.mu.Unlock()
+ return errors.New("the companion is shutting down")
+ }
if m.removing {
m.mu.Unlock()
return errors.New("the local model is being removed")
@@ -541,6 +549,7 @@ func (m *Manager) Install(format string) error {
m.cancel = cancel
done := make(chan struct{})
m.installDone = done
+ m.stopRequested = false
m.phase, m.step, m.err, m.progress = PhaseDownloading, "Preparing the local model", "", nil
m.mu.Unlock()
m.changed()
@@ -572,7 +581,11 @@ func (m *Manager) Install(format string) error {
return
}
if err := m.Start(); err != nil {
- m.setPhase(PhaseError, "", err)
+ if errors.Is(err, errStopRequested) {
+ m.setPhase(PhaseIdle, "", nil)
+ } else {
+ m.setPhase(PhaseError, "", err)
+ }
}
}()
return nil
@@ -600,6 +613,23 @@ func (m *Manager) Cancel() {
}
}
+// BeginShutdown prevents new work and waits for an installer to release its
+// child processes before the local server and proxy are stopped.
+func (m *Manager) BeginShutdown() {
+ m.restartMu.Lock()
+ m.mu.Lock()
+ m.closing, m.stopRequested = true, true
+ cancel, done := m.cancel, m.installDone
+ m.mu.Unlock()
+ m.restartMu.Unlock()
+ if cancel != nil {
+ cancel()
+ }
+ if done != nil {
+ <-done
+ }
+}
+
func (m *Manager) fetchAll(ctx context.Context, items []item) error {
var total, done int64
for _, it := range items {
@@ -827,6 +857,8 @@ func freePort(preferred int) int {
return preferred
}
+var errStopRequested = errors.New("local model stop requested")
+
// Start launches the local server for the selected format and registers it
// with the proxy once it answers.
func (m *Manager) Start() (startErr error) {
@@ -836,10 +868,18 @@ func (m *Manager) Start() (startErr error) {
plan := MakePlan(info, s.Local, format)
m.mu.Lock()
+ if m.closing {
+ m.mu.Unlock()
+ return errors.New("the companion is shutting down")
+ }
if m.removing {
m.mu.Unlock()
return errors.New("the local model is being removed")
}
+ if m.stopRequested {
+ m.mu.Unlock()
+ return errStopRequested
+ }
if m.cmd != nil || m.starting != nil {
m.mu.Unlock()
return nil
@@ -984,6 +1024,16 @@ func (m *Manager) Start() (startErr error) {
return nil
}
+// StartExplicit clears a previous user stop before launching again.
+func (m *Manager) StartExplicit() error {
+ m.restartMu.Lock()
+ defer m.restartMu.Unlock()
+ m.mu.Lock()
+ m.stopRequested = false
+ m.mu.Unlock()
+ return m.Start()
+}
+
func (m *Manager) registrationFailed(err error) {
logx.Printf("register local model: %v", err)
m.mu.Lock()
@@ -1062,6 +1112,16 @@ func (m *Manager) Stop() error {
return nil
}
+// StopExplicit wins over a queued settings restart.
+func (m *Manager) StopExplicit() error {
+ m.restartMu.Lock()
+ defer m.restartMu.Unlock()
+ m.mu.Lock()
+ m.stopRequested = true
+ m.mu.Unlock()
+ return m.Stop()
+}
+
// Running reports whether the local server is up.
func (m *Manager) Running() bool {
m.mu.Lock()
@@ -1143,12 +1203,20 @@ func (m *Manager) Remove(format string) error {
func (m *Manager) Restart() error {
m.restartMu.Lock()
defer m.restartMu.Unlock()
+ m.mu.Lock()
+ stopped := m.stopRequested || m.closing
+ m.mu.Unlock()
+ if stopped {
+ return nil
+ }
active := m.Active()
if err := m.Stop(); err != nil {
return err
}
if active {
- return m.Start()
+ if err := m.Start(); !errors.Is(err, errStopRequested) {
+ return err
+ }
}
return nil
}
diff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.go
index 3d552ed62..64bb5b152 100644
--- a/webbrain-systray/internal/localmodel/manager_test.go
+++ b/webbrain-systray/internal/localmodel/manager_test.go
@@ -102,6 +102,64 @@ func TestRestartIncludesStartingModel(t *testing.T) {
}
}
+func TestExplicitStopOverridesQueuedRestart(t *testing.T) {
+ t.Setenv("WBC_HOME", t.TempDir())
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := NewManager(store, func([]core.LocalUpstream) error { return nil }, nil)
+ m.phase = PhaseStarting
+ if err := m.StopExplicit(); err != nil {
+ t.Fatal(err)
+ }
+ if err := m.Restart(); err != nil {
+ t.Fatalf("queued restart ran after explicit stop: %v", err)
+ }
+ if err := m.StartExplicit(); err == nil {
+ t.Fatal("manual start did not clear the stop request and attempt a launch")
+ }
+}
+
+func TestShutdownWaitsForLocalInstaller(t *testing.T) {
+ t.Setenv("WBC_HOME", t.TempDir())
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ m := NewManager(store, func([]core.LocalUpstream) error { return nil }, nil)
+ installDone, canceled := make(chan struct{}), make(chan struct{})
+ t.Cleanup(func() {
+ select {
+ case <-installDone:
+ default:
+ close(installDone)
+ }
+ })
+ m.installDone, m.cancel = installDone, func() { close(canceled) }
+ shutdownDone := make(chan struct{})
+ go func() { m.BeginShutdown(); close(shutdownDone) }()
+ select {
+ case <-canceled:
+ case <-time.After(5 * time.Second):
+ t.Fatal("shutdown did not cancel installation")
+ }
+ if err := m.Install("gguf"); err == nil {
+ t.Fatal("installation started during shutdown")
+ }
+ select {
+ case <-shutdownDone:
+ t.Fatal("shutdown returned before installation finished")
+ case <-time.After(25 * time.Millisecond):
+ }
+ close(installDone)
+ select {
+ case <-shutdownDone:
+ case <-time.After(5 * time.Second):
+ t.Fatal("shutdown did not finish after installation stopped")
+ }
+}
+
func TestInstallDefaultPreservesAutostartChoice(t *testing.T) {
t.Setenv("WBC_HOME", t.TempDir())
store, err := settings.Open()
diff --git a/webbrain-systray/main.go b/webbrain-systray/main.go
index 596f1df27..0a22ea303 100644
--- a/webbrain-systray/main.go
+++ b/webbrain-systray/main.go
@@ -152,10 +152,16 @@ func main() {
_ = osutil.OpenAppWindow(a.PanelURL(fragment), 460, 820)
}
a.OpenPanel = open
+ var shutdownOnce sync.Once
shutdown := func() {
- a.Shutdown()
- _ = os.Remove(runtimeFile())
+ shutdownOnce.Do(func() {
+ a.Shutdown()
+ _ = os.Remove(runtimeFile())
+ })
}
+ sig := make(chan os.Signal, 1)
+ signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
+ defer signal.Stop(sig)
if *headless {
if startErr != nil {
@@ -164,8 +170,6 @@ func main() {
}
fmt.Fprintf(stdout, "WebBrain Companion %s\n OpenAI base URL: %s/v1\n API key: %s\n Panel: %s\n",
version, a.Proxy.BaseURL(), store.Get().APIKey, a.PanelURL(""))
- sig := make(chan os.Signal, 1)
- signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
quit := make(chan struct{})
var once sync.Once
a.Quit = func() { once.Do(func() { close(quit) }) }
@@ -180,6 +184,10 @@ func main() {
tray.SetOnTap(func() { open("") })
a.OnChange = tray.Refresh
a.Quit = tray.Quit
+ go func() {
+ <-sig
+ tray.Quit()
+ }()
tooltip := "WebBrain Companion"
if startErr != nil {
tooltip += " — " + strings.SplitN(startErr.Error(), "\n", 2)[0]