gui: the Library's Memory tab

A tab after Instructions lists what the agents remember, in use, to
review (what an agent only guessed) and archived, pinned first then
newest; searches it, narrows it by where it applies, and adds, edits,
pins, keeps, archives and deletes memories (Delete asks with a second
click). Kind and scope are picked from the app's menu, never a <select>.
A card on top switches the digest in the ticked agents' instructions on
or off and names those agents, and offers Magpie Memory while it isn't
in the Library.

/api/memory (GET; POST saves the user's own or edits by id),
/api/memory/remove and /api/memory/digest; a change publishes the digest
at once and its reply carries `problem` when that failed.

Words other code also says (Archived, Pin, Keep, the kinds…) are in core
i18n.js; the rest in the library plugin's, in zh, zh-TW, ja and de.
docs/subsystems/memory.md describes the layer.

Run (mote-run):
- node --test internal/gui/tests/library-memory.test.cjs, Chromium and
  WebKit, 5 languages, 980 and 420 wide: ok
- whole GUI suite: not run at this commit; it is queued on mote for the stack head (034f249af before the rebase)
- go vet ./internal/gui, GOOS darwin, linux, windows: ok
Broken by hand: the pinned sort read `b.pinned - a.pinned` (NaN for an
unpinned one) and the test was red in every language until `!!`.
Looked at: screenshots en light 980, zh dark 980, en 420.
This commit is contained in:
yetone
2026-11-10 03:25:44 +08:00
parent a28744c325
commit 2b2ee49ded
9 changed files with 834 additions and 3 deletions
+1
View File
@@ -16,6 +16,7 @@ These pages describe current responsibilities, runtime paths, state, and contrac
| Providers, keys, subscription accounts, refresh and allowance | [Providers and accounts](providers-accounts.md) |
| Instructions, MCP servers, skills and RTK written into agents | [Library](library.md) |
| One MCP server, magpie, given to every agent in place of the Library's servers | [MCP router](mcp-router.md) |
| Memory shared by every agent: the memory MCP server, the digest in instructions, the Memory tab | [Memory](memory.md) |
| One skill, magpie-skills, listing the Library's skills in place of each agent's own | [Skill router](skill-router.md) |
| Tray, panel, window, `magpie web` and the page's JSON API | [GUI app shell](gui-shell.md) |
| Encrypted backups and setup synchronization over WebDAV, S3 or GitHub | [Sync and backup](sync-backup.md) |
+112
View File
@@ -0,0 +1,112 @@
# Memory
What the agents know from earlier conversations, kept once for all of
them: a preference the user states in Claude Code is known to Codex the
next day. It is read and written three ways: an MCP server every agent can
mount, a digest written into the instructions of the agents ticked under
Library → Instructions, and the Library's Memory tab.
## Source of truth
`memory.json` in magpie's config folder ([internal/memory/memory.go](../../internal/memory/memory.go)).
- One writer at a time across magpies (`filelock`), written through a temp
file, the last good generation kept beside it (`lastgood`).
- A file that can't be read is unknown, never empty: nothing is written
over it, searches fail, and `Digest` returns an error so the instructions
keep what the agent has (`TestUnreadableFileIsNeverWrittenOver`,
`TestCutShortFileReadFromItsBackup`).
A memory is one short text (`MaxText` runes) with:
| Field | Values | Meaning |
| --- | --- | --- |
| `scope` | `global`, `project:<key>`, `agent:<id>` | where it holds. A project is the git repository, keyed by its remote (`ProjectOf`, `RemoteKey`), so every clone and worktree shares it. An agent id has no `@wsl:…` suffix. |
| `kind` | profile, preference, rule, reference, fact, procedure, episode | how long it stays true and where it goes in the digest. A field of its own, not a tag. |
| `tags` | free words (`CleanTags`) | the user's own grouping. |
| `origin` | user, agent, imported, inferred | who wrote it. An agent's save never changes text the user wrote (`TestUsersMemoryNotChangedByAnAgentsSave`). |
| `status` | active, candidate, archived, superseded | only active ones are searched by default and digested. Candidates wait under "To review". |
| `pinned` | bool | first in lists and digests. |
`Save` keeps one memory per scope and text (`TestSaveKeepsOneOfTheSameText`)
and refuses empty or over-long text, an unknown kind and a bad scope
(`TestSaveRefusesWhatIsntAMemory`).
`Forget` archives; `Remove` deletes.
## Runtime paths
### MCP server
[internal/gateway/memory_mcp.go](../../internal/gateway/memory_mcp.go):
`memory_search`, `memory_save`, `memory_forget`, Streamable HTTP at
`MemoryMCPPath` (`/mcp/magpie/memory`), served and guarded like the search
server (`serveMCP`): another computer reaches it only while magpie is
shared, with a gateway key, and has no folder here for a project
(`TestMemoryMCPGuarded`).
- The Library offers it in the market as `magpie-memory`
([market.go](../../internal/library/market.go)), run as
`magpie mcp memory` ([browsermcp.RunMemory](../../internal/browsermcp/browsermcp.go)),
which relays stdio to the gateway with the folder the agent started it in
(`X-Magpie-Cwd`) and the client name from `initialize`
(`X-Magpie-Mcp-Client`).
- Behind the [MCP router](mcp-router.md) the hub passes the caller in the
call's `_meta` instead (`HubRootsMeta`, `HubClientMeta`;
`TestMemoryMCPHubMetaNamesTheProject`).
- Without a folder the server can't name the project, nor the agent without
a client name: such a save says so instead of guessing, and a save with
no scope is kept for everyone (`TestMemoryMCPSaysWhatItCantKnow`).
- A save through MCP is active at once, origin `agent`.
### Digest in the instructions
[internal/memory/digest.go](../../internal/memory/digest.go) renders one
digest per scope within a budget (global 4000, project 1500, agent 1000,
the whole 8000 characters), pinned and longer-lived kinds first, no memory
cut in the middle. The text goes to every agent's vendor: it names neither
magpie nor any vendor.
The digest changes only when published, so an agent's instructions — and
the prompt cache built on them — change mid-session only then
(`TestDigestChangesOnlyWhenPublished`):
- a change the user makes in the GUI publishes at once
(`library.PublishMemory(false)` from [internal/gui/memory.go](../../internal/gui/memory.go));
- `KeepLinked`'s loop publishes once a day for what agents saved meanwhile
(`PublishMemory(true)` → `memory.PublishDue`, which writes nothing while
memory has never held anything).
`Library.memoryDigest` adds the agent's digest (global, its own, and each
project's under the folders it was seen in) to the instructions of the
agents ticked under Instructions, unless `Instructions.NoMemory`
(`TestMemoryDigestInInstructions`). The Memory tab's switch sets it.
### GUI
[internal/gui/memory.go](../../internal/gui/memory.go):
| Route | Does |
| --- | --- |
| `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/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`.
## Not built yet
Distilling sessions into candidates, a nightly pass that archives stale
memories and merges duplicates, and semantic search are planned; today
search is by words (`Search`, CJK split per character, `TestSearch`).
## Verification
```sh
mote-run go test ./internal/memory ./internal/library
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
```
+64
View File
@@ -4,6 +4,22 @@
// works. {name} slots are filled by t(str, vars).
const I18N = {
zh: {
"Archived": "已归档",
"Everywhere": "所有地方",
"Preference": "偏好",
"Rule": "规则",
"Reference": "参考",
"Fact": "事实",
"Decision": "决定",
"from {agent}": "来自 {agent}",
"Pinned": "已置顶",
"Pin": "置顶",
"Keep": "保留",
"Kept": "已保留",
"Archive": "归档",
"Restored": "已恢复",
"Remember": "记住",
"Remembered": "已记住",
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:首字后 {ms} 输出 {n} 个正文 token,{r} 个推理 token 不计。没有记录首个正文的时间,首字后的推理时间也算在里面",
"At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:从收到请求到最后一个 token,{ms} 输出 {n} 个 token,等首字的时间也算在里面",
"Collapse all": "全部收起",
@@ -4792,6 +4808,22 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "这份报告已经不在了:magpie 只保留最近 5 份。",
},
"zh-TW": {
"Archived": "已封存",
"Everywhere": "所有地方",
"Preference": "偏好",
"Rule": "規則",
"Reference": "參考",
"Fact": "事實",
"Decision": "決定",
"from {agent}": "來自 {agent}",
"Pinned": "已置頂",
"Pin": "置頂",
"Keep": "保留",
"Kept": "已保留",
"Archive": "封存",
"Restored": "已還原",
"Remember": "記住",
"Remembered": "已記住",
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:首字後 {ms} 輸出 {n} 個正文 token,{r} 個推理 token 不計。沒有記錄首個正文的時間,首字後的推理時間也算在裡面",
"At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:從收到請求到最後一個 token,{ms} 輸出 {n} 個 token,等首字的時間也算在裡面",
"Collapse all": "全部收起",
@@ -9565,6 +9597,22 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "這份報告已經不在了:magpie 只保留最近 5 份。",
},
ja: {
"Archived": "アーカイブ済み",
"Everywhere": "どこでも",
"Preference": "好み",
"Rule": "ルール",
"Reference": "参考",
"Fact": "事実",
"Decision": "決定",
"from {agent}": "{agent} から",
"Pinned": "ピン留め",
"Pin": "ピン留め",
"Keep": "残す",
"Kept": "残しました",
"Archive": "アーカイブ",
"Restored": "元に戻しました",
"Remember": "覚える",
"Remembered": "覚えました",
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "下限:最初のトークン後 {ms} で回答 {n} トークン(推論 {r} トークンは含めず)。最初の本文の時刻が記録されていないため、最初のトークン後の推論の時間も含まれます",
"At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "下限:リクエストを受けてから最後のトークンまで {ms} で {n} トークンを出力。最初のトークンを待つ時間も含まれます",
"Collapse all": "すべて折りたたむ",
@@ -14340,6 +14388,22 @@ const I18N = {
"This report is no longer kept: magpie keeps the last 5.": "このレポートはもう残っていません。magpie は最新の 5 件だけを保存します。",
},
de: {
"Archived": "Archiviert",
"Everywhere": "Überall",
"Preference": "Vorliebe",
"Rule": "Regel",
"Reference": "Verweis",
"Fact": "Fakt",
"Decision": "Entscheidung",
"from {agent}": "von {agent}",
"Pinned": "Angeheftet",
"Pin": "Anheften",
"Keep": "Behalten",
"Kept": "Behalten",
"Archive": "Archivieren",
"Restored": "Wiederhergestellt",
"Remember": "Merken",
"Remembered": "Gemerkt",
"At least: {n} answer tokens in {ms} after the first token, the {r} reasoning tokens left out. No first text was recorded, so reasoning after the first token is counted too": "Mindestens: {n} Antwort-Token in {ms} nach dem ersten Token, ohne die {r} Reasoning-Token. Kein erster Text aufgezeichnet, also zählt Reasoning nach dem ersten Token mit",
"At least: {n} output tokens in {ms}, from the request to its last token, the wait for the first one counted too": "Mindestens: {n} Ausgabe-Token in {ms}, von der Anfrage bis zu ihrem letzten Token, das Warten auf das erste mitgezählt",
"Collapse all": "Alle einklappen",
+233 -3
View File
@@ -810,6 +810,8 @@ magpie.plugin("library", (ctx) => {
box.append(card, head("60px"), rows(6, true));
} else if (which === "rtk") {
box.append(rows(1, false), head("60px"), rows(5, true));
} else if (which === "memory") {
box.append(rows(1, true), rows(6, false));
} else if (which === "pi") {
box.append(head("60px"), rows(4, true));
} else {
@@ -826,6 +828,8 @@ magpie.plugin("library", (ctx) => {
if (id === "rtk" && rtk) loadRTK();
// Pi's extensions too: one installed or changed outside magpie since
if (id === "pi" && piView) loadPi();
// memory too: agents save to it while the page is open
if (id === "memory" && mem) loadMemory();
if (!lib) return page.querySelector(":scope > .lib-skel")?.replaceWith(skeleton(id));
render(); syncLists();
}
@@ -837,6 +841,7 @@ magpie.plugin("library", (ctx) => {
const n = (k) => (counts?.[k] ? " · " + counts[k] : "");
const tabs = segs(agentless() ? [["mcp", t("MCP servers") + n("mcp")]] : [
["instructions", t("Instructions")],
["memory", t("Memory")],
["mcp", t("MCP servers") + n("mcp")],
["skills", t("Skills") + n("skills")],
["hooks", t("Hooks") + n("hooks")],
@@ -910,6 +915,7 @@ magpie.plugin("library", (ctx) => {
if (tab === "instructions") renderInstructions(body);
else if (tab === "mcp") renderServers(body);
else if (tab === "rtk") renderRTK(body);
else if (tab === "memory") renderMemory(body);
else if (tab === "pi") renderPi(body);
else if (tab === "hooks") renderHooks(body);
else if (tab === "subagents") renderSubagents(body);
@@ -934,6 +940,227 @@ magpie.plugin("library", (ctx) => {
function intro(text) { return el("p", "lib-intro", text); }
// ---------- memory ----------
// What the agents know about the user and their projects, shared by all
// of them (internal/memory): agents search it and save to it through the
// Magpie Memory server, and the ones ticked for instructions read its
// digest. A memory an agent only guessed waits under Suggested until the
// user keeps it.
let mem = null; // /api/memory
let memLoading = false;
let memQ = ""; // the search typed
let memStatus = "active";
let memScope = ""; // "" every scope
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
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) {
if (!s || s === "global") return t("Everywhere");
if (s.startsWith("project:")) {
const k = s.slice(8), p = mem?.projects?.[k];
return p?.name || k;
}
if (s.startsWith("agent:")) return t("Only {agent}", { agent: nameOf(s.slice(6)) });
return s;
}
async function loadMemory() {
if (memLoading) return;
memLoading = true;
try {
mem = await api("memory");
} catch (e) {
status(e.message, "err");
}
memLoading = false;
if (tab === "memory" && mem) render();
}
function memDirty() {
if (!memOpen || !memDraft) return false;
const m = mem?.memories.find((x) => x.id === memOpen);
if (!m) return !!memDraft.text.trim();
return memDraft.text !== m.text || memDraft.why !== (m.why || "") || memDraft.tags !== (m.tags || []).join(", ") || memDraft.kind !== m.kind || memDraft.scope !== m.scope;
}
let memBusy = false;
async function memChange(path, body, done) {
if (memBusy) return false;
memBusy = true;
page.setAttribute("aria-busy", "true");
try {
const v = await api(path, body);
mem = v;
if (v.problem) status(v.problem, "err", 10000);
else if (done) status(done, "", 4000);
return true;
} catch (e) {
status(e.message, "err", 6000);
return false;
} finally {
memBusy = false;
page.removeAttribute("aria-busy");
render();
}
}
// a picker: the app's menu, never a <select>
function menuButton(text, cls, onclick) {
const b = el("button", "sess-pick lib-menu " + cls);
b.type = "button";
b.setAttribute("aria-haspopup", "menu");
b.append(el("span", "", text), svg(CHEV, 11, 1.6));
b.onclick = (e) => { e.stopPropagation(); onclick(e); };
return b;
}
const memTags = (s) => s.split(/[,,]/).map((x) => x.trim()).filter(Boolean);
function openMemory(m) {
memRemoving = null;
if (!m) { memOpen = "new"; memDraft = { text: "", why: "", tags: "", kind: "preference", scope: memScope || "global" }; return; }
memOpen = m.id;
memDraft = { text: m.text, why: m.why || "", tags: (m.tags || []).join(", "), kind: m.kind, scope: m.scope };
}
async function saveMemory() {
if (!memDraft || !memDraft.text.trim()) return;
const isNew = memOpen === "new";
const body = { text: memDraft.text.trim(), why: memDraft.why.trim(), tags: memTags(memDraft.tags), kind: memDraft.kind, scope: memDraft.scope };
if (!isNew) body.id = memOpen;
if (await memChange("memory", body, isNew ? t("Remembered") : t("Saved"))) { memOpen = null; memDraft = null; render(); }
}
// every scope a memory is kept in, and the places one can be put
function memScopes(withAgents) {
const out = ["global"];
for (const k of Object.keys(mem.projects || {})) out.push("project:" + k);
for (const m of mem.memories) if (!out.includes(m.scope) && (withAgents || !m.scope.startsWith("agent:"))) out.push(m.scope);
if (withAgents) for (const a of shownAgents()) if (!out.includes("agent:" + a.id.split("@")[0])) out.push("agent:" + a.id.split("@")[0]);
return out;
}
function renderMemory(body) {
body.append(intro(t("What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.")));
if (!mem) {
loadMemory();
body.append(skeleton("memory").lastChild);
return;
}
const card = el("div", "list lib-list lib-memcard");
const row = el("div", "row lib-row");
const who = el("div", "who");
who.append(el("div", "name", t("In the agents' instructions")));
who.append(el("div", "sub", mem.agents.length ? mem.agents.map(nameOf).join(", ") : t("No agent is switched on under Instructions")));
const sw = toggle(mem.digest, t("In the agents' instructions"), (on) => memChange("memory/digest", { on }, on ? t("The agents read the memories' summary") : t("The memories' summary is taken out of the agents' instructions")));
row.append(glyph(GLYPH.doc), who, sw);
card.append(row);
if (!lib.servers.some((s) => s.name === "magpie-memory")) {
const r = el("div", "row lib-row lib-memtools");
const w = el("div", "who");
w.append(el("div", "name", "Magpie Memory"), el("div", "sub", t("Add it for agents to search and save memories")));
r.append(glyph(GLYPH.search), w, button(t("Add"), "action", () => change("market/server", { id: "magpie-memory", values: {} }, t("{name} is in the library now", { name: "Magpie Memory" }))));
card.append(r);
}
body.append(card);
const all = mem.memories;
const count = (st) => all.filter((m) => st === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === st).length;
const bar = el("div", "lib-membar");
const q = input(memQ, t("Search memories"));
q.type = "search";
q.className = "lib-memq";
q.dataset.lib = "memq";
q.oninput = () => { memQ = q.value; render(); };
q.onkeydown = (e) => e.stopPropagation();
const sugg = count("candidate");
const st = segs([
["active", t("In use") + (count("active") ? " · " + count("active") : "")],
...(sugg || memStatus === "candidate" ? [["candidate", t("To review") + (sugg ? " · " + sugg : "")]] : []),
["archived", t("Archived") + (count("archived") ? " · " + count("archived") : "")],
], 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");
if (memOpen === "new") list.append(memDetail(null));
for (const m of shown) list.append(...memRow(m));
if (!shown.length && memOpen !== "new") {
list.append(el("div", "lib-none", words.length || memScope ? t("No memory matches.")
: memStatus === "candidate" ? t("Nothing to review.")
: memStatus === "archived" ? t("Nothing archived.")
: t("Nothing remembered yet. Tell an agent “remember that…”, or add one here.")));
}
body.append(list);
}
function memRow(m) {
const isOpen = 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");
who.append(el("div", "name", m.text));
const sub = [scopeName(m.scope), ...(m.tags || []).map((x) => "#" + x)];
const from = m.origin === "agent" || m.origin === "inferred" ? (m.sources || []).find((s) => s.agent)?.agent : "";
if (from) sub.push(t("from {agent}", { agent: nameOf(from) }));
who.append(el("div", "sub", sub.join(" · ")));
const tags = el("div", "lib-tags");
if (m.pinned) tags.append(tag(t("Pinned"), "", t("Given to the agents first")));
tags.append(tag(kindName(m.kind)));
const chev = el("span", "chev");
chev.append(svg(CHEV_R, 11, 1.7));
row.append(who, tags, chev);
row.onclick = () => { if (isOpen) { memOpen = null; memDraft = null; } else openMemory(m); render(); };
return isOpen ? [row, memDetail(m)] : [row];
}
function memDetail(m) {
const d = memDraft;
const det = el("div", "lib-detail lib-memdetail");
const ta = el("textarea", "lib-text small");
ta.dataset.lib = "mem:" + (m ? m.id : "new");
ta.value = d.text;
ta.placeholder = t("What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo");
ta.oninput = () => { d.text = ta.value; };
ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && (e.key === "s" || e.key === "Enter")) { e.preventDefault(); saveMemory(); } };
autosize(ta, 52);
if (!m) queueMicrotask(() => ta.focus());
const pick = (label, value, opts, head, set) => {
const b = menuButton(label(value), "lib-mempick", () => openProtoMenu(b, opts.map((v) => ({ v, name: label(v), literalName: true, note: "" })), value, (v) => { set(v); render(); }, head));
return b;
};
const line = el("div", "lib-memline");
line.append(pick(kindName, d.kind, MEM_KINDS, "Kind", (v) => { d.kind = v; }), pick(scopeName, d.scope, memScopes(true), "Where it applies", (v) => { d.scope = v; }));
const tg = input(d.tags, t("Tags, separated by commas"));
tg.className = "lib-memtags grow";
tg.dataset.lib = "memtags:" + (m ? m.id : "new");
tg.oninput = () => { d.tags = tg.value; };
tg.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") saveMemory(); };
line.append(tg);
const why = input(d.why, t("Why (optional)"));
why.className = "lib-memwhy";
why.dataset.lib = "memwhy:" + (m ? m.id : "new");
why.oninput = () => { d.why = why.value; };
why.onkeydown = tg.onkeydown;
det.append(ta, line, why);
const acts = el("div", "lib-acts");
if (m) {
acts.append(button(m.pinned ? t("Unpin") : t("Pin"), "action", () => memChange("memory", { id: m.id, pinned: !m.pinned })));
if (m.status === "candidate") acts.append(button(t("Keep"), "action", () => memChange("memory", { id: m.id, status: "active" }, t("Kept"))));
else if (m.status === "active") acts.append(button(t("Archive"), "action", () => { memOpen = null; memChange("memory", { id: m.id, status: "archived" }, t("Archived")); }));
else acts.append(button(t("Restore"), "action", () => { memOpen = null; memChange("memory", { id: m.id, status: "active" }, t("Restored")); }));
const sure = memRemoving === m.id;
acts.append(button(sure ? t("Delete for good") : t("Delete"), sure ? "primary danger-fill" : "action danger", () => {
if (!sure) { memRemoving = m.id; render(); return; }
memRemoving = null; memOpen = null; memDraft = null;
memChange("memory/remove", { ids: [m.id] }, t("Deleted"));
}));
}
acts.append(el("span", "grow"), button(t("Cancel"), "", () => { memOpen = null; memDraft = null; memRemoving = null; render(); }), button(m ? t("Save") : t("Remember"), "primary", saveMemory));
det.append(acts);
det.onclick = (e) => e.stopPropagation();
return det;
}
// ---------- RTK ----------
// RTK (rtk-ai.app) cuts down what the shell commands an agent runs print,
@@ -1475,6 +1702,7 @@ magpie.plugin("library", (ctx) => {
}
async function discard(force = false) {
if (force !== true && dirty() && !(await confirmDiscard())) return;
if (force === true) { memOpen = null; memDraft = null; }
for (const k of Object.keys(texts)) delete texts[k];
for (const k of Object.keys(extras)) delete extras[k];
render();
@@ -6968,7 +7196,9 @@ magpie.plugin("library", (ctx) => {
// unsaved text, or a lookup under way.
// What changed there changes what the market calls added, too: take asks it again.
async function quietLoad() {
if (page.hidden || modal || dirty() || probing) return;
if (page.hidden || modal || dirty() || memDirty() || probing) return;
// what agents saved meanwhile
if (tab === "memory" && mem) loadMemory();
await load(true);
}
const shelf = () => JSON.stringify([lib?.servers?.map((x) => x.name), lib?.skills?.map((x) => x.name)]);
@@ -6988,7 +7218,7 @@ magpie.plugin("library", (ctx) => {
if (!confirmationPending && modal && e.key === "Escape") { e.preventDefault(); e.stopImmediatePropagation(); closeLibModal(); }
}, true);
// leaving the page with the shared text not saved asks first
window.addEventListener("beforeunload", (e) => { if (lib && dirty()) e.preventDefault(); });
window.addEventListener("beforeunload", (e) => { if (lib && (dirty() || memDirty())) e.preventDefault(); });
page.addEventListener("scroll", () => page.querySelector(".lib-head")?.classList.toggle("stuck", page.scrollTop > 0), { passive: true });
document.addEventListener("visibilitychange", () => { if (!document.hidden) quietLoad(); });
window.addEventListener("focus", quietLoad);
@@ -7016,7 +7246,7 @@ magpie.plugin("library", (ctx) => {
redraw: () => { if (lib) render(); },
// the reader leaving the page: its dialog closed, and what isn't saved
close: () => { if (modal) closeLibModal(true); else closeModal(); },
dirty: () => !!lib && dirty(),
dirty: () => !!lib && (dirty() || memDirty()),
discard: () => discard(true),
});
});
@@ -2,6 +2,29 @@
// kernel adds them to i18n.js's (magpie.strings).
magpie.strings({
zh: {
"What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Agent 们对你和你的项目的了解,所有 Agent 共用。它们通过 Magpie Memory 搜索和保存记忆;在「指令」中开启的 Agent 还会读到记忆摘要。",
"In the agents' instructions": "写入 Agent 的指令",
"No agent is switched on under Instructions": "「指令」中没有开启任何 Agent",
"The agents read the memories' summary": "Agent 现在会读到记忆摘要",
"The memories' summary is taken out of the agents' instructions": "已从 Agent 的指令中移除记忆摘要",
"Add it for agents to search and save memories": "添加后,Agent 才能搜索和保存记忆",
"Search memories": "搜索记忆",
"To review": "待确认",
"Everywhere and every project": "全部范围和项目",
"Where it applies": "适用范围",
"Only {agent}": "仅 {agent}",
"About you": "关于你",
"How-to": "做法",
"No memory matches.": "没有匹配的记忆。",
"Nothing to review.": "没有待确认的记忆。",
"Nothing archived.": "没有归档的记忆。",
"Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "还没有记忆。对 Agent 说「记住……」,或在这里添加。",
"Given to the agents first": "优先提供给 Agent",
"What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "用一句话写下要记住的内容,例如:这个仓库用 pnpm,不用 npm",
"Tags, separated by commas": "标签,用逗号分隔",
"Why (optional)": "原因(可选)",
"Unpin": "取消置顶",
"Delete for good": "永久删除",
"Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agent 会自己直接调用它,与 magpie 的联网搜索各管各的,magpie 的联网搜索不会用到它。",
"As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "若在 设置 → 模型 → 联网搜索 中把 {name} 添加为搜索 API,它会为所有模型搜索,无需添加服务器。",
"Skill router": "Skill 路由",
@@ -845,6 +868,29 @@ magpie.strings({
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已复制到 {agent}:Pi 下次启动或 /reload 时加载它",
},
"zh-TW": {
"What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Agent 們對你和你的專案的了解,所有 Agent 共用。它們透過 Magpie Memory 搜尋和儲存記憶;在「指令」中開啟的 Agent 還會讀到記憶摘要。",
"In the agents' instructions": "寫入 Agent 的指令",
"No agent is switched on under Instructions": "「指令」中沒有開啟任何 Agent",
"The agents read the memories' summary": "Agent 現在會讀到記憶摘要",
"The memories' summary is taken out of the agents' instructions": "已從 Agent 的指令中移除記憶摘要",
"Add it for agents to search and save memories": "新增後,Agent 才能搜尋和儲存記憶",
"Search memories": "搜尋記憶",
"To review": "待確認",
"Everywhere and every project": "全部範圍和專案",
"Where it applies": "適用範圍",
"Only {agent}": "僅 {agent}",
"About you": "關於你",
"How-to": "做法",
"No memory matches.": "沒有符合的記憶。",
"Nothing to review.": "沒有待確認的記憶。",
"Nothing archived.": "沒有封存的記憶。",
"Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "還沒有記憶。對 Agent 說「記住……」,或在這裡新增。",
"Given to the agents first": "優先提供給 Agent",
"What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "用一句話寫下要記住的內容,例如:這個儲存庫用 pnpm,不用 npm",
"Tags, separated by commas": "標籤,用逗號分隔",
"Why (optional)": "原因(選填)",
"Unpin": "取消置頂",
"Delete for good": "永久刪除",
"Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agent 會自己直接呼叫它,與 magpie 的聯網搜尋各自獨立,magpie 的聯網搜尋不會用到它。",
"As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "若在 設定 → 模型 → 聯網搜尋 中把 {name} 新增為搜尋 API,它會為所有模型搜尋,無需新增伺服器。",
"Skill router": "Skill 路由",
@@ -1688,6 +1734,29 @@ magpie.strings({
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已複製到 {agent}:Pi 下次啟動或 /reload 時載入它",
},
ja: {
"What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "エージェントが知っているあなたとプロジェクトのこと。すべてのエージェントで共有されます。エージェントは Magpie Memory で検索・保存し、「指示」でオンにしたエージェントはその要約も読みます。",
"In the agents' instructions": "エージェントの指示に含める",
"No agent is switched on under Instructions": "「指示」でオンのエージェントはありません",
"The agents read the memories' summary": "エージェントが記憶の要約を読むようになりました",
"The memories' summary is taken out of the agents' instructions": "記憶の要約をエージェントの指示から外しました",
"Add it for agents to search and save memories": "追加すると、エージェントが記憶を検索・保存できます",
"Search memories": "記憶を検索",
"To review": "確認待ち",
"Everywhere and every project": "すべての範囲とプロジェクト",
"Where it applies": "適用範囲",
"Only {agent}": "{agent} のみ",
"About you": "あなたについて",
"How-to": "手順",
"No memory matches.": "一致する記憶はありません。",
"Nothing to review.": "確認待ちの記憶はありません。",
"Nothing archived.": "アーカイブ済みの記憶はありません。",
"Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "まだ記憶はありません。エージェントに「…を覚えて」と伝えるか、ここで追加してください。",
"Given to the agents first": "エージェントに優先して渡されます",
"What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "覚えておくことを一文で — 例:このリポジトリでは npm ではなく pnpm を使う",
"Tags, separated by commas": "タグ(カンマ区切り)",
"Why (optional)": "理由(任意)",
"Unpin": "ピン留めを外す",
"Delete for good": "完全に削除",
"Agents call it themselves, beside magpie's web search, which doesn't use it.": "エージェントが自分で直接呼び出します。magpie のウェブ検索とは別のもので、magpie のウェブ検索はこれを使いません。",
"As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "設定 → モデル → ウェブ検索 で {name} を検索 API として追加すると、すべてのモデルのために検索し、サーバーを追加する必要はありません。",
"Skill router": "スキルルーター",
@@ -2531,6 +2600,29 @@ magpie.strings({
"{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} を {agent} にコピーしました。Pi は次回起動時か /reload で読み込みます",
},
de: {
"What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Was Ihre Agenten über Sie und Ihre Projekte wissen, von allen geteilt. Sie durchsuchen und speichern es mit Magpie Memory, und die unter Anweisungen eingeschalteten Agenten lesen eine Zusammenfassung davon.",
"In the agents' instructions": "In den Anweisungen der Agenten",
"No agent is switched on under Instructions": "Unter Anweisungen ist kein Agent eingeschaltet",
"The agents read the memories' summary": "Die Agenten lesen jetzt die Zusammenfassung der Erinnerungen",
"The memories' summary is taken out of the agents' instructions": "Die Zusammenfassung wurde aus den Anweisungen der Agenten entfernt",
"Add it for agents to search and save memories": "Hinzufügen, damit Agenten Erinnerungen suchen und speichern können",
"Search memories": "Erinnerungen durchsuchen",
"To review": "Zu prüfen",
"Everywhere and every project": "Überall und jedes Projekt",
"Where it applies": "Wo es gilt",
"Only {agent}": "Nur {agent}",
"About you": "Über Sie",
"How-to": "Anleitung",
"No memory matches.": "Keine passende Erinnerung.",
"Nothing to review.": "Nichts zu prüfen.",
"Nothing archived.": "Nichts archiviert.",
"Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "Noch keine Erinnerungen. Sagen Sie einem Agenten „merk dir…“, oder fügen Sie hier eine hinzu.",
"Given to the agents first": "Wird den Agenten zuerst gegeben",
"What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "Was gemerkt werden soll, in einem Satz – z. B. In diesem Repo pnpm statt npm verwenden",
"Tags, separated by commas": "Tags, durch Kommas getrennt",
"Why (optional)": "Warum (optional)",
"Unpin": "Lösen",
"Delete for good": "Endgültig löschen",
"Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agenten rufen ihn selbst auf, neben magpies Websuche, die ihn nicht nutzt.",
"As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "Als Such-API unter Einstellungen → Modelle → Websuche sucht {name} für jedes Modell, ohne einen Server hinzuzufügen.",
"Skill router": "Skill-Router",
@@ -861,3 +861,20 @@ body.window .lib-list .lib-row { --lib-indent: 38px; }
.lib-pi-head > .lib-path { flex: 0 1 auto; min-width: 0; }
.lib-pi-row > .lib-pi-copy { flex: none; }
.lib-pi + .lib-pi-head { margin-top: 18px; }
/* Memory: the digest switch, a search with its filters, and the memories */
.lib-memcard { margin-bottom: 12px; }
.lib-membar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0 2px 8px; }
.lib-membar .lib-memq { flex: 1 1 180px; min-width: 0; max-width: 320px; height: 28px; }
.lib-membar .lib-menu { height: 28px; max-width: 220px; color: var(--fg); }
.lib-membar .lib-menu > span:first-child, .lib-memline .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.lib-mems .lib-mem > .who .name { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; font-weight: 400; }
.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; }
.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; }
.lib-memdetail .lib-memwhy { height: 28px; }
input.lib-memq, input.lib-memtags, input.lib-memwhy { padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-size: 12.5px; outline: none; box-sizing: border-box; transition: border-color .12s, box-shadow .12s; }
input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); }
+1
View File
@@ -175,6 +175,7 @@ func revealable(v *library.View) []string {
func libraryRoutes(mux *http.ServeMux, w Windows) {
browserRoutes(mux, w)
memoryRoutes(mux)
mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) {
v, err := libraryRead(nil, r.URL.Query().Get("glance") == "1")
if err != nil {
+123
View File
@@ -0,0 +1,123 @@
package gui
import (
"encoding/json"
"errors"
"net/http"
"github.com/yetone/magpie/internal/library"
"github.com/yetone/magpie/internal/memory"
)
// memoryView is the Library's Memory tab: every memory, newest change
// first, the projects they are kept for, and whether the agents ticked
// for instructions are given the digest.
type memoryView struct {
Memories []*memory.Memory `json:"memories"`
Projects map[string]*memory.Project `json:"projects"`
Digest bool `json:"digest"`
Agents []string `json:"agents"` // ticked for instructions
}
func readMemory() (*memoryView, error) {
ms, ps, err := memory.All()
if err != nil {
return nil, err
}
on, agents, err := library.MemoryInInstructions()
if err != nil {
return nil, err
}
if ms == nil {
ms = []*memory.Memory{}
}
if ps == nil {
ps = map[string]*memory.Project{}
}
return &memoryView{Memories: ms, Projects: ps, Digest: on, Agents: agents}, nil
}
// memoryChanged publishes the user's change to the agents' instructions
// and answers with the tab as it is now. A publish that fails is the
// change kept and not yet given out, said beside it.
func memoryChanged(rw http.ResponseWriter) {
_, perr := library.PublishMemory(false)
v, err := readMemory()
if err != nil {
fail(rw, err)
return
}
if perr != nil {
writeJSON(rw, struct {
*memoryView
Problem string `json:"problem"`
}{v, perr.Error()})
return
}
writeJSON(rw, v)
}
func memoryRoutes(mux *http.ServeMux) {
mux.HandleFunc("GET /api/memory", func(rw http.ResponseWriter, r *http.Request) {
v, err := readMemory()
if err != nil {
fail(rw, err)
return
}
writeJSON(rw, v)
})
// a memory added, or one changed by its id: the user's own from then on
mux.HandleFunc("POST /api/memory", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
ID string `json:"id"`
memory.Input
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
var err error
if in.ID != "" {
_, err = memory.Edit(in.ID, in.Input, true)
} else {
_, _, err = memory.Save(in.Input, memory.FromUser, nil, nil)
}
if err != nil {
fail(rw, err)
return
}
memoryChanged(rw)
})
mux.HandleFunc("POST /api/memory/remove", func(rw http.ResponseWriter, r *http.Request) {
var in struct {
IDs []string `json:"ids"`
}
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 remove"))
return
}
if err := memory.Remove(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"`
}
if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
fail(rw, err)
return
}
if _, err := library.SetMemoryInInstructions(in.On); err != nil {
fail(rw, err)
return
}
memoryChanged(rw)
})
}
+191
View File
@@ -0,0 +1,191 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// The Library's Memory tab (internal/memory, /api/memory): the switch that
// gives the agents ticked for instructions the memories' summary, the
// Magpie Memory server offered while it isn't in the library, the memories
// in use pinned first, a search, the ones an agent only guessed waiting
// under To review, and a memory added, edited through the app's menu (never
// a <select>), kept and deleted. 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: "claude", name: "Claude Code", icon: "", instructions: `${HOME}/.claude/CLAUDE.md` }, { 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() {
return {
memories: [
{ id: "m1", text: "Use pnpm, never npm, in this repo", kind: "rule", scope: "project:p1", origin: "user", status: "active", created: at(1), updated: at(5) },
{ id: "m2", text: "Answers in Chinese, code comments in English", kind: "preference", scope: "global", origin: "user", status: "active", pinned: true, created: at(1), updated: at(2) },
{ id: "m3", text: "Deploys go out on Fridays", kind: "fact", scope: "global", origin: "inferred", status: "candidate", sources: [{ agent: "codex", at: at(3) }], created: at(3), updated: at(3) },
],
projects: { p1: { key: "p1", name: "magpie", roots: [`${HOME}/magpie`] } },
digest: true,
agents: ["claude"],
};
}
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/library/")) {
sent.push({ path: url.pathname, body: route.request().postDataJSON() });
return route.fulfill({ json: { ...library, result: { changed: [] } } });
}
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/digest") state.digest = body.on;
else if (url.pathname === "/api/memory/remove") state.memories = state.memories.filter((m) => !body.ids.includes(m.id));
else if (body.id) Object.assign(state.memories.find((m) => m.id === body.id), body, { id: body.id });
else state.memories.push({ id: "m" + (state.memories.length + 1), kind: "preference", scope: "global", origin: "user", status: "active", created: at(6), updated: at(6), ...body });
}
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 words = {
en: { tab: "Memory", review: "To review", rule: "Rule", fact: "Fact" },
zh: { tab: "记忆", review: "待确认", rule: "规则", fact: "事实" },
"zh-TW": { tab: "記憶", review: "待確認", rule: "規則", fact: "事實" },
ja: { tab: "メモリ", review: "確認待ち", rule: "ルール", fact: "事実" },
de: { tab: "Memory", review: "Zu prüfen", rule: "Regel", fact: "Fakt" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
test(engine + ": the Library's Memory tab lists, searches, adds, edits, keeps and deletes memories", 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(words)) for (const width of [980, 420]) {
await t.test(`${lang} ${width}`, async () => {
const w = words[lang];
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();
// the tab is named, after Instructions
const tabs = await page.locator(`${view} .lib-tabs .opt`).allTextContents();
assert.equal(tabs[1].trim(), w.tab);
assert.ok((await page.locator(`${view} .lib-tabs .opt.on`).textContent()).includes(w.tab));
// the page is in the reader's language and fits the window
if (lang !== "en") assert.doesNotMatch(await page.locator(`${view} .lib-intro`).textContent(), /What your agents know/);
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 > *`).all()) {
const r = await b.boundingBox();
assert.ok(r.x + r.width <= body.x + body.width + 1, "a control of the bar is cut off");
}
// in use: the pinned one first, then the newer one; the one guessed waits
assert.equal(await rows.count(), 2);
assert.match(await rows.nth(0).textContent(), /Answers in Chinese/);
assert.match(await rows.nth(1).textContent(), /Use pnpm/);
assert.match(await rows.nth(1).textContent(), /magpie/);
assert.match(await rows.nth(1).textContent(), new RegExp(w.rule));
// Magpie Memory isn't in the library: it is offered
assert.equal(await page.locator(`${view} .lib-memtools`).count(), 1);
// the search narrows the list
await page.locator(`${view} input.lib-memq`).fill("pnpm");
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 1);
await page.locator(`${view} input.lib-memq`).fill("");
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 2);
if (width === 980) {
// edited: the kind through the app's menu
await rows.nth(1).click();
const ta = page.locator(`${view} textarea[data-lib="mem:m1"]`);
await ta.waitFor();
assert.equal(await page.locator(`${view} select`).count(), 0, "a native select");
await ta.fill("Use pnpm in this repo");
await page.locator(`${view} .lib-memdetail .lib-mempick`).first().click();
await page.locator(".proto-menu .pm-item", { hasText: w.fact }).click();
await page.locator(`${view} .lib-memdetail .primary`).click();
await page.waitForFunction(() => !document.querySelector("#view-library .lib-memdetail"));
let s = sent.findLast((x) => x.path === "/api/memory");
assert.deepEqual({ id: s.body.id, text: s.body.text, kind: s.body.kind, scope: s.body.scope }, { id: "m1", text: "Use pnpm in this repo", kind: "fact", scope: "project:p1" });
// added: everywhere by default, the user's own
await page.locator(`${view} .lib-memadd`).click();
const nt = page.locator(`${view} textarea[data-lib="mem:new"]`);
await nt.waitFor();
await nt.fill("Never push to main");
await page.locator(`${view} input.lib-memtags`).fill("git, 规则");
await page.locator(`${view} .lib-memdetail .primary`).click();
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 3);
s = sent.findLast((x) => x.path === "/api/memory");
assert.equal(s.body.id, undefined);
assert.deepEqual([s.body.text, s.body.scope, s.body.tags], ["Never push to main", "global", ["git", "规则"]]);
// the one guessed is kept
await page.locator(`${view} .lib-memstatus .opt`, { hasText: w.review }).click();
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 1);
const guessed = page.locator(`${view} .lib-mems .lib-mem`).first();
assert.match(await guessed.textContent(), /Codex/);
await guessed.click();
await page.locator(`${view} .lib-memdetail .lib-acts button`).nth(1).click();
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 0);
s = sent.findLast((x) => x.path === "/api/memory");
assert.deepEqual(s.body, { id: "m3", status: "active" });
// deleted, on a second click
await page.locator(`${view} .lib-memstatus .opt`).first().click();
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 4);
await page.locator(`${view} .lib-mems .lib-mem`, { hasText: "Never push" }).click();
const del = page.locator(`${view} .lib-memdetail .danger`);
await del.click();
assert.equal(sent.filter((x) => x.path === "/api/memory/remove").length, 0);
await page.locator(`${view} .lib-memdetail .danger-fill`).click();
await page.waitForFunction(() => document.querySelectorAll("#view-library .lib-mems .lib-mem").length === 3);
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/remove").body, { ids: ["m4"] });
// the summary switched off
await page.locator(`${view} .lib-memcard button.lib-switch`).click();
await page.waitForFunction(() => document.querySelector("#view-library .lib-memcard button.lib-switch")?.getAttribute("aria-checked") === "false");
assert.deepEqual(sent.findLast((x) => x.path === "/api/memory/digest").body, { on: false });
}
await ctx.close();
});
}
assert.deepEqual(errors, []);
});
}