Skip to content

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

WebBrain Companion: install new versions automatically

Emre Sokullu3fb7766ac85a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 018e73c42..c49050dd0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,9 @@ This changelog was generated from the repository Git history and release tags. V
## [Unreleased]
+### Added
+- WebBrain Companion updates itself from 0.1.3 on. Every six hours it checks GitHub for a newer Companion release, downloads it, and installs it only when the package matches the release's SHA256SUMS. It installs once nothing has used it for ten minutes, then restarts in the background. *Settings, Updates* turns automatic installs off, *Update now* in the tray menu or the panel installs at once, and `webbrain-companion --update` updates from the command line (`--headless` copies only report new versions). See `webbrain-systray/README.md`.
+
### Changed
- Shorter planner requests: the planner and the intent check now ask for one-line JSON, include the Instagram carousel, Gmail count and CMS recipe rules only on turns that involve those sites or an enabled CMS recipe, and send the latest request, the page address and the prior request once each instead of two or three times.
- WebBrain Companion planning: planner and classifier calls now ask for no thinking (`reasoning_effort: "none"`). Companion maps it per model (off where the model allows it, the lowest level where it cannot, dropped for models without thinking), and its local Bonsai 2 model now accepts it, so planning there no longer runs at the model's default xhigh reasoning.
diff --git a/webbrain-systray/README.md b/webbrain-systray/README.md
index 6f0f5e0e0..b7a8362ee 100644
--- a/webbrain-systray/README.md
+++ b/webbrain-systray/README.md
@@ -44,7 +44,44 @@ language, network access, the port, the log file and *Quit*.
| Linux (x64, Arm64) | `WebBrain-Companion-*-linux-*.tar.gz` | Run `webbrain-companion`. The tray uses StatusNotifierItem (KDE, XFCE, GNOME with the AppIndicator extension). |
`--headless` runs the proxy and APIs without a tray icon, `--background` starts
-without opening the panel (used at login), `--version` prints the version.
+without opening the panel (used at login), `--version` prints the version and
+`--update` installs the newest version over this copy.
+
+## Updates
+
+From 0.1.3 on, the companion keeps itself current. Two minutes after it
+starts, and every six hours, it asks GitHub for the newest published
+`systray-v*` release of `webbrain-one/webbrain` (drafts and pre-releases are
+skipped). It downloads the package for this system and installs it only when
+the package's SHA-256 matches the release's `SHA256SUMS` file. Then it waits
+until nothing has used it for ten minutes: no model or decision request (its
+own usage refreshes do not count), no open panel, no model download, no
+sign-in in progress. Waking the computer counts as use. It installs the
+update, shuts down and starts the new version without opening the panel.
+
+- **macOS** swaps *WebBrain Companion.app* in its folder and **Linux** the
+ `webbrain-companion` program; the new version then takes over the same
+ process. The replaced copy stays hidden next to it until the new version
+ has started, and is put back if the new version cannot start. A copy that
+ macOS runs from a temporary location (not moved to Applications) cannot
+ replace itself. If macOS refuses the swap, allow WebBrain Companion under
+ *System Settings, Privacy & Security, App Management*, or download the new
+ version by hand. On Linux the program's folder must be writable.
+- **Windows** runs the new setup program silently (`/S /UPDATE=<pid>`). It
+ waits for the companion to quit, installs over the registered installation,
+ and starts the new version. If a file cannot be written, the setup stops and
+ starts the copy that is in place. The installation folder must be writable
+ without administrator rights.
+
+An update that fails is shown under *Settings, Updates* and is not tried again
+by itself; *Update now* tries again, and a newer release is installed as usual.
+
+*Settings, Updates* turns automatic installs off. New versions are then only
+reported, and *Update now* (also in the tray menu) installs them. With
+`--headless` the companion only reports new versions; run
+`webbrain-companion --update` and restart it. Development builds (a version
+with a suffix, such as `0.1.0-dev`) never update. Releases before 0.1.3 have no
+updater: download 0.1.3 or later once by hand.
## Connect WebBrain
@@ -150,7 +187,13 @@ it.
pass through the panel.
- No analytics. Besides the providers you sign in to, the embedded proxy
refreshes CLIProxyAPI's public model catalog every few hours, and installing a
- model downloads from Hugging Face, GitHub and (MLX only) PyPI.
+ model downloads from Hugging Face, GitHub and (MLX only) PyPI. The update
+ check reads GitHub's release list every six hours and downloads releases from
+ GitHub.
+- Updates are trusted as much as the GitHub release they come from: the
+ checksum file is part of the same release, so it catches damaged downloads,
+ not a release published by someone else. Packages are not signed with a
+ separate update key.
- Using consumer subscriptions through a proxy may conflict with a provider's
terms. Read WebBrain's
[setup, security and account-risk guide](https://webbrain.one/docs/easy-cli-proxy/)
diff --git a/webbrain-systray/internal/app/app.go b/webbrain-systray/internal/app/app.go
index daadf07da..176286c28 100644
--- a/webbrain-systray/internal/app/app.go
+++ b/webbrain-systray/internal/app/app.go
@@ -12,6 +12,7 @@ import (
"sort"
"strings"
"sync"
+ "sync/atomic"
"time"
"github.com/esokullu/webbrain-systray/internal/accounts"
@@ -23,6 +24,7 @@ import (
"github.com/esokullu/webbrain-systray/internal/osutil"
"github.com/esokullu/webbrain-systray/internal/quota"
"github.com/esokullu/webbrain-systray/internal/settings"
+ "github.com/esokullu/webbrain-systray/internal/update"
)
type login struct {
@@ -65,6 +67,19 @@ type App struct {
OnProxyStart func(port int)
// OpenPanel opens the panel window (set by main).
OpenPanel func(fragment string)
+ // Headless: no tray icon (servers, CI). Updates are reported, never
+ // installed by the companion itself.
+ Headless bool
+
+ upd updater
+ // exe is the running program, which an update replaces; exec starts the
+ // installed version in its place (update.Exec; tests replace it).
+ exe string
+ exec func(exe string, args ...string) error
+ // activeReqs and lastActive (Unix nanoseconds) track use for the
+ // automatic update (activity).
+ activeReqs atomic.Int64
+ lastActive atomic.Int64
// internalKey authenticates apps on this computer with the proxy; it never
// leaves the process.
@@ -86,6 +101,10 @@ func New(version string, store *settings.Store) *App {
internalKey: "wbc-local-" + settings.RandomSecret(),
}
a.ctx, a.cancel = context.WithCancel(context.Background())
+ a.upd.kick = make(chan struct{}, 1)
+ a.exe = osutil.Executable()
+ a.exec = update.Exec
+ a.lastActive.Store(time.Now().UnixNano())
a.Local = localmodel.NewManager(store, a.registerLocal, a.changed)
a.D1 = d1.NewManager(store, a.changed)
return a
@@ -179,6 +198,7 @@ func (a *App) Start() error {
_ = osutil.SetAutostart(s.Autostart)
}
go a.loop()
+ go a.updateLoop()
go func() {
if s.Local.AutoStart {
if err := a.Local.Start(); err != nil {
@@ -507,7 +527,7 @@ func (a *App) proxyOptionsOn(s settings.Settings, local []core.LocalUpstream, po
APIKeys: []string{s.APIKey, a.internalKey},
Routes: a.routes,
Local: local,
- Middleware: []gin.HandlerFunc{noCORS, a.access},
+ Middleware: []gin.HandlerFunc{a.activity, noCORS, a.access},
}
}
diff --git a/webbrain-systray/internal/app/menu.go b/webbrain-systray/internal/app/menu.go
index d73ed49e6..d15469ae1 100644
--- a/webbrain-systray/internal/app/menu.go
+++ b/webbrain-systray/internal/app/menu.go
@@ -162,8 +162,18 @@ func (a *App) Menu(act MenuActions) []tray.Item {
if len(s.Accounts) == 0 {
items = append(items, tray.Item{Title: i18n.T("add"), OnClick: func() { act.OpenPanel("add") }})
}
+ items = append(items, tray.Item{Separator: true})
+ if u := s.Update; u.Latest != "" && u.Supported {
+ switch u.State {
+ case "downloading":
+ items = append(items, tray.Item{Title: fmt.Sprintf(i18n.T("update_downloading"), u.Latest), Disabled: true})
+ case "installing":
+ items = append(items, tray.Item{Title: fmt.Sprintf(i18n.T("update_installing"), u.Latest), Disabled: true})
+ default:
+ items = append(items, tray.Item{Title: fmt.Sprintf(i18n.T("update_now"), u.Latest), OnClick: a.InstallUpdate})
+ }
+ }
return append(items,
- tray.Item{Separator: true},
tray.Item{Title: i18n.T("open_panel"), OnClick: func() { act.OpenPanel("") }},
tray.Item{Title: i18n.T("quit"), OnClick: act.Quit},
)
diff --git a/webbrain-systray/internal/app/routes.go b/webbrain-systray/internal/app/routes.go
index 697413cf4..911f1e937 100644
--- a/webbrain-systray/internal/app/routes.go
+++ b/webbrain-systray/internal/app/routes.go
@@ -481,11 +481,23 @@ func (a *App) routes(e *gin.Engine) {
Language *string `json:"language"`
Welcomed *bool `json:"welcomed"`
Network *bool `json:"network"`
+ // AutoUpdate installs new versions by themselves when idle.
+ AutoUpdate *bool `json:"auto_update"`
}
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
+ if req.AutoUpdate != nil {
+ if _, err := a.Store.Update(func(s *settings.Settings) { s.ManualUpdates = !*req.AutoUpdate }); err != nil {
+ fail(c, http.StatusInternalServerError, err)
+ return
+ }
+ if *req.AutoUpdate {
+ a.CheckForUpdate()
+ }
+ a.changed()
+ }
if req.Autostart != nil {
if err := a.SetAutostart(*req.Autostart); err != nil {
fail(c, http.StatusInternalServerError, err)
@@ -549,6 +561,19 @@ func (a *App) routes(e *gin.Engine) {
}()
}
})
+ api.POST("/update/check", func(c *gin.Context) {
+ a.CheckForUpdate()
+ c.JSON(http.StatusOK, gin.H{"ok": true})
+ })
+ api.POST("/update/install", func(c *gin.Context) {
+ if st := a.UpdateStatus(); st.Dev || a.Headless {
+ fail(c, http.StatusConflict, errors.New("this copy does not install updates by itself"))
+ return
+ }
+ // Reply first: installing quits the companion.
+ c.JSON(http.StatusOK, gin.H{"ok": true})
+ a.InstallUpdate()
+ })
api.POST("/key/rotate", func(c *gin.Context) {
a.queueRestart("rotate key", a.RotateKey)
c.JSON(http.StatusOK, gin.H{"ok": true})
diff --git a/webbrain-systray/internal/app/snapshot.go b/webbrain-systray/internal/app/snapshot.go
index 5ffcd5e5e..dc14cfd2a 100644
--- a/webbrain-systray/internal/app/snapshot.go
+++ b/webbrain-systray/internal/app/snapshot.go
@@ -56,6 +56,7 @@ type Snapshot struct {
QuotaBusy bool `json:"quota_busy"`
Welcomed bool `json:"welcomed"`
LocalContext int `json:"local_context"`
+ Update UpdateStatus `json:"update"`
}
func (a *App) Snapshot() Snapshot {
@@ -86,6 +87,7 @@ func (a *App) Snapshot() Snapshot {
OS: runtime.GOOS,
Welcomed: s.Welcomed,
LocalContext: s.Local.Context,
+ Update: a.UpdateStatus(),
}
snap.Decision.Endpoint = base + "/companion/v1/decide"
if snap.Network {
diff --git a/webbrain-systray/internal/app/update.go b/webbrain-systray/internal/app/update.go
new file mode 100644
index 000000000..4ab6fa356
--- /dev/null
+++ b/webbrain-systray/internal/app/update.go
@@ -0,0 +1,520 @@
+package app
+
+// Updates. Shortly after it starts, and every six hours, the companion asks
+// GitHub for a newer release (internal/update). With automatic updates on, the
+// default, it downloads the release, checks it against the release's
+// SHA256SUMS, and installs it once nothing has used the companion for ten
+// minutes. On macOS and Linux the new version then replaces this process when
+// it quits (Restart); on Windows the setup program starts it. The tray menu
+// and the panel can install a downloaded update at once.
+//
+// An automatic install is tried once per version: when it fails, here or after
+// the restart (the attempt record), the companion reports the error and waits
+// for a newer release or for Update now.
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/esokullu/webbrain-systray/internal/d1"
+ "github.com/esokullu/webbrain-systray/internal/download"
+ "github.com/esokullu/webbrain-systray/internal/logx"
+ "github.com/esokullu/webbrain-systray/internal/paths"
+ "github.com/esokullu/webbrain-systray/internal/update"
+)
+
+const (
+ updateFirstCheck = 2 * time.Minute
+ updateEvery = 6 * time.Hour
+ updateIdle = 10 * time.Minute
+ updateTick = 30 * time.Second
+ // A tick this late means the computer slept; waking up counts as use.
+ updateWakeGap = 3 * updateTick
+ // A download that makes no progress this long is abandoned until the
+ // next check.
+ updateStall = 2 * time.Minute
+ updateMaxDownload = 2 * time.Hour
+)
+
+var restartArgs = []string{"--background", "--after-update"}
+
+const msgHeadless = "With --headless the companion only reports new versions. Run webbrain-companion --update, then restart it."
+
+// UpdateStatus is what the panel shows about updates.
+type UpdateStatus struct {
+ // Auto installs a downloaded update once the companion is idle.
+ Auto bool `json:"auto"`
+ // Supported: this copy can replace itself. Reason says why it cannot.
+ Supported bool `json:"supported"`
+ Reason string `json:"reason,omitempty"`
+ // Dev: a development build, which never updates.
+ Dev bool `json:"dev,omitempty"`
+ // State is idle, checking, downloading, ready, installing or error.
+ State string `json:"state"`
+ Current string `json:"current"`
+ Latest string `json:"latest,omitempty"`
+ Page string `json:"page,omitempty"`
+ CheckedAt *time.Time `json:"checked_at,omitempty"`
+ Progress *download.Progress `json:"progress,omitempty"`
+ Error string `json:"error,omitempty"`
+}
+
+type updater struct {
+ mu sync.Mutex
+ busy string // "", checking, downloading or installing
+ release *update.Release
+ pkg string // the release's package, downloaded and verified
+ failed string // a version whose install failed: not retried automatically
+ checkedAt time.Time
+ err string
+ reason string // why this copy cannot replace itself
+ progress *download.Progress
+ kick chan struct{}
+ // restart: an installed update replaces this process when it quits.
+ restart *update.Target
+}
+
+var errNoUpdate = errors.New("no update is available")
+
+func (u *updater) begin(state string) bool {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ if u.busy != "" {
+ return false
+ }
+ u.busy = state
+ return true
+}
+
+func (u *updater) latest() *update.Release {
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ return u.release
+}
+
+func (u *updater) setReason(reason string) {
+ u.mu.Lock()
+ u.reason = reason
+ u.mu.Unlock()
+}
+
+// UpdateStatus reports the update state for the panel and the tray.
+func (a *App) UpdateStatus() UpdateStatus {
+ st := UpdateStatus{Auto: !a.Store.Get().ManualUpdates, Current: a.Version, State: "idle"}
+ if _, ok := update.ParseVersion(a.Version); !ok {
+ st.Dev = true
+ return st
+ }
+ u := &a.upd
+ u.mu.Lock()
+ defer u.mu.Unlock()
+ st.Supported, st.Reason, st.Error = u.reason == "", u.reason, u.err
+ if !u.checkedAt.IsZero() {
+ at := u.checkedAt
+ st.CheckedAt = &at
+ }
+ if u.release != nil {
+ st.Latest, st.Page = u.release.Version, u.release.Page
+ }
+ switch {
+ case u.busy != "":
+ st.State = u.busy
+ case u.err != "":
+ st.State = "error"
+ case u.pkg != "":
+ st.State = "ready"
+ }
+ if u.busy == "downloading" && u.progress != nil {
+ p := *u.progress
+ st.Progress = &p
+ }
+ return st
+}
+
+// CheckForUpdate asks the update loop to check now (and, with automatic
+// updates on, to download what it finds).
+func (a *App) CheckForUpdate() {
+ select {
+ case a.upd.kick <- struct{}{}:
+ default:
+ }
+}
+
+// InstallUpdate installs the newest release now, downloading it first when
+// needed, and restarts the companion. It returns at once; the status reports
+// progress and failures.
+func (a *App) InstallUpdate() { go a.installUpdate() }
+
+func (a *App) updateLoop() {
+ update.Cleanup(a.exe, paths.Updates(), a.Version)
+ if _, ok := update.ParseVersion(a.Version); !ok {
+ return
+ }
+ a.readAttempt()
+ if a.Headless {
+ a.upd.setReason(msgHeadless)
+ } else if _, err := update.Locate(a.exe); err != nil {
+ a.upd.setReason(err.Error())
+ }
+ next := time.Now().Add(updateFirstCheck).Round(0)
+ last := time.Now().Round(0)
+ tick := time.NewTicker(updateTick)
+ defer tick.Stop()
+ for {
+ select {
+ case <-a.ctx.Done():
+ return
+ case <-a.upd.kick:
+ next = time.Now().Round(0)
+ case <-tick.C:
+ }
+ // Wall-clock time: the monotonic clock stops while a Mac sleeps. A
+ // late tick means the computer slept; someone may be about to use
+ // the companion again.
+ now := time.Now().Round(0)
+ if now.Sub(last) > updateWakeGap {
+ a.lastActive.Store(now.UnixNano())
+ }
+ last = now
+ if !now.Before(next) {
+ next = now.Add(updateEvery)
+ a.checkUpdate()
+ if a.autoDownload() {
+ _, _ = a.downloadUpdate()
+ }
+ }
+ if a.autoInstallDue() {
+ a.installUpdate()
+ }
+ }
+}
+
+func (a *App) autoDownload() bool {
+ if a.Headless || a.Store.Get().ManualUpdates {
+ return false
+ }
+ a.upd.mu.Lock()
+ defer a.upd.mu.Unlock()
+ return a.upd.release != nil && a.upd.pkg == "" && a.upd.reason == "" && a.upd.failed != a.upd.release.Version
+}
+
+func (a *App) checkUpdate() {
+ if !a.upd.begin("checking") {
+ return
+ }
+ a.changed()
+ ctx, cancel := context.WithTimeout(a.ctx, 2*time.Minute)
+ rel, err := update.Latest(ctx, a.Version)
+ cancel()
+ u := &a.upd
+ u.mu.Lock()
+ u.busy = ""
+ u.checkedAt = time.Now()
+ switch {
+ case err != nil:
+ u.err = err.Error()
+ default:
+ if rel == nil || u.release == nil || rel.Version != u.release.Version {
+ u.pkg = ""
+ }
+ u.release = rel
+ // A failed version keeps its message until a newer one comes out.
+ if rel == nil || rel.Version != u.failed {
+ u.err = ""
+ }
+ }
+ u.mu.Unlock()
+ a.changed()
+ switch {
+ case err != nil:
+ logx.Printf("update check: %v", err)
+ case rel != nil:
+ logx.Printf("update: WebBrain Companion %s is available", rel.Version)
+ }
+}
+
+// downloadUpdate fetches and verifies the newest release's package, once.
+func (a *App) downloadUpdate() (string, error) {
+ u := &a.upd
+ u.mu.Lock()
+ rel, pkg := u.release, u.pkg
+ switch {
+ case rel == nil:
+ u.mu.Unlock()
+ return "", errNoUpdate
+ case pkg != "":
+ u.mu.Unlock()
+ return pkg, nil
+ case u.busy != "":
+ u.mu.Unlock()
+ return "", errors.New("an update step is already running")
+ }
+ u.busy, u.progress = "downloading", nil
+ u.mu.Unlock()
+ a.changed()
+
+ ctx, cancel := context.WithTimeout(a.ctx, updateMaxDownload)
+ defer cancel()
+ var lastProgress atomic.Int64
+ lastProgress.Store(time.Now().UnixNano())
+ stalled := make(chan struct{})
+ go func() {
+ t := time.NewTicker(10 * time.Second)
+ defer t.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-t.C:
+ if time.Since(time.Unix(0, lastProgress.Load())) > updateStall {
+ close(stalled)
+ cancel()
+ return
+ }
+ }
+ }
+ }()
+ var shown time.Time
+ path, err := update.Download(ctx, rel, filepath.Join(paths.Updates(), rel.Version), func(p download.Progress) {
+ lastProgress.Store(time.Now().UnixNano())
+ u.mu.Lock()
+ u.progress = &p
+ u.mu.Unlock()
+ if time.Since(shown) > time.Second {
+ shown = time.Now()
+ a.changed()
+ }
+ })
+ select {
+ case <-stalled:
+ err = errors.New("the download stopped making progress; it resumes with the next check")
+ default:
+ }
+ u.mu.Lock()
+ u.busy, u.progress = "", nil
+ if err != nil {
+ u.err = fmt.Sprintf("download %s: %v", rel.Version, err)
+ } else if u.release != nil && u.release.Version == rel.Version {
+ u.pkg = path
+ if u.failed != rel.Version {
+ u.err = ""
+ }
+ }
+ u.mu.Unlock()
+ a.changed()
+ if err != nil {
+ logx.Printf("update download: %v", err)
+ return "", err
+ }
+ logx.Printf("update: %s downloaded and verified", rel.Version)
+ return path, nil
+}
+
+func (a *App) installUpdate() {
+ if a.Headless {
+ return
+ }
+ if a.upd.latest() == nil {
+ a.checkUpdate()
+ }
+ rel := a.upd.latest()
+ if rel == nil {
+ return
+ }
+ target, err := update.Locate(a.exe)
+ if err != nil {
+ a.upd.setReason(err.Error())
+ a.changed()
+ return
+ }
+ a.upd.setReason("")
+ pkg, err := a.downloadUpdate()
+ if err != nil {
+ return
+ }
+ if !a.upd.begin("installing") {
+ return
+ }
+ a.changed()
+ logx.Printf("update: installing %s", rel.Version)
+ a.writeAttempt(rel.Version)
+ if target.Kind == "installer" {
+ // The setup program waits for this process to exit, installs, and
+ // starts the new version.
+ err = update.StartInstaller(pkg, os.Getpid())
+ } else if err = update.Install(pkg, target); err == nil {
+ a.upd.mu.Lock()
+ a.upd.restart = &target
+ a.upd.mu.Unlock()
+ }
+ if err != nil {
+ logx.Printf("update install: %v", err)
+ a.installFailed(rel.Version, fmt.Sprintf("install %s: %v", rel.Version, err))
+ return
+ }
+ logx.Printf("update: %s installed; restarting", rel.Version)
+ if a.Quit != nil {
+ a.Quit()
+ }
+}
+
+// installFailed reports a failed install and stops automatic retries of that
+// version.
+func (a *App) installFailed(version, msg string) {
+ u := &a.upd
+ u.mu.Lock()
+ u.busy, u.err, u.failed = "", msg, version
+ u.mu.Unlock()
+ a.changed()
+}
+
+// RestartPending reports whether an installed update should replace this
+// process once it has shut down (macOS and Linux).
+func (a *App) RestartPending() bool {
+ a.upd.mu.Lock()
+ defer a.upd.mu.Unlock()
+ return a.upd.restart != nil
+}
+
+// Restart replaces this process with the installed update; main calls it
+// after shutdown, with the single-instance lock released. When the new
+// version cannot start, it puts the previous version back and starts that.
+// It returns only when neither starts.
+func (a *App) Restart() {
+ a.upd.mu.Lock()
+ target := a.upd.restart
+ a.upd.mu.Unlock()
+ if target == nil {
+ return
+ }
+ err := a.exec(a.exe, restartArgs...)
+ logx.Printf("update: start the new version: %v", err)
+ if err := update.Rollback(*target); err != nil {
+ logx.Printf("update: put the previous version back: %v", err)
+ return
+ }
+ err = a.exec(a.exe, restartArgs...)
+ logx.Printf("update: start the previous version: %v", err)
+}
+
+// attempt records an install about to start. After the restart, a version
+// still older than the attempt's means the install did not take.
+type attempt struct {
+ Version string `json:"version"`
+ From string `json:"from"`
+ At time.Time `json:"at"`
+}
+
+func attemptPath() string { return filepath.Join(paths.Updates(), "attempt.json") }
+
+func (a *App) writeAttempt(version string) {
+ data, _ := json.Marshal(attempt{Version: version, From: a.Version, At: time.Now()})
+ if err := os.MkdirAll(paths.Updates(), 0o700); err == nil {
+ err = os.WriteFile(attemptPath(), data, 0o600)
+ if err != nil {
+ logx.Printf("update: record attempt: %v", err)
+ }
+ }
+}
+
+func (a *App) readAttempt() {
+ data, err := os.ReadFile(attemptPath())
+ if err != nil {
+ return
+ }
+ var at attempt
+ if json.Unmarshal(data, &at) != nil || !update.Newer(at.Version, a.Version) {
+ // The update took (or the record is unreadable).
+ _ = os.Remove(attemptPath())
+ return
+ }
+ logx.Printf("update: the update to %s did not finish; still %s", at.Version, a.Version)
+ a.upd.mu.Lock()
+ a.upd.failed = at.Version
+ a.upd.err = fmt.Sprintf("The update to %s didn't finish. Choose Update now to try again, or download it by hand.", at.Version)
+ a.upd.mu.Unlock()
+}
+
+// autoInstallDue: a verified update waits, its version has not failed
+// before, and the companion has been idle long enough.
+func (a *App) autoInstallDue() bool {
+ if a.Headless || a.Store.Get().ManualUpdates {
+ return false
+ }
+ a.upd.mu.Lock()
+ ready := a.upd.busy == "" && a.upd.pkg != "" && a.upd.reason == "" &&
+ a.upd.release != nil && a.upd.failed != a.upd.release.Version
+ a.upd.mu.Unlock()
+ return ready && a.idleFor() >= updateIdle
+}
+
+// idleFor is how long nothing has used the companion: no request that does
+// work for a client, no open panel, no local or decision model being
+// installed or started, no sign-in in progress.
+func (a *App) idleFor() time.Duration {
+ if a.activeReqs.Load() > 0 || a.listeners() > 0 || a.Local.Busy() || a.loginPending() {
+ return 0
+ }
+ switch a.D1.Status().Phase {
+ case d1.PhaseDownloading, d1.PhaseInstalling, d1.PhaseLoading:
+ return 0
+ }
+ return time.Duration(time.Now().UnixNano() - a.lastActive.Load())
+}
+
+func (a *App) loginPending() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ for _, l := range a.logins {
+ if l.Status == "wait" {
+ return true
+ }
+ }
+ return false
+}
+
+// clientWork reports whether a request does work for a client: a model call
+// or a model session (WebSocket), a decision, or a change made in the panel.
+// Lists and status reads (GET) are not work, and neither is the companion's
+// own traffic to the proxy's management API (usage refreshes, for one).
+func clientWork(c *gin.Context) bool {
+ p := c.Request.URL.Path
+ if strings.HasPrefix(p, "/v8/management") || strings.HasPrefix(p, "/v0/management") {
+ return false
+ }
+ if c.IsWebsocket() {
+ return apiPath(p)
+ }
+ switch c.Request.Method {
+ case http.MethodGet, http.MethodHead, http.MethodOptions:
+ return false
+ }
+ return apiPath(p) || strings.HasPrefix(p, "/companion/")
+}
+
+// activity records use of the companion for the automatic update. A request
+// counts while it runs; when it ends it marks the companion as used, unless
+// it was refused (a web page without the key, say).
+func (a *App) activity(c *gin.Context) {
+ if !clientWork(c) {
+ c.Next()
+ return
+ }
+ a.activeReqs.Add(1)
+ defer a.activeReqs.Add(-1)
+ c.Next()
+ if s := c.Writer.Status(); s != http.StatusUnauthorized && s != http.StatusForbidden {
+ a.lastActive.Store(time.Now().UnixNano())
+ }
+}
diff --git a/webbrain-systray/internal/app/update_test.go b/webbrain-systray/internal/app/update_test.go
new file mode 100644
index 000000000..7eeafadd2
--- /dev/null
+++ b/webbrain-systray/internal/app/update_test.go
@@ -0,0 +1,315 @@
+package app
+
+import (
+ "archive/tar"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/esokullu/webbrain-systray/internal/paths"
+ "github.com/esokullu/webbrain-systray/internal/settings"
+ "github.com/esokullu/webbrain-systray/internal/update"
+)
+
+func newTestApp(t *testing.T, version string) *App {
+ t.Helper()
+ t.Setenv("WBC_HOME", t.TempDir())
+ store, err := settings.Open()
+ if err != nil {
+ t.Fatal(err)
+ }
+ return New(version, store)
+}
+
+func TestDevelopmentBuildsDoNotUpdate(t *testing.T) {
+ a := newTestApp(t, "0.1.0-dev")
+ if st := a.UpdateStatus(); !st.Dev || st.Supported || !st.Auto {
+ t.Fatalf("status = %+v", st)
+ }
+}
+
+func TestAutomaticInstallWaitsUntilIdle(t *testing.T) {
+ a := newTestApp(t, "0.1.2")
+ a.upd.release = &update.Release{Version: "0.1.3"}
+ a.upd.pkg = "/downloads/0.1.3/package"
+ idle := func(ago time.Duration) { a.lastActive.Store(time.Now().Add(-ago).UnixNano()) }
+
+ idle(time.Minute)
+ if a.autoInstallDue() {
+ t.Fatal("installed one minute after the last request")
+ }
+ idle(11 * time.Minute)
+ if !a.autoInstallDue() {
+ t.Fatal("did not install after ten idle minutes")
+ }
+ if st := a.UpdateStatus(); st.State != "ready" || st.Latest != "0.1.3" {
+ t.Fatalf("status = %+v", st)
+ }
+
+ a.activeReqs.Add(1)
+ if a.autoInstallDue() {
+ t.Fatal("installed during a request")
+ }
+ a.activeReqs.Add(-1)
+
+ _, unsubscribe := a.Subscribe() // an open panel
+ if a.autoInstallDue() {
+ t.Fatal("installed while the panel is open")
+ }
+ unsubscribe()
+
+ a.mu.Lock()
+ a.logins["s"] = &login{Status: "wait"}
+ a.mu.Unlock()
+ if a.autoInstallDue() {
+ t.Fatal("installed during a sign-in")
+ }
+ a.mu.Lock()
+ delete(a.logins, "s")
+ a.mu.Unlock()
+
+ if _, err := a.Store.Update(func(s *settings.Settings) { s.ManualUpdates = true }); err != nil {
+ t.Fatal(err)
+ }
+ if a.autoInstallDue() || a.UpdateStatus().Auto {
+ t.Fatal("installed with automatic updates off")
+ }
+ if _, err := a.Store.Update(func(s *settings.Settings) { s.ManualUpdates = false }); err != nil {
+ t.Fatal(err)
+ }
+ a.Headless = true
+ if a.autoInstallDue() {
+ t.Fatal("a headless companion installed by itself")
+ }
+}
+
+// Only work a client asked for counts as use: not the companion's own calls
+// to the proxy's management API (usage refreshes run every few minutes), not
+// reads, not refused requests. A model session over a WebSocket counts for as
+// long as it lasts.
+func TestActivityCountsOnlyClientWork(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ a := newTestApp(t, "0.1.2")
+ e := gin.New()
+ e.Use(a.activity)
+ var during int64
+ ok := func(c *gin.Context) { during = a.activeReqs.Load(); c.Status(http.StatusOK) }
+ e.GET("/v1/models", ok)
+ e.GET("/v1/responses", ok)
+ e.POST("/v1/chat/completions", ok)
+ e.POST("/v8/management/requests/api-call", ok)
+ e.POST("/v1/messages", func(c *gin.Context) { c.AbortWithStatus(http.StatusForbidden) })
+ e.POST("/companion/api/update/check", ok)
+
+ past := time.Now().Add(-time.Hour).UnixNano()
+ serve := func(method, path string, websocket bool) (counted bool, inFlight int64) {
+ a.lastActive.Store(past)
+ during = 0
+ r := httptest.NewRequest(method, path, nil)
+ if websocket {
+ r.Header.Set("Connection", "Upgrade")
+ r.Header.Set("Upgrade", "websocket")
+ }
+ e.ServeHTTP(httptest.NewRecorder(), r)
+ if a.activeReqs.Load() != 0 {
+ t.Fatalf("%s %s left %d requests in flight", method, path, a.activeReqs.Load())
+ }
+ return a.lastActive.Load() != past, during
+ }
+ for _, tc := range []struct {
+ method, path string
+ websocket bool
+ counts bool
+ }{
+ {http.MethodGet, "/v1/models", false, false},
+ {http.MethodPost, "/v8/management/requests/api-call", false, false},
+ {http.MethodPost, "/v1/messages", false, false}, // refused
+ {http.MethodPost, "/v1/chat/completions", false, true},
+ {http.MethodGet, "/v1/responses", true, true}, // a Codex WebSocket session
+ {http.MethodPost, "/companion/api/update/check", false, true},
+ } {
+ counted, inFlight := serve(tc.method, tc.path, tc.websocket)
+ if counted != tc.counts {
+ t.Errorf("%s %s (websocket %v): counted %v, want %v", tc.method, tc.path, tc.websocket, counted, tc.counts)
+ }
+ if tc.counts && tc.path != "/v1/messages" && inFlight != 1 {
+ t.Errorf("%s %s was not in flight while it ran", tc.method, tc.path)
+ }
+ }
+}
+
+// releaseFeed serves one Linux release whose program is body.
+func releaseFeed(t *testing.T, version string, files map[string]string) {
+ t.Helper()
+ name, _ := update.PackageName(version, "linux", runtime.GOARCH)
+ pkg := tarGz(t, files)
+ sum := sha256.Sum256(pkg)
+ sums := fmt.Sprintf("%s %s\n", hex.EncodeToString(sum[:]), name)
+ var base string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/releases":
+ _ = json.NewEncoder(w).Encode([]map[string]any{{
+ "tag_name": "systray-v" + version, "html_url": base + "/page",
+ "assets": []map[string]any{
+ {"name": name, "browser_download_url": base + "/files/pkg", "size": len(pkg)},
+ {"name": "WebBrain-Companion-" + version + "-SHA256SUMS.txt", "browser_download_url": base + "/files/sums"},
+ },
+ }})
+ case "/files/pkg":
+ _, _ = w.Write(pkg)
+ case "/files/sums":
+ _, _ = w.Write([]byte(sums))
+ default:
+ http.NotFound(w, r)
+ }
+ }))
+ t.Cleanup(server.Close)
+ base = server.URL
+ t.Setenv("WBC_UPDATE_FEED", server.URL+"/releases")
+}
+
+func installedProgram(t *testing.T, a *App) {
+ t.Helper()
+ a.exe = filepath.Join(t.TempDir(), "webbrain-companion")
+ if err := os.WriteFile(a.exe, []byte("old program"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+}
+
+// The whole update on Linux: find the release, download and check it,
+// replace the program, quit, and start the new version in this process. When
+// the new version does not start, the previous one is put back and started.
+func TestInstallUpdateReplacesTheProgramAndRestarts(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("installs the Linux package")
+ }
+ a := newTestApp(t, "0.1.2")
+ installedProgram(t, a)
+ releaseFeed(t, "0.1.3", map[string]string{"webbrain-companion/webbrain-companion": "new program", "webbrain-companion/README.md": "readme"})
+
+ quit := 0
+ a.Quit = func() { quit++ }
+ a.installUpdate()
+ if quit != 1 || !a.RestartPending() {
+ t.Fatalf("quit %d times, restart pending %v; status %+v", quit, a.RestartPending(), a.UpdateStatus())
+ }
+ if got, _ := os.ReadFile(a.exe); string(got) != "new program" {
+ t.Fatalf("the program was not replaced: %q", got)
+ }
+
+ var started []string
+ a.exec = func(exe string, args ...string) error {
+ got, _ := os.ReadFile(exe)
+ started = append(started, string(got)+" "+strings.Join(args, " "))
+ return errors.New("exec format error") // the new program does not start
+ }
+ a.Restart()
+ want := []string{"new program --background --after-update", "old program --background --after-update"}
+ if strings.Join(started, "|") != strings.Join(want, "|") {
+ t.Fatalf("started %q, want the new version and then the previous one %q", started, want)
+ }
+ if got, _ := os.ReadFile(a.exe); string(got) != "old program" {
+ t.Fatalf("the previous program was not put back: %q", got)
+ }
+
+ // Started again, the previous version knows the update did not take and
+ // does not try it again by itself.
+ b := New("0.1.2", a.Store)
+ b.exe = a.exe
+ b.readAttempt()
+ b.upd.release = &update.Release{Version: "0.1.3"}
+ b.upd.pkg = "/downloads/package"
+ b.lastActive.Store(time.Now().Add(-time.Hour).UnixNano())
+ if b.autoInstallDue() {
+ t.Fatal("retried a failed version by itself")
+ }
+ if st := b.UpdateStatus(); st.State != "error" || !strings.Contains(st.Error, "0.1.3") {
+ t.Fatalf("status = %+v, want the failed update reported", st)
+ }
+ // A newer release is tried again.
+ b.upd.release = &update.Release{Version: "0.1.4"}
+ if !b.autoInstallDue() {
+ t.Fatal("a newer release was not installed")
+ }
+}
+
+// A failed install is reported and not retried every half minute.
+func TestFailedInstallIsReportedNotRetried(t *testing.T) {
+ if runtime.GOOS != "linux" {
+ t.Skip("installs the Linux package")
+ }
+ a := newTestApp(t, "0.1.2")
+ installedProgram(t, a)
+ releaseFeed(t, "0.1.3", map[string]string{"webbrain-companion/README.md": "a package without the program"})
+ a.Quit = func() { t.Fatal("quit after a failed install") }
+ a.installUpdate()
+ st := a.UpdateStatus()
+ if st.State != "error" || !strings.Contains(st.Error, "incomplete") {
+ t.Fatalf("status = %+v", st)
+ }
+ a.lastActive.Store(time.Now().Add(-time.Hour).UnixNano())
+ if a.autoInstallDue() {
+ t.Fatal("a failed version is due again")
+ }
+ if a.RestartPending() {
+ t.Fatal("restart pending after a failed install")
+ }
+ if got, _ := os.ReadFile(a.exe); string(got) != "old program" {
+ t.Fatalf("a failed install changed the program: %q", got)
+ }
+}
+
+func TestAttemptRecordClearsAfterASuccessfulUpdate(t *testing.T) {
+ a := newTestApp(t, "0.1.2")
+ a.writeAttempt("0.1.3")
+ if _, err := os.Stat(filepath.Join(paths.Updates(), "attempt.json")); err != nil {
+ t.Fatal(err)
+ }
+ b := New("0.1.3", a.Store) // the new version started
+ b.readAttempt()
+ if _, err := os.Stat(filepath.Join(paths.Updates(), "attempt.json")); !os.IsNotExist(err) {
+ t.Fatal("the record of a finished update was kept")
+ }
+ if st := b.UpdateStatus(); st.State != "idle" || st.Error != "" {
+ t.Fatalf("status = %+v", st)
+ }
+}
+
+func tarGz(t *testing.T, files map[string]string) []byte {
+ t.Helper()
+ path := filepath.Join(t.TempDir(), "pkg.tar.gz")
+ f, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gz := gzip.NewWriter(f)
+ tw := tar.NewWriter(gz)
+ for name, body := range files {
+ if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = tw.Write([]byte(body))
+ }
+ _ = tw.Close()
+ _ = gz.Close()
+ _ = f.Close()
+ data, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return data
+}
diff --git a/webbrain-systray/internal/i18n/i18n.go b/webbrain-systray/internal/i18n/i18n.go
index d4baac63c..01ccdca66 100644
--- a/webbrain-systray/internal/i18n/i18n.go
+++ b/webbrain-systray/internal/i18n/i18n.go
@@ -10,44 +10,50 @@ import (
var catalog = map[string]map[string]string{
"en": {
- "running": "Running",
- "stopped": "Not running",
- "copy": "Copy",
- "copy_hint": "Click to copy",
- "add": "Add subscription…",
- "paused": "paused",
- "quota_loading": "reading usage…",
- "quota_error": "usage unavailable",
- "quota_none": "usage not reported",
- "open_panel": "Open panel…",
- "quit": "Quit WebBrain Companion",
- "dur_days": "%dd",
- "dur_hours": "%dh %02dm",
- "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.",
+ "running": "Running",
+ "stopped": "Not running",
+ "copy": "Copy",
+ "copy_hint": "Click to copy",
+ "add": "Add subscription…",
+ "paused": "paused",
+ "quota_loading": "reading usage…",
+ "quota_error": "usage unavailable",
+ "quota_none": "usage not reported",
+ "open_panel": "Open panel…",
+ "quit": "Quit WebBrain Companion",
+ "dur_days": "%dd",
+ "dur_hours": "%dh %02dm",
+ "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.",
+ "update_now": "Update to %s and restart",
+ "update_downloading": "Downloading update %s…",
+ "update_installing": "Installing update %s…",
},
"tr": {
- "running": "Çalışıyor",
- "stopped": "Çalışmıyor",
- "copy": "Kopyala",
- "copy_hint": "Kopyalamak için tıkla",
- "add": "Abonelik ekle…",
- "paused": "duraklatıldı",
- "quota_loading": "kullanım okunuyor…",
- "quota_error": "kullanım okunamadı",
- "quota_none": "kullanım bildirilmiyor",
- "open_panel": "Paneli aç…",
- "quit": "WebBrain Companion'dan çık",
- "dur_days": "%d gün",
- "dur_hours": "%d sa %02d dk",
- "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.",
+ "running": "Çalışıyor",
+ "stopped": "Çalışmıyor",
+ "copy": "Kopyala",
+ "copy_hint": "Kopyalamak için tıkla",
+ "add": "Abonelik ekle…",
+ "paused": "duraklatıldı",
+ "quota_loading": "kullanım okunuyor…",
+ "quota_error": "kullanım okunamadı",
+ "quota_none": "kullanım bildirilmiyor",
+ "open_panel": "Paneli aç…",
+ "quit": "WebBrain Companion'dan çık",
+ "dur_days": "%d gün",
+ "dur_hours": "%d sa %02d dk",
+ "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.",
+ "update_now": "%s sürümüne güncelle ve yeniden başlat",
+ "update_downloading": "%s güncellemesi indiriliyor…",
+ "update_installing": "%s güncellemesi kuruluyor…",
},
}
diff --git a/webbrain-systray/internal/panel/assets/app.js b/webbrain-systray/internal/panel/assets/app.js
index aab6edb7f..20496089c 100644
--- a/webbrain-systray/internal/panel/assets/app.js
+++ b/webbrain-systray/internal/panel/assets/app.js
@@ -133,6 +133,19 @@
hideList: "Hide",
logFile: "Show log file",
version: "Version {v}",
+ updates: "Updates",
+ updAuto: "Install updates automatically",
+ updAutoHelp: "New versions download in the background and install after 10 minutes without use. The companion then restarts by itself.",
+ updCheck: "Check for updates",
+ updChecking: "Checking for updates…",
+ updCurrent: "You have the newest version.",
+ updAvailable: "Version {v} is available.",
+ updDownloading: "Downloading version {v}…",
+ updReady: "Version {v} is ready to install.",
+ updInstalling: "Installing version {v}…",
+ updInstall: "Update to {v} now",
+ updFailed: "The update didn't finish: {e}",
+ updPage: "Download page",
quit: "Quit WebBrain Companion",
quitConfirm: "WebBrain loses access to your subscriptions until you open the companion again.",
trayHidden: "macOS is hiding the WebBrain Companion icon because the menu bar is full. You can always come back here by opening WebBrain Companion again. To make room, hide menu bar icons you don't use in System Settings, Menu Bar.",
@@ -282,6 +295,19 @@
hideList: "Gizle",
logFile: "Günlük dosyasını göster",
version: "Sürüm {v}",
+ updates: "Güncellemeler",
+ updAuto: "Güncellemeleri otomatik kur",
+ updAutoHelp: "Yeni sürümler arka planda iner ve 10 dakika kullanılmadığında kurulur. Ardından Companion kendiliğinden yeniden başlar.",
+ updCheck: "Güncellemeleri denetle",
+ updChecking: "Güncellemeler denetleniyor…",
+ updCurrent: "En yeni sürümü kullanıyorsun.",
+ updAvailable: "{v} sürümü çıktı.",
+ updDownloading: "{v} sürümü indiriliyor…",
+ updReady: "{v} sürümü kurulmaya hazır.",
+ updInstalling: "{v} sürümü kuruluyor…",
+ updInstall: "Şimdi {v} sürümüne güncelle",
+ updFailed: "Güncelleme tamamlanamadı: {e}",
+ updPage: "İndirme sayfası",
quit: "WebBrain Companion'dan çık",
quitConfirm: "Yeniden açana kadar WebBrain aboneliklerine erişemez.",
trayHidden: "Menü çubuğu dolu olduğu için macOS, WebBrain Companion simgesini gizliyor. Bu panele her zaman WebBrain Companion'ı yeniden açarak dönebilirsin. Yer açmak için kullanmadığın simgeleri Sistem Ayarları, Menü Çubuğu bölümünden gizle.",
@@ -847,6 +873,40 @@
: `<div class="sheet-actions end"><button class="btn small danger" data-act="ask-d1-remove" ${busy ? "disabled" : ""}>${t("removeFiles")}</button></div>`) : ""}`;
}
+ // Updates: the automatic-install switch, where the update stands, and a
+ // button to check or install now. Development builds never update.
+ function updateSection(s) {
+ const u = s.update || {};
+ if (u.dev) return "";
+ const busy = ["checking", "downloading", "installing"].includes(u.state);
+ let status = "";
+ switch (u.state) {
+ case "checking": status = t("updChecking"); break;
+ case "downloading": {
+ const p = u.progress;
+ status = t("updDownloading", { v: u.latest }) + (p && p.total ? ` ${Math.floor((p.done / p.total) * 100)}%` : "");
+ break;
+ }
+ case "installing": status = t("updInstalling", { v: u.latest }); break;
+ case "ready": status = t("updReady", { v: u.latest }); break;
+ case "error": status = t("updFailed", { e: u.error }); break;
+ default: status = u.latest ? t("updAvailable", { v: u.latest }) : (u.checked_at ? t("updCurrent") : "");
+ }
+ const notes = [status ? `<p class="sheet-note${u.state === "error" ? " warn" : ""}">${esc(status)}</p>` : ""];
+ if (u.latest && !u.supported && u.reason) notes.push(`<p class="sheet-note warn">${esc(u.reason)}</p>`);
+ const action = u.latest && u.supported
+ ? `<button class="btn small primary" data-act="update-install" ${busy ? "disabled" : ""}>${esc(t("updInstall", { v: u.latest }))}</button>`
+ : `<button class="btn small" data-act="update-check" ${busy ? "disabled" : ""}>${t("updCheck")}</button>`;
+ const page = u.latest && !u.supported ? ` <button class="link" data-act="update-page">${t("updPage")}</button>` : "";
+ return `<h4>${t("updates")}</h4>
+ <div class="opts">
+ <label class="toggle"><input type="checkbox" data-change="auto-update" ${u.auto ? "checked" : ""}>${t("updAuto")}</label>
+ <p class="sheet-note">${t("updAutoHelp")}</p>
+ ${notes.join("")}
+ <div>${action}${page}</div>
+ </div>`;
+ }
+
function settingsSheet() {
const s = state;
const models = s.models || [];
@@ -882,6 +942,7 @@
${models.length ? `<button class="btn small quiet" data-act="toggle-models" aria-expanded="${ui.showModels}">${ui.showModels ? t("hideList") : t("showList")}</button>` : ""}</div>
${ui.showModels && models.length ? `<ul class="chips">${models.map((m) => `<li><button data-act="copy" data-text="${esc(m)}" title="${t("copy")}">${esc(m)}</button></li>`).join("")}</ul>` : ""}
</div>
+ ${updateSection(s)}
<div class="sheet-foot">
<button class="link" data-act="logs">${t("logFile")}</button>
<span>${esc(t("version", { v: s.version }))}</span>
@@ -1091,6 +1152,9 @@
break;
}
case "logs": run(api("POST", "/open", { target: "logs" })); break;
+ case "update-check": run(api("POST", "/update/check")); break;
+ case "update-install": run(api("POST", "/update/install")); break;
+ case "update-page": run(api("POST", "/open", { target: "url", url: (state.update && state.update.page) || "https://github.com/webbrain-one/webbrain/releases" })); break;
case "port": {
const v = parseInt((document.getElementById("port-input") || {}).value, 10);
if (!v || v === state.preferred_port) break;
@@ -1112,6 +1176,7 @@
switch (el.dataset.change) {
case "autostart": run(api("PATCH", "/settings", { autostart: v })); break;
case "network": run(api("PATCH", "/settings", { network: v })); break;
+ case "auto-update": run(api("PATCH", "/settings", { auto_update: v })); break;
case "language": lang = v; state.language = v; run(api("PATCH", "/settings", { language: v })); el.blur(); reRender(); break;
case "local-vision": run(api("PATCH", "/local", { vision: v })); el.blur(); break;
case "local-context": state.local_context_setting = parseInt(v, 10); run(api("PATCH", "/local", { context: parseInt(v, 10) })); el.blur(); break;
diff --git a/webbrain-systray/internal/paths/paths.go b/webbrain-systray/internal/paths/paths.go
index fe91c872b..e0a9271f3 100644
--- a/webbrain-systray/internal/paths/paths.go
+++ b/webbrain-systray/internal/paths/paths.go
@@ -78,6 +78,7 @@ func LockFile() string { return filepath.Join(Config(), "companion.lock") }
func Logs() string { return filepath.Join(Data(), "logs") }
func Models() string { return filepath.Join(Data(), "models") }
func Runtimes() string { return filepath.Join(Data(), "runtimes") }
+func Updates() string { return filepath.Join(Data(), "updates") }
// Ensure creates every directory the companion writes to.
func Ensure() error {
diff --git a/webbrain-systray/internal/settings/settings.go b/webbrain-systray/internal/settings/settings.go
index 6c21cf8df..42ad9426e 100644
--- a/webbrain-systray/internal/settings/settings.go
+++ b/webbrain-systray/internal/settings/settings.go
@@ -64,6 +64,9 @@ type Settings struct {
Decision Decision `json:"decision"`
// Welcomed is set after the first panel opening so it is not repeated.
Welcomed bool `json:"welcomed"`
+ // ManualUpdates turns off automatic updates: new versions are still
+ // reported, and install only when asked.
+ ManualUpdates bool `json:"manual_updates,omitempty"`
}
type Store struct {
diff --git a/webbrain-systray/internal/update/install.go b/webbrain-systray/internal/update/install.go
new file mode 100644
index 000000000..a21a1778e
--- /dev/null
+++ b/webbrain-systray/internal/update/install.go
@@ -0,0 +1,256 @@
+package update
+
+import (
+ "archive/zip"
+ "errors"
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+
+ "github.com/esokullu/webbrain-systray/internal/download"
+)
+
+// Target is what an update replaces for the running copy.
+type Target struct {
+ // Kind is "bundle" (the macOS app), "binary" (the Linux program) or
+ // "installer" (Windows, where the setup program installs over the
+ // registered installation).
+ Kind string
+ // Path is the .app bundle or the executable.
+ Path string
+}
+
+// ErrTranslocated: macOS runs the app from a temporary read-only copy because
+// it was opened where it was downloaded.
+var ErrTranslocated = errors.New("macOS runs this copy from a temporary location; move WebBrain Companion to Applications and open it from there")
+
+// bundleName and binaryName are the files scripts/build.sh packages.
+const (
+ bundleName = "WebBrain Companion.app"
+ bundleExe = "WebBrain Companion"
+ binaryName = "webbrain-companion"
+ stagingPre = ".wbc-update-"
+)
+
+// Locate finds what to replace for the executable exe, or why this copy cannot
+// update itself.
+func Locate(exe string) (Target, error) { return locate(exe, runtime.GOOS) }
+
+func locate(exe, goos string) (Target, error) {
+ switch goos {
+ case "darwin":
+ if strings.Contains(exe, "/AppTranslocation/") {
+ return Target{}, ErrTranslocated
+ }
+ bundle := bundleOf(exe)
+ if bundle == "" {
+ return Target{}, errors.New("this copy does not run from an app bundle; download the new version by hand")
+ }
+ if err := writable(filepath.Dir(bundle)); err != nil {
+ return Target{}, err
+ }
+ return Target{Kind: "bundle", Path: bundle}, nil
+ case "linux":
+ if err := writable(filepath.Dir(exe)); err != nil {
+ return Target{}, err
+ }
+ return Target{Kind: "binary", Path: exe}, nil
+ case "windows":
+ if err := installedHere(exe); err != nil {
+ return Target{}, err
+ }
+ return Target{Kind: "installer", Path: exe}, nil
+ }
+ return Target{}, fmt.Errorf("no WebBrain Companion package exists for %s", goos)
+}
+
+// bundleOf returns the app bundle around exe (…/X.app/Contents/MacOS/x), or "".
+func bundleOf(exe string) string {
+ macos := filepath.Dir(exe)
+ contents := filepath.Dir(macos)
+ bundle := filepath.Dir(contents)
+ if filepath.Base(macos) != "MacOS" || filepath.Base(contents) != "Contents" || !strings.HasSuffix(bundle, ".app") {
+ return ""
+ }
+ return bundle
+}
+
+// writable checks that files can be created in dir, where the update swaps
+// the old copy for the new one.
+func writable(dir string) error {
+ f, err := os.CreateTemp(dir, stagingPre+"check-")
+ if err != nil {
+ return fmt.Errorf("cannot write to %s, so this copy cannot replace itself; download the new version by hand", dir)
+ }
+ name := f.Name()
+ _ = f.Close()
+ return os.Remove(name)
+}
+
+// Install puts the package at pkg in place of t. The swap happens in the same
+// folder, so the running process keeps its old files until it exits. On
+// Windows use StartInstaller instead.
+func Install(pkg string, t Target) error {
+ switch t.Kind {
+ case "bundle":
+ return installBundle(pkg, t.Path)
+ case "binary":
+ return installBinary(pkg, t.Path)
+ }
+ return fmt.Errorf("a %q target is updated by its setup program", t.Kind)
+}
+
+// oldBundle is where the replaced app waits until the new version has
+// started and removes it (Cleanup).
+func oldBundle(bundle string) string {
+ return filepath.Join(filepath.Dir(bundle), "."+filepath.Base(bundle)+".old")
+}
+
+func installBundle(zipPath, bundle string) error {
+ if err := checkZip(zipPath); err != nil {
+ return err
+ }
+ parent := filepath.Dir(bundle)
+ stage, err := os.MkdirTemp(parent, stagingPre)
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(stage)
+ keep := func(rel string) bool { return strings.HasPrefix(rel, bundleName+"/") }
+ if err := download.ExtractZip(zipPath, stage, 0, keep); err != nil {
+ return fmt.Errorf("unpack the new version: %w", err)
+ }
+ fresh := filepath.Join(stage, bundleName)
+ exe := filepath.Join(fresh, "Contents", "MacOS", bundleExe)
+ if st, err := os.Lstat(exe); err != nil || !st.Mode().IsRegular() || st.Mode().Perm()&0o111 == 0 {
+ return errors.New("the downloaded app is incomplete")
+ }
+ if st, err := os.Lstat(filepath.Join(fresh, "Contents", "Info.plist")); err != nil || !st.Mode().IsRegular() {
+ return errors.New("the downloaded app is incomplete")
+ }
+ old := oldBundle(bundle)
+ _ = os.RemoveAll(old)
+ if err := os.Rename(bundle, old); err != nil {
+ if errors.Is(err, fs.ErrPermission) {
+ // macOS 13 and later guard apps against changes by other apps.
+ return fmt.Errorf("macOS did not let WebBrain Companion replace itself; allow it under System Settings, Privacy & Security, App Management, or download the new version by hand (%w)", err)
+ }
+ return fmt.Errorf("move the running app aside: %w", err)
+ }
+ if err := os.Rename(fresh, bundle); err != nil {
+ if restoreErr := os.Rename(old, bundle); restoreErr != nil {
+ return errors.Join(fmt.Errorf("put the new app in place: %w", err), restoreErr)
+ }
+ return fmt.Errorf("put the new app in place: %w", err)
+ }
+ return nil
+}
+
+// checkZip refuses archives with links: the extractor writes plain files, and
+// a bundle that relies on links would come out broken.
+func checkZip(path string) error {
+ r, err := zip.OpenReader(path)
+ if err != nil {
+ return err
+ }
+ defer r.Close()
+ for _, f := range r.File {
+ if f.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("the package contains a link (%s); install this version by hand", f.Name)
+ }
+ }
+ return nil
+}
+
+func installBinary(tarPath, exe string) error {
+ stage, err := os.MkdirTemp(filepath.Dir(exe), stagingPre)
+ if err != nil {
+ return err
+ }
+ defer os.RemoveAll(stage)
+ keep := func(rel string) bool { return rel == binaryName }
+ if err := download.ExtractTarGz(tarPath, stage, 1, keep); err != nil {
+ return fmt.Errorf("unpack the new version: %w", err)
+ }
+ fresh := filepath.Join(stage, binaryName)
+ st, err := os.Lstat(fresh)
+ if err != nil || !st.Mode().IsRegular() || st.Size() == 0 {
+ return errors.New("the downloaded program is incomplete")
+ }
+ if err := os.Chmod(fresh, 0o755); err != nil {
+ return err
+ }
+ // The running process keeps its file (the inode) whatever the name; the
+ // old program stays next to it until the new version has started.
+ old := oldBinary(exe)
+ _ = os.Remove(old)
+ if err := os.Rename(exe, old); err != nil {
+ return fmt.Errorf("move the running program aside: %w", err)
+ }
+ if err := os.Rename(fresh, exe); err != nil {
+ if restoreErr := os.Rename(old, exe); restoreErr != nil {
+ return errors.Join(fmt.Errorf("put the new program in place: %w", err), restoreErr)
+ }
+ return fmt.Errorf("put the new program in place: %w", err)
+ }
+ return nil
+}
+
+// oldBinary is where the replaced Linux program waits until the new version
+// has started.
+func oldBinary(exe string) string {
+ return filepath.Join(filepath.Dir(exe), "."+filepath.Base(exe)+".old")
+}
+
+// Rollback puts back the version an Install replaced, for when the new one
+// does not start.
+func Rollback(t Target) error {
+ switch t.Kind {
+ case "bundle":
+ old := oldBundle(t.Path)
+ if _, err := os.Stat(old); err != nil {
+ return fmt.Errorf("the previous app is gone: %w", err)
+ }
+ failed := filepath.Join(filepath.Dir(t.Path), "."+filepath.Base(t.Path)+".failed")
+ _ = os.RemoveAll(failed)
+ if err := os.Rename(t.Path, failed); err != nil {
+ return err
+ }
+ if err := os.Rename(old, t.Path); err != nil {
+ return errors.Join(err, os.Rename(failed, t.Path))
+ }
+ return os.RemoveAll(failed)
+ case "binary":
+ return os.Rename(oldBinary(t.Path), t.Path)
+ }
+ return fmt.Errorf("a %q target has nothing to put back", t.Kind)
+}
+
+// Cleanup removes what an earlier update left: the replaced app bundle
+// (macOS) or program (Linux), unfinished staging folders next to exe, and
+// downloaded packages (one folder per version) that are not newer than
+// current.
+func Cleanup(exe, downloads, current string) {
+ dir := filepath.Dir(exe)
+ if bundle := bundleOf(exe); bundle != "" {
+ _ = os.RemoveAll(oldBundle(bundle))
+ _ = os.RemoveAll(filepath.Join(filepath.Dir(bundle), "."+filepath.Base(bundle)+".failed"))
+ dir = filepath.Dir(bundle)
+ } else if filepath.Base(exe) == binaryName {
+ _ = os.Remove(oldBinary(exe))
+ }
+ if matches, err := filepath.Glob(filepath.Join(dir, stagingPre+"*")); err == nil {
+ for _, m := range matches {
+ _ = os.RemoveAll(m)
+ }
+ }
+ entries, _ := os.ReadDir(downloads)
+ for _, e := range entries {
+ if e.IsDir() && !Newer(e.Name(), current) {
+ _ = os.RemoveAll(filepath.Join(downloads, e.Name()))
+ }
+ }
+}
diff --git a/webbrain-systray/internal/update/install_test.go b/webbrain-systray/internal/update/install_test.go
new file mode 100644
index 000000000..1d1b27194
--- /dev/null
+++ b/webbrain-systray/internal/update/install_test.go
@@ -0,0 +1,331 @@
+package update
+
+import (
+ "archive/tar"
+ "archive/zip"
+ "compress/gzip"
+ "errors"
+ "fmt"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+type entry struct {
+ name string
+ body string
+ mode os.FileMode
+}
+
+func writeZip(t *testing.T, path string, entries ...entry) {
+ t.Helper()
+ f, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ zw := zip.NewWriter(f)
+ for _, e := range entries {
+ h := &zip.FileHeader{Name: e.name, Method: zip.Deflate}
+ h.SetMode(e.mode)
+ w, err := zw.CreateHeader(h)
+ if err != nil {
+ t.Fatal(err)
+ }
+ _, _ = w.Write([]byte(e.body))
+ }
+ if err := zw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ _ = f.Close()
+}
+
+func writeTarGz(t *testing.T, path string, entries ...entry) {
+ t.Helper()
+ f, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ gz := gzip.NewWriter(f)
+ tw := tar.NewWriter(gz)
+ for _, e := range entries {
+ if err := tw.WriteHeader(&tar.Header{Name: e.name, Mode: int64(e.mode.Perm()), Size: int64(len(e.body)), Typeflag: tar.TypeReg}); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = tw.Write([]byte(e.body))
+ }
+ _ = tw.Close()
+ _ = gz.Close()
+ _ = f.Close()
+}
+
+// fakeBundle lays out an installed app whose program prints "old".
+func fakeBundle(t *testing.T, apps string) (bundle, exe string) {
+ t.Helper()
+ bundle = filepath.Join(apps, "WebBrain Companion.app")
+ exe = filepath.Join(bundle, "Contents", "MacOS", "WebBrain Companion")
+ if err := os.MkdirAll(filepath.Dir(exe), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(exe, []byte("old"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(bundle, "Contents", "Info.plist"), []byte("old plist"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ return bundle, exe
+}
+
+func newMacPackage(t *testing.T, dir string, extra ...entry) string {
+ pkg := filepath.Join(dir, "WebBrain-Companion-0.1.3-macos-universal.zip")
+ entries := append([]entry{
+ {"WebBrain Companion.app/Contents/MacOS/WebBrain Companion", "new", 0o755},
+ {"WebBrain Companion.app/Contents/Info.plist", "new plist", 0o644},
+ {"WebBrain Companion.app/Contents/Resources/app.icns", "icon", 0o644},
+ {"README.md", "readme", 0o644},
+ {"LICENSE", "license", 0o644},
+ }, extra...)
+ writeZip(t, pkg, entries...)
+ return pkg
+}
+
+func TestLocate(t *testing.T) {
+ apps := t.TempDir()
+ bundle, exe := fakeBundle(t, apps)
+ got, err := locate(exe, "darwin")
+ if err != nil || got.Kind != "bundle" || got.Path != bundle {
+ t.Fatalf("locate(darwin) = %+v, %v; want the bundle %s", got, err, bundle)
+ }
+ if _, err := locate("/private/var/folders/x/AppTranslocation/ABC/d/WebBrain Companion.app/Contents/MacOS/WebBrain Companion", "darwin"); !errors.Is(err, ErrTranslocated) {
+ t.Fatalf("a translocated copy: err = %v", err)
+ }
+ if _, err := locate(filepath.Join(apps, "webbrain-companion"), "darwin"); err == nil {
+ t.Fatal("a program outside a bundle cannot replace itself on macOS")
+ }
+ linuxExe := filepath.Join(t.TempDir(), "webbrain-companion")
+ if got, err := locate(linuxExe, "linux"); err != nil || got.Kind != "binary" || got.Path != linuxExe {
+ t.Fatalf("locate(linux) = %+v, %v", got, err)
+ }
+ if runtime.GOOS != "windows" && os.Geteuid() != 0 {
+ ro := t.TempDir()
+ if err := os.Chmod(ro, 0o555); err != nil {
+ t.Fatal(err)
+ }
+ defer os.Chmod(ro, 0o755)
+ if _, err := locate(filepath.Join(ro, "webbrain-companion"), "linux"); err == nil {
+ t.Fatal("a copy in a read-only folder cannot replace itself")
+ }
+ }
+ if entries, _ := os.ReadDir(apps); len(entries) != 1 {
+ t.Fatalf("the write check left files behind: %v", entries)
+ }
+}
+
+func TestInstallBundleSwapsTheApp(t *testing.T) {
+ apps := t.TempDir()
+ bundle, exe := fakeBundle(t, apps)
+ pkg := newMacPackage(t, t.TempDir())
+ if err := Install(pkg, Target{Kind: "bundle", Path: bundle}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(exe); string(got) != "new" {
+ t.Fatalf("program after the update: %q", got)
+ }
+ if st, err := os.Stat(exe); err != nil || st.Mode().Perm()&0o111 == 0 {
+ t.Fatalf("the new program is not executable: %v %v", st, err)
+ }
+ if _, err := os.Stat(filepath.Join(bundle, "README.md")); !os.IsNotExist(err) {
+ t.Fatal("files outside the app were copied into it")
+ }
+ old := filepath.Join(apps, ".WebBrain Companion.app.old")
+ if got, _ := os.ReadFile(filepath.Join(old, "Contents", "MacOS", "WebBrain Companion")); string(got) != "old" {
+ t.Fatalf("the replaced app was not kept for cleanup: %q", got)
+ }
+ entries, _ := os.ReadDir(apps)
+ if len(entries) != 2 {
+ t.Fatalf("Applications holds %v, want the app and its old copy", names(entries))
+ }
+
+ // The new version removes the old copy when it starts.
+ downloads := t.TempDir()
+ for _, v := range []string{"0.1.2", "0.1.3", "0.1.4", "junk"} {
+ _ = os.MkdirAll(filepath.Join(downloads, v), 0o755)
+ }
+ _ = os.MkdirAll(filepath.Join(apps, ".wbc-update-123"), 0o755)
+ Cleanup(exe, downloads, "0.1.3")
+ if entries, _ := os.ReadDir(apps); len(entries) != 1 || entries[0].Name() != "WebBrain Companion.app" {
+ t.Fatalf("after cleanup Applications holds %v", names(entries))
+ }
+ if entries, _ := os.ReadDir(downloads); len(entries) != 1 || entries[0].Name() != "0.1.4" {
+ t.Fatalf("after cleanup downloads hold %v, want only 0.1.4", names(entries))
+ }
+}
+
+func TestInstallBundleRefusesBrokenPackages(t *testing.T) {
+ for name, build := range map[string]func(t *testing.T, dir string) string{
+ "no program": func(t *testing.T, dir string) string {
+ p := filepath.Join(dir, "pkg.zip")
+ writeZip(t, p, entry{"WebBrain Companion.app/Contents/Info.plist", "plist", 0o644})
+ return p
+ },
+ "program not executable": func(t *testing.T, dir string) string {
+ p := filepath.Join(dir, "pkg.zip")
+ writeZip(t, p, entry{"WebBrain Companion.app/Contents/MacOS/WebBrain Companion", "new", 0o644},
+ entry{"WebBrain Companion.app/Contents/Info.plist", "plist", 0o644})
+ return p
+ },
+ "a link": func(t *testing.T, dir string) string {
+ return newMacPackage(t, dir, entry{"WebBrain Companion.app/Contents/Frameworks/x", "../../x", os.ModeSymlink | 0o777})
+ },
+ "not a zip": func(t *testing.T, dir string) string {
+ p := filepath.Join(dir, "pkg.zip")
+ _ = os.WriteFile(p, []byte("nope"), 0o644)
+ return p
+ },
+ } {
+ t.Run(name, func(t *testing.T) {
+ apps := t.TempDir()
+ bundle, exe := fakeBundle(t, apps)
+ if err := Install(build(t, t.TempDir()), Target{Kind: "bundle", Path: bundle}); err == nil {
+ t.Fatal("a broken package was installed")
+ }
+ if got, _ := os.ReadFile(exe); string(got) != "old" {
+ t.Fatalf("the running app changed: %q", got)
+ }
+ if entries, _ := os.ReadDir(apps); len(entries) != 1 {
+ t.Fatalf("Applications holds %v after a refused update", names(entries))
+ }
+ })
+ }
+}
+
+func TestInstallBinaryReplacesTheProgram(t *testing.T) {
+ dir := t.TempDir()
+ exe := filepath.Join(dir, "webbrain-companion")
+ if err := os.WriteFile(exe, []byte("old"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ pkg := filepath.Join(t.TempDir(), "WebBrain-Companion-0.1.3-linux-x64.tar.gz")
+ writeTarGz(t, pkg,
+ entry{"webbrain-companion/webbrain-companion", "new", 0o755},
+ entry{"webbrain-companion/webbrain-companion.desktop", "desktop", 0o644},
+ entry{"webbrain-companion/README.md", "readme", 0o644},
+ )
+ if err := Install(pkg, Target{Kind: "binary", Path: exe}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(exe); string(got) != "new" {
+ t.Fatalf("program after the update: %q", got)
+ }
+ if st, _ := os.Stat(exe); st.Mode().Perm() != 0o755 {
+ t.Fatalf("mode %v", st.Mode())
+ }
+ if got, _ := os.ReadFile(filepath.Join(dir, ".webbrain-companion.old")); string(got) != "old" {
+ t.Fatalf("the replaced program was not kept for a rollback: %q", got)
+ }
+ if entries, _ := os.ReadDir(dir); len(entries) != 2 {
+ t.Fatalf("the program's folder holds %v", names(entries))
+ }
+
+ broken := filepath.Join(t.TempDir(), "broken.tar.gz")
+ writeTarGz(t, broken, entry{"webbrain-companion/README.md", "readme", 0o644})
+ if err := Install(broken, Target{Kind: "binary", Path: exe}); err == nil {
+ t.Fatal("a package without the program was installed")
+ }
+ if got, _ := os.ReadFile(exe); string(got) != "new" {
+ t.Fatalf("a refused update changed the program: %q", got)
+ }
+}
+
+// Exec replaces the process: same process ID, the new program's arguments.
+func TestExecReplacesTheProcess(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("macOS and Linux only")
+ }
+ if script := os.Getenv("WBC_EXEC_SCRIPT"); script != "" {
+ err := Exec(script, "--background", "--after-update")
+ t.Fatalf("Exec returned: %v", err)
+ }
+ dir := t.TempDir()
+ marker := filepath.Join(dir, "started")
+ script := filepath.Join(dir, "companion")
+ if err := os.WriteFile(script, []byte("#!/bin/sh\necho \"$$ $@\" > \""+marker+"\"\n"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ cmd := exec.Command(os.Args[0], "-test.run=^TestExecReplacesTheProcess$")
+ cmd.Env = append(os.Environ(), "WBC_EXEC_SCRIPT="+script)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("helper: %v\n%s", err, out)
+ }
+ got, err := os.ReadFile(marker)
+ if err != nil {
+ t.Fatal(err)
+ }
+ want := fmt.Sprintf("%d --background --after-update", cmd.Process.Pid)
+ if strings.TrimSpace(string(got)) != want {
+ t.Fatalf("the new program saw %q, want %q", got, want)
+ }
+}
+
+func TestRollbackPutsThePreviousVersionBack(t *testing.T) {
+ apps := t.TempDir()
+ bundle, exe := fakeBundle(t, apps)
+ if err := Install(newMacPackage(t, t.TempDir()), Target{Kind: "bundle", Path: bundle}); err != nil {
+ t.Fatal(err)
+ }
+ if err := Rollback(Target{Kind: "bundle", Path: bundle}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(exe); string(got) != "old" {
+ t.Fatalf("app after the rollback: %q", got)
+ }
+ if entries, _ := os.ReadDir(apps); len(entries) != 1 {
+ t.Fatalf("Applications holds %v after the rollback", names(entries))
+ }
+
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "webbrain-companion")
+ _ = os.WriteFile(bin, []byte("old"), 0o755)
+ pkg := filepath.Join(t.TempDir(), "pkg.tar.gz")
+ writeTarGz(t, pkg, entry{"webbrain-companion/webbrain-companion", "new", 0o755})
+ if err := Install(pkg, Target{Kind: "binary", Path: bin}); err != nil {
+ t.Fatal(err)
+ }
+ if err := Rollback(Target{Kind: "binary", Path: bin}); err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(bin); string(got) != "old" {
+ t.Fatalf("program after the rollback: %q", got)
+ }
+ if err := Rollback(Target{Kind: "binary", Path: bin}); err == nil {
+ t.Fatal("a second rollback found something to put back")
+ }
+}
+
+func TestCleanupAfterAnUpdate(t *testing.T) {
+ dir := t.TempDir()
+ bin := filepath.Join(dir, "webbrain-companion")
+ _ = os.WriteFile(bin, []byte("new"), 0o755)
+ _ = os.WriteFile(filepath.Join(dir, ".webbrain-companion.old"), []byte("old"), 0o755)
+ _ = os.MkdirAll(filepath.Join(dir, ".wbc-update-1"), 0o755)
+ downloads := t.TempDir()
+ _ = os.MkdirAll(filepath.Join(downloads, "0.1.3"), 0o755)
+ _ = os.WriteFile(filepath.Join(downloads, "attempt.json"), []byte("{}"), 0o600)
+ Cleanup(bin, downloads, "0.1.3")
+ if entries, _ := os.ReadDir(dir); len(entries) != 1 {
+ t.Fatalf("the program's folder holds %v", names(entries))
+ }
+ if entries, _ := os.ReadDir(downloads); len(entries) != 1 || entries[0].Name() != "attempt.json" {
+ t.Fatalf("downloads hold %v; files such as the attempt record stay", names(entries))
+ }
+}
+
+func names(entries []os.DirEntry) []string {
+ var out []string
+ for _, e := range entries {
+ out = append(out, e.Name())
+ }
+ return out
+}
diff --git a/webbrain-systray/internal/update/install_unix.go b/webbrain-systray/internal/update/install_unix.go
new file mode 100644
index 000000000..d9fdd7a24
--- /dev/null
+++ b/webbrain-systray/internal/update/install_unix.go
@@ -0,0 +1,28 @@
+//go:build !windows
+
+package update
+
+import (
+ "errors"
+ "os"
+ "syscall"
+)
+
+// Exec replaces this process with exe. The process keeps its ID, session and
+// (under systemd) its unit, so nothing outside notices a new program; files
+// this process opened close, which also releases the single-instance lock. It
+// returns only when exe could not be started.
+func Exec(exe string, args ...string) error {
+ return syscall.Exec(exe, append([]string{exe}, args...), os.Environ())
+}
+
+func installedHere(string) error { return errors.New("the setup program exists only on Windows") }
+
+// StartInstaller runs the Windows setup program; other systems install in
+// place (Install).
+func StartInstaller(string, int) error {
+ return errors.New("the setup program exists only on Windows")
+}
+
+// StartSetup opens the Windows setup program; other systems install in place.
+func StartSetup(string) error { return errors.New("the setup program exists only on Windows") }
diff --git a/webbrain-systray/internal/update/install_windows.go b/webbrain-systray/internal/update/install_windows.go
new file mode 100644
index 000000000..536198b38
--- /dev/null
+++ b/webbrain-systray/internal/update/install_windows.go
@@ -0,0 +1,76 @@
+//go:build windows
+
+package update
+
+import (
+ "errors"
+ "fmt"
+ "os/exec"
+ "path/filepath"
+ "strconv"
+ "strings"
+ "syscall"
+
+ "golang.org/x/sys/windows/registry"
+)
+
+// uninstallKey is where packaging/windows/installer.nsi records the
+// installation.
+const uninstallKey = `Software\Microsoft\Windows\CurrentVersion\Uninstall\WebBrainCompanion`
+
+const (
+ createNewProcessGroup = 0x00000200
+ detachedProcess = 0x00000008
+)
+
+func detach(cmd *exec.Cmd) {
+ cmd.SysProcAttr = &syscall.SysProcAttr{CreationFlags: createNewProcessGroup | detachedProcess}
+}
+
+// installedHere checks that exe is the copy the setup program installed, which
+// the silent setup replaces.
+func installedHere(exe string) error {
+ k, err := registry.OpenKey(registry.CURRENT_USER, uninstallKey, registry.QUERY_VALUE)
+ if err != nil {
+ return errors.New("this copy was not installed with the setup program; download the new version by hand")
+ }
+ defer k.Close()
+ loc, _, err := k.GetStringValue("InstallLocation")
+ if err != nil || loc == "" {
+ return errors.New("this copy was not installed with the setup program; download the new version by hand")
+ }
+ dir := filepath.Dir(exe)
+ if !strings.EqualFold(filepath.Clean(loc), filepath.Clean(dir)) {
+ return fmt.Errorf("WebBrain Companion is installed in %s, but this copy runs from %s; download the new version by hand", loc, dir)
+ }
+ // The silent setup runs without administrator rights; a folder it cannot
+ // write (an installation made as administrator) would make it fail.
+ return writable(dir)
+}
+
+// Exec is how macOS and Linux start an installed update; on Windows the setup
+// program starts it.
+func Exec(string, ...string) error { return errors.New("not used on Windows") }
+
+// StartInstaller runs the setup program silently in update mode: it waits for
+// process pid (this companion, which quits next) to exit, installs over the
+// registered installation and starts the new version.
+func StartInstaller(setup string, pid int) error {
+ cmd := exec.Command(setup, "/S", "/UPDATE="+strconv.Itoa(pid))
+ detach(cmd)
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
+
+// StartSetup opens the setup program with its usual pages, for an update
+// started from the command line.
+func StartSetup(setup string) error {
+ cmd := exec.Command(setup)
+ detach(cmd)
+ if err := cmd.Start(); err != nil {
+ return err
+ }
+ return cmd.Process.Release()
+}
diff --git a/webbrain-systray/internal/update/update.go b/webbrain-systray/internal/update/update.go
new file mode 100644
index 000000000..902c32240
--- /dev/null
+++ b/webbrain-systray/internal/update/update.go
@@ -0,0 +1,331 @@
+// Package update keeps WebBrain Companion current. A new version is a
+// published (not draft, not pre-release) GitHub release of
+// webbrain-one/webbrain tagged systray-v<version>, as the WebBrain Companion
+// workflow creates it. Every release carries a SHA256SUMS file, and a package
+// is installed only when its checksum matches the one listed there.
+package update
+
+import (
+ "context"
+ "encoding/hex"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "time"
+
+ "github.com/esokullu/webbrain-systray/internal/download"
+)
+
+const (
+ // TagPrefix marks Companion releases among the repository's other releases.
+ TagPrefix = "systray-v"
+ // ReleasesPage lists every release, for downloading one by hand.
+ ReleasesPage = "https://github.com/webbrain-one/webbrain/releases"
+
+ defaultFeed = "https://api.github.com/repos/webbrain-one/webbrain/releases?per_page=100"
+ downloadHost = "github.com"
+ downloadPath = "/webbrain-one/webbrain/releases/download/"
+ userAgent = "WebBrain-Companion-Updater/1 (+https://webbrain.one/companion)"
+)
+
+// Asset is one file attached to a release.
+type Asset struct {
+ Name string `json:"name"`
+ URL string `json:"browser_download_url"`
+ Size int64 `json:"size"`
+}
+
+// Release is a newer version and the files this computer needs from it.
+type Release struct {
+ Version string
+ Page string
+ Package Asset // the package for this system
+ Sums Asset // the release's SHA256SUMS file
+}
+
+type ghRelease struct {
+ Tag string `json:"tag_name"`
+ Draft bool `json:"draft"`
+ Prerelease bool `json:"prerelease"`
+ Page string `json:"html_url"`
+ Assets []Asset `json:"assets"`
+}
+
+var client = &http.Client{
+ Timeout: 90 * time.Second,
+ Transport: &http.Transport{
+ Proxy: http.ProxyFromEnvironment,
+ ResponseHeaderTimeout: 30 * time.Second,
+ },
+}
+
+// feed returns the address of the release list. WBC_UPDATE_FEED points tests
+// at a server on this computer; any other address is ignored, so a changed
+// environment cannot send the companion to another host.
+func feed() (string, bool) {
+ if v := os.Getenv("WBC_UPDATE_FEED"); v != "" {
+ if u, err := url.Parse(v); err == nil && (u.Scheme == "http" || u.Scheme == "https") && loopback(u.Hostname()) {
+ return v, true
+ }
+ }
+ return defaultFeed, false
+}
+
+func loopback(host string) bool {
+ if strings.EqualFold(host, "localhost") {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+// allowedDownload accepts release files from the repository's own download
+// path (GitHub then redirects to its file storage), or from the local test
+// server.
+func allowedDownload(raw string, testFeed bool) bool {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return false
+ }
+ if testFeed {
+ return (u.Scheme == "http" || u.Scheme == "https") && loopback(u.Hostname())
+ }
+ return u.Scheme == "https" && u.Host == downloadHost && strings.HasPrefix(u.Path, downloadPath)
+}
+
+// ParseVersion reads a release version, major.minor.patch. Builds with a
+// suffix (a local "0.1.0-dev", CI's "0.0.0-abc1234") are not releases.
+func ParseVersion(s string) ([3]int, bool) {
+ var v [3]int
+ parts := strings.Split(s, ".")
+ if len(parts) != 3 {
+ return v, false
+ }
+ for i, p := range parts {
+ if p == "" || len(p) > 6 {
+ return v, false
+ }
+ n := 0
+ for _, c := range p {
+ if c < '0' || c > '9' {
+ return v, false
+ }
+ n = n*10 + int(c-'0')
+ }
+ v[i] = n
+ }
+ return v, true
+}
+
+// Newer reports whether release version a comes after b. It is false when
+// either is not a release version.
+func Newer(a, b string) bool {
+ va, okA := ParseVersion(a)
+ vb, okB := ParseVersion(b)
+ if !okA || !okB {
+ return false
+ }
+ for i := range va {
+ if va[i] != vb[i] {
+ return va[i] > vb[i]
+ }
+ }
+ return false
+}
+
+// PackageName is the release file that installs version on goos/goarch, as
+// scripts/build.sh names it.
+func PackageName(version, goos, goarch string) (string, bool) {
+ base := "WebBrain-Companion-" + version + "-"
+ switch goos {
+ case "windows":
+ return base + "windows-setup.exe", true
+ case "darwin":
+ return base + "macos-universal.zip", true
+ case "linux":
+ switch goarch {
+ case "amd64":
+ return base + "linux-x64.tar.gz", true
+ case "arm64":
+ return base + "linux-arm64.tar.gz", true
+ }
+ }
+ return "", false
+}
+
+func sumsName(version string) string { return "WebBrain-Companion-" + version + "-SHA256SUMS.txt" }
+
+func findAsset(assets []Asset, name string) (Asset, bool) {
+ for _, a := range assets {
+ if a.Name == name {
+ return a, true
+ }
+ }
+ return Asset{}, false
+}
+
+// Latest returns the newest published release after current that has a
+// package for this system, or nil when current is the newest.
+func Latest(ctx context.Context, current string) (*Release, error) {
+ return latest(ctx, current, runtime.GOOS, runtime.GOARCH)
+}
+
+// maxPages bounds how far back the release list is read. The repository's
+// other releases (the extension's) share the list, newest first.
+const maxPages = 10
+
+func latest(ctx context.Context, current, goos, goarch string) (*Release, error) {
+ feedURL, testFeed := feed()
+ var best *Release
+ next := feedURL
+ for page := 0; next != "" && page < maxPages; page++ {
+ list, link, err := fetchReleases(ctx, next)
+ if err != nil {
+ return nil, err
+ }
+ passed := false
+ for _, r := range list {
+ if r.Draft || r.Prerelease || !strings.HasPrefix(r.Tag, TagPrefix) {
+ continue
+ }
+ v := strings.TrimPrefix(r.Tag, TagPrefix)
+ if _, ok := ParseVersion(v); ok && !Newer(v, current) {
+ // Releases come newest first: from the running version on,
+ // nothing further down is newer.
+ passed = true
+ continue
+ }
+ if !Newer(v, current) || (best != nil && !Newer(v, best.Version)) {
+ continue
+ }
+ name, ok := PackageName(v, goos, goarch)
+ if !ok {
+ continue
+ }
+ pkg, okPkg := findAsset(r.Assets, name)
+ sums, okSums := findAsset(r.Assets, sumsName(v))
+ if !okPkg || !okSums || !allowedDownload(pkg.URL, testFeed) || !allowedDownload(sums.URL, testFeed) {
+ continue
+ }
+ best = &Release{Version: v, Page: r.Page, Package: pkg, Sums: sums}
+ }
+ if passed {
+ break
+ }
+ next = nextPage(link, feedURL)
+ }
+ return best, nil
+}
+
+func fetchReleases(ctx context.Context, pageURL string) ([]ghRelease, string, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, pageURL, nil)
+ if err != nil {
+ return nil, "", err
+ }
+ req.Header.Set("Accept", "application/vnd.github+json")
+ req.Header.Set("User-Agent", userAgent)
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, "", fmt.Errorf("release list: %w", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, "", fmt.Errorf("release list: %s", resp.Status)
+ }
+ var list []ghRelease
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 16<<20)).Decode(&list); err != nil {
+ return nil, "", fmt.Errorf("release list: %w", err)
+ }
+ return list, resp.Header.Get("Link"), nil
+}
+
+// nextPage returns the rel="next" address of a GitHub Link header when it
+// stays on the feed's own host.
+func nextPage(link, feedURL string) string {
+ feed, err := url.Parse(feedURL)
+ if err != nil {
+ return ""
+ }
+ for _, part := range strings.Split(link, ",") {
+ target, params, ok := strings.Cut(strings.TrimSpace(part), ";")
+ if !ok || !strings.Contains(params, `rel="next"`) {
+ continue
+ }
+ u, err := url.Parse(strings.Trim(strings.TrimSpace(target), "<>"))
+ if err != nil || u.Scheme != feed.Scheme || u.Host != feed.Host {
+ return ""
+ }
+ return u.String()
+ }
+ return ""
+}
+
+// ParseSums reads sha256sum output: "<hex> <name>" or "<hex> *<name>".
+func ParseSums(data []byte) map[string]string {
+ out := map[string]string{}
+ for _, line := range strings.Split(string(data), "\n") {
+ sum, name, ok := strings.Cut(strings.TrimSpace(line), " ")
+ if !ok || len(sum) != 64 {
+ continue
+ }
+ if _, err := hex.DecodeString(sum); err != nil {
+ continue
+ }
+ name = strings.TrimPrefix(strings.TrimSpace(name), "*")
+ if name != "" {
+ out[name] = strings.ToLower(sum)
+ }
+ }
+ return out
+}
+
+func fetchSmall(ctx context.Context, rawURL string, limit int64) ([]byte, error) {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("User-Agent", userAgent)
+ resp, err := client.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusOK {
+ return nil, errors.New(resp.Status)
+ }
+ data, err := io.ReadAll(io.LimitReader(resp.Body, limit+1))
+ if err != nil {
+ return nil, err
+ }
+ if int64(len(data)) > limit {
+ return nil, errors.New("file is larger than expected")
+ }
+ return data, nil
+}
+
+// Download fetches rel's package into dir and checks it against the
+// release's SHA256SUMS. A package already there and intact is reused. It
+// returns the package's path.
+func Download(ctx context.Context, rel *Release, dir string, onProgress func(download.Progress)) (string, error) {
+ sums, err := fetchSmall(ctx, rel.Sums.URL, 64<<10)
+ if err != nil {
+ return "", fmt.Errorf("checksums: %w", err)
+ }
+ want := ParseSums(sums)[rel.Package.Name]
+ if want == "" {
+ return "", fmt.Errorf("%s is not listed in %s", rel.Package.Name, rel.Sums.Name)
+ }
+ dest := filepath.Join(dir, rel.Package.Name)
+ if err := download.File(ctx, rel.Package.URL, dest, rel.Package.Size, want, onProgress); err != nil {
+ return "", err
+ }
+ return dest, nil
+}
diff --git a/webbrain-systray/internal/update/update_test.go b/webbrain-systray/internal/update/update_test.go
new file mode 100644
index 000000000..e2ccbb5b0
--- /dev/null
+++ b/webbrain-systray/internal/update/update_test.go
@@ -0,0 +1,268 @@
+package update
+
+import (
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "strings"
+ "testing"
+)
+
+func TestVersions(t *testing.T) {
+ for _, tc := range []struct {
+ a, b string
+ newer bool
+ }{
+ {"0.1.3", "0.1.2", true},
+ {"0.2.0", "0.1.9", true},
+ {"1.0.0", "0.99.99", true},
+ {"0.1.10", "0.1.9", true},
+ {"0.1.2", "0.1.2", false},
+ {"0.1.1", "0.1.2", false},
+ // Development and CI builds never update, and never count as releases.
+ {"0.1.3", "0.1.0-dev", false},
+ {"0.1.3", "0.0.0-abc1234", false},
+ {"0.1.3-rc1", "0.1.2", false},
+ {"0.1", "0.0.9", false},
+ } {
+ if got := Newer(tc.a, tc.b); got != tc.newer {
+ t.Errorf("Newer(%q, %q) = %v, want %v", tc.a, tc.b, got, tc.newer)
+ }
+ }
+}
+
+func TestPackageNames(t *testing.T) {
+ for _, tc := range []struct{ goos, goarch, want string }{
+ {"darwin", "arm64", "WebBrain-Companion-0.1.3-macos-universal.zip"},
+ {"darwin", "amd64", "WebBrain-Companion-0.1.3-macos-universal.zip"},
+ {"windows", "amd64", "WebBrain-Companion-0.1.3-windows-setup.exe"},
+ {"windows", "arm64", "WebBrain-Companion-0.1.3-windows-setup.exe"},
+ {"linux", "amd64", "WebBrain-Companion-0.1.3-linux-x64.tar.gz"},
+ {"linux", "arm64", "WebBrain-Companion-0.1.3-linux-arm64.tar.gz"},
+ } {
+ if got, ok := PackageName("0.1.3", tc.goos, tc.goarch); !ok || got != tc.want {
+ t.Errorf("PackageName(%s/%s) = %q, %v; want %q", tc.goos, tc.goarch, got, ok, tc.want)
+ }
+ }
+ if _, ok := PackageName("0.1.3", "linux", "386"); ok {
+ t.Error("linux/386 has no package")
+ }
+}
+
+func TestParseSums(t *testing.T) {
+ a := strings.Repeat("ab", 32)
+ b := strings.Repeat("CD", 32)
+ sums := ParseSums([]byte(a + " WebBrain-Companion-0.1.3-linux-x64.tar.gz\n" + b + " *WebBrain-Companion-0.1.3-windows-setup.exe\nnot a line\n"))
+ if sums["WebBrain-Companion-0.1.3-linux-x64.tar.gz"] != a || sums["WebBrain-Companion-0.1.3-windows-setup.exe"] != strings.ToLower(b) || len(sums) != 2 {
+ t.Fatalf("ParseSums = %v", sums)
+ }
+}
+
+func TestFeedOverrideStaysOnThisComputer(t *testing.T) {
+ t.Setenv("WBC_UPDATE_FEED", "https://example.com/releases")
+ if got, test := feed(); got != defaultFeed || test {
+ t.Fatalf("feed() = %q, %v; a non-loopback override must be ignored", got, test)
+ }
+ t.Setenv("WBC_UPDATE_FEED", "http://127.0.0.1:9/releases")
+ if got, test := feed(); got != "http://127.0.0.1:9/releases" || !test {
+ t.Fatalf("feed() = %q, %v", got, test)
+ }
+ if !allowedDownload("https://github.com/webbrain-one/webbrain/releases/download/systray-v0.1.3/x.zip", false) {
+ t.Error("the repository's release download path must be accepted")
+ }
+ for _, u := range []string{
+ "http://github.com/webbrain-one/webbrain/releases/download/systray-v0.1.3/x.zip",
+ "https://github.com/someone/else/releases/download/systray-v0.1.3/x.zip",
+ "https://example.com/webbrain-one/webbrain/releases/download/x.zip",
+ "http://127.0.0.1/x.zip",
+ } {
+ if allowedDownload(u, false) {
+ t.Errorf("allowedDownload(%q) = true", u)
+ }
+ }
+}
+
+// releaseServer serves a GitHub-like release list and the files it names.
+type releaseServer struct {
+ *httptest.Server
+ files map[string][]byte
+}
+
+func newReleaseServer(t *testing.T, build func(base string) []ghRelease) *releaseServer {
+ t.Helper()
+ rs := &releaseServer{files: map[string][]byte{}}
+ rs.Server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/releases" {
+ if r.Header.Get("User-Agent") == "" {
+ http.Error(w, "GitHub requires a User-Agent", http.StatusForbidden)
+ return
+ }
+ _ = json.NewEncoder(w).Encode(build(rs.URL))
+ return
+ }
+ data, ok := rs.files[strings.TrimPrefix(r.URL.Path, "/files/")]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ _, _ = w.Write(data)
+ }))
+ t.Cleanup(rs.Close)
+ t.Setenv("WBC_UPDATE_FEED", rs.URL+"/releases")
+ return rs
+}
+
+func assetsFor(base string, names ...string) []Asset {
+ var out []Asset
+ for _, n := range names {
+ out = append(out, Asset{Name: n, URL: base + "/files/" + n})
+ }
+ return out
+}
+
+func TestLatestPicksNewestPublishedCompanionRelease(t *testing.T) {
+ pkg := func(v string) string { n, _ := PackageName(v, "linux", "amd64"); return n }
+ newReleaseServer(t, func(base string) []ghRelease {
+ return []ghRelease{
+ {Tag: "v45.0.0", Page: base + "/ext", Assets: assetsFor(base, pkg("45.0.0"), sumsName("45.0.0"))},
+ {Tag: "systray-v0.1.5", Prerelease: true, Assets: assetsFor(base, pkg("0.1.5"), sumsName("0.1.5"))},
+ {Tag: "systray-v0.1.4", Draft: true, Assets: assetsFor(base, pkg("0.1.4"), sumsName("0.1.4"))},
+ {Tag: "systray-v0.2.0", Assets: assetsFor(base, pkg("0.2.0"))}, // no SHA256SUMS
+ {Tag: "systray-v0.1.3", Page: base + "/0.1.3", Assets: assetsFor(base, pkg("0.1.3"), sumsName("0.1.3"), "WebBrain-Companion-0.1.3-macos-universal.zip")},
+ {Tag: "systray-v0.1.2", Assets: assetsFor(base, pkg("0.1.2"), sumsName("0.1.2"))},
+ }
+ })
+ rel, err := latest(context.Background(), "0.1.2", "linux", "amd64")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rel == nil || rel.Version != "0.1.3" || rel.Package.Name != pkg("0.1.3") || rel.Sums.Name != sumsName("0.1.3") {
+ t.Fatalf("latest = %+v, want 0.1.3", rel)
+ }
+ if rel, err := latest(context.Background(), "0.1.3", "linux", "amd64"); err != nil || rel != nil {
+ t.Fatalf("on the newest version: %+v, %v", rel, err)
+ }
+ if rel, err := latest(context.Background(), "0.1.0-dev", "linux", "amd64"); err != nil || rel != nil {
+ t.Fatalf("a development build must not update: %+v, %v", rel, err)
+ }
+ // A release without this system's package is skipped.
+ if rel, err := latest(context.Background(), "0.1.2", "linux", "arm64"); err != nil || rel != nil {
+ t.Fatalf("linux/arm64 has no package here: %+v, %v", rel, err)
+ }
+}
+
+func TestLatestReportsServerErrors(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ http.Error(w, "rate limited", http.StatusForbidden)
+ }))
+ defer server.Close()
+ t.Setenv("WBC_UPDATE_FEED", server.URL)
+ if _, err := latest(context.Background(), "0.1.2", "linux", "amd64"); err == nil || !strings.Contains(err.Error(), "403") {
+ t.Fatalf("err = %v, want the HTTP status", err)
+ }
+}
+
+func TestDownloadChecksThePackage(t *testing.T) {
+ body := []byte("the new companion")
+ sum := sha256.Sum256(body)
+ name, _ := PackageName("0.1.3", "linux", "amd64")
+ rs := newReleaseServer(t, func(string) []ghRelease { return nil })
+ rs.files[name] = body
+ rs.files[sumsName("0.1.3")] = []byte(fmt.Sprintf("%s %s\n", hex.EncodeToString(sum[:]), name))
+ rel := &Release{
+ Version: "0.1.3",
+ Package: Asset{Name: name, URL: rs.URL + "/files/" + name, Size: int64(len(body))},
+ Sums: Asset{Name: sumsName("0.1.3"), URL: rs.URL + "/files/" + sumsName("0.1.3")},
+ }
+ dir := t.TempDir()
+ path, err := Download(context.Background(), rel, dir, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, _ := os.ReadFile(path); string(got) != string(body) {
+ t.Fatalf("downloaded %q", got)
+ }
+
+ // A package that does not match its checksum is refused and removed.
+ rs.files[name] = []byte("tampered companion")
+ rel.Package.Size = int64(len(rs.files[name]))
+ other := t.TempDir()
+ if _, err := Download(context.Background(), rel, other, nil); err == nil || !strings.Contains(err.Error(), "checksum") {
+ t.Fatalf("err = %v, want a checksum mismatch", err)
+ }
+ if entries, _ := os.ReadDir(other); len(entries) != 0 {
+ t.Fatalf("a refused package was left behind: %v", entries)
+ }
+
+ // A package missing from SHA256SUMS is refused.
+ rs.files[sumsName("0.1.3")] = []byte(fmt.Sprintf("%s something-else\n", hex.EncodeToString(sum[:])))
+ if _, err := Download(context.Background(), rel, t.TempDir(), nil); err == nil || !strings.Contains(err.Error(), "not listed") {
+ t.Fatalf("err = %v, want not listed", err)
+ }
+}
+
+// Extension releases share the list: the Companion release may sit on a later
+// page, and reading stops once the running version's release has passed.
+func TestLatestReadsLaterPages(t *testing.T) {
+ pkg := func(v string) string { n, _ := PackageName(v, "linux", "amd64"); return n }
+ var base string
+ var pages []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ page := r.URL.Query().Get("page")
+ pages = append(pages, page)
+ var list []ghRelease
+ switch page {
+ case "":
+ w.Header().Set("Link", fmt.Sprintf(`<%s/releases?page=2>; rel="next", <%s/releases?page=3>; rel="last"`, base, base))
+ for i := 0; i < 100; i++ {
+ list = append(list, ghRelease{Tag: fmt.Sprintf("v46.0.%d", i)})
+ }
+ case "2":
+ w.Header().Set("Link", fmt.Sprintf(`<%s/releases?page=3>; rel="next"`, base))
+ list = []ghRelease{
+ {Tag: "systray-v0.1.3", Assets: assetsFor(base, pkg("0.1.3"), sumsName("0.1.3"))},
+ {Tag: "v45.0.0"},
+ {Tag: "systray-v0.1.2", Assets: assetsFor(base, pkg("0.1.2"), sumsName("0.1.2"))},
+ }
+ default:
+ t.Errorf("read page %q after passing the running version", page)
+ }
+ _ = json.NewEncoder(w).Encode(list)
+ }))
+ defer server.Close()
+ base = server.URL
+ t.Setenv("WBC_UPDATE_FEED", server.URL+"/releases")
+ rel, err := latest(context.Background(), "0.1.2", "linux", "amd64")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if rel == nil || rel.Version != "0.1.3" {
+ t.Fatalf("latest = %+v, want 0.1.3 from the second page", rel)
+ }
+ if len(pages) != 2 {
+ t.Fatalf("read pages %q", pages)
+ }
+}
+
+func TestNextPageStaysOnTheFeedHost(t *testing.T) {
+ feed := "https://api.github.com/repos/webbrain-one/webbrain/releases?per_page=100"
+ next := "https://api.github.com/repositories/1/releases?per_page=100&page=2"
+ if got := nextPage(`<`+next+`>; rel="next", <https://api.github.com/repositories/1/releases?page=9>; rel="last"`, feed); got != next {
+ t.Fatalf("nextPage = %q", got)
+ }
+ for _, link := range []string{
+ `<https://example.com/releases?page=2>; rel="next"`,
+ `<http://api.github.com/releases?page=2>; rel="next"`,
+ `<https://api.github.com/releases?page=9>; rel="last"`,
+ ``,
+ } {
+ if got := nextPage(link, feed); got != "" {
+ t.Errorf("nextPage(%q) = %q", link, got)
+ }
+ }
+}
diff --git a/webbrain-systray/main.go b/webbrain-systray/main.go
index 0a22ea303..cc4d3c859 100644
--- a/webbrain-systray/main.go
+++ b/webbrain-systray/main.go
@@ -5,10 +5,12 @@
package main
import (
+ "context"
"encoding/json"
"errors"
"flag"
"fmt"
+ "io"
"net/http"
"os"
"os/signal"
@@ -26,6 +28,7 @@ import (
"github.com/esokullu/webbrain-systray/internal/paths"
"github.com/esokullu/webbrain-systray/internal/settings"
"github.com/esokullu/webbrain-systray/internal/tray"
+ "github.com/esokullu/webbrain-systray/internal/update"
)
var version = "0.1.0-dev"
@@ -86,6 +89,66 @@ func waitForInstance(timeout time.Duration) (int, settings.Settings, bool) {
}
}
+// acquireLock takes the single-instance lock, retrying for up to wait while
+// another process holds it.
+func acquireLock(path string, wait time.Duration) (*instance.Lock, error) {
+ deadline := time.Now().Add(wait)
+ for {
+ l, err := instance.TryAcquire(path)
+ if !errors.Is(err, instance.ErrHeld) || !time.Now().Before(deadline) {
+ return l, err
+ }
+ time.Sleep(250 * time.Millisecond)
+ }
+}
+
+// runUpdate installs the newest release over this copy from the command line
+// (servers and --headless setups, where the companion does not replace
+// itself). A running companion keeps its old files until it restarts.
+func runUpdate(stdout, stderr io.Writer) int {
+ if _, ok := update.ParseVersion(version); !ok {
+ fmt.Fprintf(stderr, "WebBrain Companion %s is a development build; it does not update.\n", version)
+ return 1
+ }
+ ctx := context.Background()
+ rel, err := update.Latest(ctx, version)
+ if err != nil {
+ fmt.Fprintln(stderr, "update check failed:", err)
+ return 1
+ }
+ if rel == nil {
+ fmt.Fprintf(stdout, "WebBrain Companion %s is the newest version.\n", version)
+ return 0
+ }
+ exe := osutil.Executable()
+ target, err := update.Locate(exe)
+ if err != nil {
+ fmt.Fprintln(stderr, err)
+ fmt.Fprintln(stderr, "Download it from", rel.Page)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Downloading WebBrain Companion %s…\n", rel.Version)
+ pkg, err := update.Download(ctx, rel, filepath.Join(paths.Updates(), rel.Version), nil)
+ if err != nil {
+ fmt.Fprintln(stderr, "download failed:", err)
+ return 1
+ }
+ if target.Kind == "installer" {
+ if err := update.StartSetup(pkg); err != nil {
+ fmt.Fprintln(stderr, "could not open the setup program:", err)
+ return 1
+ }
+ fmt.Fprintln(stdout, "The setup program is open; it closes a running companion and installs the new version.")
+ return 0
+ }
+ if err := update.Install(pkg, target); err != nil {
+ fmt.Fprintln(stderr, "install failed:", err)
+ return 1
+ }
+ fmt.Fprintf(stdout, "Installed WebBrain Companion %s. Restart the companion to use it.\n", rel.Version)
+ return 0
+}
+
func isTerminal() bool {
st, err := os.Stdout.Stat()
return err == nil && st.Mode()&os.ModeCharDevice != 0
@@ -96,6 +159,8 @@ func main() {
background := flag.Bool("background", false, "started at login: do not open the panel")
_ = flag.Bool("panel", false, "open the panel (the default unless --background)")
showVersion := flag.Bool("version", false, "print the version and exit")
+ updateNow := flag.Bool("update", false, "install the newest version over this copy and exit")
+ afterUpdate := flag.Bool("after-update", false, "started by an update: wait for the previous version to quit")
flag.Parse()
if *showVersion {
fmt.Println("WebBrain Companion", version)
@@ -105,7 +170,16 @@ func main() {
fmt.Fprintln(os.Stderr, "cannot create data folders:", err)
os.Exit(1)
}
- instanceLock, err := instance.TryAcquire(paths.LockFile())
+ if *updateNow {
+ os.Exit(runUpdate(os.Stdout, os.Stderr))
+ }
+ timeout := time.Duration(0)
+ if *afterUpdate {
+ // The previous version quits right after starting this one; it holds
+ // the lock until its servers have stopped.
+ timeout = 2 * time.Minute
+ }
+ instanceLock, err := acquireLock(paths.LockFile(), timeout)
if errors.Is(err, instance.ErrHeld) {
if port, s, ok := waitForInstance(15 * time.Second); ok {
if !*background {
@@ -133,6 +207,15 @@ func main() {
os.Exit(1)
}
a := app.New(version, store)
+ a.Headless = *headless
+ // Quit is set before Start: the update loop that Start launches calls it.
+ headlessQuit := make(chan struct{})
+ if *headless {
+ var once sync.Once
+ a.Quit = func() { once.Do(func() { close(headlessQuit) }) }
+ } else {
+ a.Quit = tray.Quit
+ }
writeRuntime := func(port int) {
data, _ := json.Marshal(runtimeInfo{PID: os.Getpid(), Port: port})
_ = os.WriteFile(runtimeFile(), data, 0o600)
@@ -157,6 +240,13 @@ func main() {
shutdownOnce.Do(func() {
a.Shutdown()
_ = os.Remove(runtimeFile())
+ if a.RestartPending() {
+ // An installed update takes over this process (macOS, Linux).
+ // It runs here because the macOS tray ends the process right
+ // after this function.
+ _ = instanceLock.Close()
+ a.Restart()
+ }
})
}
sig := make(chan os.Signal, 1)
@@ -170,12 +260,9 @@ 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(""))
- quit := make(chan struct{})
- var once sync.Once
- a.Quit = func() { once.Do(func() { close(quit) }) }
select {
case <-sig:
- case <-quit:
+ case <-headlessQuit:
}
shutdown()
return
@@ -183,7 +270,6 @@ func main() {
tray.SetOnTap(func() { open("") })
a.OnChange = tray.Refresh
- a.Quit = tray.Quit
go func() {
<-sig
tray.Quit()
diff --git a/webbrain-systray/main_test.go b/webbrain-systray/main_test.go
index 558627191..c699e3dbf 100644
--- a/webbrain-systray/main_test.go
+++ b/webbrain-systray/main_test.go
@@ -2,14 +2,17 @@ package main
import (
"encoding/json"
+ "errors"
"net"
"net/http"
"net/http/httptest"
"os"
+ "path/filepath"
"strconv"
"testing"
"time"
+ "github.com/esokullu/webbrain-systray/internal/instance"
"github.com/esokullu/webbrain-systray/internal/paths"
"github.com/esokullu/webbrain-systray/internal/settings"
)
@@ -71,3 +74,28 @@ func TestExistingInstanceRejectsAnotherInstallation(t *testing.T) {
t.Fatalf("accepted unrelated companion on port %d", got)
}
}
+
+// A version started by an update waits for the previous one to quit.
+func TestAcquireLockWaitsForThePreviousVersion(t *testing.T) {
+ path := filepath.Join(t.TempDir(), "companion.lock")
+ previous, err := instance.TryAcquire(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := acquireLock(path, 0); !errors.Is(err, instance.ErrHeld) {
+ t.Fatalf("without waiting: err = %v, want ErrHeld", err)
+ }
+ go func() {
+ time.Sleep(400 * time.Millisecond)
+ _ = previous.Close()
+ }()
+ started := time.Now()
+ next, err := acquireLock(path, 5*time.Second)
+ if err != nil {
+ t.Fatalf("after the previous version quit: %v", err)
+ }
+ defer next.Close()
+ if waited := time.Since(started); waited < 300*time.Millisecond {
+ t.Fatalf("took the lock after %v, while the previous version still held it", waited)
+ }
+}
diff --git a/webbrain-systray/packaging/windows/installer.nsi b/webbrain-systray/packaging/windows/installer.nsi
index 7ed1e824c..17abd84d3 100644
--- a/webbrain-systray/packaging/windows/installer.nsi
+++ b/webbrain-systray/packaging/windows/installer.nsi
@@ -60,10 +60,50 @@ LangString FinishText ${LANG_TURKISH} "WebBrain Companion, saatin yanındaki bil
LangString RemoveData ${LANG_ENGLISH} "Also delete your WebBrain Companion settings, sign-ins and downloaded models?"
LangString RemoveData ${LANG_TURKISH} "WebBrain Companion ayarların, girişlerin ve indirilen modeller de silinsin mi?"
+; Automatic updates run this program silently as
+; setup.exe /S /UPDATE=<pid>
+; where <pid> is the companion that downloaded the update. It quits by itself
+; after starting this program; the new version starts when installing is done.
+Var UpdatePID
+
+; A file that cannot be written stops the installation instead of being
+; skipped, which in silent mode would leave the old program and a new version
+; number behind.
+AllowSkipFiles off
+
+Function .onInit
+ ${GetParameters} $R0
+ ClearErrors
+ ${GetOptions} $R0 "/UPDATE=" $UpdatePID
+ ${If} ${Errors}
+ StrCpy $UpdatePID ""
+ ${EndIf}
+FunctionEnd
+
+; An update that could not finish starts the version that is in place, which
+; reports the failure and does not retry it by itself.
+Function .onInstFailed
+ ${If} $UpdatePID != ""
+ Exec '"$INSTDIR\${EXE}" --background --after-update'
+ ${EndIf}
+FunctionEnd
+
; Stops a running copy (and the local model server it started) so its files
; can be replaced.
!macro CloseRunning
- nsExec::Exec 'taskkill /F /T /IM "${EXE}"'
+ ${If} $UpdatePID != ""
+ ; Wait up to a minute for the companion that started the update to stop
+ ; its local model server and quit, then stop any copy still running. No /T
+ ; here: this program is that companion's child, and /T would stop it too.
+ System::Call 'kernel32::OpenProcess(i 0x00100000, i 0, i $UpdatePID) p .r0'
+ ${If} $0 <> 0
+ System::Call 'kernel32::WaitForSingleObject(p r0, i 60000) i .r1'
+ System::Call 'kernel32::CloseHandle(p r0)'
+ ${EndIf}
+ nsExec::Exec 'taskkill /F /IM "${EXE}"'
+ ${Else}
+ nsExec::Exec 'taskkill /F /T /IM "${EXE}"'
+ ${EndIf}
Pop $0
Sleep 600
!macroend
@@ -95,6 +135,11 @@ Section "Install"
${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2
IntFmt $0 "0x%08X" $0
WriteRegDWORD HKCU "${UNINSTKEY}" "EstimatedSize" "$0"
+
+ ${If} $UpdatePID != ""
+ ; Start the new version the way the companion starts at login.
+ Exec '"$INSTDIR\${EXE}" --background --after-update'
+ ${EndIf}
SectionEnd
Section "Uninstall"