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
Restore API key on failed restart and report removal errors
Barack Sokulluc72afd1d935d
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.goindex b1c8168bc..4e08527ff 100644--- a/webbrain-systray/internal/app/app.go+++ b/webbrain-systray/internal/app/app.go@@ -454,15 +454,30 @@ func (a *App) SetAccountDisabled(name string, disabled bool) error {func (a *App) RotateKey() error {a.restartMu.Lock()defer a.restartMu.Unlock()+ previous := a.Store.Get()+ previousPort := a.Proxy.Port()s, err := a.Store.Update(func(s *settings.Settings) { s.APIKey = settings.NewAPIKey() })if err != nil {return err}- port := a.Proxy.Port()+ port := previousPortif port == 0 {port = s.Port}- return a.restartOn(s, port, false)+ if err := a.restartOn(s, port, false); err != nil {+ restored, saveErr := a.Store.Update(func(s *settings.Settings) { s.APIKey = previous.APIKey })+ restored.APIKey = previous.APIKey // restore the listener even if disk is full+ restorePort := previousPort+ if restorePort == 0 {+ restorePort = previous.Port+ }+ restartErr := a.restartOn(restored, restorePort, previousPort != 0)+ if restartErr == nil {+ a.setNotice(i18n.T("key_failed"))+ }+ return errors.Join(err, saveErr, restartErr)+ }+ return nil}// proxyOptions builds the proxy configuration from the settings. The internaldiff --git a/webbrain-systray/internal/app/port_test.go b/webbrain-systray/internal/app/port_test.goindex 0758f2d24..b55840d55 100644--- a/webbrain-systray/internal/app/port_test.go+++ b/webbrain-systray/internal/app/port_test.go@@ -52,6 +52,41 @@ func TestSetPortRestoresWorkingProxyWhenLastPortIsOccupied(t *testing.T) {}}+func TestRotateKeyRestoresSavedKeyWhenProxyCannotRestart(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()+ previous := store.Get().APIKey+ // A directory at the config's temporary path makes both restart attempts+ // fail after the new key has been saved.+ if err := os.Mkdir(paths.ProxyConfig()+".tmp", 0o700); err != nil {+ t.Fatal(err)+ }+ if err := a.RotateKey(); err == nil {+ t.Fatal("RotateKey succeeded although the proxy config could not be written")+ }+ if got := store.Get().APIKey; got != previous {+ t.Fatal("failed rotation left the new key in memory")+ }+ reopened, err := settings.Open()+ if err != nil {+ t.Fatal(err)+ }+ if got := reopened.Get().APIKey; got != previous {+ t.Fatal("failed rotation left the new key on disk")+ }+}+func TestRapidNetworkTogglesApplyInRequestOrder(t *testing.T) {gin.SetMode(gin.TestMode)t.Setenv("WBC_HOME", t.TempDir())diff --git a/webbrain-systray/internal/i18n/i18n.go b/webbrain-systray/internal/i18n/i18n.goindex 8f0e1160d..d4baac63c 100644--- a/webbrain-systray/internal/i18n/i18n.go+++ b/webbrain-systray/internal/i18n/i18n.go@@ -26,6 +26,7 @@ var catalog = map[string]map[string]string{"dur_minutes": "%dm","port_moved": "Another app (often CLIProxyAPI or EasyCLIProxyAPI) uses port %d, so the companion runs on %d. Use the address shown here in WebBrain.","port_failed": "Port %d is unavailable. The companion is still running on port %d.",+ "key_failed": "Could not rotate the API key. The previous key is still in use.","network_failed": "Network access stays off: another app uses port %d on the network. Pick another port in Settings and try again.",},"tr": {@@ -45,6 +46,7 @@ var catalog = map[string]map[string]string{"dur_minutes": "%d dk","port_moved": "%d portunu başka bir uygulama (çoğu zaman CLIProxyAPI ya da EasyCLIProxyAPI) kullanıyor, bu yüzden Companion %d portunda çalışıyor. WebBrain'de burada gösterilen adresi kullan.","port_failed": "%d portu kullanılamıyor. Companion hâlâ %d portunda çalışıyor.",+ "key_failed": "API anahtarı yenilenemedi. Önceki anahtar kullanılmaya devam ediyor.","network_failed": "Ağ erişimi kapalı kaldı: %d portunu ağda başka bir uygulama kullanıyor. Ayarlar'dan başka bir port seçip tekrar dene.",},}diff --git a/webbrain-systray/internal/localmodel/manager.go b/webbrain-systray/internal/localmodel/manager.goindex 75ef88600..56a4303c1 100644--- a/webbrain-systray/internal/localmodel/manager.go+++ b/webbrain-systray/internal/localmodel/manager.go@@ -795,19 +795,37 @@ func (m *Manager) Remove(format string) error {return err}m.Stop()+ var removeErrs []error+ remove := func(path string) {+ if err := os.RemoveAll(path); err != nil {+ removeErrs = append(removeErrs, fmt.Errorf("remove %s: %w", path, err))+ }+ }switch format {case "mlx":- _ = os.RemoveAll(mlxDir())- _ = os.RemoveAll(mlxVenv())+ remove(mlxDir())+ remove(mlxVenv())default:- _ = os.RemoveAll(ggufDir())- entries, _ := os.ReadDir(paths.Runtimes())+ remove(ggufDir())+ entries, err := os.ReadDir(paths.Runtimes())+ if err != nil {+ // Some platforms classify "path is a file" as not-exist for+ // ReadDir. Only an actually missing path means there is nothing+ // left to remove.+ if _, statErr := os.Stat(paths.Runtimes()); !os.IsNotExist(statErr) {+ removeErrs = append(removeErrs, fmt.Errorf("list runtimes: %w", err))+ }+ }for _, e := range entries {if strings.HasPrefix(e.Name(), "llama-") {- _ = os.RemoveAll(filepath.Join(paths.Runtimes(), e.Name()))+ remove(filepath.Join(paths.Runtimes(), e.Name()))}}}+ if err := errors.Join(removeErrs...); err != nil {+ m.setPhase(PhaseError, "", err)+ return err+ }m.setPhase(PhaseIdle, "", nil)return nil}diff --git a/webbrain-systray/internal/localmodel/manager_test.go b/webbrain-systray/internal/localmodel/manager_test.goindex 0757be99e..fbbf37ee9 100644--- a/webbrain-systray/internal/localmodel/manager_test.go+++ b/webbrain-systray/internal/localmodel/manager_test.go@@ -132,6 +132,25 @@ func TestInstallRejectsFailedSettingsSaveBeforeDownload(t *testing.T) {}}+func TestRemoveReportsRuntimeDirectoryReadError(t *testing.T) {+ t.Setenv("WBC_HOME", t.TempDir())+ store, err := settings.Open()+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(paths.Runtimes(), []byte("not a directory"), 0o600); err != nil {+ t.Fatal(err)+ }+ m := NewManager(store, func([]core.LocalUpstream) error { return nil }, nil)+ if err := m.Remove("gguf"); err == nil {+ t.Fatal("Remove reported success when runtime files could not be listed")+ }+ status := m.Status()+ if status.Phase != PhaseError || status.Error == "" {+ t.Fatalf("failed removal was not shown as an error: phase=%q error=%q", status.Phase, status.Error)+ }+}+func TestRuntimeArchivesHavePinnedChecksums(t *testing.T) {for asset, size := range llamaAssetSizes {if size <= 0 || len(llamaAssetSHA[asset]) != 64 {diff --git a/webbrain-systray/internal/logx/logx.go b/webbrain-systray/internal/logx/logx.goindex 2c5ea240e..303d6af8f 100644--- a/webbrain-systray/internal/logx/logx.go+++ b/webbrain-systray/internal/logx/logx.go@@ -34,6 +34,7 @@ func (r *rotating) Write(p []byte) (int, error) {}if r.size+int64(len(p)) > maxSize {_ = r.f.Close()+ r.f = nil_ = os.Remove(r.path + ".1")_ = os.Rename(r.path, r.path+".1")if err := r.open(); err != nil {@@ -42,7 +43,12 @@ func (r *rotating) Write(p []byte) (int, error) {}n, err := r.f.Write(p)r.size += int64(n)- return n, err+ if err != nil {+ _ = r.f.Close()+ r.f = nil // retry opening on the next write; keep draining stdout+ return len(p), nil+ }+ return n, nil}func (r *rotating) open() error {@@ -85,9 +91,15 @@ func Init(dir string, alsoConsole bool) {logrus.SetFormatter(&logrus.TextFormatter{DisableColors: true, FullTimestamp: true})if !alsoConsole {// The embedded proxy prints a few progress lines with fmt.Println.- if f, err := os.OpenFile(file.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600); err == nil {- os.Stdout = f- os.Stderr = f+ // Send those writes through the rotating writer too, so they cannot+ // keep appending to the old file after it has been renamed.+ if reader, writer, err := os.Pipe(); err == nil {+ os.Stdout = writer+ os.Stderr = writer+ go func() {+ _, _ = io.Copy(file, reader)+ _ = reader.Close()+ }()}}fmt.Fprintf(w, "\n==== WebBrain Companion started %s ====\n", time.Now().Format(time.RFC3339))diff --git a/webbrain-systray/internal/logx/logx_test.go b/webbrain-systray/internal/logx/logx_test.gonew file mode 100644index 000000000..e22ffd880--- /dev/null+++ b/webbrain-systray/internal/logx/logx_test.go@@ -0,0 +1,47 @@+package logx++import (+ "bytes"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "testing"+ "time"+)++func TestGUIOutputRotates(t *testing.T) {+ if os.Getenv("WBC_LOG_ROTATION_HELPER") == "1" {+ originalStderr := os.Stderr+ dir := os.Getenv("WBC_LOG_ROTATION_DIR")+ Init(dir, false)+ chunk := bytes.Repeat([]byte("x"), 32<<10)+ for i := 0; i < 9<<20/len(chunk); i++ {+ if _, err := os.Stdout.Write(chunk); err != nil {+ fmt.Fprintln(originalStderr, err)+ os.Exit(1)+ }+ }+ deadline := time.Now().Add(5 * time.Second)+ for time.Now().Before(deadline) {+ current, currentErr := os.Stat(Path())+ previous, previousErr := os.Stat(Path() + ".1")+ if currentErr == nil && previousErr == nil && current.Size() <= maxSize && previous.Size() <= maxSize && current.Size()+previous.Size() >= 9<<20 {+ os.Exit(0)+ }+ time.Sleep(10 * time.Millisecond)+ }+ fmt.Fprintln(originalStderr, "redirected GUI output did not rotate within 5 seconds")+ os.Exit(1)+ }+ dir := t.TempDir()+ cmd := exec.Command(os.Args[0], "-test.run=^TestGUIOutputRotates$")+ cmd.Env = append(os.Environ(), "WBC_LOG_ROTATION_HELPER=1", "WBC_LOG_ROTATION_DIR="+dir)+ output, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("GUI logging helper failed: %v: %s", err, output)+ }+ if _, err := os.Stat(filepath.Join(dir, "companion.log.1")); err != nil {+ t.Fatalf("rotated log missing: %v", err)+ }+}