mission control for agent skills
Go agent-skillsagent-toolsai-agentsai-toolsai-workflowclaude-codeclicoding-agentscommand-line-tooldeveloper-toolsgoopencodeproductivity-toolsskill-discoveryskill-managementskillsterminal-appterminal-uituiworkflow-automation
Enable updates
alvinreale4594db9f1c7
diff --git a/README.md b/README.mdindex 3c8b7f2..c0e756c 100644--- a/README.md+++ b/README.md@@ -96,6 +96,31 @@ Useful keys:LazySkills previews actions before running them, and destructive actions require confirmation.+## 🔄 Updates++Keep LazySkills up to date using the built-in update command or the TUI interface.++### CLI Update++Run the update command directly from your terminal:++```bash+lazyskills update+```++Options:+* `--check`: Query if a newer version is available without downloading or printing commands. Exits 0.+* `--print-command`: Print the command required to upgrade on your channel (e.g. `brew upgrade`) and exit.+* `--yes`: Automatically perform the update if supported by the installation channel (direct Unix manual binary installations only).++### TUI Update++When a newer version of LazySkills is available, an update notification will automatically appear in the TUI footer:+`· U update (vX.Y.Z available)`++Press **`U`** (capital U) from the inventory view to open the update flow:+* For **manual binary installs** on macOS/Linux, you can perform the update directly inside the TUI.+* For **managed package installs** (like Homebrew, Scoop, WinGet, deb, or rpm packages), the TUI will display the specific terminal command you need to run to upgrade.## ⭐ Star for a chance to win stickersdiff --git a/cmd/lazyskills/main.go b/cmd/lazyskills/main.goindex 009c1c1..be53a28 100644--- a/cmd/lazyskills/main.go+++ b/cmd/lazyskills/main.go@@ -1,12 +1,15 @@package mainimport (+ "context""encoding/json""flag""fmt""os"+ "github.com/alvinunreal/lazyskills/internal/buildinfo""github.com/alvinunreal/lazyskills/internal/scan"+ "github.com/alvinunreal/lazyskills/internal/selfupdate""github.com/alvinunreal/lazyskills/internal/tui")@@ -16,6 +19,18 @@ var (date = "unknown")+func init() {+ if version != "dev" && version != "" {+ buildinfo.Version = version+ }+ if commit != "none" && commit != "" {+ buildinfo.Commit = commit+ }+ if date != "unknown" && date != "" {+ buildinfo.Date = date+ }+}+func main() {if err := run(os.Args[1:]); err != nil {fmt.Fprintln(os.Stderr, err)@@ -25,7 +40,95 @@ func main() {func run(args []string) error {if len(args) > 0 && (args[0] == "version" || args[0] == "--version" || args[0] == "-v") {- fmt.Fprintf(os.Stdout, "lazyskills %s\ncommit: %s\nbuilt: %s\n", version, commit, date)+ fmt.Fprintf(os.Stdout, "lazyskills %s\ncommit: %s\nbuilt: %s\n", buildinfo.Version, buildinfo.Commit, buildinfo.Date)+ return nil+ }+ if len(args) > 0 && args[0] == "update" {+ fs := flag.NewFlagSet("update", flag.ContinueOnError)+ fs.SetOutput(os.Stderr)+ checkOnly := fs.Bool("check", false, "only check if update is available")+ printCmd := fs.Bool("print-command", false, "print upgrade command and exit")+ yes := fs.Bool("yes", false, "apply update automatically without confirmation")+ if err := fs.Parse(args[1:]); err != nil {+ return err+ }++ ctx := context.Background()+ plan, err := selfupdate.Plan(ctx, true, nil)+ if err != nil {+ return fmt.Errorf("update check failed: %w", err)+ }++ if *checkOnly {+ if plan.Status == selfupdate.StatusAvailable {+ fmt.Fprintf(os.Stdout, "Update available: %s (current: %s)\n", plan.Latest, plan.Current)+ } else if plan.Status == selfupdate.StatusUnknown {+ if plan.Reason != "" {+ fmt.Fprintln(os.Stdout, plan.Reason)+ } else {+ fmt.Fprintln(os.Stdout, "Update status unknown.")+ }+ } else {+ fmt.Fprintln(os.Stdout, "Already up to date.")+ }+ return nil+ }++ if *printCmd {+ if plan.Status == selfupdate.StatusAvailable {+ if plan.CommandPreview != "" {+ fmt.Fprintln(os.Stdout, plan.CommandPreview)+ } else {+ fmt.Fprintln(os.Stdout, plan.Reason)+ }+ } else if plan.Status == selfupdate.StatusUnknown {+ if plan.Reason != "" {+ fmt.Fprintln(os.Stdout, plan.Reason)+ } else {+ fmt.Fprintln(os.Stdout, "Update status unknown.")+ }+ } else {+ fmt.Fprintln(os.Stdout, "Already up to date.")+ }+ return nil+ }++ if plan.Status == selfupdate.StatusUnknown {+ if plan.Reason != "" {+ fmt.Fprintln(os.Stdout, plan.Reason)+ } else {+ fmt.Fprintln(os.Stdout, "Update status unknown.")+ }+ return nil+ }++ if plan.Status == selfupdate.StatusAvailable {+ if *yes {+ if plan.CanExecute {+ fmt.Fprintf(os.Stdout, "Updating lazyskills to %s...\n", plan.Latest)+ if err := selfupdate.Apply(ctx, plan, nil); err != nil {+ return fmt.Errorf("update failed: %w", err)+ }+ fmt.Fprintln(os.Stdout, "Update applied successfully. Please restart lazyskills.")+ return nil+ } else {+ fmt.Fprintf(os.Stdout, "Auto-update not supported for install channel: %s\n%s\n", plan.Channel, plan.Reason)+ if plan.CommandPreview != "" {+ fmt.Fprintf(os.Stdout, "Command: %s\n", plan.CommandPreview)+ }+ return nil+ }+ } else {+ fmt.Fprintf(os.Stdout, "Update available: %s (current: %s)\n", plan.Latest, plan.Current)+ fmt.Fprintf(os.Stdout, "%s\n", plan.Reason)+ if plan.CommandPreview != "" {+ fmt.Fprintf(os.Stdout, "Command: %s\n", plan.CommandPreview)+ }+ return nil+ }+ }++ fmt.Fprintln(os.Stdout, "Already up to date.")return nil}if len(args) == 0 {@@ -43,7 +146,7 @@ func run(args []string) error {return err}if fs.NArg() > 0 {- return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills version")+ return fmt.Errorf("usage: lazyskills [--cwd <path>] | lazyskills scan --json [--cwd <path>] | lazyskills update [--check] [--print-command] [--yes] | lazyskills version")}if *cwd == "" {var err errordiff --git a/cmd/lazyskills/main_test.go b/cmd/lazyskills/main_test.gonew file mode 100644index 0000000..de9c830--- /dev/null+++ b/cmd/lazyskills/main_test.go@@ -0,0 +1,124 @@+package main++import (+ "bytes"+ "context"+ "fmt"+ "io"+ "os"+ "strings"+ "testing"++ "github.com/alvinunreal/lazyskills/internal/buildinfo"+ "github.com/alvinunreal/lazyskills/internal/selfupdate"+)++type mockFetcher struct {+ release *selfupdate.GitHubRelease+ releaseErr error+}++func (m *mockFetcher) FetchRelease(ctx context.Context, url string) (*selfupdate.GitHubRelease, error) {+ if m.releaseErr != nil {+ return nil, m.releaseErr+ }+ return m.release, nil+}++func (m *mockFetcher) Download(ctx context.Context, url string) ([]byte, error) {+ return nil, fmt.Errorf("not implemented")+}++func TestCLIUpdate(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ oldOut := os.Stdout+ defer func() { os.Stdout = oldOut }()++ oldVer := buildinfo.Version+ oldCommit := buildinfo.Commit+ buildinfo.Version = "v1.0.0"+ buildinfo.Commit = "abcdef"+ defer func() {+ buildinfo.Version = oldVer+ buildinfo.Commit = oldCommit+ }()++ mockRel := &selfupdate.GitHubRelease{+ TagName: "v1.1.0",+ HTMLURL: "https://github.com/alvinunreal/lazyskills/releases/tag/v1.1.0",+ Body: "Version 1.1.0 notes",+ }++ selfupdate.DefaultPlanFetcher = &mockFetcher{release: mockRel}+ defer func() { selfupdate.DefaultPlanFetcher = nil }()++ // Help function to capture stdout during run+ captureStdout := func(args []string) (string, error) {+ r, w, _ := os.Pipe()+ os.Stdout = w++ err := run(args)++ w.Close()+ var buf bytes.Buffer+ _, _ = io.Copy(&buf, r)+ os.Stdout = oldOut++ return buf.String(), err+ }++ // 1. Check only+ out, err := captureStdout([]string{"update", "--check"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !strings.Contains(out, "Update available: v1.1.0") {+ t.Errorf("expected check output to mention Update available, got: %q", out)+ }++ // 2. Print command+ out, err = captureStdout([]string{"update", "--print-command"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ // Default channel should be "manual" on unix, or "windows" on windows.+ // Since we mock it, we just check if it returns one of the guidance/command values.+ if !strings.Contains(out, "lazyskills update") && !strings.Contains(out, "To upgrade, please download") {+ t.Errorf("expected command preview or download guidance, got: %q", out)+ }++ // 3. Default (no --yes)+ out, err = captureStdout([]string{"update"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !strings.Contains(out, "Update available: v1.1.0") {+ t.Errorf("expected default output to mention Update available, got: %q", out)+ }++ // 4. --yes with CanExecute = false check (if we mock it to a managed channel like brew)+ // We can test this by changing the channel of the executable.+ // Let's verify already up-to-date behavior.+ buildinfo.Version = "v1.1.0"+ out, err = captureStdout([]string{"update"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !strings.Contains(out, "Already up to date.") {+ t.Errorf("expected already up to date, got: %q", out)+ }++ // 5. Test LAZYSKILLS_NO_UPDATE_CHECK prints the disable reason instead of Already up to date+ os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "1")+ defer os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "")+ out, err = captureStdout([]string{"update"})+ if err != nil {+ t.Fatalf("unexpected error with env check: %v", err)+ }+ if !strings.Contains(out, "Update checks disabled by LAZYSKILLS_NO_UPDATE_CHECK") {+ t.Errorf("expected disabled reason, got: %q", out)+ }+ if strings.Contains(out, "Already up to date.") {+ t.Error("should not print Already up to date when update checks are disabled")+ }+}diff --git a/internal/buildinfo/buildinfo.go b/internal/buildinfo/buildinfo.gonew file mode 100644index 0000000..5a92403--- /dev/null+++ b/internal/buildinfo/buildinfo.go@@ -0,0 +1,29 @@+package buildinfo++import (+ "runtime/debug"+)++var (+ Version = "dev"+ Commit = "none"+ Date = "unknown"+)++func init() {+ if Version == "dev" || Version == "" {+ if info, ok := debug.ReadBuildInfo(); ok {+ if info.Main.Version != "" && info.Main.Version != "(devel)" {+ Version = info.Main.Version+ }+ for _, setting := range info.Settings {+ switch setting.Key {+ case "vcs.revision":+ Commit = setting.Value+ case "vcs.time":+ Date = setting.Value+ }+ }+ }+ }+}diff --git a/internal/selfupdate/selfupdate.go b/internal/selfupdate/selfupdate.gonew file mode 100644index 0000000..2064761--- /dev/null+++ b/internal/selfupdate/selfupdate.go@@ -0,0 +1,660 @@+package selfupdate++import (+ "archive/tar"+ "bytes"+ "compress/gzip"+ "context"+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "time"++ "github.com/alvinunreal/lazyskills/internal/buildinfo"+)++type UpdateStatus string++const (+ StatusAlreadyLatest UpdateStatus = "already_latest"+ StatusAvailable UpdateStatus = "available"+ StatusError UpdateStatus = "error"+ StatusUnknown UpdateStatus = "unknown"+)++type UpdatePlan struct {+ Current string `json:"current"`+ Latest string `json:"latest"`+ Status UpdateStatus `json:"status"`+ Channel string `json:"channel"`+ Confidence string `json:"confidence"`+ ExecutablePath string `json:"executable_path"`+ CommandPreview string `json:"command_preview"`+ CanExecute bool `json:"can_execute"`+ Reason string `json:"reason"`+ RestartRequired bool `json:"restart_required"`+ ReleaseNotes string `json:"release_notes"`+ ReleaseURL string `json:"release_url"`+ ArchiveURL string `json:"archive_url"`+ ChecksumsURL string `json:"checksums_url"`+}++type GitHubRelease struct {+ TagName string `json:"tag_name"`+ HTMLURL string `json:"html_url"`+ Body string `json:"body"`+ Assets []struct {+ Name string `json:"name"`+ BrowserDownloadURL string `json:"browser_download_url"`+ } `json:"assets"`+}++var DefaultPlanFetcher Fetcher++type Fetcher interface {+ FetchRelease(ctx context.Context, url string) (*GitHubRelease, error)+ Download(ctx context.Context, url string) ([]byte, error)+}++type DefaultFetcher struct {+ Timeout time.Duration+}++func (f *DefaultFetcher) FetchRelease(ctx context.Context, url string) (*GitHubRelease, error) {+ client := &http.Client{Timeout: f.Timeout}+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("User-Agent", "lazyskills-updater")+ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("GitHub API returned status %d", resp.StatusCode)+ }+ var rel GitHubRelease+ if err := json.NewDecoder(resp.Body).Decode(&rel); err != nil {+ return nil, err+ }+ return &rel, nil+}++func (f *DefaultFetcher) Download(ctx context.Context, url string) ([]byte, error) {+ client := &http.Client{Timeout: f.Timeout}+ req, err := http.NewRequestWithContext(ctx, "GET", url, nil)+ if err != nil {+ return nil, err+ }+ req.Header.Set("User-Agent", "lazyskills-updater")+ resp, err := client.Do(req)+ if err != nil {+ return nil, err+ }+ defer resp.Body.Close()+ if resp.StatusCode != http.StatusOK {+ return nil, fmt.Errorf("failed to download from %s: status %d", url, resp.StatusCode)+ }+ return io.ReadAll(resp.Body)+}++type CacheData struct {+ LastChecked time.Time `json:"last_checked"`+ Release GitHubRelease `json:"release"`+}++func getCachePath() (string, error) {+ dir, err := os.UserCacheDir()+ if err != nil {+ return "", err+ }+ return filepath.Join(dir, "lazyskills", "update-check.json"), nil+}++func readCache(ttl time.Duration) (*GitHubRelease, error) {+ path, err := getCachePath()+ if err != nil {+ return nil, err+ }+ f, err := os.Open(path)+ if err != nil {+ return nil, err+ }+ defer f.Close()+ var cd CacheData+ if err := json.NewDecoder(f).Decode(&cd); err != nil {+ return nil, err+ }+ if time.Since(cd.LastChecked) > ttl {+ return nil, fmt.Errorf("cache expired")+ }+ return &cd.Release, nil+}++func writeCache(rel *GitHubRelease) error {+ path, err := getCachePath()+ if err != nil {+ return err+ }+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {+ return err+ }+ f, err := os.Create(path)+ if err != nil {+ return err+ }+ defer f.Close()+ cd := CacheData{+ LastChecked: time.Now(),+ Release: *rel,+ }+ return json.NewEncoder(f).Encode(cd)+}++func CleanVersion(v string) string {+ v = strings.TrimSpace(v)+ if len(v) > 0 && (v[0] == 'v' || v[0] == 'V') {+ return v[1:]+ }+ return v+}++func CompareVersions(v1, v2 string) int {+ v1 = CleanVersion(v1)+ v2 = CleanVersion(v2)++ if v1 == v2 {+ return 0+ }++ parts1 := strings.SplitN(v1, "-", 2)+ parts2 := strings.SplitN(v2, "-", 2)++ main1 := parts1[0]+ main2 := parts2[0]++ nums1 := parseVersionComponents(main1)+ nums2 := parseVersionComponents(main2)++ for i := 0; i < len(nums1) || i < len(nums2); i++ {+ n1 := 0+ if i < len(nums1) {+ n1 = nums1[i]+ }+ n2 := 0+ if i < len(nums2) {+ n2 = nums2[i]+ }+ if n1 < n2 {+ return -1+ }+ if n1 > n2 {+ return 1+ }+ }++ if len(parts1) == 1 && len(parts2) > 1 {+ return 1+ }+ if len(parts1) > 1 && len(parts2) == 1 {+ return -1+ }+ if len(parts1) > 1 && len(parts2) > 1 {+ if parts1[1] < parts2[1] {+ return -1+ }+ if parts1[1] > parts2[1] {+ return 1+ }+ }+ return 0+}++func parseVersionComponents(v string) []int {+ parts := strings.Split(v, ".")+ res := make([]int, len(parts))+ for i, p := range parts {+ var n int+ fmt.Sscanf(p, "%d", &n)+ res[i] = n+ }+ return res+}++func isManagedByDpkg(path string) bool {+ if _, err := exec.LookPath("dpkg"); err != nil {+ return false+ }+ cmd := exec.Command("dpkg", "-S", path)+ err := cmd.Run()+ return err == nil+}++func isManagedByRpm(path string) bool {+ if _, err := exec.LookPath("rpm"); err != nil {+ return false+ }+ cmd := exec.Command("rpm", "-qf", path)+ err := cmd.Run()+ return err == nil+}++func isBrewPath(path string) bool {+ path = filepath.ToSlash(path)+ return strings.Contains(path, "/Cellar/") ||+ strings.Contains(path, "/Caskroom/") ||+ strings.Contains(path, "/homebrew/") ||+ strings.Contains(path, "/opt/homebrew/") ||+ strings.Contains(path, "/usr/local/Cellar/") ||+ strings.Contains(path, "/usr/local/Caskroom/")+}++func isScoopPath(path string) bool {+ path = strings.ToLower(filepath.ToSlash(path))+ return strings.Contains(path, "/scoop/apps/") || strings.Contains(path, "/scoop/shims/")+}++func isWinGetPath(path string) bool {+ path = strings.ToLower(filepath.ToSlash(path))+ return strings.Contains(path, "/winget/") || strings.Contains(path, "/local/microsoft/winget/")+}++func isGoPath(path string) bool {+ path = strings.ToLower(filepath.ToSlash(path))+ if strings.Contains(path, "/go/bin/") {+ return true+ }+ if gopath := os.Getenv("GOPATH"); gopath != "" {+ gopath = strings.ToLower(filepath.ToSlash(gopath))+ if strings.Contains(path, gopath) {+ return true+ }+ }+ return false+}++func isManualInstallSafe(path string) bool {+ path = filepath.Clean(filepath.ToSlash(path))+ if strings.HasPrefix(path, "/usr/bin/") ||+ strings.HasPrefix(path, "/usr/sbin/") ||+ strings.HasPrefix(path, "/bin/") ||+ strings.HasPrefix(path, "/sbin/") ||+ strings.HasPrefix(path, "/opt/") ||+ strings.HasPrefix(path, "/var/") {+ return false+ }+ home, err := os.UserHomeDir()+ if err == nil && home != "" {+ home = filepath.Clean(filepath.ToSlash(home))+ if strings.HasPrefix(path, home+"/") {+ return true+ }+ }+ if strings.HasPrefix(path, "/usr/local/bin/") || strings.HasPrefix(path, "/usr/local/sbin/") {+ return true+ }+ if strings.HasPrefix(path, "/tmp/") {+ return true+ }+ return false+}++func DetectChannel(execPath string) (string, string) {+ evalPath, err := filepath.EvalSymlinks(execPath)+ if err == nil {+ execPath = evalPath+ }++ v := strings.TrimSpace(buildinfo.Version)+ if v == "dev" || v == "" || v == "(devel)" {+ return "dev", "high"+ }++ if isBrewPath(execPath) {+ return "brew", "high"+ }+ if isScoopPath(execPath) {+ return "scoop", "high"+ }+ if isWinGetPath(execPath) {+ return "winget", "high"+ }+ if isManagedByDpkg(execPath) {+ return "deb", "high"+ }+ if isManagedByRpm(execPath) {+ return "rpm", "high"+ }+ if isGoPath(execPath) {+ return "go", "high"+ }++ if runtime.GOOS == "windows" {+ return "windows", "low"+ }+ return "manual", "high"+}++func Plan(ctx context.Context, forceLive bool, fetcher Fetcher) (*UpdatePlan, error) {+ current := buildinfo.Version++ execPath, err := os.Executable()+ if err != nil {+ execPath = "lazyskills"+ }+ resolvedPath, err := filepath.EvalSymlinks(execPath)+ if err == nil {+ execPath = resolvedPath+ }++ channel, confidence := DetectChannel(execPath)++ plan := &UpdatePlan{+ Current: current,+ Channel: channel,+ Confidence: confidence,+ ExecutablePath: execPath,+ Status: StatusUnknown,+ }++ if os.Getenv("LAZYSKILLS_NO_UPDATE_CHECK") != "" {+ plan.Reason = "Update checks disabled by LAZYSKILLS_NO_UPDATE_CHECK"+ return plan, nil+ }++ var release *GitHubRelease+ if !forceLive {+ if cached, err := readCache(24 * time.Hour); err == nil {+ release = cached+ }+ }++ if release == nil {+ if fetcher == nil {+ if DefaultPlanFetcher != nil {+ fetcher = DefaultPlanFetcher+ } else {+ fetcher = &DefaultFetcher{Timeout: 10 * time.Second}+ }+ }+ url := "https://api.github.com/repos/alvinunreal/lazyskills/releases/latest"+ rel, err := fetcher.FetchRelease(ctx, url)+ if err != nil {+ plan.Status = StatusError+ plan.Reason = fmt.Sprintf("Failed to query latest release: %v", err)+ return plan, err+ }+ release = rel+ _ = writeCache(rel)+ }++ plan.Latest = release.TagName+ plan.ReleaseNotes = release.Body+ plan.ReleaseURL = release.HTMLURL++ osName := strings.Title(runtime.GOOS)+ archName := runtime.GOARCH+ if archName == "amd64" {+ archName = "x86_64"+ }+ archiveName := fmt.Sprintf("lazyskills_%s_%s.tar.gz", osName, archName)+ if runtime.GOOS == "windows" {+ archiveName = fmt.Sprintf("lazyskills_%s_%s.zip", osName, archName)+ }++ for _, asset := range release.Assets {+ if asset.Name == archiveName {+ plan.ArchiveURL = asset.BrowserDownloadURL+ } else if asset.Name == "checksums.txt" {+ plan.ChecksumsURL = asset.BrowserDownloadURL+ }+ }++ currClean := strings.TrimSpace(current)+ if currClean == "dev" || currClean == "" || currClean == "(devel)" {+ plan.Status = StatusAlreadyLatest+ plan.CanExecute = false+ plan.Reason = "Running a development build. Rebuild from source."+ plan.CommandPreview = "go install github.com/alvinunreal/lazyskills/cmd/lazyskills@latest"+ return plan, nil+ }++ cmp := CompareVersions(current, release.TagName)+ if cmp >= 0 {+ plan.Status = StatusAlreadyLatest+ plan.CanExecute = false+ plan.Reason = "You are already running the latest version."+ return plan, nil+ }++ plan.Status = StatusAvailable++ switch channel {+ case "brew":+ plan.CommandPreview = "brew upgrade --cask alvinunreal/tap/lazyskills"+ plan.Reason = "Homebrew managed install. Please upgrade using Homebrew."+ plan.CanExecute = false+ case "go":+ plan.CommandPreview = "go install github.com/alvinunreal/lazyskills/cmd/lazyskills@latest"+ plan.Reason = "Installed via Go. Please run go install to upgrade."+ plan.CanExecute = false+ case "scoop":+ plan.CommandPreview = "scoop update lazyskills"+ plan.Reason = "Scoop managed install. Please upgrade using Scoop."+ plan.CanExecute = false+ case "winget":+ plan.CommandPreview = "winget upgrade --id alvinunreal.lazyskills"+ plan.Reason = "WinGet managed install. Please upgrade using WinGet."+ plan.CanExecute = false+ case "deb":+ plan.CommandPreview = "sudo apt update && sudo apt install --only-upgrade lazyskills"+ plan.Reason = "Installed via DEB package. If a repository is configured, upgrade via apt. Otherwise, download the latest DEB from the releases page: https://github.com/alvinunreal/lazyskills/releases/latest"+ plan.CanExecute = false+ case "rpm":+ plan.CommandPreview = "sudo dnf upgrade lazyskills"+ plan.Reason = "Installed via RPM package. If a repository is configured, upgrade via dnf/yum. Otherwise, download the latest RPM from the releases page: https://github.com/alvinunreal/lazyskills/releases/latest"+ plan.CanExecute = false+ case "dev":+ plan.CommandPreview = "go install github.com/alvinunreal/lazyskills/cmd/lazyskills@latest"+ plan.Reason = "Running a development build. Rebuild from source."+ plan.CanExecute = false+ case "windows":+ plan.CommandPreview = ""+ plan.Reason = "To upgrade, please download the latest release from: " + release.HTMLURL+ plan.CanExecute = false+ default:+ if runtime.GOOS == "windows" {+ plan.CommandPreview = ""+ plan.Reason = "To upgrade, please download the latest release from: " + release.HTMLURL+ plan.CanExecute = false+ } else {+ if !isManualInstallSafe(execPath) {+ plan.CommandPreview = ""+ plan.Reason = "Update available, but automatic replacement is disabled because the executable path (" + execPath + ") is in a system directory. Please download the release manually from: " + release.HTMLURL+ plan.CanExecute = false+ } else {+ plan.CommandPreview = "lazyskills update --yes"+ plan.Reason = "Manual binary install. Can update directly."+ plan.CanExecute = true+ }+ }+ }++ return plan, nil+}++func Apply(ctx context.Context, plan *UpdatePlan, fetcher Fetcher) error {+ if !plan.CanExecute {+ return fmt.Errorf("update execution not supported for channel %q", plan.Channel)+ }++ if fetcher == nil {+ if DefaultPlanFetcher != nil {+ fetcher = DefaultPlanFetcher+ } else {+ fetcher = &DefaultFetcher{Timeout: 30 * time.Second}+ }+ }++ osName := strings.Title(runtime.GOOS)+ archName := runtime.GOARCH+ if archName == "amd64" {+ archName = "x86_64"+ }++ archiveName := fmt.Sprintf("lazyskills_%s_%s.tar.gz", osName, archName)++ archiveURL := plan.ArchiveURL+ checksumsURL := plan.ChecksumsURL++ if archiveURL == "" || checksumsURL == "" {+ url := "https://api.github.com/repos/alvinunreal/lazyskills/releases/latest"+ rel, err := fetcher.FetchRelease(ctx, url)+ if err != nil {+ return fmt.Errorf("failed to fetch release details for download: %v", err)+ }+ if rel.TagName != plan.Latest {+ return fmt.Errorf("release mismatch: plan latest version is %s, but fetched version was %s", plan.Latest, rel.TagName)+ }+ for _, asset := range rel.Assets {+ if asset.Name == archiveName {+ archiveURL = asset.BrowserDownloadURL+ } else if asset.Name == "checksums.txt" {+ checksumsURL = asset.BrowserDownloadURL+ }+ }+ }++ if archiveURL == "" {+ return fmt.Errorf("release archive asset %q not found", archiveName)+ }+ if checksumsURL == "" {+ return fmt.Errorf("release checksums asset %q not found", "checksums.txt")+ }++ checksumsBytes, err := fetcher.Download(ctx, checksumsURL)+ if err != nil {+ return fmt.Errorf("failed to download checksums: %v", err)+ }++ archiveBytes, err := fetcher.Download(ctx, archiveURL)+ if err != nil {+ return fmt.Errorf("failed to download archive: %v", err)+ }++ hash := sha256.Sum256(archiveBytes)+ hashStr := fmt.Sprintf("%x", hash)++ var expectedSHA string+ for _, line := range strings.Split(string(checksumsBytes), "\n") {+ parts := strings.Fields(line)+ if len(parts) >= 2 && parts[1] == archiveName {+ expectedSHA = parts[0]+ break+ }+ }++ if expectedSHA == "" {+ return fmt.Errorf("checksum for %q not found in checksums.txt", archiveName)+ }++ if hashStr != expectedSHA {+ return fmt.Errorf("checksum mismatch: got %s, expected %s", hashStr, expectedSHA)+ }++ binaryName := "lazyskills"+ binaryBytes, err := extractBinaryFromTarGz(archiveBytes, binaryName)+ if err != nil {+ return fmt.Errorf("failed to extract binary from archive: %v", err)+ }++ targetPath := plan.ExecutablePath+ evalPath, err := filepath.EvalSymlinks(targetPath)+ if err == nil {+ targetPath = evalPath+ }++ if !isManualInstallSafe(targetPath) {+ return fmt.Errorf("target path %q is in an unsafe system directory for manual replacement", targetPath)+ }++ var targetMode os.FileMode = 0755+ info, statErr := os.Lstat(targetPath)+ if statErr == nil {+ if !info.Mode().IsRegular() {+ return fmt.Errorf("target path %q is not a regular file", targetPath)+ }+ targetMode = info.Mode()+ }++ execDir := filepath.Dir(targetPath)+ dirInfo, err := os.Stat(execDir)+ if err != nil {+ return fmt.Errorf("failed to access directory %q: %w", execDir, err)+ }+ if !dirInfo.IsDir() {+ return fmt.Errorf("target path parent %q is not a directory", execDir)+ }++ tempFile, err := os.CreateTemp(execDir, "lazyskills-update-")+ if err != nil {+ return fmt.Errorf("failed to create temp file (directory may not be writable): %w", err)+ }+ tempPath := tempFile.Name()+ defer func() {+ _ = os.Remove(tempPath)+ }()++ if _, err := io.Copy(tempFile, bytes.NewReader(binaryBytes)); err != nil {+ tempFile.Close()+ return fmt.Errorf("failed to write binary to temp file: %w", err)+ }+ tempFile.Close()++ if err := os.Chmod(tempPath, targetMode); err != nil {+ return fmt.Errorf("failed to chmod temp file: %w", err)+ }++ if err := os.Rename(tempPath, targetPath); err != nil {+ return fmt.Errorf("failed to replace executable: %w", err)+ }++ plan.RestartRequired = true+ return nil+}++func extractBinaryFromTarGz(tarGzBytes []byte, binaryName string) ([]byte, error) {+ gzr, err := gzip.NewReader(bytes.NewReader(tarGzBytes))+ if err != nil {+ return nil, err+ }+ defer gzr.Close()++ tr := tar.NewReader(gzr)+ for {+ header, err := tr.Next()+ if err == io.EOF {+ break+ }+ if err != nil {+ return nil, err+ }+ if filepath.Base(header.Name) == binaryName && header.Typeflag == tar.TypeReg {+ var buf bytes.Buffer+ if _, err := io.Copy(&buf, tr); err != nil {+ return nil, err+ }+ return buf.Bytes(), nil+ }+ }+ return nil, fmt.Errorf("binary %q not found in archive", binaryName)+}diff --git a/internal/selfupdate/selfupdate_test.go b/internal/selfupdate/selfupdate_test.gonew file mode 100644index 0000000..003ffc2--- /dev/null+++ b/internal/selfupdate/selfupdate_test.go@@ -0,0 +1,387 @@+package selfupdate++import (+ "archive/tar"+ "bytes"+ "compress/gzip"+ "context"+ "crypto/sha256"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"++ "github.com/alvinunreal/lazyskills/internal/buildinfo"+)++type mockFetcher struct {+ release *GitHubRelease+ releaseErr error+ downloadData map[string][]byte+ downloadErr map[string]error+}++func (m *mockFetcher) FetchRelease(ctx context.Context, url string) (*GitHubRelease, error) {+ if m.releaseErr != nil {+ return nil, m.releaseErr+ }+ return m.release, nil+}++func (m *mockFetcher) Download(ctx context.Context, url string) ([]byte, error) {+ if m.downloadErr != nil {+ if err := m.downloadErr[url]; err != nil {+ return nil, err+ }+ }+ if data, ok := m.downloadData[url]; ok {+ return data, nil+ }+ return nil, fmt.Errorf("mock download error for URL: %s", url)+}++func TestCompareVersions(t *testing.T) {+ tests := []struct {+ v1, v2 string+ want int+ }{+ {"v1.0.0", "v1.0.0", 0},+ {"1.0.0", "v1.0.0", 0},+ {"v1.2.3", "v1.2.4", -1},+ {"v1.3.0", "v1.2.9", 1},+ {"v2.0.0", "v1.9.9", 1},+ {"v1.0.0-alpha", "v1.0.0", -1},+ {"v1.0.0", "v1.0.0-beta", 1},+ {"v1.0.0-alpha", "v1.0.0-beta", -1},+ }++ for _, tt := range tests {+ got := CompareVersions(tt.v1, tt.v2)+ if got != tt.want {+ t.Errorf("CompareVersions(%q, %q) = %d; want %d", tt.v1, tt.v2, got, tt.want)+ }+ }+}++func TestDetectChannel(t *testing.T) {+ // Temporarily override version+ oldVer := buildinfo.Version+ oldCommit := buildinfo.Commit+ defer func() {+ buildinfo.Version = oldVer+ buildinfo.Commit = oldCommit+ }()++ // 1. Dev build+ buildinfo.Version = "dev"+ ch, conf := DetectChannel("/usr/local/bin/lazyskills")+ if ch != "dev" || conf != "high" {+ t.Errorf("expected dev build, got channel=%s, conf=%s", ch, conf)+ }++ // 2. Normal build, brew path+ buildinfo.Version = "v1.0.0"+ buildinfo.Commit = "abcdef"+ ch, conf = DetectChannel("/opt/homebrew/Cellar/lazyskills/1.0.0/bin/lazyskills")+ if ch != "brew" || conf != "high" {+ t.Errorf("expected brew, got channel=%s, conf=%s", ch, conf)+ }++ ch, conf = DetectChannel("/usr/local/Caskroom/lazyskills/1.0.0/bin/lazyskills")+ if ch != "brew" || conf != "high" {+ t.Errorf("expected brew caskroom, got channel=%s, conf=%s", ch, conf)+ }++ // 3. Scoop path+ ch, conf = DetectChannel("C:/Users/name/scoop/apps/lazyskills/1.0.0/lazyskills.exe")+ if ch != "scoop" || conf != "high" {+ t.Errorf("expected scoop, got channel=%s, conf=%s", ch, conf)+ }++ // 4. WinGet path+ ch, conf = DetectChannel("C:/Users/name/AppData/Local/Microsoft/WinGet/Packages/lazyskills/lazyskills.exe")+ if ch != "winget" || conf != "high" {+ t.Errorf("expected winget, got channel=%s, conf=%s", ch, conf)+ }++ // 5. Go path+ ch, conf = DetectChannel("/home/user/go/bin/lazyskills")+ if ch != "go" || conf != "high" {+ t.Errorf("expected go, got channel=%s, conf=%s", ch, conf)+ }+}++func TestPlanAndCacheTTL(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ oldVer := buildinfo.Version+ oldCommit := buildinfo.Commit+ buildinfo.Version = "v1.0.0"+ buildinfo.Commit = "abcdef"+ defer func() {+ buildinfo.Version = oldVer+ buildinfo.Commit = oldCommit+ }()++ // Mock release info+ mockRel := &GitHubRelease{+ TagName: "v1.1.0",+ HTMLURL: "https://github.com/alvinunreal/lazyskills/releases/tag/v1.1.0",+ Body: "New features!",+ }+ mockRel.Assets = append(mockRel.Assets, struct {+ Name string `json:"name"`+ BrowserDownloadURL string `json:"browser_download_url"`+ }{+ Name: "lazyskills_Linux_x86_64.tar.gz",+ BrowserDownloadURL: "https://github.com/downloads/archive.tar.gz",+ })++ fetcher := &mockFetcher{release: mockRel}++ // Make sure we have a clean state for caching+ os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "")+ cachePath, _ := getCachePath()+ _ = os.Remove(cachePath)++ ctx := context.Background()++ // 1. First plan (uncached)+ plan, err := Plan(ctx, true, fetcher)+ if err != nil {+ t.Fatalf("Plan failed: %v", err)+ }+ if plan.Status != StatusAvailable {+ t.Errorf("expected available update, got status=%s", plan.Status)+ }+ if plan.Latest != "v1.1.0" {+ t.Errorf("expected latest version v1.1.0, got %s", plan.Latest)+ }++ // 2. Cache should now exist and be valid+ if _, err := os.Stat(cachePath); os.IsNotExist(err) {+ t.Error("cache file was not created")+ }++ // 3. Test TTL expiration by writing old cache date+ oldTime := time.Now().Add(-25 * time.Hour)+ cd := CacheData{+ LastChecked: oldTime,+ Release: *mockRel,+ }+ data, err := json.Marshal(cd)+ if err != nil {+ t.Fatalf("failed to marshal cache data: %v", err)+ }+ if err := os.MkdirAll(filepath.Dir(cachePath), 0755); err != nil {+ t.Fatalf("failed to create cache dir: %v", err)+ }+ if err := os.WriteFile(cachePath, data, 0644); err != nil {+ t.Fatalf("failed to write cache file: %v", err)+ }++ // Fetcher with error, but if TTL cache is expired, Plan will try to fetch again and fail+ errFetcher := &mockFetcher{releaseErr: fmt.Errorf("network error")}+ planRes, err := Plan(ctx, false, errFetcher)+ if err == nil {+ cachedRel, readErr := readCache(24 * time.Hour)+ t.Errorf("expected error from live plan when cache expired, but got nil. cachePath: %s, readErr: %v, cachedRel: %+v, planRes: %+v", cachePath, readErr, cachedRel, planRes)+ }++ // 4. Test LAZYSKILLS_NO_UPDATE_CHECK env opt-out+ os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "1")+ planEnv, err := Plan(ctx, false, fetcher)+ if err != nil {+ t.Fatalf("Plan with env fail: %v", err)+ }+ if planEnv.Status != StatusUnknown || planEnv.Reason != "Update checks disabled by LAZYSKILLS_NO_UPDATE_CHECK" {+ t.Errorf("expected unknown/disabled status, got status=%s, reason=%s", planEnv.Status, planEnv.Reason)+ }+ os.Setenv("LAZYSKILLS_NO_UPDATE_CHECK", "")+}++func TestApplyAndChecksumMismatch(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ // Create mock binary data and tar.gz+ var binBuf bytes.Buffer+ binBuf.WriteString("dummy binary content")+ binBytes := binBuf.Bytes()++ var tarBuf bytes.Buffer+ gw := gzip.NewWriter(&tarBuf)+ tw := tar.NewWriter(gw)+ hdr := &tar.Header{+ Name: "lazyskills",+ Mode: 0755,+ Size: int64(len(binBytes)),+ Typeflag: tar.TypeReg,+ }+ _ = tw.WriteHeader(hdr)+ _, _ = tw.Write(binBytes)+ _ = tw.Close()+ _ = gw.Close()+ tarBytes := tarBuf.Bytes()++ correctHash := sha256.Sum256(tarBytes)+ correctHashStr := fmt.Sprintf("%x", correctHash)++ // Write temp target executable paths+ tmpDir, err := os.MkdirTemp("", "lazyskills-test-*")+ if err != nil {+ t.Fatalf("MkdirTemp failed: %v", err)+ }+ defer os.RemoveAll(tmpDir)++ execPath := filepath.Join(tmpDir, "lazyskills")+ _ = os.WriteFile(execPath, []byte("old binary content"), 0755)++ plan := &UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: StatusAvailable,+ Channel: "manual",+ ExecutablePath: execPath,+ CanExecute: true,+ }++ // Helper URLs+ archiveURL := "https://github.com/downloads/lazyskills_linux_amd64.tar.gz" // not exact, mock matches anyway+ checksumsURL := "https://github.com/downloads/checksums.txt"++ // Mock release info with asset list matching our helper URLs+ mockRel := &GitHubRelease{+ TagName: "v1.1.0",+ }+ // We will determine our asset based on runtime OS/Arch+ osName := "Linux"+ archName := "x86_64"+ mockRel.Assets = append(mockRel.Assets, struct {+ Name string `json:"name"`+ BrowserDownloadURL string `json:"browser_download_url"`+ }{+ Name: fmt.Sprintf("lazyskills_%s_%s.tar.gz", osName, archName),+ BrowserDownloadURL: archiveURL,+ })+ mockRel.Assets = append(mockRel.Assets, struct {+ Name string `json:"name"`+ BrowserDownloadURL string `json:"browser_download_url"`+ }{+ Name: "checksums.txt",+ BrowserDownloadURL: checksumsURL,+ })++ // 1. Checksum mismatch test+ mismatchFetcher := &mockFetcher{+ release: mockRel,+ downloadData: map[string][]byte{+ checksumsURL: []byte(fmt.Sprintf("badhash1234567890abcdef lazyskills_%s_%s.tar.gz\n", osName, archName)),+ archiveURL: tarBytes,+ },+ }++ ctx := context.Background()+ err = Apply(ctx, plan, mismatchFetcher)+ if err == nil || !bytes.Contains([]byte(err.Error()), []byte("checksum mismatch")) {+ t.Errorf("expected checksum mismatch error, got %v", err)+ }++ // 2. Successful Apply test+ successFetcher := &mockFetcher{+ release: mockRel,+ downloadData: map[string][]byte{+ checksumsURL: []byte(fmt.Sprintf("%s lazyskills_%s_%s.tar.gz\n", correctHashStr, osName, archName)),+ archiveURL: tarBytes,+ },+ }++ err = Apply(ctx, plan, successFetcher)+ if err != nil {+ t.Fatalf("expected successful Apply, got err: %v", err)+ }++ if !plan.RestartRequired {+ t.Error("expected RestartRequired to be true")+ }++ newContent, err := os.ReadFile(execPath)+ if err != nil {+ t.Fatalf("failed to read updated executable: %v", err)+ }+ if string(newContent) != "dummy binary content" {+ t.Errorf("binary content not updated properly: got %q", string(newContent))+ }++ // 3. Test TOCTOU tag mismatch (when ArchiveURL is empty and latest release tag has changed)+ mismatchTagFetcher := &mockFetcher{+ release: &GitHubRelease{TagName: "v1.2.0"}, // different from plan.Latest which is "v1.1.0"+ }+ planNoURLs := &UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: StatusAvailable,+ Channel: "manual",+ ExecutablePath: execPath,+ CanExecute: true,+ }+ err = Apply(ctx, planNoURLs, mismatchTagFetcher)+ if err == nil || !strings.Contains(err.Error(), "release mismatch") {+ t.Errorf("expected release mismatch error, got %v", err)+ }++ // 4. Test target path is not a regular file+ dirPath := filepath.Join(tmpDir, "some-dir-target")+ _ = os.Mkdir(dirPath, 0755)+ planDir := &UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: StatusAvailable,+ Channel: "manual",+ ExecutablePath: dirPath,+ CanExecute: true,+ }+ err = Apply(ctx, planDir, successFetcher)+ if err == nil || !strings.Contains(err.Error(), "is not a regular file") {+ t.Errorf("expected is not a regular file error, got %v", err)+ }++ // 5. Test symlink pointing to an unsafe target must not be executable/updatable+ baseUnsafeDir, err := os.MkdirTemp("/var/tmp", "lazyskills-test-*")+ if err == nil {+ defer os.RemoveAll(baseUnsafeDir)++ unsafeTarget := filepath.Join(baseUnsafeDir, "opt/vendor/lazyskills")+ _ = os.MkdirAll(filepath.Dir(unsafeTarget), 0755)+ _ = os.WriteFile(unsafeTarget, []byte("unsafe binary"), 0755)++ safeSymlink := filepath.Join(tmpDir, "usr/local/bin/lazyskills")+ _ = os.MkdirAll(filepath.Dir(safeSymlink), 0755)++ err = os.Symlink(unsafeTarget, safeSymlink)+ if err == nil {+ resolved, err := filepath.EvalSymlinks(safeSymlink)+ if err != nil {+ t.Fatalf("failed to resolve symlink: %v", err)+ }+ if isManualInstallSafe(resolved) {+ t.Errorf("expected resolved path %q to be unsafe", resolved)+ }++ planUnsafeSymlink := &UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: StatusAvailable,+ Channel: "manual",+ ExecutablePath: safeSymlink,+ CanExecute: true,+ }+ err = Apply(ctx, planUnsafeSymlink, successFetcher)+ if err == nil || !strings.Contains(err.Error(), "unsafe system directory") {+ t.Errorf("expected unsafe system directory error for symlink target, got %v", err)+ }+ }+ } else {+ t.Logf("skipping /var/tmp symlink safety test because /var/tmp is not writeable or available: %v", err)+ }+}diff --git a/internal/tui/tui.go b/internal/tui/tui.goindex 8f23e42..bfc6b0b 100644--- a/internal/tui/tui.go+++ b/internal/tui/tui.go@@ -1,6 +1,7 @@package tuiimport (+ "context""time""github.com/charmbracelet/bubbles/viewport"@@ -11,6 +12,7 @@ import ("github.com/alvinunreal/lazyskills/internal/model""github.com/alvinunreal/lazyskills/internal/runner""github.com/alvinunreal/lazyskills/internal/scan"+ "github.com/alvinunreal/lazyskills/internal/selfupdate")type scopeFilter int@@ -90,6 +92,12 @@ type appModel struct {modalSource stringpendingG bool // saw a lone "g"; a second "g" jumps to toppendingAction *actions.CommandPreview // action awaiting confirm (decoupled from selection)+ updatePlan *selfupdate.UpdatePlan+ updatePlanErr error+ appUpdateModal bool+ updatingApp bool+ updateSuccess bool+ updateError error}type paneLayout struct {@@ -113,7 +121,6 @@ type appLayout struct {const (minLayoutWidth = 40minLayoutHeight = 7- appVersion = "v1")var (@@ -166,6 +173,15 @@ type actionResultMsg struct {partialSuccess bool}+type updatePlanMsg struct {+ plan *selfupdate.UpdatePlan+ err error+}++type appUpdateResultMsg struct {+ err error+}+func Run(cwd string) error {program := tea.NewProgram(newModel(cwd), tea.WithAltScreen())_, err := program.Run()@@ -185,7 +201,19 @@ func newModel(cwd string) appModel {}func (m appModel) Init() tea.Cmd {- return loadSnapshot(m.cwd)+ return tea.Batch(+ loadSnapshot(m.cwd),+ m.checkUpdateCmd(false),+ )+}++func (m appModel) checkUpdateCmd(forceLive bool) tea.Cmd {+ return func() tea.Msg {+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ plan, err := selfupdate.Plan(ctx, forceLive, nil)+ return updatePlanMsg{plan: plan, err: err}+ }}func loadSnapshot(cwd string) tea.Cmd {diff --git a/internal/tui/update.go b/internal/tui/update.goindex 028cc10..b054fd8 100644--- a/internal/tui/update.go+++ b/internal/tui/update.go@@ -1,6 +1,7 @@package tuiimport (+ "context""fmt""os""os/exec"@@ -15,6 +16,7 @@ import ("github.com/alvinunreal/lazyskills/internal/locks""github.com/alvinunreal/lazyskills/internal/model""github.com/alvinunreal/lazyskills/internal/runner"+ "github.com/alvinunreal/lazyskills/internal/selfupdate")const previewRefreshDelay = 300 * time.Millisecond@@ -100,6 +102,20 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {m.syncViewport()}perfLogf("preview_refresh msg_generation=%d current_generation=%d applied=%t duration=%s", msg.generation, m.previewGeneration, msg.generation == m.previewGeneration, time.Since(refreshStart))+ case updatePlanMsg:+ m.updatePlan = msg.plan+ m.updatePlanErr = msg.err+ m.syncViewport()+ case appUpdateResultMsg:+ m.updatingApp = false+ if msg.err != nil {+ m.updateError = msg.err+ m.updateSuccess = false+ } else {+ m.updateSuccess = true+ m.updateError = nil+ }+ m.syncViewport()case tea.KeyMsg:key := msg.String()var postKeyCmd tea.Cmd@@ -109,6 +125,26 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {}return m, nil}+ if m.appUpdateModal {+ switch key {+ case "esc", "q":+ m.appUpdateModal = false+ m.updateError = nil+ m.updateSuccess = false+ m.syncViewport()+ case "ctrl+c":+ return m, tea.Quit+ case "enter":+ if m.updatePlan != nil && m.updatePlan.CanExecute && !m.updatingApp && !m.updateSuccess {+ m.updatingApp = true+ m.updateError = nil+ m.updateSuccess = false+ m.syncViewport()+ return m, m.applyUpdateCmd()+ }+ }+ return m, nil+ }if m.detailModal {switch key {case "esc", "q":@@ -386,6 +422,12 @@ func (m appModel) Update(msg tea.Msg) (tea.Model, tea.Cmd) {return m, tea.Quitcase "?":m.helpOpen = true+ case "U":+ m.appUpdateModal = true+ m.updatingApp = false+ m.updateSuccess = false+ m.updateError = nil+ m.syncViewport()case "c":m.commands = !m.commandsm.action = 0@@ -1328,3 +1370,12 @@ func insertToggleActions(previews, toggleActions []actions.CommandPreview) []actout = append(out, previews[insertAt:]...)return out}++func (m appModel) applyUpdateCmd() tea.Cmd {+ return func() tea.Msg {+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ err := selfupdate.Apply(ctx, m.updatePlan, nil)+ return appUpdateResultMsg{err: err}+ }+}diff --git a/internal/tui/update_test.go b/internal/tui/update_test.gonew file mode 100644index 0000000..88edc93--- /dev/null+++ b/internal/tui/update_test.go@@ -0,0 +1,188 @@+package tui++import (+ "fmt"+ "strings"+ "testing"++ tea "github.com/charmbracelet/bubbletea"++ "github.com/alvinunreal/lazyskills/internal/selfupdate"+)++func TestTUIFooterUpdateNotice(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ m := newModel("")+ m.width = 100+ m.height = 30++ // 1. Without update plan, no notice+ footer := m.footerText(100)+ if strings.Contains(footer, "U update") {+ t.Errorf("unexpected update notice in footer when no update is available: %q", footer)+ }++ // 2. With update available+ m.updatePlan = &selfupdate.UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: selfupdate.StatusAvailable,+ Channel: "manual",+ }++ footer = m.footerText(120)+ if !strings.Contains(footer, "U update") || !strings.Contains(footer, "v1.1.0 available") {+ t.Errorf("expected update notice in footer, got: %q", footer)+ }++ // 3. Notice omitted if width is too narrow+ footerNarrow := m.footerText(40)+ if strings.Contains(footerNarrow, "U update") {+ t.Errorf("expected update notice to be omitted in narrow viewport, got: %q", footerNarrow)+ }+}++func TestTUIAppUpdateModalTransitions(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ m := newModel("")+ m.width = 100+ m.height = 30+ m.updatePlan = &selfupdate.UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: selfupdate.StatusAvailable,+ Channel: "manual",+ CanExecute: true,+ }++ // 1. Pressing 'U' opens the modal+ modelTmp, cmd := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("U")})+ m = modelTmp.(appModel)+ if !m.appUpdateModal {+ t.Error("expected appUpdateModal to be true after pressing 'U'")+ }+ if cmd != nil {+ t.Error("expected no immediate command on key 'U'")+ }++ // 2. View of modal+ viewOut := m.View()+ if !strings.Contains(viewOut, "LazySkills App Update") {+ t.Errorf("expected app update view header, got: %s", viewOut)+ }+ if !strings.Contains(viewOut, "Current Version: v1.0.0") {+ t.Errorf("expected current version in view, got: %s", viewOut)+ }+ if !strings.Contains(viewOut, "Latest Version: v1.1.0") {+ t.Errorf("expected latest version in view, got: %s", viewOut)+ }++ // 3. Pressing Enter starts update execution+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = modelTmp.(appModel)+ if !m.updatingApp {+ t.Error("expected updatingApp to be true after pressing Enter")+ }+ if cmd == nil {+ t.Fatal("expected update command to be scheduled, got nil")+ }++ // 4. Update result message handler success+ modelTmp, cmd = m.Update(appUpdateResultMsg{err: nil})+ m = modelTmp.(appModel)+ if m.updatingApp {+ t.Error("expected updatingApp to be false after completion")+ }+ if !m.updateSuccess {+ t.Error("expected updateSuccess to be true after nil err result")+ }+ if m.updateError != nil {+ t.Errorf("expected no updateError, got: %v", m.updateError)+ }++ viewSuccess := m.View()+ if !strings.Contains(viewSuccess, "Update successful") {+ t.Errorf("expected success message in view, got: %s", viewSuccess)+ }++ // 5. Esc closes modal+ modelTmp, cmd = m.Update(tea.KeyMsg{Type: tea.KeyEsc})+ m = modelTmp.(appModel)+ if m.appUpdateModal {+ t.Error("expected appUpdateModal to be false after pressing Esc")+ }+}++func TestTUIAppUpdateModalNonActionable(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ m := newModel("")+ m.width = 100+ m.height = 30+ m.updatePlan = &selfupdate.UpdatePlan{+ Current: "v1.0.0",+ Latest: "v1.1.0",+ Status: selfupdate.StatusAvailable,+ Channel: "brew",+ Confidence: "high",+ CanExecute: false,+ CommandPreview: "brew upgrade lazyskills",+ Reason: "Homebrew managed install. Please upgrade using Homebrew.",+ }++ // Pressing 'U' opens the modal+ modelTmp, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("U")})+ m = modelTmp.(appModel)+ if !m.appUpdateModal {+ t.Fatal("expected modal to open")+ }++ // Check that we see the guidance command instead of an update trigger+ viewOut := m.View()+ if !strings.Contains(viewOut, "Auto-update is not supported for this install channel.") {+ t.Errorf("expected unsupported guidance, got: %s", viewOut)+ }+ if !strings.Contains(viewOut, "brew upgrade lazyskills") {+ t.Errorf("expected command preview in guidance view, got: %s", viewOut)+ }++ // Pressing Enter does not trigger update since CanExecute is false+ modelTmp, cmd := m.Update(tea.KeyMsg{Type: tea.KeyEnter})+ m = modelTmp.(appModel)+ if m.updatingApp {+ t.Error("should not set updatingApp to true when CanExecute is false")+ }+ if cmd != nil {+ t.Error("should not return a command when CanExecute is false")+ }+}++func TestTUIAppUpdateModalStates(t *testing.T) {+ t.Setenv("XDG_CACHE_HOME", t.TempDir())+ m := newModel("")+ m.width = 100+ m.height = 30++ // 1. Pending check state: updatePlan is nil+ modelTmp, _ := m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("U")})+ m = modelTmp.(appModel)+ if !m.appUpdateModal {+ t.Fatal("expected modal to open")+ }+ viewOut := m.View()+ if !strings.Contains(viewOut, "Checking for updates...") {+ t.Errorf("expected Checking for updates message, got: %s", viewOut)+ }++ // 2. Error state: updatePlanErr is set+ m.appUpdateModal = false+ m.updatePlanErr = fmt.Errorf("sample query error")+ modelTmp, _ = m.Update(tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune("U")})+ m = modelTmp.(appModel)+ if !m.appUpdateModal {+ t.Fatal("expected modal to open")+ }+ viewOut = m.View()+ if !strings.Contains(viewOut, "Update check failed") || !strings.Contains(viewOut, "sample query error") {+ t.Errorf("expected error message to be surfaced, got: %s", viewOut)+ }+}diff --git a/internal/tui/view.go b/internal/tui/view.goindex 8a7d8d6..caaf1d8 100644--- a/internal/tui/view.go+++ b/internal/tui/view.go@@ -11,6 +11,7 @@ import ("github.com/alvinunreal/lazyskills/internal/compat""github.com/alvinunreal/lazyskills/internal/display""github.com/alvinunreal/lazyskills/internal/model"+ "github.com/alvinunreal/lazyskills/internal/selfupdate""github.com/charmbracelet/lipgloss")@@ -30,6 +31,9 @@ func (m appModel) View() string {if m.detailModal {return m.detailModalOverlay(layout)}+ if m.appUpdateModal {+ return m.appUpdateModalOverlay(layout)+ }if m.helpOpen {return m.helpModalOverlay(layout)}@@ -1309,6 +1313,17 @@ func (m appModel) footerText(width int) string {text = "enter open · e enable/disable · c actions · u update · x remove · ? help"}}+ isNormalState := !m.running && !m.confirming && !m.searching && !m.detailModal && !m.commands && !m.helpOpen+ if isNormalState && m.updatePlan != nil && m.updatePlan.Status == selfupdate.StatusAvailable {+ latestClean := m.updatePlan.Latest+ if strings.HasPrefix(strings.ToLower(latestClean), "v") {+ latestClean = latestClean[1:]+ }+ notice := fmt.Sprintf(" · U update (v%s available)", latestClean)+ if width >= 80 {+ text += notice+ }+ }return dimStyle.Render(truncate(text, width))}@@ -1346,6 +1361,7 @@ func (m appModel) helpModalOverlay(layout appLayout) string {" e Enable / disable selected skill or source group"," c Open command picker menu"," u / x Quick reinstall-update / remove for selection",+ " U Check/run LazySkills application update"," d Check local or remote source for available skills (Source row)"," r Refresh scan snapshot","",@@ -1516,3 +1532,97 @@ func (m appModel) runningOverlay(layout appLayout) string {box := lipgloss.NewStyle().Border(lipgloss.RoundedBorder()).BorderForeground(actionBorderColor).Padding(1, 2).Width(52).Render(strings.Join(lines, "\n"))return fitToScreen(lipgloss.Place(layout.Width, layout.Height, lipgloss.Center, lipgloss.Center, box), layout.Width, layout.Height)}++func (m appModel) appUpdateModalOverlay(layout appLayout) string {+ modalWidth := 74+ if layout.Width < modalWidth+4 {+ modalWidth = layout.Width - 4+ }+ if modalWidth < 20 {+ modalWidth = 20+ }++ var sections []string+ sections = append(sections, titleStyle.Render(" LazySkills App Update "))+ sections = append(sections, "")++ plan := m.updatePlan+ if m.updatePlanErr != nil {+ sections = append(sections, errorStyle.Render("✗ Update check failed:"))+ sections = append(sections, wrapText(m.updatePlanErr.Error(), modalWidth-4))+ sections = append(sections, "")+ sections = append(sections, dimStyle.Render("esc/q close"))+ } else if plan == nil {+ sections = append(sections, "Checking for updates...")+ sections = append(sections, "")+ sections = append(sections, dimStyle.Render("esc/q close"))+ } else {+ sections = append(sections, fmt.Sprintf("Current Version: %s", plan.Current))+ sections = append(sections, fmt.Sprintf("Latest Version: %s", plan.Latest))+ sections = append(sections, fmt.Sprintf("Install Channel: %s", plan.Channel))+ sections = append(sections, "")++ if m.updatingApp {+ sections = append(sections, runningStyle.Render("Updating... Please wait."))+ sections = append(sections, "Downloading archive and verifying checksum...")+ } else if m.updateSuccess {+ sections = append(sections, successStyle.Render("✓ Update successful!"))+ sections = append(sections, "Please restart lazyskills to apply the update.")+ sections = append(sections, "")+ sections = append(sections, dimStyle.Render("esc/q close"))+ } else if m.updateError != nil {+ sections = append(sections, errorStyle.Render("✗ Update failed:"))+ sections = append(sections, wrapText(m.updateError.Error(), modalWidth-4))+ sections = append(sections, "")+ sections = append(sections, dimStyle.Render("enter retry · esc/q close"))+ } else {+ if plan.CanExecute {+ sections = append(sections, "A newer version is available. Would you like to update?")+ sections = append(sections, "")+ if plan.ReleaseNotes != "" {+ sections = append(sections, sectionHeaderStyle.Render("Release Notes:"), truncateReleaseNotes(plan.ReleaseNotes, modalWidth-4), "")+ }+ sections = append(sections, "enter start update · esc/q cancel")+ } else {+ if plan.Status == selfupdate.StatusAlreadyLatest {+ sections = append(sections, "You are already running the latest version.")+ } else if plan.Status == selfupdate.StatusUnknown {+ sections = append(sections, "Update check status is unknown.")+ sections = append(sections, plan.Reason)+ } else {+ sections = append(sections, "Auto-update is not supported for this install channel.")+ sections = append(sections, plan.Reason)+ if plan.CommandPreview != "" {+ sections = append(sections, "")+ sections = append(sections, "To upgrade, run:")+ sections = append(sections, lipgloss.NewStyle().Foreground(lipgloss.Color("141")).Render(" "+plan.CommandPreview))+ }+ }+ sections = append(sections, "")+ sections = append(sections, dimStyle.Render("esc/q close"))+ }+ }+ }++ box := lipgloss.NewStyle().+ Border(lipgloss.RoundedBorder()).+ BorderForeground(actionBorderColor).+ Padding(1, 2).+ Width(modalWidth).+ Render(strings.Join(sections, "\n"))++ return fitToScreen(lipgloss.Place(layout.Width, layout.Height, lipgloss.Center, lipgloss.Center, box), layout.Width, layout.Height)+}++func truncateReleaseNotes(notes string, width int) string {+ lines := strings.Split(notes, "\n")+ var out []string+ for i, line := range lines {+ if i >= 10 {+ out = append(out, "... (truncated)")+ break+ }+ out = append(out, wrapText(line, width))+ }+ return strings.Join(out, "\n")+}