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: preserve model settings and match own instance
Barack Sokullude2f904792a0
diff --git a/webbrain-systray/internal/app/routes.go b/webbrain-systray/internal/app/routes.goindex 509eb59e8..2c3bcaceb 100644--- a/webbrain-systray/internal/app/routes.go+++ b/webbrain-systray/internal/app/routes.go@@ -190,6 +190,7 @@ func (a *App) routes(e *gin.Engine) {}c.JSON(http.StatusOK, gin.H{"app": "webbrain-companion",+ "instance_id": settings.InstanceID(a.Store.Get().PanelToken),"version": a.Version,"base_url": s.BaseURL,"openai_base_url": s.BaseURL + "/v1",@@ -402,6 +403,7 @@ func (a *App) routes(e *gin.Engine) {}if req.AutoStart != nil {s.Local.AutoStart = *req.AutoStart+ s.Local.AutoStartConfigured = true}if req.Context != nil && *req.Context >= 0 && *req.Context <= 262144 {restart = restart || s.Local.Context != *req.Context@@ -412,7 +414,7 @@ func (a *App) routes(e *gin.Engine) {fail(c, http.StatusInternalServerError, err)return}- if restart && a.Local.Running() {+ if restart && a.Local.Active() {go func() {if err := a.Local.Restart(); err != nil {logx.Printf("restart local model: %v", err)diff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.goindex f515c0974..ed36b0815 100644--- a/webbrain-systray/internal/localmodel/manager.go+++ b/webbrain-systray/internal/localmodel/manager.go@@ -63,11 +63,12 @@ type Status struct {}type Manager struct {- mu sync.Mutex- verified download.Verifier- store *settings.Store- register func([]core.LocalUpstream) error- onChange func()+ mu sync.Mutex+ restartMu sync.Mutex+ verified download.Verifier+ store *settings.Store+ register func([]core.LocalUpstream) error+ onChange func()phase stringstep string@@ -566,7 +567,7 @@ func (m *Manager) Install(format string) error {m.setPhase(PhaseIdle, "", nil)return}- if _, err := m.store.Update(func(s *settings.Settings) { s.Local.AutoStart = true }); err != nil {+ if err := m.defaultAutoStart(); err != nil {m.setPhase(PhaseError, "", fmt.Errorf("save local-model preference: %w", err))return}@@ -577,6 +578,18 @@ func (m *Manager) Install(format string) error {return nil}+func (m *Manager) defaultAutoStart() error {+ if m.store.Get().Local.AutoStartConfigured {+ return nil+ }+ _, err := m.store.Update(func(s *settings.Settings) {+ if !s.Local.AutoStartConfigured {+ s.Local.AutoStart = true+ }+ })+ return err+}+// Cancel stops a running download; partial files are kept for resume.func (m *Manager) Cancel() {m.mu.Lock()@@ -1056,6 +1069,13 @@ func (m *Manager) Running() bool {return m.phase == PhaseRunning}+// Active includes a launch that has not finished loading the model yet.+func (m *Manager) Active() bool {+ m.mu.Lock()+ defer m.mu.Unlock()+ return m.phase == PhaseRunning || m.phase == PhaseStarting || m.starting != nil || m.cmd != nil+}+// Remove deletes the files of one format (stopping the server first).func (m *Manager) Remove(format string) error {m.mu.Lock()@@ -1121,11 +1141,13 @@ func (m *Manager) Remove(format string) error {// Restart applies new settings (vision mode, context) to a running server.func (m *Manager) Restart() error {- running := m.Running()+ m.restartMu.Lock()+ defer m.restartMu.Unlock()+ active := m.Active()if err := m.Stop(); err != nil {return err}- if running {+ if active {return m.Start()}return nildiff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.goindex 2a22730dd..3d552ed62 100644--- a/webbrain-systray/internal/localmodel/manager_test.go+++ b/webbrain-systray/internal/localmodel/manager_test.go@@ -86,6 +86,49 @@ func TestStartClaimPreventsOverlappingLaunches(t *testing.T) {}}+func TestRestartIncludesStartingModel(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 !m.Active() {+ t.Fatal("starting model was not considered active")+ }+ if err := m.Restart(); err == nil {+ t.Fatal("Restart skipped starting a replacement model")+ }+}++func TestInstallDefaultPreservesAutostartChoice(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)+ if err := m.defaultAutoStart(); err != nil {+ t.Fatal(err)+ }+ if !store.Get().Local.AutoStart {+ t.Fatal("first install did not enable autostart by default")+ }+ if _, err := store.Update(func(s *settings.Settings) {+ s.Local.AutoStart = false+ s.Local.AutoStartConfigured = true+ }); err != nil {+ t.Fatal(err)+ }+ if err := m.defaultAutoStart(); err != nil {+ t.Fatal(err)+ }+ if store.Get().Local.AutoStart {+ t.Fatal("install completion overwrote the user's disabled autostart choice")+ }+}+func TestInstallClaimsPhaseBeforeWorkerStarts(t *testing.T) {t.Setenv("WBC_HOME", t.TempDir())store, err := settings.Open()diff --git a/webbrain-systray/internal/settings/settings.go b/webbrain-systray/internal/settings/settings.goindex d0a3208ed..6c21cf8df 100644--- a/webbrain-systray/internal/settings/settings.go+++ b/webbrain-systray/internal/settings/settings.go@@ -4,6 +4,7 @@ package settingsimport ("crypto/rand"+ "crypto/sha256""encoding/hex""encoding/json""errors"@@ -29,6 +30,8 @@ type Local struct {Format string `json:"format,omitempty"`// AutoStart starts the local model server whenever the companion starts.AutoStart bool `json:"auto_start"`+ // AutoStartConfigured preserves an explicit choice made while installing.+ AutoStartConfigured bool `json:"auto_start_configured,omitempty"`// Vision is "auto" (decide from memory), "gpu", "cpu" or "off".Vision string `json:"vision,omitempty"`// Context is the context size in tokens; 0 means automatic.@@ -168,3 +171,9 @@ func (st *Store) saveLocked(s Settings) error {// RandomSecret is exposed for components that need throwaway secrets.func RandomSecret() string { return randomHex(24) }++// InstanceID identifies one data directory without exposing its panel token.+func InstanceID(panelToken string) string {+ sum := sha256.Sum256([]byte(panelToken))+ return hex.EncodeToString(sum[:])+}diff --git a/webbrain-systray/main.go b/webbrain-systray/main.goindex 04acbe772..596f1df27 100644--- a/webbrain-systray/main.go+++ b/webbrain-systray/main.go@@ -53,11 +53,12 @@ func existingInstance(s settings.Settings) (int, bool) {continue}var info struct {- App string `json:"app"`+ App string `json:"app"`+ InstanceID string `json:"instance_id"`}_ = json.NewDecoder(resp.Body).Decode(&info)_ = resp.Body.Close()- if info.App == "webbrain-companion" {+ if resp.StatusCode == http.StatusOK && info.App == "webbrain-companion" && info.InstanceID == settings.InstanceID(s.PanelToken) {return p, true}}@@ -131,15 +132,6 @@ func main() {fmt.Fprintln(stderr, "cannot read settings:", err)os.Exit(1)}- if port, ok := existingInstance(store.Get()); ok {- url := fmt.Sprintf("http://127.0.0.1:%d/companion/#k=%s", port, store.Get().PanelToken)- if !*background {- _ = osutil.OpenAppWindow(url, 460, 820)- }- logx.Printf("another instance is running on port %d", port)- return- }-a := app.New(version, store)writeRuntime := func(port int) {data, _ := json.Marshal(runtimeInfo{PID: os.Getpid(), Port: port})diff --git a/webbrain-systray/main_test.go b/webbrain-systray/main_test.goindex 701e24efa..558627191 100644--- a/webbrain-systray/main_test.go+++ b/webbrain-systray/main_test.go@@ -26,7 +26,9 @@ func TestWaitForStartingInstance(t *testing.T) {}server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.Path == "/companion/v1/info" {- _, _ = w.Write([]byte(`{"app":"webbrain-companion"}`))+ _ = json.NewEncoder(w).Encode(map[string]string{+ "app": "webbrain-companion", "instance_id": settings.InstanceID(s.PanelToken),+ })}}))defer server.Close()@@ -48,3 +50,24 @@ func TestWaitForStartingInstance(t *testing.T) {t.Fatalf("waitForInstance: got port %d, token %q, found %v", gotPort, gotSettings.PanelToken, ok)}}++func TestExistingInstanceRejectsAnotherInstallation(t *testing.T) {+ t.Setenv("WBC_HOME", t.TempDir())+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ _ = json.NewEncoder(w).Encode(map[string]string{+ "app": "webbrain-companion", "instance_id": settings.InstanceID("another-panel-token"),+ })+ }))+ defer server.Close()+ _, rawPort, err := net.SplitHostPort(server.Listener.Addr().String())+ if err != nil {+ t.Fatal(err)+ }+ port, err := strconv.Atoi(rawPort)+ if err != nil {+ t.Fatal(err)+ }+ if got, ok := existingInstance(settings.Settings{Port: port, PanelToken: "this-panel-token"}); ok {+ t.Fatalf("accepted unrelated companion on port %d", got)+ }+}