diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index cf21f46aa..f442c389d 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -110,11 +110,20 @@ further (`State.Since`), unless a range is picked. (`memdistill.All`, -1); 0 is the 7-day default, so a state from before the picker keeps its own `Since` until a range is picked (`TestRangePicked`). Every range reads from the latest 400 conversations - (`Listed`) at 10 an hour (`PerRun`), so All costs at most ~240 requests - a day until the backlog is read; the picker's All says so. + (`Listed`). +- A backlog is read at once when the user asks (`ReadAll`, through + `distillNow`): switched on, a model or a longer range picked, Read now. + It reads every conversation due, one request at a time, and the row + shows how far it has gone (`Progress`, `doing` of `of` in the view) + with a Stop (`Stop`, `POST /api/memory/distill/stop`; switching off + stops it too). A stop or a failure leaves the rest for the next run, + and the row says how many (`State.Left`) (`TestBacklogReadAtOnce`, + `TestStopEndsTheRun`). Before, every run read 10, and 400 took 40 + hours (RealZeroP27 on X). - State is `distill.json` beside `memory.json` (`memdistill.Path`): the switch, the model, the reasoning level, the range, the - conversations done, and the last run's time, counts and error. A + conversations done, and the last run's time, counts, error and how + many it left. A conversation's mark is dropped once it is before `Since`, or older than 30 days and past the oldest conversation listed; before that a conversation older than 30 days was read again every hour @@ -123,7 +132,7 @@ further (`State.Since`), unless a range is picked. (`TestUnreadableStateRunsNothing`). - `Keep` runs 5 minutes after the GUI backend starts, then hourly (`keepDistilling` in `internal/gui/memory_distill.go`). `Run` takes at - most 10 conversations (`PerRun`) quiet for 30 minutes (`Quiet`) with at + most 30 conversations (`PerRun`, more than a busy hour brings) quiet for 30 minutes (`Quiet`) with at least two turns, and skips the gateway's own records, read-only agents, subagent sessions and its own agent (`memory`). One run at a time, in this process and across processes (`.run` lock). diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 8798c2a6f..9463ca44a 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1129,12 +1129,12 @@ magpie.plugin("library", (ctx) => { return b; } // how far back conversations are read: 7 days unless picked, All the - // latest 400 (memdistill.Listed), PerRun an hour like any other + // latest 400 (memdistill.Listed); a longer range reads at once const rangeName = (n) => n === -1 ? t("All") : n === 365 ? t("1 year") : t("{n} days", { n }); function memRangePick(d) { const cur = d.days || 7; const b = menuButton(rangeName(cur), "lib-distrange", () => openProtoMenu(b, - (d.ranges || [7, 30, 90, 365, -1]).map((n) => ({ v: String(n), name: rangeName(n), literalName: true, note: n === -1 ? "The latest 400 conversations, read 10 an hour" : "" })), + (d.ranges || [7, 30, 90, 365, -1]).map((n) => ({ v: String(n), name: rangeName(n), literalName: true, note: n === -1 ? "The latest 400 conversations" : "" })), String(cur), (v) => +v !== cur && distChange("memory/distill", { on: d.on, model: d.model || "", days: +v }), "How far back it reads")); b.title = t("How far back it reads"); return b; @@ -1149,15 +1149,19 @@ magpie.plugin("library", (ctx) => { w.append(el("div", "name", t("Learn from conversations"))); let line = t("Reads each finished conversation for what to remember. You review each one before agents see it."); let err = false; - if (d.on && d.running) line = t("Reading conversations…"); - else if (d.on && d.error) { line = t("Stopped {when}: {error}", { when: ago(d.last), error: d.error }); err = true; } - else if (d.on && d.last) line = t("Read {when} · {k} new to review", { when: ago(d.last), k: d.added || 0 }); + // a run's progress, and what one left, so a long backlog is seen + // going and Read now reads the rest (RealZeroP27 on X) + const left = d.left ? " · " + t("{n} not read yet", { n: d.left }) : ""; + if (d.on && d.running) line = d.of ? t("Reading conversations… {n} of {m}", { n: d.doing || 0, m: d.of }) : t("Reading conversations…"); + else if (d.on && d.error) { line = t("Stopped {when}: {error}", { when: ago(d.last), error: d.error }) + left; err = true; } + else if (d.on && d.last) line = t("Read {when} · {k} new to review", { when: ago(d.last), k: d.added || 0 }) + left; else if (d.on) line = t("Reads conversations quiet for 30 minutes, every hour"); w.append(el("div", "sub" + (err ? " err" : ""), line)); const acts = el("div", "lib-acts"); if (d.on) { acts.append(memModelPick(d), ...[memEffortPick(d)].filter(Boolean), memRangePick(d)); if (!d.running) acts.append(button(t("Read now"), "action lib-distnow", () => distChange("memory/distill/run", {}))); + else if (d.of > 1) acts.append(button(t("Stop"), "action lib-diststop", () => distChange("memory/distill/stop", {}))); } acts.append(toggle(d.on, t("Learn from conversations"), (on) => distChange("memory/distill", { on, model: d.model || "" }))); r.append(glyph(GLYPH.search), w, acts); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index c81093381..020a1a19e 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -5,7 +5,9 @@ magpie.strings({ "The model's own": "模型自己的默认", "1 year": "1 年", "How far back it reads": "读取多久以前的对话", - "The latest 400 conversations, read 10 an hour": "最近 400 个对话,每小时读 10 个", + "The latest 400 conversations": "最近 400 个对话", + "Reading conversations… {n} of {m}": "正在读对话… {n}/{m}", + "{n} not read yet": "还有 {n} 个未读", "Turn {name} on or off": "开启或关闭 {name}", "{name} is on again": "{name} 已重新开启", "{name} is off; its settings are kept": "{name} 已关闭,设置都已保留", @@ -909,7 +911,9 @@ magpie.strings({ "The model's own": "模型自己的預設", "1 year": "1 年", "How far back it reads": "讀取多久以前的對話", - "The latest 400 conversations, read 10 an hour": "最近 400 個對話,每小時讀 10 個", + "The latest 400 conversations": "最近 400 個對話", + "Reading conversations… {n} of {m}": "正在讀對話… {n}/{m}", + "{n} not read yet": "還有 {n} 個未讀", "Turn {name} on or off": "開啟或關閉 {name}", "{name} is on again": "{name} 已重新開啟", "{name} is off; its settings are kept": "{name} 已關閉,設定都已保留", @@ -1813,7 +1817,9 @@ magpie.strings({ "The model's own": "モデル自身の既定", "1 year": "1 年", "How far back it reads": "どこまで遡って読むか", - "The latest 400 conversations, read 10 an hour": "最新の 400 件の会話を 1 時間に 10 件ずつ読みます", + "The latest 400 conversations": "最新の 400 件の会話", + "Reading conversations… {n} of {m}": "会話を読んでいます… {n}/{m}", + "{n} not read yet": "未読 {n} 件", "Turn {name} on or off": "{name} のオン/オフ", "{name} is on again": "{name} を再びオンにしました", "{name} is off; its settings are kept": "{name} をオフにしました。設定は残っています", @@ -2717,7 +2723,9 @@ magpie.strings({ "The model's own": "Die Vorgabe des Modells", "1 year": "1 Jahr", "How far back it reads": "Wie weit zurück gelesen wird", - "The latest 400 conversations, read 10 an hour": "Die neuesten 400 Unterhaltungen, 10 pro Stunde", + "The latest 400 conversations": "Die neuesten 400 Unterhaltungen", + "Reading conversations… {n} of {m}": "Lese Unterhaltungen… {n} von {m}", + "{n} not read yet": "{n} noch nicht gelesen", "Turn {name} on or off": "{name} ein- oder ausschalten", "{name} is on again": "{name} ist wieder an", "{name} is off; its settings are kept": "{name} ist aus; seine Einstellungen bleiben", diff --git a/internal/gui/memory_distill.go b/internal/gui/memory_distill.go index d5ddb2757..b5f79629e 100644 --- a/internal/gui/memory_distill.go +++ b/internal/gui/memory_distill.go @@ -32,6 +32,9 @@ type distillView struct { EffortNow string `json:"effortNow,omitempty"` // Ranges are the ranges, in days, reading can look back (All -1) Ranges []int `json:"ranges"` + // Doing of Of are the run going's progress, 0 of 0 with none + Doing int `json:"doing,omitempty"` + Of int `json:"of,omitempty"` } func readDistill() (*distillView, error) { @@ -41,6 +44,9 @@ func readDistill() (*distillView, error) { } st.Done = nil // the marks are the run's, not the page's v := &distillView{State: st, Auto: distillAuto(), Models: []modelRef{}, Running: memdistill.Running() && !memdistill.Dreaming(), Dreaming: memdistill.Dreaming(), Ranges: memdistill.Ranges} + if v.Running { + v.Doing, v.Of = memdistill.Progress() + } inUse := st.Model if inUse == "" { inUse = v.Auto @@ -131,12 +137,17 @@ func keepDistilling(ctx context.Context) { memdistill.Keep(ctx, 5*time.Minute, time.Hour, distillAuto, distillComplete) } -// distillNow starts a run in the background, for the switch turned on -// and the Read now button; the tab polls while it runs. +// distillNow reads every conversation due in the background, for the +// switch turned on, a model or a longer range picked, and the Read now +// button; the tab polls while it runs, and Stop ends it (RealZeroP27 on +// X: the hourly 10 read 400 in 40 hours). var distillNow = func() { - go memdistill.Run(backendCtx, distillAuto(), distillComplete) + go memdistill.ReadAll(backendCtx, distillAuto(), distillComplete) } +// distillStop ends the run going. +var distillStop = memdistill.Stop + func memoryDistillRoutes(mux *http.ServeMux) { mux.HandleFunc("GET /api/memory/distill", func(rw http.ResponseWriter, r *http.Request) { v, err := readDistill() @@ -207,6 +218,15 @@ func memoryDistillRoutes(mux *http.ServeMux) { v.Running = true writeJSON(rw, v) }) + mux.HandleFunc("POST /api/memory/distill/stop", func(rw http.ResponseWriter, r *http.Request) { + distillStop() + v, err := readDistill() + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) // {on}: the nightly tidy switched; the first is due at the next night mux.HandleFunc("POST /api/memory/dream", func(rw http.ResponseWriter, r *http.Request) { var in struct { diff --git a/internal/gui/memory_distill_test.go b/internal/gui/memory_distill_test.go index 3803ae201..9d97e7de1 100644 --- a/internal/gui/memory_distill_test.go +++ b/internal/gui/memory_distill_test.go @@ -6,6 +6,8 @@ import ( "io" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" @@ -188,3 +190,28 @@ func TestDistillRangeAndEffortRoutes(t *testing.T) { } } } + +// Stop on the row ends the run going (RealZeroP27 on X: a backlog read +// at once needs a way to stop it), and the view says what the last run +// left unread. +func TestDistillStopRoute(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + stops := 0 + prev := distillStop + distillStop = func() { stops++ } + t.Cleanup(func() { distillStop = prev }) + mux := http.NewServeMux() + memoryDistillRoutes(mux) + os.MkdirAll(filepath.Dir(memdistill.Path()), 0o700) + if err := os.WriteFile(memdistill.Path(), []byte(`{"on":true,"left":37}`), 0o600); err != nil { + t.Fatal(err) + } + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", "/api/memory/distill/stop", strings.NewReader(`{}`))) + var v distillView + json.Unmarshal(rec.Body.Bytes(), &v) + if rec.Code != 200 || stops != 1 || v.Left != 37 || v.Running || v.Of != 0 { + t.Fatalf("%d %d %+v", rec.Code, stops, v) + } +} diff --git a/internal/gui/tests/library-memory.test.cjs b/internal/gui/tests/library-memory.test.cjs index 7989f0e84..b200915fd 100644 --- a/internal/gui/tests/library-memory.test.cjs +++ b/internal/gui/tests/library-memory.test.cjs @@ -75,11 +75,13 @@ function server(lang, state, sent, dist) { if (route.request().method() === "POST") { const body = route.request().postDataJSON(); sent.push({ path: url.pathname, body }); - if (url.pathname === "/api/memory/distill/run") Object.assign(dist, { running: false, error: "429: too many requests", last: new Date().toISOString() }); + if (url.pathname === "/api/memory/distill/run") Object.assign(dist, { running: false, error: "429: too many requests", last: new Date().toISOString(), left: 0 }); + else if (url.pathname === "/api/memory/distill/stop") Object.assign(dist, { running: false, last: new Date().toISOString(), added: 0, left: 397, doing: 0, of: 0 }); else if ("effort" in body) Object.assign(dist, { effort: body.effort, effortNow: body.effort }); - else if ("days" in body) Object.assign(dist, { days: body.days === 7 ? 0 : body.days, running: body.days === -1 || body.days > (dist.days || 7), gets: 0 }); - else Object.assign(dist, { on: body.on, model: body.model, running: body.on, gets: 0, error: "" }); - } else if (dist.running && ++dist.gets > 1) { + else if ("days" in body) Object.assign(dist, { days: body.days === 7 ? 0 : body.days, running: body.days === -1 || body.days > (dist.days || 7), gets: 0, doing: 3, of: 400 }); + else Object.assign(dist, { on: body.on, model: body.model, running: body.on, gets: 0, error: "", doing: 12, of: 40 }); + } else if (dist.running && dist.of !== 400 && ++dist.gets > 1) { + // (All's 400 go on until stopped) // the run ends: it read three and proposed one Object.assign(dist, { running: false, last: new Date().toISOString(), read: 3, added: 1 }); if (!state.memories.some((m) => m.id === "m9")) state.memories.push({ id: "m9", text: "Ships on Tuesdays", kind: "fact", scope: "global", origin: "inferred", status: "candidate", created: at(7), updated: at(7) }); @@ -255,6 +257,9 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.match(await drow.locator(".lib-distmodel").textContent(), /Small/); assert.equal(await trow.locator(".lib-distmodel").count(), 0, "a model picked on both rows"); assert.equal(await drow.locator(".lib-distnow").count(), 0, "Read now while reading"); + // how far it has gone, and a way to stop it (RealZeroP27 on X) + assert.match(await drow.locator(".sub").textContent(), /12\D+40/); + assert.equal(await drow.locator(".lib-diststop").count(), 1, "no Stop while reading"); assert.equal(await drow.locator(".lib-disteffort").count(), 1, "no reasoning level"); const rangeShown = await drow.locator(".lib-distrange").textContent(); assert.match(rangeShown, /7/); @@ -292,7 +297,13 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", await page.locator(".proto-menu .pm-item").nth(4).click(); assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/distill").body, { on: true, model: "dt/m1", days: -1 }); await page.waitForFunction((was) => document.querySelector("#view-library .lib-distrange")?.textContent !== was, rangeShown); + // stopped: what it left is said, and Read now reads the rest + assert.match(await drow.locator(".sub").textContent(), /3\D+400/); + await drow.locator(".lib-diststop").click(); await drow.locator(".lib-distnow").waitFor({ timeout: 8000 }); + assert.ok(sent.some((x) => x.path === "/api/memory/distill/stop")); + assert.match(await drow.locator(".sub").textContent(), /397/); + assert.equal(await drow.locator(".lib-diststop").count(), 0); // a run that stopped says why await drow.locator(".lib-distnow").click(); await drow.locator(".sub.err").waitFor(); diff --git a/internal/memdistill/memdistill.go b/internal/memdistill/memdistill.go index 0c204a266..601b58c9a 100644 --- a/internal/memdistill/memdistill.go +++ b/internal/memdistill/memdistill.go @@ -4,9 +4,10 @@ // doesn't say. What it finds waits in memory as a candidate (To review) // until the user keeps it; nothing it proposes reaches an agent before. // -// It runs when switched on (State.On), on sessions quiet for Quiet, at -// most PerRun of them a run, each once for what it held when read: a -// session that goes on is read again later, whole. The model is the one +// It runs when switched on (State.On), on sessions quiet for Quiet, each +// once for what it held when read: a session that goes on is read again +// later, whole. The hourly run reads at most PerRun; one the user asked +// for (ReadAll) reads every one due, and Stop ends it. The model is the one // picked, else the caller's automatic choice. The request goes through // magpie's own gateway (Complete), so masking and routing apply as to any // agent's request. @@ -44,14 +45,16 @@ const ( // Quiet is how long a session has had no turn before it is read: one // still going is read when it stops Quiet = 30 * time.Minute - // PerRun caps the sessions one run sends to the model - PerRun = 10 + // PerRun caps the sessions an hourly run sends to the model: more + // than a busy hour brings, so only a backlog waits for the next run. + // A run the user asked for (ReadAll) reads every one due + // (RealZeroP27 on X: at 10 an hour, 400 took 40 hours) + PerRun = 30 // Back is how far back a run looks the first time it is switched on, // when no range is picked (State.Days 0) Back = 7 * 24 * time.Hour // All is State.Days for every conversation listed: the latest - // Listed, read PerRun an hour like any other, so a long history is - // read over days, not at once + // Listed, read at once when picked (ReadAll), else PerRun an hour All = -1 // Listed is how many of the latest sessions a run looks through Listed = 400 @@ -94,6 +97,9 @@ type State struct { Read int `json:"read,omitempty"` Added int `json:"added,omitempty"` Error string `json:"error,omitempty"` + // Left is how many were due and not read when the last run ended: + // stopped, failed or past PerRun + Left int `json:"left,omitempty"` // Dream is the nightly tidy switched on (dream.go), DreamSince when Dream bool `json:"dream,omitempty"` DreamSince time.Time `json:"dreamSince,omitzero"` @@ -117,11 +123,34 @@ var ( // across magpies running sync.Mutex busy atomic.Bool + // stop ends the run going (Stop), stopped says it was asked to + stopMu sync.Mutex + stop context.CancelFunc + stopped atomic.Bool + // doing and of are the run's progress: sessions gone through, of + // how many + doing, of atomic.Int64 ) // Running says a run is going in this process. func Running() bool { return busy.Load() } +// Progress is how many sessions the run going has gone through, of how +// many it will, read or passed over; 0, 0 when none is going or it is +// still listing them. +func Progress() (int, int) { return int(doing.Load()), int(of.Load()) } + +// Stop ends the run going in this process, if any: the request in flight +// is dropped and its session read next time. It isn't an error. +func Stop() { + stopMu.Lock() + defer stopMu.Unlock() + if stop != nil { + stopped.Store(true) + stop() + } +} + // ErrRunning is a run asked for while one is going. var ErrRunning = errors.New("already reading conversations") @@ -194,8 +223,11 @@ func since(days int, t time.Time) time.Time { // Set switches distilling on or off and picks its model ("" automatic). // Switched on from off, it looks back the range picked (Back by default) -// from now. +// from now; switched off, the run going stops. func Set(on bool, model string) (State, error) { + if !on { + Stop() + } return change(func(s *State) { if on && !s.On { s.Since = since(s.Days, now()) @@ -239,10 +271,20 @@ type Result struct { Added int } -// Run reads the sessions due, if switched on, with model when the state -// names none. A model that fails stops the run: the sessions not read -// yet are read next time. +// Run reads up to PerRun of the sessions due, if switched on, with auto +// when the state names no model. A model that fails stops the run: the +// sessions not read yet are read next time. func Run(ctx context.Context, auto string, complete Complete) (Result, error) { + return runUpTo(ctx, auto, complete, PerRun) +} + +// ReadAll is Run over every session due, for a run the user asked for: +// switched on, a model or a longer range picked, Read now. Stop ends it. +func ReadAll(ctx context.Context, auto string, complete Complete) (Result, error) { + return runUpTo(ctx, auto, complete, Listed) +} + +func runUpTo(ctx context.Context, auto string, complete Complete, limit int) (Result, error) { if !running.TryLock() { return Result{}, ErrRunning } @@ -258,6 +300,19 @@ func Run(ctx context.Context, auto string, complete Complete) (Result, error) { if err != nil || !st.On { return Result{}, err } + ctx, cancel := context.WithCancel(ctx) + stopMu.Lock() + stop = cancel + stopped.Store(false) + stopMu.Unlock() + defer func() { + stopMu.Lock() + stop = nil + stopMu.Unlock() + cancel() + doing.Store(0) + of.Store(0) + }() model := st.Model if model == "" { model = auto @@ -267,10 +322,13 @@ func Run(ctx context.Context, auto string, complete Complete) (Result, error) { if model == "" { runErr = errors.New("no model to read conversations with: pick one") } else { - res, runErr = run(ctx, st, model, st.Effort, complete) + res, runErr = run(ctx, st, model, st.Effort, complete, limit) + } + if stopped.Load() && errors.Is(runErr, context.Canceled) { + runErr = nil } _, err = change(func(s *State) { - s.Last, s.LastModel, s.Read, s.Added, s.Error = now().UTC(), model, res.Read, res.Added, "" + s.Last, s.LastModel, s.Read, s.Added, s.Error, s.Left = now().UTC(), model, res.Read, res.Added, "", res.left if runErr != nil { s.Error = runErr.Error() } @@ -295,6 +353,8 @@ type ran struct { // oldest is the last turn of the oldest session listed, zero when // none was oldest time.Time + // left is how many due weren't gone through + left int } // forget says a read session's mark, its last turn at, can go: the @@ -333,17 +393,21 @@ func due(st State, t time.Time) ([]sessions.Session, time.Time) { func key(s sessions.Session) string { return s.Agent + "/" + s.ID } -func run(ctx context.Context, st State, model, effort string, complete Complete) (ran, error) { +func run(ctx context.Context, st State, model, effort string, complete Complete, limit int) (ran, error) { r := ran{done: map[string]time.Time{}} ss, oldest := due(st, now()) r.oldest = oldest + r.left = len(ss) + of.Store(int64(len(ss))) for _, s := range ss { - if r.Read >= PerRun { + if r.Read >= limit { break } if ctx.Err() != nil { return r, ctx.Err() } + r.left-- + doing.Add(1) tr, err := read(s) if err != nil { // one that can't be read now is tried again when it changes @@ -358,6 +422,10 @@ func run(ctx context.Context, st State, model, effort string, complete Complete) proj := memory.ProjectOf(s.Cwd) reply, err := complete(ctx, model, effort, prompt, request(text, known(proj), proj)) if err != nil { + r.left++ // read again next time + if ctx.Err() != nil { + return r, ctx.Err() + } return r, fmt.Errorf("%s: %w", model, err) } r.Read++ diff --git a/internal/memdistill/memdistill_test.go b/internal/memdistill/memdistill_test.go index e282324bb..a1b803df5 100644 --- a/internal/memdistill/memdistill_test.go +++ b/internal/memdistill/memdistill_test.go @@ -430,3 +430,92 @@ func TestOldConversationReadOnce(t *testing.T) { t.Fatalf("%+v", st.Done) } } + +// A backlog is read at once when asked for (RealZeroP27 on X: at 10 an +// hour, 400 conversations took 40 hours). The hourly run reads PerRun +// and says how many it left; ReadAll reads every one left, with its +// progress seen while it goes; what is read isn't read again. +func TestBacklogReadAtOnce(t *testing.T) { + sb := newSandbox(t) + on(t, "") + if _, err := SetRange(All); err != nil { + t.Fatal(err) + } + for i := range Listed { + sb.session(fmt.Sprint("s", i), time.Hour+time.Duration(i)*time.Hour, fmt.Sprint("n", i), "more") + } + res, err := Run(context.Background(), "a/m", sb.complete) + if err != nil || res.Read != PerRun { + t.Fatalf("hourly %+v %v", res, err) + } + if st, _ := Load(); st.Left != Listed-PerRun { + t.Fatalf("left %d", st.Left) + } + var seen [][2]int + sb.reply = func(string) (string, error) { + n, m := Progress() + seen = append(seen, [2]int{n, m}) + return "[]", nil + } + sb.asked = nil + res, err = ReadAll(context.Background(), "a/m", sb.complete) + if err != nil || res.Read != Listed-PerRun || len(sb.asked) != Listed-PerRun { + t.Fatalf("read all %+v %v %d", res, err, len(sb.asked)) + } + if seen[0] != [2]int{1, Listed - PerRun} || seen[len(seen)-1] != [2]int{Listed - PerRun, Listed - PerRun} { + t.Fatalf("progress %v … %v", seen[0], seen[len(seen)-1]) + } + if n, m := Progress(); n != 0 || m != 0 || Running() { + t.Fatalf("after the run %d of %d", n, m) + } + if st, _ := Load(); st.Left != 0 || st.Error != "" { + t.Fatalf("%+v", st) + } + sb.asked = nil + if res, _ := ReadAll(context.Background(), "a/m", sb.complete); res.Read != 0 || len(sb.asked) != 0 { + t.Fatalf("read again %+v", res) + } +} + +// Stop ends a run going, and so does switching off: the request in +// flight is dropped and read next time, and it isn't an error. +func TestStopEndsTheRun(t *testing.T) { + sb := newSandbox(t) + on(t, "") + for i := range 20 { + sb.session(fmt.Sprint("s", i), time.Hour+time.Duration(i)*time.Minute, fmt.Sprint("n", i), "more") + } + stopAt := func(n int, stop func()) func(context.Context, string, string, string, string) (string, error) { + return func(ctx context.Context, model, effort, system, user string) (string, error) { + if len(sb.asked) == n-1 { + stop() + <-ctx.Done() + sb.asked = append(sb.asked, "stopped") + return "", ctx.Err() + } + return sb.complete(ctx, model, effort, system, user) + } + } + res, err := ReadAll(context.Background(), "a/m", stopAt(5, Stop)) + if err != nil || res.Read != 4 { + t.Fatalf("%+v %v", res, err) + } + if st, _ := Load(); st.Error != "" || st.Left != 16 || len(st.Done) != 4 || !st.On { + t.Fatalf("%+v", st) + } + sb.asked = nil + res, err = ReadAll(context.Background(), "a/m", stopAt(3, func() { Set(false, "") })) + if err != nil || res.Read != 2 { + t.Fatalf("switched off: %+v %v", res, err) + } + if st, _ := Load(); st.On || st.Left != 14 { + t.Fatalf("%+v", st) + } + // with none going, Stop does nothing, and the next run reads the rest + Stop() + on(t, "") + sb.asked = nil + if res, err := ReadAll(context.Background(), "a/m", sb.complete); err != nil || res.Read != 14 { + t.Fatalf("%+v %v", res, err) + } +}