diff --git a/docs/subsystems/memory.md b/docs/subsystems/memory.md index 27fdd0f88..cb5b758b0 100644 --- a/docs/subsystems/memory.md +++ b/docs/subsystems/memory.md @@ -155,8 +155,14 @@ after adding. [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. Its header puts the project's own instruction files +cut in the middle. A memory written in several lines keeps them, in its +file, the digest and `memory_search`: the lines after the first are +indented under its item (`memory.Indented`; _meouwu on X, +`TestMultiLineMemoryKeepsItsLines`, `TestMemorySearchKeepsTheLines`). The +dream's and distillation's lists for the model still run each memory into +one line, which their replies are read by; the user's own memories are +never rewritten from them (`Fixed`). The text goes to every agent's +vendor: it names neither magpie nor any vendor. Its header puts the project's own instruction files (AGENTS.md and the like) and docs first: where a memory disagrees with them the agent follows the files and says which memory is out of date, and a project's rule or fact belongs in its files, memory keeping what holds @@ -192,6 +198,9 @@ agents ticked under Instructions, unless `Instructions.NoMemory` 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`. +A memory's row, folded, shows its first line and an ellipsis when more +follow (`firstLine`, suggestions too); open, it shows every line as written +(`library-memory-lines.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 diff --git a/internal/gateway/memory_mcp.go b/internal/gateway/memory_mcp.go index c80d60e9a..5a0851ba9 100644 --- a/internal/gateway/memory_mcp.go +++ b/internal/gateway/memory_mcp.go @@ -569,7 +569,7 @@ func memoryLine(m *memory.Memory, c memoryCaller) string { if m.Pinned { l += ", pinned" } - l += ", " + memoryStamp(m.Updated) + ": " + strings.Join(strings.Fields(m.Text), " ") + l += ", " + memoryStamp(m.Updated) + ": " + memory.Indented(m.Text, " ") if m.Why != "" { l += " (why: " + strings.Join(strings.Fields(m.Why), " ") + ")" } @@ -718,7 +718,7 @@ func memoryForget(a memoryArgs) (string, error) { if err != nil { return "", err } - return "Forgotten: [" + m.ID + "] " + strings.Join(strings.Fields(m.Text), " "), nil + return "Forgotten: [" + m.ID + "] " + memory.Indented(m.Text, " "), nil } // memoryStamp is when a memory was last changed, in the reader's own zone diff --git a/internal/gateway/memory_mcp_test.go b/internal/gateway/memory_mcp_test.go index dbbf8d9dc..64146bbef 100644 --- a/internal/gateway/memory_mcp_test.go +++ b/internal/gateway/memory_mcp_test.go @@ -550,3 +550,18 @@ func TestMemorySavePointsProjectRulesToItsFiles(t *testing.T) { t.Fatalf("memory_save's description: %s", desc) } } + +// A memory the user wrote in several lines reaches an agent in them, the +// lines after the first indented under it, so the next memory listed is +// still told apart (_meouwu on X: the line breaks were run together). +func TestMemorySearchKeepsTheLines(t *testing.T) { + fresh(t) + if _, _, err := memory.Save(memory.Input{Text: ptr("Release steps:\n1. tag the commit\n2. push the tag by name"), Kind: ptr(memory.Procedure), Scope: ptr(memory.Global)}, memory.FromUser, nil, nil); err != nil { + t.Fatal(err) + } + h := lanGuard(New().Handler()) + said, bad := memPost(t, h, memorySearchTool, `{"query":"release steps"}`) + if bad || !strings.Contains(said, ": Release steps:\n 1. tag the commit\n 2. push the tag by name\n") { + t.Fatalf("memory_search said %q", said) + } +} diff --git a/internal/gui/assets/plugins/library/client.js b/internal/gui/assets/plugins/library/client.js index a12f36bac..a432ad75c 100644 --- a/internal/gui/assets/plugins/library/client.js +++ b/internal/gui/assets/plugins/library/client.js @@ -1336,7 +1336,7 @@ magpie.plugin("library", (ctx) => { const r = el("div", "row lib-row"); r.dataset.sugg = s.key; const w = el("div", "who"); - w.append(el("div", "name", s.text)); + w.append(el("div", "name", firstLine(s.text))); const acts = el("div", "lib-acts"); if (s.to === "global") { w.append(el("div", "sub", t("Learned in {projects}", { projects: s.projects.map((k) => mem.projects?.[k]?.name || k).join(", ") }))); @@ -1648,12 +1648,18 @@ magpie.plugin("library", (ctx) => { if (old) old.replaceWith(make()); else render(); } + // a memory folded: its first line, and an ellipsis when more follow + // (_meouwu on X: a memory of several lines was run into one) + function firstLine(text) { + const lines = String(text || "").trim().split(/\r?\n/); + return lines[0].trimEnd() + (lines.length > 1 ? " …" : ""); + } function memRow(m) { 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"); - who.append(el("div", "name", m.text)); + who.append(el("div", "name", isOpen ? m.text : firstLine(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) })); diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index a8208c9e8..8ec543b2e 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -911,7 +911,7 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } .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.open > .who .name { -webkit-line-clamp: unset; white-space: pre-wrap; } .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 */ diff --git a/internal/gui/tests/library-memory-lines.test.cjs b/internal/gui/tests/library-memory-lines.test.cjs new file mode 100644 index 000000000..064a4d8fb --- /dev/null +++ b/internal/gui/tests/library-memory-lines.test.cjs @@ -0,0 +1,117 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A memory written in several lines keeps them (_meouwu on X: "手动添加的 +// 多行记忆被折叠成了一行,把我的换行都去掉了,应当保留原本的格式,收起展示的 +// 时候显示首行+缩略符"). Folded, its row shows the first line and an +// ellipsis; open, the row shows every line as written and the editor holds +// them; one added in the editor is sent with its line breaks. A suggestion +// folds the same way. 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(process.env.MAGPIE_ASSETS || path.join(__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`; +const STEPS = "Release steps:\n1. tag the commit\n2. push the tag by name\n never --tags"; +const memories = () => ({ + memories: [ + { id: "a1", text: STEPS, why: "", kind: "procedure", 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) }, + ], + suggestions: [{ key: "skill:a1", to: "skill", ids: ["a1"], text: STEPS, uses: 4 }], + projects: {}, digest: true, agents: [], +}); + +function server(lang, sent) { + return async (route) => { + const req = route.request(); + const url = new URL(req.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 === "/api/memory/semantic") return route.fulfill({ json: { on: false } }); + if (url.pathname === "/api/memory/distill") return route.fulfill({ json: { on: false, models: [] } }); + if (url.pathname === "/api/memory") { + if (req.method() === "POST") sent.push(JSON.parse(req.postData() || "{}")); + return route.fulfill({ json: memories() }); + } + if (url.pathname.startsWith("/api/memory")) return route.fulfill({ json: memories() }); + 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 langs = ["en", "zh", "zh-TW", "ja", "de"]; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + test(engine + ": a memory of several lines keeps them", 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 langs) for (const width of [980, 420]) { + await t.test(`${lang} ${width}`, async () => { + const ctx = await browser.newContext({ viewport: { width, height: 860 } }); + await ctx.addInitScript(() => { try { localStorage.setItem("magpie.libTab", "memory"); } catch {} }); + const page = await ctx.newPage(); + page.setDefaultTimeout(8000); + page.setDefaultNavigationTimeout(60000); + page.on("pageerror", (e) => errors.push(e.message)); + const sent = []; + await page.route("**/*", server(lang, sent)); + await page.goto("http://magpie.test/"); + await page.locator('button[data-view="library"]').click(); + const row = page.locator(`${view} .lib-mems .lib-mem[data-id="a1"]`); + await row.waitFor(); + const name = row.locator(".who .name"); + const lineH = await name.evaluate((e) => parseFloat(getComputedStyle(e).lineHeight) || parseFloat(getComputedStyle(e).fontSize) * 1.3); + + // folded: the first line and an ellipsis, on one line + assert.equal(await name.textContent(), "Release steps: …"); + assert((await name.evaluate((e) => e.getBoundingClientRect().height)) < lineH * 1.5, "the folded row is more than a line"); + // a suggestion folds the same way + assert.equal(await page.locator(`${view} .lib-memsugg [data-sugg="skill:a1"] .name`).textContent(), "Release steps: …"); + + // open: every line as written, in the row and in the editor + await row.evaluate((e) => e.click()); // at 420px the header can sit over it while the page settles + const ta = page.locator(`${view} textarea[data-lib="mem:a1"]`); + await ta.waitFor(); + assert.equal(await name.textContent(), STEPS); + assert.equal(await name.evaluate((e) => getComputedStyle(e).whiteSpace), "pre-wrap"); + assert((await name.evaluate((e) => e.getBoundingClientRect().height)) >= lineH * 3.5, "the open row ran its lines together"); + assert.equal(await ta.inputValue(), STEPS); + + // a line added in the editor is saved with its break + await ta.focus(); + await ta.evaluate((e) => e.setSelectionRange(e.value.length, e.value.length)); + await page.keyboard.press("Enter"); + await page.keyboard.type("3. wait for the assets"); + await page.locator(`${view} .lib-memdetail .primary`).click(); + await page.waitForFunction(() => !document.querySelector("#view-library .lib-memdetail")); + assert.equal(sent.at(-1).text, STEPS + "\n3. wait for the assets"); + assert.deepEqual(errors, []); + await ctx.close(); + }); + } + }); +} diff --git a/internal/memory/digest.go b/internal/memory/digest.go index d5bba742d..23836cd08 100644 --- a/internal/memory/digest.go +++ b/internal/memory/digest.go @@ -38,7 +38,7 @@ var kindTitles = map[string]string{ } // render is the digest of one scope's memories within budget characters: -// a heading per kind, a line per memory, pinned and newer ones first, and +// a heading per kind, an item per memory (its own lines kept), pinned and newer ones first, and // none cut in the middle. "" when the scope has none. func render(ms []*Memory, scope string, budget int) string { pool := []*Memory{} @@ -63,7 +63,7 @@ func render(ms []*Memory, scope string, budget int) string { picked := map[string][]string{} used := 0 for _, m := range pool { - line := "- " + oneLine(m.Text) + line := "- " + Indented(m.Text, " ") if m.Why != "" { line += " (why: " + oneLine(m.Why) + ")" } @@ -91,6 +91,22 @@ func render(ms []*Memory, scope string, budget int) string { func oneLine(s string) string { return strings.Join(strings.Fields(s), " ") } +// Indented is a memory's text with its line breaks kept, each line after +// the first led by pad, so a memory the user wrote in several lines reads +// as they wrote it and stays one item of a list. Spaces closing a line and +// blank lines' pads are left out. +func Indented(s, pad string) string { + lines := strings.Split(strings.TrimSpace(strings.ReplaceAll(s, "\r\n", "\n")), "\n") + for i, l := range lines { + l = strings.TrimRight(l, " \t\r") + if i > 0 && l != "" { + l = pad + l + } + lines[i] = l + } + return strings.Join(lines, "\n") +} + // publish renders every scope's digest into f. func publish(f *file) { scopes := map[string]bool{} diff --git a/internal/memory/digest_test.go b/internal/memory/digest_test.go index 641828078..9b49d4d77 100644 --- a/internal/memory/digest_test.go +++ b/internal/memory/digest_test.go @@ -1,6 +1,7 @@ package memory import ( + "os" "strings" "testing" "time" @@ -118,3 +119,53 @@ func TestDigestDefersToTheProjectsFiles(t *testing.T) { } } } + +// A memory the user writes in several lines keeps them: on save, on an +// edit, in its file, and in the digest, where the lines after the first +// are indented under its item (_meouwu on X: the line breaks were gone). +func TestMultiLineMemoryKeepsItsLines(t *testing.T) { + fresh(t) + text := "Release steps:\n1. tag the commit\n2. push the tag by name\n\n - never --tags" + m, _, err := Save(Input{Text: str(text + "\n"), Kind: str(Procedure), Scope: str(Global)}, FromUser, nil, nil) + if err != nil { + t.Fatal(err) + } + if m.Text != text { + t.Fatalf("saved %q, want %q", m.Text, text) + } + text += "\n3. wait for the assets" + if _, err := Edit(m.ID, Input{Text: str(text)}, true); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(in(m.ID + ".md")) + if err != nil { + t.Fatal(err) + } + if got, err := decode(m.ID, b, time.Now()); err != nil || got.Text != text { + t.Fatalf("the file reads %q (%v), want %q", got.Text, err, text) + } + if got, _ := Get(m.ID); got.Text != text { + t.Fatalf("Get %q, want %q", got.Text, text) + } + if _, err := Publish(); err != nil { + t.Fatal(err) + } + d, _ := Digest("codex") + want := "How things are done:\n- Release steps:\n 1. tag the commit\n 2. push the tag by name\n\n - never --tags\n 3. wait for the assets" + if !strings.Contains(d, want) { + t.Fatalf("digest %q, want it to hold %q", d, want) + } +} + +func TestIndented(t *testing.T) { + for in, want := range map[string]string{ + "one line": "one line", + " a\r\nb \n\n\tc\n": "a\n> b\n\n> \tc", + "a \t\n \nb": "a\n\n> b", + "\n\nonly after blanks\n\n": "only after blanks", + } { + if got := Indented(in, "> "); got != want { + t.Errorf("Indented(%q) = %q, want %q", in, got, want) + } + } +}