memory: a memory of several lines keeps them, folded to its first line (_meouwu on X)

_meouwu on X: a memory added by hand in several lines showed as one line
with its breaks gone; it should keep its format and, folded, show the
first line and an ellipsis.

Cause: the store never lost the breaks. A memory file's body is
m.Text as written (encode/apply trim only the ends). They were lost
where it was shown: the Library row clamped the name to two lines with
white-space normal, the digest given to agents went through oneLine
(strings.Fields), and so did memory_search / memory_list in the memory
MCP.

Now:
- Library: a folded row and a suggestion show firstLine(text) (first
  line, " …" when more follow); an open row shows the whole text
  pre-wrap. The editor already kept "\n".
- Digest and memory MCP: memory.Indented keeps each line, the lines
  after the first indented two spaces so the memory stays one list
  item.
- Dream and distill listings stay one line on purpose: the model's
  reply is read line by line, and a user's memory is Fixed, never
  rewritten by them. Written in docs/subsystems/memory.md.

Memories saved before: their files already hold the breaks, so after
updating they show, edit and reach agents in their own lines. Nothing
to redo, no migration.

Run at 3fabaf8f2 (on origin/main b332ef7ef, the pushed head),
f6452d777 (on 1622484a8) and ee84e288a (on 54117164c), on the WSL VM magpie-desktop: mote and mica were over
their cores with other sessions' suites for ~2h.
- go vet -tags gtk3 ./... ok; gofmt -l clean.
- go test -tags gtk3 -count=1 -timeout 45m ./... at ee84e288a: 101 ok,
  2 FAIL, both red at origin/main 2416beed6 on the same VM:
  internal/gui TestClipboardReadBack (#7074, #7073), internal/usage
  TestRequestStateKeptAcrossACatalogFetchedAgain (#6572).
- Whole GUI suite (concurrency 8): 1355 of 29368 red in 221 files under
  load. Those 221 again at concurrency 3: 71 red; 66 of them red at
  base 54117164c too. Of the other 5, 3 pass alone;
  codex-auto-reset-settings (#6108) and copilot-ghe (#1949) are red at
  base alone too (2 of 3 and 3 of 3 rounds), commented there.
- After the rebase (f6452d777): internal/memory, internal/memdistill
  and -run "Memory|Budget|I18n" in gateway, gui, library ok. All 84
  library-*.test.cjs: 1920 of 1950 pass; each red file alone, beside
  1622484a8: commands-import, group-steady, mcp-copy-config,
  mcp-off-fold, open-again and all are red at base too (#7097; all 3 of
  3 at base); memory-suggest, mcp-json and bili pass alone.
- At 3fabaf8f2 (b332ef7ef brought flying_crp's digest header and
  memory_save note; conflicts were only both sides adding tests and
  doc text): go vet memory, gateway, memdistill; go test memory,
  memdistill, access, and -run "Memory|Budget|I18n|Digest" in gateway,
  gui, library ok; library-memory*.test.cjs 112 of 112.
- library-memory-lines.test.cjs: 5 langs x 980/420 x chromium/webkit.

Broken by hand (old code, new tests): TestMultiLineMemoryKeepsItsLines
red at the digest step only (save, edit and the file passed: the store
kept the breaks), TestIndented and TestMemorySearchKeepsTheLines red,
library-memory-lines red ("Release steps: …" expected).

Not tried: a macOS run (mote, mica busy), Windows, the real app.
This commit is contained in:
yetone
2026-11-19 06:32:40 +08:00
parent b332ef7efe
commit a18ed4995f
8 changed files with 223 additions and 9 deletions
+11 -2
View File
@@ -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
+2 -2
View File
@@ -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
+15
View File
@@ -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)
}
}
@@ -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) }));
@@ -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 */
@@ -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();
});
}
});
}
+18 -2
View File
@@ -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{}
+51
View File
@@ -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)
}
}
}