diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index f442c389d..df86b6450 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -93,11 +93,20 @@ agents ticked under Instructions, unless `Instructions.NoMemory` | `GET /api/memory` | `{memories, projects, digest, agents}` | | `POST /api/memory` | `{id?, …Input}`: `Edit` with an id, else `Save` as the user's | | `POST /api/memory/remove` | `{ids}` | +| `POST /api/memory/status` | `{ids, status}`: `SetStatus`, in one write, as `Edit` by the user per memory (`TestSetStatusOfSome`, `TestMemoryStatusRouteActsOnSome`) | | `POST /api/memory/digest` | `{on}` | A reply after a change carries `problem` when publishing the digest failed. The tab is in [plugins/library/client.js](../../internal/gui/assets/plugins/library/client.js) (`renderMemory`), tested by `internal/gui/tests/library-memory.test.cjs`. +Its Select puts a box on each memory listed: a click picks one, a +Shift-click the range from the last one clicked, ↑ ↓ move between the +boxes (Shift picks as it goes), ⌘A / Ctrl+A picks every one shown, Escape +ends it. The bar under the list keeps (To review), archives (In use) or +restores (Archived) the ones picked through `/api/memory/status`, and +deletes them on a second click through `/api/memory/remove`; a search or +filter unpicks what it hides (RealZeroP27 on X, +`library-memory-select.test.cjs`). ### Distillation @@ -213,5 +222,5 @@ mote-run go test ./internal/memory ./internal/memdistill ./internal/library mote-run go test -run 'Distill|Dream' ./internal/gui mote-run go test -tags nogui -run 'MemoryMCP|OwnMCP' ./internal/gateway mote-run go test ./internal/browsermcp ./internal/cli -mote-run node --test internal/gui/tests/library-memory.test.cjs +mote-run node --test internal/gui/tests/library-memory.test.cjs internal/gui/tests/library-memory-select.test.cjs ``` diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index 65067028b..6778c8066 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -964,6 +964,13 @@ magpie.plugin("library", (ctx) => { let memOpen = null; // the memory open to edit, or "new" let memDraft = null; // its fields as typed let memRemoving = null; // the memory whose Delete was clicked once + // Select (RealZeroP27 on X): a box on each memory shown, and a bar that + // keeps, archives, restores or deletes the ones picked at once + let memPicking = false; + const memPicked = new Set(); // ids + let memAnchor = null; // the one picked or unpicked last: a Shift-click's range starts there + let memSure = false; // the bar's Delete was clicked once + let memShown = []; // the memories listed, in their order const MEM_KINDS = ["profile", "preference", "rule", "reference", "fact", "procedure", "episode"]; const kindName = (k) => ({ profile: t("About you"), preference: t("Preference"), rule: t("Rule"), reference: t("Reference"), fact: t("Fact"), procedure: t("How-to"), episode: t("Decision") })[k] || k; function scopeName(s) { @@ -1086,15 +1093,23 @@ magpie.plugin("library", (ctx) => { ], memStatus, (v) => { memStatus = v; memOpen = null; render(); }); st.classList.add("lib-memstatus"); const sc = menuButton(memScope ? scopeName(memScope) : t("All"), "lib-memscope", () => openProtoMenu(sc, [{ v: "", name: t("Everywhere and every project"), literalName: true, note: "" }, ...memScopes(true).filter((s) => all.some((m) => m.scope === s)).map((s) => ({ v: s, name: scopeName(s), literalName: true, note: "" }))], memScope, (v) => { memScope = v; render(); }, "Where it applies")); - bar.append(q, sc, st, el("span", "grow"), button("+ " + t("Add"), "action lib-memadd", () => { openMemory(null); render(); })); - body.append(bar); - const words = memQ.trim().toLowerCase().split(/\s+/).filter(Boolean); const shown = all.filter((m) => (memStatus === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === memStatus) && (!memScope || m.scope === memScope) && words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w))) .sort((a, b) => (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0)); - const list = el("div", "list lib-list lib-mems"); + // what's picked is what's listed: a search, a filter or another + // status leaves the rest unpicked, and an empty list ends Select + memShown = shown; + for (const id of memPicked) if (!shown.some((m) => m.id === id)) memPicked.delete(id); + if (memAnchor && !memPicked.has(memAnchor) && !shown.some((m) => m.id === memAnchor)) memAnchor = null; + if (memPicking && !shown.length) endMemPick(); + bar.append(q, sc, st, el("span", "grow")); + if (memPicking || shown.length > 1) bar.append(memPickButton()); + bar.append(button("+ " + t("Add"), "action lib-memadd", () => { endMemPick(); openMemory(null); render(); })); + body.append(bar); + + const list = el("div", "list lib-list lib-mems" + (memPicking ? " picking" : "")); if (memOpen === "new") list.append(memDetail(null)); for (const m of shown) list.append(...memRow(m)); if (!shown.length && memOpen !== "new") { @@ -1104,6 +1119,121 @@ magpie.plugin("library", (ctx) => { : t("Nothing remembered yet. Tell an agent “remember that…”, or add one here."))); } body.append(list); + if (memPicking) body.append(memPickBar()); + } + + // ---------- some memories, picked, acted on at once ---------- + + function endMemPick() { + memPicking = false; + memPicked.clear(); + memAnchor = null; + memSure = false; + } + function memPickButton() { + const b = button(memPicking ? t("Done") : t("Select"), "action lib-select lib-memselect", () => { + const on = !memPicking; + endMemPick(); + if (on) { memPicking = true; memOpen = null; memDraft = null; memRemoving = null; } + render(); + if (on) requestAnimationFrame(() => page.querySelector(".lib-mems .lib-pickbox")?.focus({ preventScroll: true })); + }); + b.dataset.alt = memPicking ? t("Select") : t("Done"); // as wide as the other, see library.css + b.title = memPicking ? t("Stop picking memories") : t("Pick some memories and act on them together"); + return b; + } + // a click picks one or unpicks it; with Shift, every one from the last + // clicked to this one takes the last one's state + function memPick(id, range) { + const ids = memShown.map((m) => m.id); + const to = ids.indexOf(id), from = range && memAnchor ? ids.indexOf(memAnchor) : -1; + if (from >= 0 && to >= 0) { + const on = memPicked.has(memAnchor); + for (const x of ids.slice(Math.min(from, to), Math.max(from, to) + 1)) on ? memPicked.add(x) : memPicked.delete(x); + } else if (memPicked.has(id)) memPicked.delete(id); + else memPicked.add(id); + memAnchor = id; + memSync(); + } + function memPickAll(on) { + for (const m of memShown) on ? memPicked.add(m.id) : memPicked.delete(m.id); + memSync(); + } + // every box and the bar as the picks are now, without drawing the page + // again: the box with the focus keeps it + function memSync() { + memSure = false; + for (const row of page.querySelectorAll(".lib-mems .lib-mem")) { + const on = memPicked.has(row.dataset.id); + row.classList.toggle("picked", on); + const box = row.querySelector(".lib-pickbox"); + if (box) box.checked = on; + } + page.querySelector(".lib-mempickbar")?.replaceWith(memPickBar()); + } + // the keys a picked list answers to: ↑ ↓ move between the boxes (with + // Shift, picking as they go), ⌘A / Ctrl+A picks every one shown, Escape + // ends Select + function memPickKeys(e, id) { + if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); endMemPick(); render(); page.querySelector(".lib-memselect")?.focus({ preventScroll: true }); return; } + if ((e.metaKey || e.ctrlKey) && !e.altKey && e.key.toLowerCase() === "a") { e.preventDefault(); e.stopPropagation(); memPickAll(memPicked.size !== memShown.length); return; } + if (e.key !== "ArrowDown" && e.key !== "ArrowUp") return; + e.preventDefault(); + e.stopPropagation(); + const boxes = [...page.querySelectorAll(".lib-mems .lib-pickbox")]; + const i = boxes.findIndex((b) => b.closest(".lib-mem")?.dataset.id === id); + const next = boxes[i + (e.key === "ArrowDown" ? 1 : -1)]; + if (!next) return; + next.focus({ preventScroll: true }); + next.closest(".lib-mem")?.scrollIntoView({ block: "nearest" }); + if (e.shiftKey) { + const nid = next.closest(".lib-mem").dataset.id; + if (!memAnchor) memAnchor = id; + memPick(nid, true); + } + } + function memPickBar() { + const bar = el("div", "row lib-row lib-pickbar lib-mempickbar"); + const n = memShown.filter((m) => memPicked.has(m.id)).length; + const every = el("label", "lib-pickall"); + const all = el("input", "lib-pickbox lib-mempickall"); + all.type = "checkbox"; + all.checked = n > 0 && n === memShown.length; + all.indeterminate = n > 0 && n < memShown.length; + all.onclick = (e) => { e.stopPropagation(); memPickAll(n !== memShown.length); }; + all.onkeydown = (e) => { if (e.key === "Escape") memPickKeys(e, ""); }; + every.append(all, el("span", "", t("All {n}", { n: memShown.length }))); + bar.append(every, el("span", "lib-pickn" + (n ? "" : " none"), n ? t("{n} selected", { n }) : t("Shift-click picks a range")), el("span", "grow")); + if (n) { + const ids = memShown.filter((m) => memPicked.has(m.id)).map((m) => m.id); + const act = async (path, body, done) => { + const ok = await memChange(path, body, done); + if (ok) { memPicked.clear(); memAnchor = null; memSure = false; render(); } + }; + // what the status shown moves them to: kept, archived or brought back + const to = memStatus === "candidate" ? ["active", t("Keep"), t("{n} kept", { n })] + : memStatus === "active" ? ["archived", t("Archive"), t("{n} archived", { n })] + : ["active", t("Restore"), t("{n} restored", { n })]; + bar.append(button(to[1], "action lib-updall lib-memto", () => act("memory/status", { ids, status: to[0] }, to[2]))); + // deleted on a second click, as one memory's Delete is + const del = button(memSure ? t("Delete {n} for good", { n }) : t("Delete"), (memSure ? "primary danger-fill" : "action danger") + " lib-updall lib-memdel", () => { + if (!memSure) { + memSure = true; + const b = memPickBar(); + bar.replaceWith(b); + b.querySelector(".lib-memdel")?.focus({ preventScroll: true }); + return; + } + act("memory/remove", { ids }, t("{n} deleted", { n })); + }); + bar.append(del); + const c = button(t("Clear"), "lib-updall lib-pickclear", () => { memPicked.clear(); memAnchor = null; memSync(); }); + c.title = t("Unpick them all"); + bar.append(c); + } + bar.append(button(t("Done"), "action lib-updall lib-pickdone", () => { endMemPick(); render(); })); + bar.onkeydown = (e) => { if (e.key === "Escape") memPickKeys(e, ""); }; + return bar; } // the model conversations are read and memory tidied with: the // automatic one or one picked, shared by both rows @@ -1219,7 +1349,7 @@ magpie.plugin("library", (ctx) => { }, 2000); } function memRow(m) { - const isOpen = memOpen === m.id; + const isOpen = !memPicking && memOpen === m.id; const row = el("div", "row lib-row click lib-mem" + (isOpen ? " open" : "")); row.dataset.id = m.id; const who = el("div", "who"); @@ -1234,6 +1364,21 @@ magpie.plugin("library", (ctx) => { const chev = el("span", "chev"); chev.append(svg(CHEV_R, 11, 1.7)); row.append(who, tags, chev); + if (memPicking) { + // a row with a box, which its click ticks rather than opening it + const box = el("input", "lib-pickbox"); + box.type = "checkbox"; + box.checked = memPicked.has(m.id); + box.setAttribute("aria-label", m.text); + box.onclick = (e) => { e.stopPropagation(); memPick(m.id, e.shiftKey); }; + box.onkeydown = (e) => memPickKeys(e, m.id); + row.prepend(box); + row.classList.toggle("picked", box.checked); + // a Shift-click picks a range, not the text between + row.onmousedown = (e) => { if (e.shiftKey) e.preventDefault(); }; + row.onclick = (e) => { memPick(m.id, e.shiftKey); box.focus({ preventScroll: true }); }; + return [row]; + } row.onclick = () => { if (isOpen) { memOpen = null; memDraft = null; } else openMemory(m); render(); }; return isOpen ? [row, memDetail(m)] : [row]; } diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 1fdf551e6..2c121f0e1 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,14 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "Stop picking memories": "不再选择记忆", + "Pick some memories and act on them together": "选几条记忆,一起处理", + "Shift-click picks a range": "按住 Shift 点击可选一段", + "{n} kept": "已保留 {n} 条", + "{n} archived": "已归档 {n} 条", + "{n} restored": "已恢复 {n} 条", + "{n} deleted": "已删除 {n} 条", + "Delete {n} for good": "永久删除 {n} 条", "The model's own": "模型自己的默认", "1 year": "1 年", "How far back it reads": "读取多久以前的对话", @@ -915,6 +923,14 @@ magpie.strings({ "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 现在没有运行。", }, "zh-TW": { + "Stop picking memories": "不再選擇記憶", + "Pick some memories and act on them together": "選幾條記憶,一起處理", + "Shift-click picks a range": "按住 Shift 點擊可選一段", + "{n} kept": "已保留 {n} 條", + "{n} archived": "已封存 {n} 條", + "{n} restored": "已還原 {n} 條", + "{n} deleted": "已刪除 {n} 條", + "Delete {n} for good": "永久刪除 {n} 條", "The model's own": "模型自己的預設", "1 year": "1 年", "How far back it reads": "讀取多久以前的對話", @@ -1828,6 +1844,14 @@ magpie.strings({ "As of {time}: billion-context isn't running now.": "截至 {time}:billion-context 現在沒有執行。", }, ja: { + "Stop picking memories": "メモリの選択を終える", + "Pick some memories and act on them together": "いくつかのメモリを選んでまとめて操作する", + "Shift-click picks a range": "Shift クリックで範囲を選択", + "{n} kept": "{n} 件を残しました", + "{n} archived": "{n} 件をアーカイブしました", + "{n} restored": "{n} 件を元に戻しました", + "{n} deleted": "{n} 件を削除しました", + "Delete {n} for good": "{n} 件を完全に削除", "The model's own": "モデル自身の既定", "1 year": "1 年", "How far back it reads": "どこまで遡って読むか", @@ -2741,6 +2765,14 @@ magpie.strings({ "As of {time}: billion-context isn't running now.": "{time} 時点:billion-context は現在動いていません。", }, de: { + "Stop picking memories": "Keine Erinnerungen mehr auswählen", + "Pick some memories and act on them together": "Mehrere Erinnerungen auswählen und gemeinsam bearbeiten", + "Shift-click picks a range": "Shift-Klick wählt einen Bereich", + "{n} kept": "{n} behalten", + "{n} archived": "{n} archiviert", + "{n} restored": "{n} wiederhergestellt", + "{n} deleted": "{n} gelöscht", + "Delete {n} for good": "{n} endgültig löschen", "The model's own": "Die Vorgabe des Modells", "1 year": "1 Jahr", "How far back it reads": "Wie weit zurück gelesen wird", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index d2f3eb110..ca1283a27 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -878,6 +878,14 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } .lib-mems .lib-mem.open > .who .name { -webkit-line-clamp: unset; } .lib-mems .lib-mem > .who .sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .lib-memdetail { padding-left: 12px; } +/* Select: a box on each memory, the ones picked tinted, the bar under the list */ +.lib-mems.picking .lib-mem > .chev { display: none; } +.lib-mems .lib-mem.picked { background: var(--accent-soft); } +/* a row moved to with ↑ ↓ stops above the bar, not under it */ +.lib-mems.picking .lib-mem { scroll-margin-bottom: 96px; } +.lib-mems .lib-mem > .lib-pickbox { margin: 0; flex: none; } +.lib-membar .lib-memselect { height: 28px; } +.lib-mempickbar .lib-memdel.danger { color: var(--red); } .lib-memline { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } .lib-memline .lib-menu { height: 28px; max-width: 220px; color: var(--fg); } .lib-memline .lib-memtags { flex: 1 1 160px; min-width: 0; height: 28px; } diff --git a/internal/gui/memory.go b/internal/gui/memory.go index 08f390672..51afa0ab6 100644 --- a/internal/gui/memory.go +++ b/internal/gui/memory.go @@ -106,6 +106,27 @@ func memoryRoutes(mux *http.ServeMux) { } memoryChanged(rw) }) + // some memories given one status at once: kept, archived or brought + // back from the Memory tab's Select (RealZeroP27 on X) + mux.HandleFunc("POST /api/memory/status", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + IDs []string `json:"ids"` + Status string `json:"status"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if len(in.IDs) == 0 { + fail(rw, errors.New("name the memories to change")) + return + } + if _, err := memory.SetStatus(in.Status, in.IDs...); err != nil { + fail(rw, err) + return + } + memoryChanged(rw) + }) mux.HandleFunc("POST /api/memory/digest", func(rw http.ResponseWriter, r *http.Request) { var in struct { On bool `json:"on"` diff --git a/internal/gui/memory_test.go b/internal/gui/memory_test.go new file mode 100644 index 000000000..b5cea382c --- /dev/null +++ b/internal/gui/memory_test.go @@ -0,0 +1,76 @@ +package gui + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/memory" +) + +// The Memory tab's Select acts on the memories picked at once +// (RealZeroP27 on X): /api/memory/status keeps the ones to review and +// answers with the tab as it is now; deleting several goes through +// /api/memory/remove. A request naming none, or a status that isn't +// one, is refused and changes nothing. +func TestMemoryStatusRouteActsOnSome(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + mux := http.NewServeMux() + memoryRoutes(mux) + post := func(path, body string) (int, memoryView) { + t.Helper() + rec := httptest.NewRecorder() + mux.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + var v memoryView + if rec.Code == 200 { + if err := json.Unmarshal(rec.Body.Bytes(), &v); err != nil { + t.Fatalf("%s: %s", path, rec.Body) + } + } + return rec.Code, v + } + var ids []string + for _, text := range []string{"Prefers pnpm.", "Ships on Fridays.", "Answers in Chinese."} { + kind, scope, st := memory.Preference, memory.Global, memory.Candidate + m, _, err := memory.Save(memory.Input{Text: &text, Kind: &kind, Scope: &scope, Status: &st}, memory.FromInferred, nil, nil) + if err != nil { + t.Fatal(err) + } + ids = append(ids, m.ID) + } + statuses := func(v memoryView) map[string]string { + out := map[string]string{} + for _, m := range v.Memories { + out[m.ID] = m.Status + } + return out + } + + code, v := post("/api/memory/status", `{"ids":["`+ids[0]+`","`+ids[1]+`"],"status":"active"}`) + if code != 200 { + t.Fatalf("keep: %d", code) + } + if s := statuses(v); s[ids[0]] != "active" || s[ids[1]] != "active" || s[ids[2]] != "candidate" { + t.Fatalf("after keeping two: %v", s) + } + if code, _ := post("/api/memory/status", `{"ids":[],"status":"active"}`); code != 400 { + t.Fatalf("none named: %d", code) + } + if code, _ := post("/api/memory/status", `{"ids":["`+ids[2]+`"],"status":"gone"}`); code != 400 { + t.Fatalf("a bad status: %d", code) + } + if m, _ := memory.Get(ids[2]); m.Status != memory.Candidate { + t.Fatalf("a refused request changed it: %s", m.Status) + } + + code, v = post("/api/memory/remove", `{"ids":["`+ids[0]+`","`+ids[2]+`"]}`) + if code != 200 { + t.Fatalf("remove: %d", code) + } + if s := statuses(v); len(s) != 1 || s[ids[1]] != "active" { + t.Fatalf("after removing two: %v", s) + } +} diff --git a/internal/gui/tests/library-memory-select.test.cjs b/internal/gui/tests/library-memory-select.test.cjs new file mode 100644 index 000000000..42549e43f --- /dev/null +++ b/internal/gui/tests/library-memory-select.test.cjs @@ -0,0 +1,182 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Library's Memory tab picks several memories and acts on them at once +// (RealZeroP27 on X): Select puts a box on each row, a click picks one and +// a Shift-click every one from the last picked, ↑ ↓ move between the boxes +// and ⌘A / Ctrl+A picks them all, and the bar under the list keeps the ones +// to review, archives the ones in use, and deletes on a second click, each +// in one request. Escape ends it. Every language, wide and narrow, +// Chromium and WebKit; no backend, the API is faked here. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const HOME = "/Users/mem"; +const library = { + dir: `${HOME}/.magpie/library`, backups: `${HOME}/.magpie/backups`, home: HOME, + agents: [{ id: "codex", name: "Codex", icon: "", instructions: `${HOME}/.codex/AGENTS.md` }], + instructions: { shared: "", sets: [{ id: "default", name: "", active: true, text: "" }], agents: [] }, + foundServers: [], projects: [], foundSkills: [], skills: [], servers: [], +}; +const at = (d) => `2026-11-0${d}T10:00:00Z`; +function memories() { + const guessed = ["Deploys go out on Fridays", "Prefers pnpm", "Answers in Chinese", "Runs tests on mote", "Ships on Tuesdays"]; + return { + memories: [ + { id: "a1", text: "Use pnpm, never npm, in this repo", kind: "rule", scope: "global", origin: "user", status: "active", created: at(1), updated: at(2) }, + { id: "a2", text: "Never push to main", kind: "rule", scope: "global", origin: "user", status: "active", created: at(1), updated: at(1) }, + // newest first in the list: c1 … c5 + ...guessed.map((text, i) => ({ id: "c" + (i + 1), text, kind: "fact", scope: "global", origin: "inferred", status: "candidate", sources: [{ agent: "codex", at: at(3) }], created: at(3), updated: at(9 - i) })), + ], + projects: {}, digest: true, agents: [], + }; +} + +function server(lang, state, sent) { + return async (route) => { + const url = new URL(route.request().url()); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return route.fulfill({ json: { agents: [], profiles: [], settings: { lang, theme: "light" } } }); + if (url.pathname === "/api/plugins") return route.fulfill({ json: { plugins: [] } }); + if (url.pathname === "/api/library") return route.fulfill({ json: library }); + if (url.pathname.startsWith("/api/memory/distill")) return route.fulfill({ json: { on: false, model: "", auto: "", running: false, models: [] } }); + if (url.pathname.startsWith("/api/memory")) { + if (route.request().method() === "POST") { + const body = route.request().postDataJSON(); + sent.push({ path: url.pathname, body }); + if (url.pathname === "/api/memory/remove") state.memories = state.memories.filter((m) => !body.ids.includes(m.id)); + else if (url.pathname === "/api/memory/status") for (const m of state.memories) if (body.ids.includes(m.id)) m.status = body.status; + } + return route.fulfill({ json: state }); + } + if (url.pathname === "/api/usage/quotas") return route.fulfill({ json: [] }); + if (url.pathname === "/api/groups") return route.fulfill({ json: { groups: [] } }); + if (url.pathname === "/api/providers") return route.fulfill({ json: { providers: [], gateway: { running: true } } }); + if (url.pathname.startsWith("/api/")) return route.fulfill({ json: {} }); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + await route.fulfill({ body: await fs.readFile(file), contentType }); + }; +} + +const view = "#view-library"; +const review = { en: "To review", zh: "待确认", "zh-TW": "待確認", ja: "確認待ち", de: "Zu prüfen" }; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": the Memory tab keeps, archives and deletes the memories picked at once", async (t) => { + assert(["chromium", "webkit"].includes(engine), "BROWSER must be chromium or webkit"); + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + const errors = []; + t.after(async () => { + if (errors.length) console.log(errors); + await browser.close(); + }); + for (const lang of Object.keys(review)) for (const width of [980, 420]) { + await t.test(`${lang} ${width}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 860 }, reducedMotion: "reduce" }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const sent = []; + const state = memories(); + await page.route("**/*", server(lang, state, sent)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const rows = page.locator(`${view} .lib-mems .lib-mem`); + await rows.first().waitFor(); + const count = (n) => page.waitForFunction((n) => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === n, n); + const picked = () => page.evaluate(() => [...document.querySelectorAll("#view-library .lib-mems .lib-mem.picked")].map((r) => r.dataset.id)); + const fits = async () => { + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1), "the page scrolls sideways"); + const body = await page.locator(`${view} .lib-body`).boundingBox(); + for (const b of await page.locator(`${view} .lib-membar > *, ${view} .lib-mempickbar > *`).all()) { + const r = await b.boundingBox(); + if (r) assert.ok(r.x + r.width <= body.x + body.width + 1, "a control is cut off"); + } + }; + + await page.locator(`${view} .lib-memstatus .opt`, { hasText: review[lang] }).click(); + await count(5); + // no boxes until Select + assert.equal(await page.locator(`${view} .lib-mems .lib-pickbox`).count(), 0); + await page.locator(`${view} .lib-memselect`).click(); + await page.locator(`${view} .lib-mempickbar`).waitFor(); + assert.equal(await page.locator(`${view} .lib-mems .lib-pickbox`).count(), 5); + assert.equal(await page.locator(`${view} select`).count(), 0, "a native select"); + assert.equal(await page.locator(`${view} .lib-mempickbar .lib-memto`).count(), 0, "an action with nothing picked"); + await fits(); + + // a click picks one and opens nothing; a Shift-click every one from it + await rows.nth(0).click(); + assert.equal(await page.locator(`${view} .lib-memdetail`).count(), 0, "a picked row opened"); + assert.deepEqual(await picked(), ["c1"]); + await rows.nth(3).click({ modifiers: ["Shift"] }); + assert.deepEqual(await picked(), ["c1", "c2", "c3", "c4"]); + assert.match(await page.locator(`${view} .lib-mempickbar .lib-pickn`).textContent(), /4/); + // a Shift-click selects no text + assert.equal(await page.evaluate(() => String(getSelection())), ""); + // the keys: ↓ to the last box, Space picks it, ⌘A / Ctrl+A unpicks every one and picks them again + await page.keyboard.press("ArrowDown"); + assert.equal(await page.evaluate(() => document.activeElement.closest(".lib-mem")?.dataset.id), "c5"); + await page.keyboard.press("Space"); + assert.deepEqual(await picked(), ["c1", "c2", "c3", "c4", "c5"]); + assert.ok(await page.locator(`${view} .lib-mempickall`).isChecked()); + await page.keyboard.press("ControlOrMeta+a"); + assert.deepEqual(await picked(), []); + await page.keyboard.press("ControlOrMeta+a"); + assert.equal((await picked()).length, 5); + // Shift+↑ unpicks as it goes back from an unpicked one + await rows.nth(4).click(); + assert.equal((await picked()).length, 4); + await page.keyboard.press("Shift+ArrowUp"); + assert.deepEqual(await picked(), ["c1", "c2", "c3"]); + await fits(); + + // kept, the three in one request + await page.locator(`${view} .lib-mempickbar .lib-memto`).click(); + await count(2); + assert.deepEqual(sent.filter((x) => x.path === "/api/memory/status").map((x) => x.body), [{ ids: ["c1", "c2", "c3"], status: "active" }]); + assert.equal(await page.locator(`${view} .lib-mems .lib-pickbox`).count(), 2, "Select ended with memories left"); + assert.deepEqual(await picked(), []); + + // deleted on a second click + await rows.nth(0).click(); + await rows.nth(1).click({ modifiers: ["Shift"] }); + await page.locator(`${view} .lib-mempickbar .lib-memdel`).click(); + assert.equal(sent.filter((x) => x.path === "/api/memory/remove").length, 0, "deleted on the first click"); + assert.match(await page.locator(`${view} .lib-mempickbar .lib-memdel`).textContent(), /2/); + await fits(); + await page.locator(`${view} .lib-mempickbar .lib-memdel`).click(); + await count(0); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/remove").body, { ids: ["c4", "c5"] }); + // an empty list ends Select + assert.equal(await page.locator(`${view} .lib-mempickbar`).count(), 0); + + // in use: archived at once; Escape ends Select + await page.locator(`${view} .lib-memstatus .opt`).first().click(); + await count(5); + await page.locator(`${view} .lib-memselect`).click(); + await page.locator(`${view} .lib-mempickbar`).waitFor(); + await page.locator(`${view} .lib-mems .lib-mem[data-id="a1"]`).click(); + await page.locator(`${view} .lib-mems .lib-mem[data-id="a2"]`).click(); + await page.locator(`${view} .lib-mempickbar .lib-memto`).click(); + await count(3); + assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/status").body, { ids: ["a1", "a2"], status: "archived" }); + await rows.first().click(); + await page.keyboard.press("Escape"); + await page.locator(`${view} .lib-mempickbar`).waitFor({ state: "detached" }); + assert.equal(await page.locator(`${view} .lib-mems .lib-pickbox`).count(), 0); + // and a row opens again + await rows.first().click(); + await page.locator(`${view} .lib-memdetail`).waitFor(); + await ctx.close(); + }); + } + assert.deepEqual(errors, []); + }); +} diff --git a/internal/memory/memory.go b/internal/memory/memory.go index 7c164b1ee..68d50b206 100644 --- a/internal/memory/memory.go +++ b/internal/memory/memory.go @@ -473,25 +473,57 @@ func Edit(id string, in Input, byUser bool) (*Memory, error) { if m == nil { return ErrNotFound } - c := *m - apply(&c, in) - if err := check(&c); err != nil { - return err - } - if byUser && c.Status == Archived && m.Status != Archived { - dismiss(f, m) - } - if byUser && (in.Text != nil || in.Kind != nil || in.Scope != nil || in.Why != nil) { - c.Origin = FromUser - } - c.Updated = now().UTC() - *m = c out = m - return nil + return editIn(f, m, in, byUser) }) return out, err } +// editIn applies in to m, held in f, as Edit does. +func editIn(f *file, m *Memory, in Input, byUser bool) error { + c := *m + apply(&c, in) + if err := check(&c); err != nil { + return err + } + if byUser && c.Status == Archived && m.Status != Archived { + dismiss(f, m) + } + if byUser && (in.Text != nil || in.Kind != nil || in.Scope != nil || in.Why != nil) { + c.Origin = FromUser + } + c.Updated = now().UTC() + *m = c + return nil +} + +// SetStatus gives the user's status to the memories with ids, in one +// write: those to review kept at once, or archived or brought back, as +// Edit would one by one (RealZeroP27 on X). An id no longer there is +// passed over; n is how many were changed, and none found is ErrNotFound. +// A status that isn't one changes nothing. +func SetStatus(status string, ids ...string) (n int, err error) { + err = change(func(f *file) error { + for _, m := range f.Memories { + if !slices.Contains(ids, m.ID) { + continue + } + if err := editIn(f, m, Input{Status: &status}, true); err != nil { + return err + } + n++ + } + if n == 0 { + return ErrNotFound + } + return nil + }) + if err != nil { + n = 0 + } + return n, err +} + // Forget sets the memory with id aside (archived): out of searches and // digests, kept to be brought back. func Forget(id string) (*Memory, error) { diff --git a/internal/memory/memory_test.go b/internal/memory/memory_test.go index 7186e71bf..bf8f8ffdc 100644 --- a/internal/memory/memory_test.go +++ b/internal/memory/memory_test.go @@ -215,3 +215,61 @@ func TestDismissedNotProposedAgain(t *testing.T) { t.Fatalf("dismissed: %q", f.Dismissed) } } + +// Some memories to review, kept or archived at once (RealZeroP27 on X): +// the ones named change in one write as Edit changes one, an archived +// candidate is not proposed again, an id no longer there is passed over, +// and a status that isn't one changes none of them. +func TestSetStatusOfSome(t *testing.T) { + fresh(t) + cand := Candidate + propose := func(text string) *Memory { + t.Helper() + k, s := Preference, Global + m, _, err := Save(Input{Text: &text, Kind: &k, Scope: &s, Status: &cand}, FromInferred, &Source{Agent: "codex"}, nil) + if err != nil { + t.Fatal(err) + } + return m + } + a, b, c, d := propose("Prefers pnpm."), propose("Ships on Fridays."), propose("Answers in Chinese."), propose("Runs tests on mote.") + status := func(id string) string { + t.Helper() + m, err := Get(id) + if err != nil { + t.Fatal(err) + } + return m.Status + } + + if n, err := SetStatus(Active, a.ID, b.ID, "m_gone"); err != nil || n != 2 { + t.Fatalf("kept %d, %v", n, err) + } + if status(a.ID) != Active || status(b.ID) != Active || status(c.ID) != Candidate || status(d.ID) != Candidate { + t.Fatalf("after keeping two: %s %s %s %s", status(a.ID), status(b.ID), status(c.ID), status(d.ID)) + } + if hits, _ := Search(Query{Text: "pnpm"}); len(hits) != 1 { + t.Fatalf("a kept memory isn't searched: %+v", hits) + } + + if n, err := SetStatus("gone", c.ID, d.ID); err == nil || n != 0 { + t.Fatalf("a bad status: %d, %v", n, err) + } + if status(c.ID) != Candidate || status(d.ID) != Candidate { + t.Fatal("a bad status changed a memory") + } + + if n, err := SetStatus(Archived, c.ID, d.ID); err != nil || n != 2 { + t.Fatalf("archived %d, %v", n, err) + } + if status(c.ID) != Archived || status(d.ID) != Archived { + t.Fatal("not archived") + } + if m := propose("answers in chinese"); m != nil { + t.Fatalf("archived, then proposed again: %+v", m) + } + + if _, err := SetStatus(Active, "m_gone", "m_none"); !errors.Is(err, ErrNotFound) { + t.Fatalf("none of them there: %v", err) + } +}