Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.
update: a download that breaks off is tried five more times, from where it stopped
yetone6335625a6016
diff --git a/internal/update/download_test.go b/internal/update/download_test.goindex cbd2019e7..aa28c298c 100644--- a/internal/update/download_test.go+++ b/internal/update/download_test.go@@ -1,15 +1,20 @@package updateimport (+ "bytes""context""crypto/sha256""encoding/hex"+ "fmt""net/http""net/http/httptest""os""path/filepath"+ "slices""strconv"+ "strings""testing"+ "time")// A download that drops part way is tried again, and reports its progress.@@ -47,3 +52,148 @@ func TestDownloadRetriesAndReports(t *testing.T) {t.Fatalf("file has %d bytes", len(b))}}++// quickRetries has download's tries follow each other at once.+func quickRetries(t *testing.T) {+ t.Helper()+ old := retryWaits+ retryWaits = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond, time.Millisecond}+ t.Cleanup(func() { retryWaits = old })+}++// A download the connection cuts part way goes on from where it broke+// off: the next try asks for the rest with Range, and the hash is checked+// over the whole file, the bytes of the first try included.+func TestDownloadResumesWhereItBrokeOff(t *testing.T) {+ quickRetries(t)+ body := make([]byte, 512<<10)+ for i := range body {+ body[i] = byte(i * 7)+ }+ sum := sha256.Sum256(body)+ var ranges []string+ cut := []int{100 << 10, 300 << 10} // where the first two tries break off+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ ranges = append(ranges, r.Header.Get("Range"))+ from := 0+ if rg := r.Header.Get("Range"); rg != "" {+ from, _ = strconv.Atoi(strings.TrimSuffix(strings.TrimPrefix(rg, "bytes="), "-"))+ w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", from, len(body)-1, len(body)))+ w.Header().Set("Content-Length", strconv.Itoa(len(body)-from))+ w.WriteHeader(http.StatusPartialContent)+ } else {+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))+ }+ to := len(body)+ if n := len(ranges) - 1; n < len(cut) {+ to = cut[n]+ }+ w.Write(body[from:to])+ if to < len(body) {+ w.(http.Flusher).Flush()+ conn, _, _ := w.(http.Hijacker).Hijack()+ conn.Close() // mid-stream+ }+ }))+ defer srv.Close()++ var done, total int64+ ctx := WithProgress(context.Background(), func(d, t int64) { done, total = d, t })+ path := filepath.Join(t.TempDir(), "magpie.new")+ if err := download(ctx, Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path); err != nil {+ t.Fatal(err)+ }+ want := []string{"", "bytes=102400-", "bytes=307200-"}+ if !slices.Equal(ranges, want) {+ t.Fatalf("ranges asked = %q, want %q", ranges, want)+ }+ if b, _ := os.ReadFile(path); !bytes.Equal(b, body) {+ t.Fatalf("file has %d bytes, not the release's", len(b))+ }+ if done != int64(len(body)) || total != int64(len(body)) {+ t.Fatalf("progress = %d/%d, want %d/%d", done, total, len(body), len(body))+ }+}++// The rest of a file sent with other bytes than the release's (a host+// that resumes wrongly) fails the hash, which covers the whole file, and+// nothing is kept.+func TestDownloadResumedFileIsStillChecked(t *testing.T) {+ quickRetries(t)+ body := bytes.Repeat([]byte("magpie"), 50<<10)+ sum := sha256.Sum256(body)+ tries := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ tries+++ if tries == 1 {+ w.Header().Set("Content-Length", strconv.Itoa(len(body)))+ w.Write(body[:1000])+ w.(http.Flusher).Flush()+ conn, _, _ := w.(http.Hijacker).Hijack()+ conn.Close()+ return+ }+ w.Header().Set("Content-Range", fmt.Sprintf("bytes 1000-%d/%d", len(body)-1, len(body)))+ w.WriteHeader(http.StatusPartialContent)+ w.Write(bytes.Repeat([]byte("x"), len(body)-1000))+ }))+ defer srv.Close()+ path := filepath.Join(t.TempDir(), "magpie.new")+ err := download(context.Background(), Asset{URL: srv.URL, SHA256: hex.EncodeToString(sum[:])}, path)+ if err == nil || !strings.Contains(err.Error(), "does not match its checksum") {+ t.Fatalf("err = %v, want a checksum mismatch", err)+ }+ if _, serr := os.Stat(path); !os.IsNotExist(serr) {+ t.Fatal("the mismatched file was kept")+ }+}++// A connection dropped before any answer (EOF at the connect, what the+// reporter's Windows box got from GitHub's asset host) is tried again+// every time retryWaits allows, and the error that ends it names the file+// and the cause, not the signed address it was redirected to.+func TestDownloadDroppedConnectionErrorKeepsAddressOut(t *testing.T) {+ quickRetries(t)+ tries := 0+ assets := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ tries+++ conn, _, _ := w.(http.Hijacker).Hijack()+ conn.Close() // EOF, no answer at all+ }))+ defer assets.Close()+ signed := assets.URL + "/github-production-release-asset/1?sig=SECRETSIG&jwt=SECRETJWT"+ gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ http.Redirect(w, r, signed, http.StatusFound)+ }))+ defer gh.Close()+ path := filepath.Join(t.TempDir(), "magpie.new")+ err := download(context.Background(), Asset{URL: gh.URL + "/magpie-windows-amd64.exe", SHA256: "00"}, path)+ if err == nil || !Network(err) {+ t.Fatalf("err = %v, want a network error", err)+ }+ if tries != len(retryWaits)+1 {+ t.Fatalf("tries = %d, want %d", tries, len(retryWaits)+1)+ }+ if msg := err.Error(); strings.Contains(msg, "SECRET") || strings.Contains(msg, "http") || !strings.Contains(msg, "magpie.new") || !strings.Contains(msg, "EOF") {+ t.Fatalf("error = %q", msg)+ }+ if _, serr := os.Stat(path); !os.IsNotExist(serr) {+ t.Fatal("a partial file was kept")+ }+}++// A refusal that isn't the network's (404: not uploaded yet) isn't tried+// again and again.+func TestDownloadNotFoundIsNotRetried(t *testing.T) {+ quickRetries(t)+ tries := 0+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ tries+++ http.NotFound(w, r)+ }))+ defer srv.Close()+ err := download(context.Background(), Asset{URL: srv.URL, SHA256: "00"}, filepath.Join(t.TempDir(), "magpie.new"))+ if err == nil || Network(err) || tries != 1 {+ t.Fatalf("err = %v after %d tries, want one 404", err, tries)+ }+}diff --git a/internal/update/update.go b/internal/update/update.goindex a0656a9ba..027b9ec8b 100644--- a/internal/update/update.go+++ b/internal/update/update.go@@ -21,6 +21,7 @@ import ("io""io/fs""net/http"+ "net/url""os""path/filepath""regexp"@@ -852,81 +853,166 @@ func WithProgress(ctx context.Context, f func(done, total int64)) context.Contexreturn context.WithValue(ctx, progressKey{}, f)}+// retryWaits are the pauses before each try after the first: a+// connection that drops at the start or part way (GitHub's asset host from+// some networks: AIMetaPhD on X, "EOF" at 0.1.1618) is tried again, from+// where it broke off. A var for tests.+var retryWaits = []time.Duration{2 * time.Second, 4 * time.Second, 8 * time.Second, 16 * time.Second, 30 * time.Second}+// download fetches a to path and checks its hash. A connection that drops-// part way — GitHub from some networks — gets two more tries.+// is tried again after each of retryWaits, asking with Range for what is+// still missing; the hash is checked over the whole file, the bytes kept+// from the tries before included.func download(ctx context.Context, a Asset, path string) error {if a.SHA256 == "" {return errors.New("the release lists no checksum for " + filepath.Base(path))}+ os.Remove(path) // a file left by an earlier run is no part of this onevar err error- for try := 0; try < 3; try++ {+ for try := 0; try <= len(retryWaits); try++ {if try > 0 {select {case <-ctx.Done():return err- case <-time.After(time.Duration(try) * 2 * time.Second):+ case <-time.After(retryWaits[try-1]):}}- if err = fetch(ctx, a, path); err == nil || ctx.Err() != nil {+ if err = fetch(ctx, a, path); err == nil || ctx.Err() != nil || !Network(err) {break}}+ if err != nil {+ os.Remove(path)+ }return err}+// NetError is a download the network broke off: the connection failed or+// dropped part way. It names the file and the cause, never the address:+// GitHub's redirect is a signed URL, hundreds of characters of signature+// and token that say nothing to the user.+type NetError struct {+ File string+ Err error+}++func (e *NetError) Error() string {+ cause := e.Err+ var ue *url.Error+ if errors.As(cause, &ue) {+ cause = ue.Err+ }+ return fmt.Sprintf("the download of %s broke off (%v)", e.File, cause)+}++func (e *NetError) Unwrap() error { return e.Err }++// Network reports whether err is a download the network broke off, which+// trying again may get through.+func Network(err error) bool { return errors.As(err, new(*NetError)) }++// fetch downloads a to path, or the rest of it when path holds the start+// already (a try before broke off): what is there is asked for no more+// (Range), and a host that sends the whole file again has it written from+// the beginning. A try the network breaks off keeps what came, for the next+// one; any other failure removes it.func fetch(ctx context.Context, a Asset, path string) error {// through a mirror when one is given (mirror.go): the hash checked// below is still the feed'su := mirrored(mirrorOf(ctx), a.URL)+ mirror := strings.TrimSuffix(u, a.URL)+ name := filepath.Base(path)+ var have int64+ if fi, err := os.Stat(path); err == nil && fi.Mode().IsRegular() {+ have = fi.Size()+ }req, err := http.NewRequestWithContext(ctx, "GET", u, nil)if err != nil {return err}+ if have > 0 {+ req.Header.Set("Range", fmt.Sprintf("bytes=%d-", have))+ }+ fail := func(err error) error {+ if !Network(err) {+ os.Remove(path)+ }+ if u != a.URL && !errors.As(err, new(*MirrorError)) {+ err = &MirrorError{Mirror: mirror, Err: err}+ }+ return err+ }res, err := source.Do(client, req)if err != nil {- if u != a.URL {- return &MirrorError{Mirror: strings.TrimSuffix(u, a.URL), Err: err}+ if ctx.Err() != nil {+ return fail(err)}- return err+ return fail(&NetError{File: name, Err: err})}defer res.Body.Close()- if res.StatusCode != 200 {+ flag := os.O_WRONLY | os.O_CREATE | os.O_TRUNC+ switch {+ case res.StatusCode == http.StatusPartialContent && have > 0 && strings.HasPrefix(res.Header.Get("Content-Range"), fmt.Sprintf("bytes %d-", have)):+ flag = os.O_WRONLY | os.O_APPEND+ case res.StatusCode == http.StatusOK:+ have = 0 // the whole file again+ default:if u != a.URL {- return &MirrorError{Mirror: strings.TrimSuffix(u, a.URL), Err: fmt.Errorf("download %s through the mirror %s: %s", filepath.Base(path), strings.TrimSuffix(u, a.URL), res.Status)}+ return fail(&MirrorError{Mirror: mirror, Err: fmt.Errorf("download %s through the mirror %s: %s", name, mirror, res.Status)})}- return fmt.Errorf("download %s: %s", filepath.Base(path), res.Status)+ return fail(fmt.Errorf("download %s: %s", name, res.Status))}- f, err := os.Create(path)+ f, err := os.OpenFile(path, flag, 0o644)if err != nil {- return err+ return fail(err)}- h := sha256.New()- var body io.Reader = res.Body+ // a read that fails is the network's; a write that fails (a full+ // disk) is not, and isn't tried again+ in := &readErr{r: res.Body}+ var body io.Reader = inif report, ok := ctx.Value(progressKey{}).(func(done, total int64)); ok {total := res.ContentLength- if total <= 0 {+ if total > 0 {+ total += have+ } else {total = a.Size}- body = &counter{r: res.Body, total: max(total, 0), report: report}- report(0, max(total, 0))+ body = &counter{r: in, done: have, total: max(total, 0), report: report}+ report(have, max(total, 0))}- _, err = io.Copy(io.MultiWriter(f, h), body)+ _, err = io.Copy(f, body)if cerr := f.Close(); err == nil {err = cerr}- if err == nil && !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), a.SHA256) {- err = fmt.Errorf("%s does not match its checksum", filepath.Base(path))- if u != a.URL {- err = fmt.Errorf("%s from the mirror %s does not match its checksum from %s; not installed", filepath.Base(path), strings.TrimSuffix(u, a.URL), Site)+ if err != nil {+ if ctx.Err() == nil && in.err != nil {+ err = &NetError{File: name, Err: err}}+ return fail(err)}- if err != nil && u != a.URL && !errors.As(err, new(*MirrorError)) {- err = &MirrorError{Mirror: strings.TrimSuffix(u, a.URL), Err: err}+ // the whole file, what earlier tries kept included, against the feed's+ if !strings.EqualFold(fileHash(path), a.SHA256) {+ err = fmt.Errorf("%s does not match its checksum", name)+ if u != a.URL {+ err = fmt.Errorf("%s from the mirror %s does not match its checksum from %s; not installed", name, mirror, Site)+ }+ return fail(err)}- if err != nil {- os.Remove(path)+ return nil+}++// readErr keeps the error its reader returned, io.EOF aside.+type readErr struct {+ r io.Reader+ err error+}++func (r *readErr) Read(p []byte) (int, error) {+ n, err := r.r.Read(p)+ if err != nil && err != io.EOF {+ r.err = err}- return err+ return n, err}// counter reports bytes as they are read.