From 5b370f3e62689f4e50feeccc4d804bc74cdbe6fb Mon Sep 17 00:00:00 2001
From: SadWood <24450652+SadWood@users.noreply.github.com>
Date: Mon, 2 Nov 2026 05:14:03 +0800
Subject: [PATCH] nowledge-mem 0.1.5: one Settings dialog for every option on
released hosts (#588, SadWood)
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
The Nowledge Mem page's dialog now sets every option the hook reads, on Magpie's released bridge (options.get/set only), by SadWood.
- One Settings dialog: connection, key (an empty field keeps the saved key; Remove saved key / Undo), API key variable, recall and remote recall, Context Bundle, apps without memory, capture and remote capture, the human-dialogue filter (a switch, Cindy only with it on, tool results only with it off) and the advanced numbers. Remote HTTP needs the Advanced exception.
- A × beside a field that holds an explicit value returns it to the default. Saving re-reads the options, writes only edited fields, and refuses (keeping the draft) when one of them, or a gate's remote grant or the endpoint behind a newly allowed HTTP exception, changed elsewhere.
- page/validate.js is shared by the page and resolveOptions, so both refuse the same values.
- The footer wraps at narrow widths (German Save was cut off at 380px).
- No native select. Every language has every key; the English fallback loop is gone.
Reviewed at 75a09d19e, run merged onto main 04f3608 (main's later 24cd0b9 touches packages/cursor only). Mac mini, Bun 1.4.2, temp HOME:
- packages/nowledge-mem: 130 pass, 2 skip (live Mem, Linux-only Chrome layout), 0 fail.
- whole repo bun test: 4699 pass, 12 skip, 0 fail. bun scripts/check.mjs: exit 0.
- PR CI at this head ran the Linux Chrome layout test (pass, 30 layouts) and 4587 pass.
- Browser harness: page/ framed with sandbox="allow-scripts", magpie's CSP and magpie's real pagebridge.js; Chromium and WebKit, en/zh/zh-TW/ja/de, 320/380/900px, light/dark (60 runs). No request beyond the page's own files, no console or page errors, the key never in the DOM, no select, no overflow, key field password again after show/close/reopen, recallRemote shown but disabled while recall is off. Flows (en 380, both engines): editing Space gives one options.set keeping custom, apiKey, requestTimeoutMs:900, skipAgents and recallRemote; http://100.64.0.5 refused until the HTTP exception is on, then saved; a Space changed elsewhere conflicts and writes nothing; Bearer key replaces and empties the field; Remove saved key deletes apiKey; turning recall on keeps recallRemote.
Broken by hand:
- Main's footer CSS back: the harness flags 12 runs (en 320, de 320/380, both engines).
- settings.js dependency check off: "enabling a global gate conflicts…" and "enabling HTTP exception conflicts…" go red.
- validateExplicitOptions removed from resolveOptions: two hook option tests go red.
Not tried: a real Mem server.
---
packages/nowledge-mem/README.md | 28 +-
packages/nowledge-mem/mem.mjs | 49 +--
packages/nowledge-mem/nowledge-mem.test.mjs | 232 +----------
packages/nowledge-mem/package.json | 2 +-
packages/nowledge-mem/page-layout.test.mjs | 64 +++
packages/nowledge-mem/page.test.mjs | 413 ++++++++++++++++++++
packages/nowledge-mem/page/i18n.js | 101 +++--
packages/nowledge-mem/page/settings.html | 45 ++-
packages/nowledge-mem/page/settings.js | 389 +++++++++++-------
packages/nowledge-mem/page/style.css | 16 +-
packages/nowledge-mem/page/validate.js | 33 ++
11 files changed, 924 insertions(+), 448 deletions(-)
create mode 100644 packages/nowledge-mem/page-layout.test.mjs
create mode 100644 packages/nowledge-mem/page.test.mjs
create mode 100644 packages/nowledge-mem/page/validate.js
diff --git a/packages/nowledge-mem/README.md b/packages/nowledge-mem/README.md
index 78241b6..2e74084 100644
--- a/packages/nowledge-mem/README.md
+++ b/packages/nowledge-mem/README.md
@@ -70,17 +70,12 @@ environment Magpie starts with, as Mem's own clients do:
A key saved in the page is kept in Magpie's local plugin configuration, not the
system keychain, and takes precedence over the environment. Enter it directly;
-the form also accepts an existing `Bearer …` value. The page's **Configure
-connection** form also sets the Space, Agent and the recall, Context Bundle,
-capture switches; Magpie's plugin **Options** editor remains available for
-advanced settings. Saving conversations remains a separate opt-in.
+the form also accepts an existing `Bearer …` value. The page's **Settings** form also sets the Space, Agent, recall, Context Bundle,
+capture and advanced options; Magpie's plugin **Options** editor remains available. Saving conversations remains a separate opt-in.
`serverUrl` must be HTTPS, or HTTP only for `localhost`, `127.0.0.1` and
`[::1]`. Credentials, a query or a fragment in the URL are refused. Set
-`allowInsecureHttp` (the page's **Allow HTTP to another machine** switch) only
-on a network you trust, such as a Tailscale tailnet, whose link is already
-encrypted: then `http://mac-studio.tailnet.ts.net:14242` or
-`http://100.x.y.z:14242` is accepted by the page and the hook alike.
+`allowInsecureHttp` only for a trusted network, such as a Tailscale tailnet; prefer HTTPS elsewhere.
## One gateway, several harnesses
@@ -153,8 +148,7 @@ derived value for all of them.
the protocol role does not establish authorship. It does not infer native Side
Chat boundaries. Configure both options in Plugins → Options.
- `allowInsecureHttp`: default **false**. Permits plain HTTP to a server that
- is not a loopback address, for a network you trust such as Tailscale. Prefer
- HTTPS elsewhere. The page has a switch for it.
+ is not a loopback address. Prefer HTTPS.
- `recallRemote`: default **false**. Recall and the Context Bundle go only to
direct local requests and `magpie-key` from this computer. Set it to give
recall also to `remote` requests (another machine) and `gateway-key`
@@ -163,7 +157,7 @@ derived value for all of them.
- `captureRemote`: default **false**. With `capture` on, also save
conversations from `remote` and `gateway-key` requests. It does not grant
recall: without `recallRemote` those requests are saved but get nothing from
- Mem. Set these two in Plugins → Options; the page does not show them.
+ Mem. The Settings page has separate switches for these options.
- `port`: the loopback port of the page's connection test, default 3479. Change
it only when another program holds that port; the page reads the same value.
@@ -277,14 +271,14 @@ own: the offline tests replace `globalThis.fetch` to keep Cursor's token local
## Page
-The page uses only Magpie's released `magpie.options` and theme bridge. It
+The page uses Magpie's released `magpie.options` and theme bridge. Before
+saving it re-reads and merges edited fields, but another write between the read
+and write can still be lost. The released bridge can also round integers outside
+JavaScript's exact range, including in unlisted options. Use one editor at a time. It
declares no reads and saving stores configuration without probing the
-connection or writing Memory. It shows the Server, API key, Space, Agent, the
-apps without memory (`skipAgents`), the recall, Context Bundle and capture
-switches, and **Allow HTTP to another machine** (`allowInsecureHttp`). Its **What is sent** section says
+connection or writing Memory. It shows connection, local and remote recall, apps excluded with `skipAgents`, local and remote capture, filtering and advanced options. Its **What is sent** section says
the scope: direct local requests and `magpie-key` from this computer; other
-gateway keys and remote requests are included only through `recallRemote` and
-`captureRemote`. It follows Magpie's language (English, Simplified and
+gateway keys and remote requests require separate `recallRemote` or `captureRemote` opt-ins. It follows Magpie's language (English, Simplified and
Traditional Chinese, Japanese, German) and theme, and preserves options it does
not show.
diff --git a/packages/nowledge-mem/mem.mjs b/packages/nowledge-mem/mem.mjs
index d6937a3..010e18b 100644
--- a/packages/nowledge-mem/mem.mjs
+++ b/packages/nowledge-mem/mem.mjs
@@ -4,9 +4,11 @@
// same options and environment, so they never disagree about where Mem is or
// which Space they speak to.
import { createHash } from "node:crypto";
+import "./page/validate.js";
+const validateExplicitOptions = globalThis.__nowledgeMemValidateOptions;
// Bumped with package.json: Mem's own clients record it on imported Threads.
-export const version = "0.1.4";
+export const version = "0.1.5";
// The only report codes magpie's Plugins page shows; tools turn these into
// messages, never the service's own text.
@@ -24,6 +26,7 @@ export class MemFailure extends Error {
const maxResponseBytes = 512 << 10;
export function resolveOptions(raw = {}, env = process.env) {
+ try { validateExplicitOptions(raw); } catch { throw new MemFailure("invalid"); }
const text = (v) => {
if (v === undefined || v === null || v === "")
return undefined;
@@ -31,28 +34,12 @@ export function resolveOptions(raw = {}, env = process.env) {
throw new MemFailure("invalid");
return v;
};
- const bool = (name, fallback) => {
- if (raw[name] !== undefined && typeof raw[name] !== "boolean")
- throw new MemFailure("invalid");
- return raw[name] ?? fallback;
- };
- const integer = (name, fallback, min, max) => {
- const value = raw[name] ?? fallback;
- if (!Number.isInteger(value) || value < min || value > max)
- throw new MemFailure("invalid");
- return value;
- };
- // skipAgents names the apps whose requests this plugin leaves alone: a
- // list, or one string of names split by commas or new lines.
+ // A name may be a list or comma/newline-separated text, as in #597.
let skip = raw.skipAgents ?? [];
- if (typeof skip === "string")
- skip = skip.split(/[,,\n]/u);
- if (!Array.isArray(skip) || skip.some((name) => typeof name !== "string"))
- throw new MemFailure("invalid");
+ if (typeof skip === "string") skip = skip.split(/[,,\n]/u);
+ if (!Array.isArray(skip) || skip.some((name) => typeof name !== "string")) throw new MemFailure("invalid");
const skipAgents = new Set(skip.map(agentKey).filter(Boolean));
const captureFilter = raw.captureFilter === undefined ? "off" : raw.captureFilter;
- if (captureFilter !== "off" && captureFilter !== "human")
- throw new MemFailure("invalid");
// The Mem endpoint, as its own clients resolve it: the option, then the
// portable NMEM_API_URL, then the local desktop default. A URL from the
// environment that isn't an HTTP(S) address is ignored rather than fatal.
@@ -99,18 +86,18 @@ export function resolveOptions(raw = {}, env = process.env) {
agentId: text(raw.agentId),
hostAgentId: text(raw.hostAgentId),
skipAgents,
- recall: bool("recall", true),
- contextBundle: bool("contextBundle", true),
- capture: bool("capture", false),
- recallRemote: bool("recallRemote", false),
- captureRemote: bool("captureRemote", false),
- captureTools: bool("captureTools", true),
+ recall: raw.recall ?? true,
+ contextBundle: raw.contextBundle ?? true,
+ capture: raw.capture ?? false,
+ recallRemote: raw.recallRemote ?? false,
+ captureRemote: raw.captureRemote ?? false,
+ captureTools: raw.captureTools ?? true,
captureFilter,
- captureCindy: bool("captureCindy", false),
- maxMemories: integer("maxMemories", 5, 1, 20),
- maxBytes: integer("maxBytes", 6000, 512, 32768),
- requestTimeoutMs: integer("requestTimeoutMs", 1500, 50, 5000),
- recallBackoffMs: integer("recallBackoffMs", 30_000, 100, 300_000),
+ captureCindy: raw.captureCindy ?? false,
+ maxMemories: raw.maxMemories ?? 5,
+ maxBytes: raw.maxBytes ?? 6000,
+ requestTimeoutMs: raw.requestTimeoutMs ?? 1500,
+ recallBackoffMs: raw.recallBackoffMs ?? 30_000,
};
}
diff --git a/packages/nowledge-mem/nowledge-mem.test.mjs b/packages/nowledge-mem/nowledge-mem.test.mjs
index 231de96..4d25570 100644
--- a/packages/nowledge-mem/nowledge-mem.test.mjs
+++ b/packages/nowledge-mem/nowledge-mem.test.mjs
@@ -709,7 +709,6 @@ test("a canceled request keeps its reason and does not back off the service", as
expect(body.messages[1].content).toContain("QUARTZ-8413")
})
-// The official sandbox page may configure options, but has no network or custom host API.
test("remote and gateway-key requests get recall and capture only by their own opt-in (#608)", async () => {
for (const origin of ["remote", "gateway-key"]) {
for (const [recallRemote, captureRemote] of [[false, false], [true, false], [false, true], [true, true]]) {
@@ -750,222 +749,19 @@ test("remote and gateway-key requests get recall and capture only by their own o
}
})
-test("configuration page uses only the released options and theme bridge", async () => {
- const source = await Bun.file(new URL("./page/settings.js", import.meta.url)).text()
- const calls = [...source.matchAll(/magpie\.([\w.]+)/g)].map((match) => match[1])
- expect([...new Set(calls)].sort()).toEqual(["onTheme", "options.get", "options.set", "ready.then", "theme"])
- expect(source).not.toMatch(/\b(fetch|XMLHttpRequest|WebSocket|EventSource)\b/)
- const html = await Bun.file(new URL("./page/settings.html", import.meta.url)).text()
- expect([...html.matchAll(/`
+ const temp = await mkdtemp(join(tmpdir(), "nowledge-layout-"))
+ try {
+ const proc = Bun.spawn({
+ cmd: [chrome, "--headless=new", "--no-sandbox", "--disable-gpu", "--disable-dev-shm-usage", "--disable-background-networking", "--disable-extensions", "--disable-sync", "--no-first-run", "--no-default-browser-check", "--password-store=basic", "--host-resolver-rules=MAP * ~NOTFOUND", `--user-data-dir=${temp}/profile`, "--window-size=1200,1600", "--dump-dom", `data:text/html;charset=utf-8,${encodeURIComponent(page)}`],
+ env: { HOME: temp, PATH: "/usr/bin:/bin", XDG_CONFIG_HOME: `${temp}/config`, XDG_CACHE_HOME: `${temp}/cache` },
+ stdout: "pipe", stderr: "pipe",
+ })
+ const [out, err, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited])
+ expect({ code, error: code ? err : "" }).toEqual({ code: 0, error: "" })
+ const result = out.match(/
([^<]+)<\/pre>/)?.[1]
+ expect(result).toBeTruthy()
+ const rows = JSON.parse(result)
+ expect(rows).toHaveLength(30)
+ for (const row of rows) {
+ expect({ language: row.language, width: row.width, fits: row.fits }).toEqual({ language: row.language, width: row.width, fits: true })
+ expect(row.gap).toBeGreaterThanOrEqual(11)
+ }
+ } finally {
+ await rm(temp, { recursive: true, force: true })
+ }
+}, 30000)
diff --git a/packages/nowledge-mem/page.test.mjs b/packages/nowledge-mem/page.test.mjs
new file mode 100644
index 0000000..9911f9a
--- /dev/null
+++ b/packages/nowledge-mem/page.test.mjs
@@ -0,0 +1,413 @@
+import { expect, test } from "bun:test"
+import { runInNewContext } from "node:vm"
+import { onRequest, onResponse, reset } from "./nowledge-mem.hooks.mjs"
+
+test("the shared validator remains available after its module is cached", async () => {
+ const validator=globalThis.__nowledgeMemValidateOptions
+ await import("./page/validate.js")
+ expect(typeof validator).toBe("function")
+ expect(globalThis.__nowledgeMemValidateOptions).toBe(validator)
+})
+
+// The sandboxed page must not acquire network or additional host privileges.
+// These checks are a regression guard, not a JavaScript security parser.
+function pageCalls(source) {
+ return [...source.matchAll(/\bmagpie\s*(?:\?\.|\.)\s*([\w$]+(?:\s*(?:\?\.|\.)\s*[\w$]+)*)/g)]
+ .map(([,call]) => call.replace(/\s/g, "").replaceAll("?.", "."))
+}
+function pageScriptAllowed(source, allowedCalls) {
+ if (/\b(fetch|XMLHttpRequest|WebSocket|EventSource)\b/.test(source)) return false
+ if (/\bmagpie\s*\[|\b(?:window|globalThis)\s*\[\s*["']magpie["']\s*\]/.test(source)) return false
+ return pageCalls(source).every((call) => allowedCalls.includes(call))
+}
+
+test("page scripts use only the released bridge and do not perform network calls", async () => {
+ const read=(file)=>Bun.file(new URL(`./page/${file}`,import.meta.url)).text()
+ const [settings,validator,dictionary,html]=await Promise.all([read("settings.js"),read("validate.js"),read("i18n.js"),read("settings.html")])
+ const allowed=["service","options.get","options.set","theme.lang","ready.then","onTheme"]
+ expect(pageScriptAllowed(settings,allowed)).toBe(true)
+ expect([...new Set(pageCalls(settings))].sort()).toEqual([...allowed].sort())
+ expect(pageScriptAllowed(validator,[])).toBe(true)
+ expect(pageScriptAllowed(dictionary,[])).toBe(true)
+ const tags=[...html.matchAll(/
+
-
Nowledge Mem
Recall your Mem memory in every agent behind Magpie.
+
Nowledge Mem
Recall your Mem memory in every agent behind Magpie.
Connection
Server URL
—
Space ID
—
Memory recall
—
Apps without memory
—
Save conversations
Memory tools
This plugin does not add a Library entry. To give agents Mem’s tools, add Mem’s own MCP server once in Magpie’s Library › MCP, using the Server URL below (NMEM_API_URL when it is empty) and its key.
What is sent
Recall sends the latest user turn to the configured Mem URL (NMEM_API_URL when Server URL is empty, else the local default), even when saving conversations is off.
Saving conversations is off by default. When enabled, completed user and assistant turns are imported to that Mem, plus client tool results unless captureTools is off.
-
Recall and saving apply to direct local requests and to the Magpie sharing key this computer writes into your own agents (magpie-key). Other gateway keys, a sharing key from another machine, and remote requests are not included. The recallRemote and captureRemote options let them in, each separately; saving does not grant recall.
+
By default, recall and saving apply to direct local requests and to the Magpie sharing key this computer writes into your own agents (magpie-key). Other gateway keys, a sharing key from another machine, and remote requests are not included. The recallRemote and captureRemote options let them in, each separately; saving does not grant recall.