From 92b811be4dbe7a2de1db8fd73d2f1d47a07bc277 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Tue, 3 Nov 2026 20:11:40 +0100 Subject: [PATCH] Check for updates once a day and show a note when there is one lazygit currently checks for updates only when the user presses `u` in the status panel. We want users to learn about a new release within a day. Check at startup if the last successful check is at least update.days ago, and change the default from 14 days to 1. Also check every hour whether a check is due, so that users who keep lazygit running for days get the check too. Do all of this on a worker, with a timeout. When a check finds a newer version, show "Update available" before the version in the bottom-right corner. Clicking it opens the update menu. After an update is installed, the note says "Restart to use ". The result of a check goes into state.yml, so a lazygit that starts later on the same day shows the note without asking GitHub again. For the same reason, other running instances see the result the next time they look at the file. Builds that can't check for updates, and users who set update.method to never, don't get any of this. Co-Authored-By: Claude Opus 5.5 --- docs-master/Config.md | 2 +- pkg/config/app_state.go | 6 +- pkg/config/user_config.go | 2 +- pkg/gui/background.go | 8 ++ pkg/gui/controllers/helpers/update_helper.go | 58 +++++++- pkg/gui/gui.go | 4 + pkg/gui/information_panel.go | 7 +- pkg/i18n/english.go | 4 + pkg/updates/updates.go | 105 ++++++++++++-- pkg/updates/updates_test.go | 139 +++++++++++++++++-- schema-master/config.json | 2 +- 11 files changed, 308 insertions(+), 29 deletions(-) diff --git a/docs-master/Config.md b/docs-master/Config.md index d8de794be..d1c6b8f20 100644 --- a/docs-master/Config.md +++ b/docs-master/Config.md @@ -591,7 +591,7 @@ update: method: prompt # Period in days between update checks - days: 14 + days: 1 # Background refreshes refresher: diff --git a/pkg/config/app_state.go b/pkg/config/app_state.go index 20e918ff9..6a4e1bb58 100644 --- a/pkg/config/app_state.go +++ b/pkg/config/app_state.go @@ -235,7 +235,6 @@ func writeAndClose(file *os.File, content []byte) error { // AppState stores data between runs of the app like when the last update check // was performed and which other repos have been checked out type AppState struct { - LastUpdateCheck int64 RecentRepos []string StartupPopupVersion int LastVersion string // this is the last version the user was using, for the purpose of showing release notes @@ -251,6 +250,11 @@ type AppState struct { // UpdatesState is what lazygit remembers about updates type UpdatesState struct { + // When the last successful check for an update happened (Unix time), and + // the latest version that it found + LastCheck int64 + LatestVersion string + // The version that an update installed in place of the executable at // InstalledPath. It takes effect when lazygit is restarted. InstalledVersion string diff --git a/pkg/config/user_config.go b/pkg/config/user_config.go index 095509e07..fadd30cec 100644 --- a/pkg/config/user_config.go +++ b/pkg/config/user_config.go @@ -1005,7 +1005,7 @@ func GetDefaultConfigForPlatform(platform string) *UserConfig { }, Update: UpdateConfig{ Method: "prompt", - Days: 14, + Days: 1, }, ConfirmOnQuit: false, QuitOnTopLevelReturn: false, diff --git a/pkg/gui/background.go b/pkg/gui/background.go index 6a4c529a1..86fce576f 100644 --- a/pkg/gui/background.go +++ b/pkg/gui/background.go @@ -80,6 +80,14 @@ func (self *BackgroundRoutineMgr) startBackgroundRoutines() { } } + // The check itself happens at most once a day (see update.days); checking + // every hour whether it is due makes sure that it happens even if lazygit + // keeps running for days. + self.goEvery(time.Hour, self.gui.stopChan, nil, func(_ bool) error { + self.gui.helpers.Update.CheckForUpdateInBackground() + return nil + }) + if self.gui.Config.GetDebug() { self.goEvery(time.Second*time.Duration(10), self.gui.stopChan, nil, func(_ bool) error { formatBytes := func(b uint64) string { diff --git a/pkg/gui/controllers/helpers/update_helper.go b/pkg/gui/controllers/helpers/update_helper.go index 61caa7641..30194f23c 100644 --- a/pkg/gui/controllers/helpers/update_helper.go +++ b/pkg/gui/controllers/helpers/update_helper.go @@ -25,13 +25,69 @@ func NewUpdateHelper(c *HelperCommon, updater *updates.Updater) *UpdateHelper { } } +// The link of the note that tells the user about an update +const UpdateNoteLink = "lazygit-update:" + func (self *UpdateHelper) OnStartup() { self.c.OnWorkerBackground(func(gocui.Task) error { self.updater.CleanUpAfterUpdate() + self.CheckForUpdateInBackground() return nil }) } +// CheckForUpdateInBackground checks for an update if one is due, and shows the +// result in the note in the bottom-right corner. Call it on a worker. +func (self *UpdateHelper) CheckForUpdateInBackground() { + if err := self.updater.CheckForUpdateIfDue(); err != nil { + self.c.Log.Errorf("Error checking for an update: %v", err) + } + self.rerenderNote() +} + +func (self *UpdateHelper) rerenderNote() { + // The information view is rendered in every layout, so we only need to + // trigger one + self.c.OnUIThreadBackground(func() error { return nil }) +} + +// Note returns the note that tells the user about an update, for the bottom-right +// corner, or "" if there's nothing to tell +func (self *UpdateHelper) Note() string { + if !self.updater.ChecksEnabled() { + return "" + } + + status := self.updater.Status() + if status.InstalledVersion != nil { + return style.FgGreen.Sprint(utils.ResolvePlaceholderString( + self.c.Tr.RestartToUseNewVersion, map[string]string{"newVersion": status.InstalledVersion.String()}, + )) + } + if status.AvailableVersion != nil { + return style.FgGreen.Sprint(style.PrintHyperlink(self.c.Tr.UpdateAvailableNote, UpdateNoteLink)) + } + return "" +} + +// ShowUpdateMenu shows the menu for the update that the note in the +// bottom-right corner tells the user about +func (self *UpdateHelper) ShowUpdateMenu() error { + status := self.updater.Status() + if status.AvailableVersion == nil || status.InstalledVersion != nil { + return nil + } + + self.c.OnWorker(func(gocui.Task) error { + menuOpts := self.updateMenuOptions(status.AvailableVersion) + self.c.OnUIThread(func() error { + return self.c.Menu(menuOpts) + }) + return nil + }) + return nil +} + func (self *UpdateHelper) CheckForUpdateDisabledReason() *types.DisabledReason { if self.updater.Installation().Kind == updates.InstallKindDevBuild { return &types.DisabledReason{ @@ -72,7 +128,7 @@ func (self *UpdateHelper) CheckForUpdateInForeground() error { return nil } - if installedVersion := self.updater.InstalledVersion(); installedVersion != nil && !installedVersion.IsOlderThan(newVersion) { + if installedVersion := self.updater.Status().InstalledVersion; installedVersion != nil && !installedVersion.IsOlderThan(newVersion) { self.c.OnUIThread(func() error { self.c.Toast(self.updateInstalledMessage(installedVersion)) return nil diff --git a/pkg/gui/gui.go b/pkg/gui/gui.go index 429d23acd..f51d3a95e 100644 --- a/pkg/gui/gui.go +++ b/pkg/gui/gui.go @@ -412,6 +412,10 @@ func (gui *Gui) onNewRepo(startArgs appTypes.StartArgs, contextKey types.Context return gui.helpers.Diff.EditFilesOfDiff([]string{filepath}) } + if url == helpers.UpdateNoteLink { + return gui.helpers.Update.ShowUpdateMenu() + } + if entry, ok := strings.CutPrefix(url, helpers.DiffStatLinkScheme); ok { view, err := gui.g.View(viewname) if err != nil { diff --git a/pkg/gui/information_panel.go b/pkg/gui/information_panel.go index a5977336a..a9b84d35e 100644 --- a/pkg/gui/information_panel.go +++ b/pkg/gui/information_panel.go @@ -9,7 +9,12 @@ func (gui *Gui) informationStr() string { return activeMode.InfoLabel() } - return gui.Config.GetVersion() + version := gui.Config.GetVersion() + if note := gui.helpers.Update.Note(); note != "" { + version = note + " " + version + } + + return version } func (gui *Gui) handleInfoClick() error { diff --git a/pkg/i18n/english.go b/pkg/i18n/english.go index c2d91e972..59c9f516b 100644 --- a/pkg/i18n/english.go +++ b/pkg/i18n/english.go @@ -287,6 +287,8 @@ type TranslationSet struct { InstallingUpdateStatus string UpdateInstalled string UpdateInstallFailed string + UpdateAvailableNote string + RestartToUseNewVersion string IntroPopupMessage string NonReloadableConfigWarningTitle string NonReloadableConfigWarning string @@ -1521,6 +1523,8 @@ func EnglishTranslationSet() *TranslationSet { InstallingUpdateStatus: "Installing {{.newVersion}}", UpdateInstalled: "lazygit {{.newVersion}} is installed. It takes effect the next time you start lazygit.", UpdateInstallFailed: "Couldn't install lazygit {{.newVersion}}: {{.error}}", + UpdateAvailableNote: "Update available", + RestartToUseNewVersion: "Restart to use {{.newVersion}}", IntroPopupMessage: englishIntroPopupMessage, NonReloadableConfigWarningTitle: "Config changed", NonReloadableConfigWarning: englishNonReloadableConfigWarning, diff --git a/pkg/updates/updates.go b/pkg/updates/updates.go index 57df85791..c9b332e0a 100644 --- a/pkg/updates/updates.go +++ b/pkg/updates/updates.go @@ -43,6 +43,9 @@ type Updater struct { installing atomic.Bool + statusMutex sync.Mutex + status Status + // Held while we replace the executable, so that lazygit doesn't exit in // the middle of it replaceMutex sync.Mutex @@ -83,6 +86,40 @@ func (u *Updater) CurrentVersion() *types.VersionNumber { return u.currentVersion } +// Status is what lazygit knows about updates +type Status struct { + // The latest release that a check found, if it is newer than the running + // lazygit + AvailableVersion *types.VersionNumber + // The version that an update installed in place of the running lazygit. + // This lazygit, or another one running from the same executable, can have + // installed it. The new version takes effect when lazygit is restarted. + InstalledVersion *types.VersionNumber +} + +// ChecksEnabled returns whether lazygit checks for updates regularly +func (u *Updater) ChecksEnabled() bool { + return u.installation.Kind != InstallKindDevBuild && u.UserConfig().Update.Method != "never" +} + +// CheckForUpdateIfDue checks for an update if lazygit checks regularly, and +// the last successful check is long enough ago. +func (u *Updater) CheckForUpdateIfDue() error { + if !u.ChecksEnabled() { + return nil + } + + state := u.readAppState() + interval := time.Duration(u.UserConfig().Update.Days) * 24 * time.Hour + if time.Since(time.Unix(state.Updates.LastCheck, 0)) < interval { + u.RefreshStatus() + return nil + } + + _, err := u.CheckForUpdate() + return err +} + // CheckForUpdate returns the latest version if it is newer than the current // one, or nil if it isn't. Don't call it for dev builds. func (u *Updater) CheckForUpdate() (*types.VersionNumber, error) { @@ -95,6 +132,12 @@ func (u *Updater) CheckForUpdate() (*types.VersionNumber, error) { } u.Log.Infof("Current version is %s, latest version is %s", u.currentVersion, latestVersion) + u.updateAppState(func(state *config.AppState) { + state.Updates.LastCheck = time.Now().Unix() + state.Updates.LatestVersion = latestVersion.String() + }) + u.RefreshStatus() + if !u.currentVersion.IsOlderThan(latestVersion) { return nil, nil } @@ -131,14 +174,11 @@ func (u *Updater) Install(version *types.VersionNumber) error { return err } - err = u.appState.UpdateAppState(func(state *config.AppState) { + u.updateAppState(func(state *config.AppState) { state.Updates.InstalledVersion = version.String() state.Updates.InstalledPath = u.installation.ExecutablePath }) - if err != nil { - // The update is installed; only other lazygit instances won't know - u.Log.Errorf("Error saving the app state: %v", err) - } + u.RefreshStatus() return nil } @@ -148,26 +188,61 @@ func (u *Updater) replaceExecutable(binary []byte) error { return replaceExecutable(u.installation.ExecutablePath, binary, u.goos) } -// InstalledVersion returns the version that an update installed in place of -// the running lazygit, or nil if there's none. This lazygit, or another one -// running from the same executable, can have installed it. The new version -// takes effect when lazygit is restarted. -func (u *Updater) InstalledVersion() *types.VersionNumber { - state, err := u.appState.ReadAppState() - if err != nil { - u.Log.Errorf("Error reading the app state: %v", err) +// RefreshStatus reads the status from the app state, where other lazygit +// instances can have changed it, and returns it. Don't call it on the UI +// thread, because it accesses the file system. +func (u *Updater) RefreshStatus() Status { + state := u.readAppState() + + status := Status{ + AvailableVersion: u.newerVersion(state.Updates.LatestVersion), + } + if state.Updates.InstalledPath == u.installation.ExecutablePath { + status.InstalledVersion = u.newerVersion(state.Updates.InstalledVersion) } - if state.Updates.InstalledPath != u.installation.ExecutablePath { + u.statusMutex.Lock() + defer u.statusMutex.Unlock() + u.status = status + return status +} + +// Status returns the status as of the last refresh +func (u *Updater) Status() Status { + u.statusMutex.Lock() + defer u.statusMutex.Unlock() + return u.status +} + +// newerVersion parses the given version and returns it if it is newer than the +// running lazygit, or nil otherwise +func (u *Updater) newerVersion(versionStr string) *types.VersionNumber { + if u.currentVersion == nil { return nil } - version, err := types.ParseVersionNumber(state.Updates.InstalledVersion) + version, err := types.ParseVersionNumber(versionStr) if err != nil || !u.currentVersion.IsOlderThan(version) { return nil } return version } +func (u *Updater) readAppState() *config.AppState { + state, err := u.appState.ReadAppState() + if err != nil { + u.Log.Errorf("Error reading the app state: %v", err) + } + return state +} + +// Errors from saving the update state aren't worth bothering the user with; at +// worst, we check or remind again. +func (u *Updater) updateAppState(update func(state *config.AppState)) { + if err := u.appState.UpdateAppState(update); err != nil { + u.Log.Errorf("Error saving the app state: %v", err) + } +} + func (u *Updater) IsInstalling() bool { return u.installing.Load() } diff --git a/pkg/updates/updates_test.go b/pkg/updates/updates_test.go index 3baa21086..0190c1750 100644 --- a/pkg/updates/updates_test.go +++ b/pkg/updates/updates_test.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "testing" + "time" "github.com/jesseduffield/lazygit/pkg/common" "github.com/jesseduffield/lazygit/pkg/config" @@ -34,10 +35,129 @@ func TestCheckForUpdate(t *testing.T) { newVersion, err := updater.CheckForUpdate() assert.NoError(t, err) assert.Equal(t, s.expected, newVersion) + assert.Equal(t, s.expected, updater.Status().AvailableVersion) + + state := updater.readAppState() + assert.Equal(t, "v0.67.0", state.Updates.LatestVersion) + assert.WithinDuration(t, time.Now(), time.Unix(state.Updates.LastCheck, 0), time.Minute) }) } } +func TestCheckForUpdateIfDue(t *testing.T) { + requests := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests++ + _, _ = w.Write([]byte(`{"tag_name":"v0.67.0"}`)) + })) + defer server.Close() + + now := time.Now() + scenarios := []struct { + name string + version string + method string + days int64 + lastCheck time.Time + latestVersion string + expectCheck bool + expectStatus *types.VersionNumber + }{ + { + name: "never checked", + version: "0.66.2", + method: "prompt", + days: 1, + expectCheck: true, + expectStatus: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "checked recently", + version: "0.66.2", + method: "prompt", + days: 1, + lastCheck: now.Add(-23 * time.Hour), + latestVersion: "v0.66.3", + expectCheck: false, + expectStatus: &types.VersionNumber{Major: 0, Minor: 66, Patch: 3}, + }, + { + name: "checked a day ago", + version: "0.66.2", + method: "prompt", + days: 1, + lastCheck: now.Add(-25 * time.Hour), + expectCheck: true, + expectStatus: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, + { + name: "checked two days ago, checking once a week", + version: "0.66.2", + method: "prompt", + days: 7, + lastCheck: now.Add(-48 * time.Hour), + latestVersion: "v0.66.2", + expectCheck: false, + expectStatus: nil, + }, + { + name: "checks turned off", + version: "0.66.2", + method: "never", + days: 1, + expectCheck: false, + }, + { + name: "dev build", + version: "0123abcd", + method: "prompt", + days: 1, + expectCheck: false, + }, + } + + for _, s := range scenarios { + t.Run(s.name, func(t *testing.T) { + requests = 0 + updater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease}) + updater.installation = DetectInstallation(BuildSourceRelease, s.version, "/home/user/.local/bin/lazygit") + updater.UserConfig().Update.Method = s.method + updater.UserConfig().Update.Days = s.days + if !s.lastCheck.IsZero() { + updater.appState.(*fakeAppStateStore).state.Updates.LastCheck = s.lastCheck.Unix() + } + updater.appState.(*fakeAppStateStore).state.Updates.LatestVersion = s.latestVersion + + assert.NoError(t, updater.CheckForUpdateIfDue()) + assert.Equal(t, s.expectCheck, requests == 1) + assert.Equal(t, s.expectStatus, updater.Status().AvailableVersion) + }) + } +} + +func TestRefreshStatus(t *testing.T) { + updater := newTestUpdater(t, nil, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/bin/lazygit"}) + state := updater.appState.(*fakeAppStateStore).state + + assert.Equal(t, Status{}, updater.RefreshStatus()) + + state.Updates.LatestVersion = "v0.66.2" + assert.Equal(t, Status{}, updater.RefreshStatus()) + + state.Updates.LatestVersion = "v0.67.0" + assert.Equal(t, Status{AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}}, updater.RefreshStatus()) + + state.Updates.InstalledVersion = "v0.67.0" + state.Updates.InstalledPath = "/other/lazygit" + assert.Equal(t, Status{AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}}, updater.RefreshStatus()) + + state.Updates.InstalledPath = "/bin/lazygit" + assert.Equal(t, Status{ + AvailableVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + InstalledVersion: &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, + }, updater.RefreshStatus()) +} + func TestInstall(t *testing.T) { archive := makeTarGz(t, map[string]string{"LICENSE": "license", "lazygit": "new"}) server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -55,28 +175,28 @@ func TestInstall(t *testing.T) { updater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: executablePath}) assert.NoError(t, updater.CheckCanInstall()) - assert.Nil(t, updater.InstalledVersion()) + assert.Nil(t, updater.RefreshStatus().InstalledVersion) assert.NoError(t, updater.Install(&types.VersionNumber{Major: 0, Minor: 67, Patch: 0})) assertFileContent(t, executablePath, "new") assertDirContains(t, dir, "lazygit") - assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.InstalledVersion()) + assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.Status().InstalledVersion) err := updater.Install(&types.VersionNumber{Major: 0, Minor: 68, Patch: 0}) assert.ErrorContains(t, err, "lazygit_0.68.0_linux_x86_64.tar.gz returned 404 Not Found") assertFileContent(t, executablePath, "new") - assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.InstalledVersion()) + assert.Equal(t, &types.VersionNumber{Major: 0, Minor: 67, Patch: 0}, updater.RefreshStatus().InstalledVersion) // Another lazygit, running from a different executable, doesn't see the // installed version otherUpdater := newTestUpdater(t, server, "0.66.2", Installation{Kind: InstallKindRelease, ExecutablePath: "/other/lazygit"}) otherUpdater.appState = updater.appState - assert.Nil(t, otherUpdater.InstalledVersion()) + assert.Nil(t, otherUpdater.RefreshStatus().InstalledVersion) // After a restart, the installed version is the running one restartedUpdater := newTestUpdater(t, server, "0.67.0", Installation{Kind: InstallKindRelease, ExecutablePath: executablePath}) restartedUpdater.appState = updater.appState - assert.Nil(t, restartedUpdater.InstalledVersion()) + assert.Nil(t, restartedUpdater.RefreshStatus().InstalledVersion) } func newTestUpdater(t *testing.T, server *httptest.Server, currentVersion string, installation Installation) *Updater { @@ -85,16 +205,19 @@ func newTestUpdater(t *testing.T, server *httptest.Server, currentVersion string version, err := types.ParseVersionNumber(currentVersion) assert.NoError(t, err) - return &Updater{ + updater := &Updater{ Common: common.NewDummyCommon(), appState: &fakeAppStateStore{state: &config.AppState{}}, installation: installation, currentVersion: version, - httpClient: server.Client(), - repoURL: server.URL, goos: "linux", goarch: "amd64", } + if server != nil { + updater.httpClient = server.Client() + updater.repoURL = server.URL + } + return updater } type fakeAppStateStore struct { diff --git a/schema-master/config.json b/schema-master/config.json index f956217ca..42c10b62e 100644 --- a/schema-master/config.json +++ b/schema-master/config.json @@ -4145,7 +4145,7 @@ "type": "integer", "minimum": 0, "description": "Period in days between update checks", - "default": 14 + "default": 1 } }, "additionalProperties": false,