nowledge-mem 0.1.5: one Settings dialog for every option on released hosts (#588, SadWood)

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.
This commit is contained in:
SadWood
2026-11-02 05:14:03 +08:00
committed by GitHub
parent 24cd0b9123
commit 5b370f3e62
11 changed files with 924 additions and 448 deletions
+11 -17
View File
@@ -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.
+18 -31
View File
@@ -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,
};
}
+14 -218
View File
@@ -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(/<script\b[^>]*\bsrc="([^"]+)"/g)].map(([, src]) => src).sort()).toEqual(["_magpie/bridge.js", "i18n.js", "settings.js"])
expect(html).not.toMatch(/<script(?![^>]*\bsrc=)[^>]*>/)
expect([...html.matchAll(/\b(?:src|href)="((?:https?:)?\/\/[^"]+)"/g)]).toEqual([])
})
test("configuration page saves the Mem connection for the shipped hook", async () => {
const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text()
const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")])
const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, {
dataset: {}, value: "", type: id === "key" ? "password" : "text", checked: false,
setAttribute(name, value) { this[name] = value }, focus() {}, showModal() {}, close() {},
}]))
const document = { documentElement: {}, getElementById: (id) => elements[id], querySelectorAll: () => [] }
const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign(url) { this.assigned = url } }
const window = { name: "" }
let options = { apiKeyEnv: "NMEM_API_KEY", recall: true, contextBundle: true, capture: false, maxMemories: 5, maxBytes: 6000 }
let writes = 0
const magpie = {
theme: { lang: "en" }, ready: Promise.resolve(), onTheme() {},
options: { get: async () => ({ ...options }), set: async (next) => { options = { ...next }; writes++ } },
}
runInNewContext(`${dictionary}\n${source}`, { document, magpie, window, location, navigator: { language: "en" }, URL })
await new Promise(setImmediate)
const save = () => elements.save.onclick({ preventDefault() {} })
const original = { ...options }
elements.url.value = "http://127.0.0.1:14242"
elements.space.value = " space-7 "
elements.agent.value = "agent-3"
elements.key.value = "Bearer nmem_page_key"
elements.capture.checked = true
elements["skip-agents"].value = " Mozilla,, Claude Code ,"
await save()
expect(options).toEqual({
...original,
serverUrl: "http://127.0.0.1:14242/",
spaceId: "space-7",
agentId: "agent-3",
apiKey: "nmem_page_key",
capture: true,
skipAgents: ["Mozilla", "Claude Code"],
})
expect(elements["summary-skip"].textContent).toBe("Mozilla, Claude Code")
// Run the shipped hook with exactly what the page saved.
mock({ "threads/import": (body) => Response.json({ success: true, failed_count: 0, results: [{ success: true, thread_id: body.thread_id, message_count: body.messages.length, messages_added: body.messages.length }] }) })
const hookContext = ctx("chat", { options })
hookContext.state = {}
await onRequest(structuredClone(chat), hookContext)
expect(of("memories/search")[0].init.headers.Authorization).toBe("Bearer nmem_page_key")
expect(of("memories/search")[0].url.origin).toBe("http://127.0.0.1:14242")
await onResponse(reply, { ...hookContext, success: true })
expect(of("threads/import")[0].body.space_id).toBe("space-7")
expect(of("threads/import")[0].body.metadata.agent_id).toBe("agent-3")
elements.configure.onclick()
expect(elements.key.type).toBe("password")
expect(elements.key.value).toBe("nmem_page_key")
elements["show-key"].onclick()
expect(elements.key.type).toBe("text")
expect(elements["show-key"]["aria-pressed"]).toBe("true")
elements.settings.onclose()
expect(elements.key.type).toBe("password")
expect(elements.key.value).toBe("")
for (const invalid of ["bad key", "bad\nkey"]) {
elements.key.value = invalid
await save()
expect(writes).toBe(1)
expect(elements.result.dataset.message).toBe("invalidKey")
}
for (const invalid of ["ftp://mem.example.com", "http://mem.example.com", "https://mem.example.com?token=x"]) {
elements.url.value = invalid
await save()
expect(writes).toBe(1)
expect(elements.result.dataset.message).toBe("invalidUrl")
}
elements.configure.onclick()
expect(elements["skip-agents"].value).toBe("Mozilla, Claude Code")
elements.url.value = "https://mem.example.com"
elements.key.value = ""
elements.space.value = " "
elements.agent.value = ""
elements.capture.checked = false
elements["skip-agents"].value = " , "
await save()
expect(options.skipAgents).toBeUndefined()
expect(elements["summary-skip"].textContent).toBe("None")
expect(options.serverUrl).toBe("https://mem.example.com/")
// The main page's Test button tests the saved connection; the test page
// reads only the way back and the language.
elements["test-saved"].onclick()
expect(location.assigned).toBe("http://127.0.0.1:3479/test?lang=en")
expect(options.apiKey).toBeUndefined()
expect(options.spaceId).toBeUndefined()
expect(options.agentId).toBeUndefined()
expect(options.apiKeyEnv).toBe("NMEM_API_KEY")
expect(options.maxBytes).toBe(6000)
expect(elements["summary-space"].textContent).toBe("Default Space")
})
test("configuration page takes a tailnet HTTP server only with Allow HTTP to another machine (#608)", async () => {
const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text()
const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")])
const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, {
dataset: {}, value: "", type: id === "key" ? "password" : "text", checked: false,
setAttribute(name, value) { this[name] = value }, focus() {}, showModal() {}, close() {},
}]))
expect(elements["insecure-http"]).toBeDefined()
const document = { documentElement: {}, getElementById: (id) => elements[id], querySelectorAll: () => [] }
const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign(url) { this.assigned = url } }
let options = { serverUrl: "http://mac-studio.tailnet.ts.net:14242", recall: true, maxBytes: 6000 }
let writes = 0
const magpie = {
theme: { lang: "en" }, ready: Promise.resolve(), onTheme() {},
options: { get: async () => ({ ...options }), set: async (next) => { options = { ...next }; writes++ } },
}
runInNewContext(`${dictionary}\n${source}`, { document, magpie, window: { name: "" }, location, navigator: { language: "en" }, URL })
await new Promise(setImmediate)
const save = () => elements.save.onclick({ preventDefault() {} })
// without the option, a saved tailnet HTTP URL can't be tested or saved
expect(elements["insecure-http"].checked).toBe(false)
elements["test-saved"].onclick()
expect(location.assigned).toBeUndefined()
expect(elements.configured.dataset.message).toBe("invalidUrl")
for (const url of ["http://mac-studio.tailnet.ts.net:14242", "http://100.101.102.103:14242"]) {
elements.url.value = url
await save()
expect(writes).toBe(0)
expect(elements.result.dataset.message).toBe("invalidUrl")
}
// with it, the page saves what the hook then uses
elements["insecure-http"].checked = true
for (const url of ["http://100.101.102.103:14242", "http://mac-studio.tailnet.ts.net:14242"]) {
elements.url.value = url
await save()
expect(elements.result.dataset.message).toBe("saveSucceeded")
expect(options).toMatchObject({ serverUrl: `${url}/`, allowInsecureHttp: true, maxBytes: 6000 })
expect(resolveOptions(options).server.href).toBe(`${url}/`)
}
expect(writes).toBe(2)
elements["test-saved"].onclick()
expect(location.assigned).toBe("http://127.0.0.1:3479/test?lang=en")
mock()
calls.length = 0
await onRequest(structuredClone(chat), ctx("chat", { options }))
expect(of("memories/search")[0].url.href).toBe("http://mac-studio.tailnet.ts.net:14242/memories/search")
// the dialog shows the saved option; the rest of the URL rules still hold
elements["insecure-http"].checked = false
elements.configure.onclick()
expect(elements["insecure-http"].checked).toBe(true)
for (const invalid of ["ftp://mem.example.com", "http://user:pw@mac-studio.tailnet.ts.net:14242", "http://mac-studio.tailnet.ts.net:14242?token=x"]) {
elements.url.value = invalid
await save()
expect(writes).toBe(2)
expect(elements.result.dataset.message).toBe("invalidUrl")
}
// turning it off drops the option, so the tailnet URL is refused again
elements["insecure-http"].checked = false
elements.url.value = "https://mem.example.com"
await save()
expect(writes).toBe(3)
expect(options.allowInsecureHttp).toBeUndefined()
elements.url.value = "http://mac-studio.tailnet.ts.net:14242"
await save()
expect(writes).toBe(3)
expect(elements.result.dataset.message).toBe("invalidUrl")
})
test("configuration page follows the host language without losing edits or messages", async () => {
const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text()
const [dictionary, source, html] = await Promise.all([read("i18n.js"), read("settings.js"), read("settings.html")])
const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, {
dataset: {}, value: "", hidden: false, checked: false, setAttribute(name, value) { this[name] = value }, focus() {},
}]))
const translated = [...html.matchAll(/data-t="([^"]+)"/g)].map(([, key]) => ({ dataset: { t: key } }))
const document = {
documentElement: {}, getElementById: (id) => elements[id],
querySelectorAll: (selector) => selector === "[data-t]" ? translated : Object.values(elements).filter((el) => el.dataset.message),
}
let repaint
const magpie = {
theme: { lang: "zh" }, ready: Promise.resolve(), onTheme: (fn) => { repaint = fn },
options: { get: async () => ({ serverUrl: "http://127.0.0.1:14242", capture: true }) },
}
const window = { name: "" }
const location = { href: "http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html", assign() {} }
const { messages, languageFor, languageTags } = runInNewContext(`${dictionary}\n${source}\nnowledgeMemI18n`, { document, magpie, window, location, navigator: { language: "en" }, URL })
await new Promise(setImmediate)
for (const language of ["en", "zh", "zh-TW", "ja", "de"]) {
expect(Object.keys(messages[language]).sort()).toEqual(Object.keys(messages.en).sort())
expect(Object.values(messages[language]).every((text) => typeof text === "string" && text.length > 0)).toBe(true)
}
for (const [input, expected] of [["zh-CN", "zh"], ["zh-Hant-TW", "zh-TW"], ["zh_HK", "zh-TW"], ["ja-JP", "ja"], ["de-AT", "de"], ["fr-FR", "en"]]) {
expect(languageFor(input)).toBe(expected)
}
elements.url.value = "unsaved address"
await elements.save.onclick({ preventDefault() {} })
for (const language of ["en", "zh-TW", "ja", "de", "zh"]) {
magpie.theme.lang = language
repaint()
expect(document.documentElement.lang).toBe(languageTags[language])
expect(elements.url.value).toBe("unsaved address")
expect(elements.configured.textContent).toBe(messages[language].loaded)
expect(elements.result.textContent).toBe(messages[language].invalidUrl)
expect(elements.result.dataset.error).toBe("true")
for (const el of translated) expect(el.textContent).toBe(messages[language][el.dataset.t])
test("remote opt-ins apply consistently across all gateway protocols", async () => {
const fixtures = [
["chat",chat,reply],
["responses",{input:[{role:"user",content:[{type:"input_text",text:"Quartz codename?"}]}]},{status:"completed",output:[{type:"message",role:"assistant",content:[{type:"output_text",text:"answer"}]}]}],
["anthropic",{messages:[{role:"user",content:[{type:"text",text:"Quartz codename?"}]}]},{type:"message",role:"assistant",content:[{type:"text",text:"answer"}],stop_reason:"end_turn"}],
["gemini",{contents:[{role:"user",parts:[{text:"Quartz codename?"}]}]},{candidates:[{content:{role:"model",parts:[{text:"answer"}]},finishReason:"STOP"}]}],
]
for (const origin of ["remote","gateway-key"]) for (const [protocol,input,response] of fixtures) {
reset();calls.length=0;mock()
const [,c]=capturing(protocol,{origin,options:{recallRemote:true,captureRemote:true}})
await onRequest(structuredClone(input),c)
await onResponse(response,{...c,success:true})
expect(of("memories/search")).toHaveLength(1)
expect(of("threads/import")).toHaveLength(1)
}
})
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/gateway-nowledge-mem",
"version": "0.1.4",
"version": "0.1.5",
"description": "Nowledge Mem recall, Context Bundle and optional conversation capture at the Magpie gateway, for every connected harness",
"type": "module",
"files": [
@@ -0,0 +1,64 @@
// This small layout regression runs only with Linux Chrome. It uses a data
// URL, a temporary profile and no network or user browser state.
import { expect, test } from "bun:test"
import { mkdtemp, rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { runInNewContext } from "node:vm"
const chrome = process.platform === "linux" &&
(Bun.which("google-chrome") || Bun.which("google-chrome-stable") || Bun.which("chromium") || Bun.which("chromium-browser"))
test.skipIf(!chrome)("narrow settings footer keeps translated actions inside the dialog", async () => {
const read = (name) => Bun.file(new URL(`./page/${name}`, import.meta.url)).text()
const [html, css, dictionary] = await Promise.all([read("settings.html"), read("style.css"), read("i18n.js")])
const footer = html.match(/<footer>[\s\S]*?<\/footer>/)?.[0]
expect(footer).toBeTruthy()
const { messages } = runInNewContext(`${dictionary}\nnowledgeMemI18n`)
const translations = Object.fromEntries(["en", "zh", "zh-TW", "ja", "de"].map((lang) => [lang, {
saveHelp: messages[lang].saveHelp, cancel: messages[lang].cancel, save: messages[lang].save,
}]))
const script = `
const translations = ${JSON.stringify(translations)};
const footer = ${JSON.stringify(footer)};
const results = [];
for (const language of Object.keys(translations)) for (const width of [320, 380, 900]) for (const theme of ['light', 'dark']) {
const host = document.createElement('div'); host.style.width = width + 'px';
host.style.colorScheme = theme;
if (theme === 'dark') { host.style.setProperty('--magpie-card', '#222'); host.style.setProperty('--magpie-fg', '#eee'); }
host.innerHTML = '<dialog open><form><div class="dialog-body"><small id="key-help">Help</small><div class="field-wrap"><label>Key environment</label></div></div>' + footer + '</form></dialog>';
host.querySelectorAll('[data-t]').forEach((el) => { el.textContent = translations[language][el.dataset.t]; });
document.body.append(host);
const box = host.querySelector('dialog').getBoundingClientRect();
const form = host.querySelector('form').getBoundingClientRect();
const foot = host.querySelector('footer').getBoundingClientRect();
const actions = host.querySelector('.actions').getBoundingClientRect();
const save = host.querySelector('#save').getBoundingClientRect();
const gap = host.querySelector('.field-wrap').getBoundingClientRect().top - host.querySelector('#key-help').getBoundingClientRect().bottom;
const inside = (r, p) => r.left >= p.left - 1 && r.right <= p.right + 1;
results.push({language, width, theme, fits: inside(form, box) && inside(foot, box) && inside(actions, foot) && inside(save, foot), gap});
}
document.getElementById('results').textContent = JSON.stringify(results);
`
const page = `<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'"><style>${css}\ndialog { position: relative; inset: auto; margin: 0; }</style><pre id="results"></pre><script>${script}</script>`
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 id="results">([^<]+)<\/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)
+413
View File
@@ -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(/<script\b([^>]*)>/gi)]
expect(tags).toHaveLength(4)
const sources=tags.map(([,attrs])=>attrs.match(/(?:^|\s)src\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/i)?.slice(1).find((s)=>s !== undefined))
expect(sources.sort())
.toEqual(["_magpie/bridge.js","i18n.js","settings.js","validate.js"])
expect(html).not.toMatch(/<script\b(?![^>]*\bsrc\s*=)[^>]*>/i)
expect(html).not.toMatch(/\b(?:src|href)\s*=\s*(?:["']\s*)?(?:https?:)?\/\//i)
// Prove that each checked source rejects both classes of regression.
for (const [source,calls] of [[settings,allowed],[validator,[]]]) {
expect(pageScriptAllowed(`${source}\nfetch("https://evil.example/x")`,calls)).toBe(false)
expect(pageScriptAllowed(`${source}\nmagpie.read?.("secrets")`,calls)).toBe(false)
expect(pageScriptAllowed(`${source}\nwindow.magpie?.read("secrets")`,calls)).toBe(false)
expect(pageScriptAllowed(`${source}\nmagpie["read"]("secrets")`,calls)).toBe(false)
}
})
async function pageFixture(initial) {
const read = (file) => Bun.file(new URL(`./page/${file}`, import.meta.url)).text()
const [dictionary, validator, source, html] = await Promise.all([read("i18n.js"), read("validate.js"), read("settings.js"), read("settings.html")])
const make = () => ({
dataset: {}, value: "", type: "text", checked: false, children: [], hidden: false,
listeners: {},
setAttribute(name, value) { this[name] = value }, focus() { this.focused = true }, showModal() { this.open = true }, close() { this.open = false; this.onclose?.() },
before(node) { this.beforeNode = node },
addEventListener(type, fn) { (this.listeners[type] ??= []).push(fn) },
dispatchEvent(event) { for (const fn of this.listeners[event.type] ?? []) fn(event) },
append(...xs) { this.children.push(...xs); for (const x of xs) x.parent = this },
replaceChildren(...xs) { this.children = xs }, remove() { if (this.parent) this.parent.children = this.parent.children.filter((x) => x !== this) },
})
const elements = Object.fromEntries([...html.matchAll(/\bid="([^"]+)"/g)].map(([, id]) => [id, make()]))
const labels = Object.fromEntries([...html.matchAll(/<label\b[^>]*\bfor="([^"]+)"/g)].map(([, id]) => [id, make()]))
for (const [id, label] of Object.entries(labels)) if (elements[id]) elements[id].closest = (selector) => selector === 'label' ? label : null
const translated = [...html.matchAll(/data-t="([^"]+)"/g)].map(([, key]) => ({dataset:{t:key}}))
const document = {documentElement:{},getElementById:(id)=>elements[id],createElement:make,
querySelectorAll:(selector)=>selector === "[data-t]" ? translated : Object.values(elements).filter((el)=>el.dataset.message)}
let options = structuredClone(initial), version = 0, repaint, writes = 0
const magpie = {theme:{lang:"en"},ready:Promise.resolve(),onTheme:(fn)=>{repaint=fn},options:{get:async()=>structuredClone(options),set:async(next)=>{options=structuredClone(next);version++;writes++}}}
const location = {href:"http://127.0.0.1:3425/_magpie/plugin/t/page/settings.html",assign(url){this.assigned=url}}
const window = {name:""}
const i18n = runInNewContext(`${dictionary}\n${validator}\n${source}\nnowledgeMemI18n`, {document,magpie,window,location,navigator:{language:"en"},URL})
await new Promise(setImmediate)
return {elements,labels,magpie,i18n,translated,document,location,repaint:()=>repaint(),get:()=>options,writes:()=>writes,
external:(next)=>{options=structuredClone(next);version++},save:()=>elements.save.onclick({preventDefault(){}})}
}
test("default buttons execute their real handlers and clear explicit values", async () => {
const f=await pageFixture({recall:false,requestTimeoutMs:900,skipAgents:["Mozilla"],apiKey:"saved",future:{v:1}}),e=f.elements
await e.configure.onclick()
expect(f.labels.space.parent.children.find((child)=>child.className === "option-reset").hidden).toBe(true)
for (const id of ["recall","request-timeout","skip-agents"]) {
const reset=f.labels[id].parent.children.find((child)=>child.className === "option-reset")
expect(typeof reset?.onclick).toBe("function")
expect(reset.hidden).toBe(false)
expect(reset["aria-label"]).toContain(f.i18n.messages.en.useDefault)
reset.onclick()
expect(reset.hidden).toBe(true)
expect(e[id].focused).toBe(true)
}
expect(e.recall.checked).toBe(true)
expect(e["request-timeout"].value).toBe("")
expect(e["skip-agents"].value).toBe("")
await f.save()
expect(f.get()).toEqual({apiKey:"saved",future:{v:1}})
// Typing after a reset cancels inheritance and saves an explicit value.
const reset=f.labels.recall.parent.children.find((child)=>child.className === "option-reset")
reset.onclick();e.recall.checked=false;e.recall.dispatchEvent({type:"change"})
await f.save();expect(f.get().recall).toBe(false)
})
test("an explicit value equal to its default can still return to inheritance", async () => {
const f=await pageFixture({recall:true}),e=f.elements
await e.configure.onclick()
const reset=f.labels.recall.parent.children.find((child)=>child.className === "option-reset")
expect(reset.hidden).toBe(false)
reset.onclick();await f.save()
expect(Object.hasOwn(f.get(),"recall")).toBe(false)
})
test("skipAgents retains existing formats, edits names, and updates the summary", async () => {
for (const original of [["Mozilla", "Claude Code"], "Mozilla,Claude Code"]) {
const f=await pageFixture({skipAgents:original,apiKey:"saved"}),e=f.elements
expect(e["summary-skip"].textContent).toBe("Mozilla, Claude Code")
await e.configure.onclick()
expect(e["skip-agents"].value).toBe("Mozilla, Claude Code")
e.space.value="space-a";await f.save()
expect(f.get().skipAgents).toEqual(original)
e["skip-agents"].value="Mozilla,, Codex,";await f.save()
expect(f.get().skipAgents).toEqual(["Mozilla","Codex"])
expect(e["summary-skip"].textContent).toBe("Mozilla, Codex")
e["skip-agents"].value=" , ";await f.save()
expect(f.get().skipAgents).toBeUndefined()
expect(e["summary-skip"].textContent).toBe("None")
}
})
test("a skipped app saved by the page reaches the hook without Mem requests", async () => {
const f=await pageFixture({capture:true}),e=f.elements
await e.configure.onclick();e["skip-agents"].value="Mozilla, Claude Code";await f.save()
const previousFetch=globalThis.fetch, calls=[]
globalThis.fetch=async (...args)=>{calls.push(args);return Response.json([])}
try {
reset()
const state={}, body={messages:[{role:"user",content:"hello"}]}
const context={protocol:"chat",origin:"local",agent:"claude-code",query:"hello",session:"s",options:f.get(),state,signal:new AbortController().signal}
await onRequest(body,context)
await onResponse({choices:[{message:{role:"assistant",content:"answer"},finish_reason:"stop"}]},{...context,success:true})
expect(calls).toHaveLength(0)
expect(state.nowledgeMem).toBeUndefined()
expect(body.messages[0].content).toBe("hello")
} finally { globalThis.fetch=previousFetch;reset() }
})
test("released hosts save only edited fields using a fresh read and retain secrets", async () => {
const f=await pageFixture({serverUrl:"http://127.0.0.1:14242",apiKey:"saved_secret",custom:{a:1}}), e=f.elements
expect(e.configure.disabled).toBe(false)
expect(e.configured.dataset.message).toBe("loaded")
await e.configure.onclick()
expect(e.save.disabled).toBe(false)
e.space.value="space-2"
f.external({serverUrl:"http://127.0.0.1:14242",apiKey:"new_secret",custom:{a:2},future:true})
await f.save()
expect(f.get()).toEqual({serverUrl:"http://127.0.0.1:14242",apiKey:"new_secret",custom:{a:2},future:true,spaceId:"space-2"})
expect(f.writes()).toBe(1)
})
test("connection status stays separate from the concurrency notice", async () => {
const html=await Bun.file(new URL("./page/settings.html",import.meta.url)).text()
const noticePos=html.indexOf('data-t="concurrencyHelp"')
expect(noticePos).toBeGreaterThan(html.indexOf('class="dialog-body"'))
expect(noticePos).toBeLessThan(html.indexOf('</div><footer>'))
for (const [options,status] of [[{},"notConfigured"],[{serverUrl:"https://mem.example"},"loaded"]]) {
const f=await pageFixture(options), e=f.elements
expect(e.configured.dataset.message).toBe(status)
await e.configure.onclick()
expect(e.configured.dataset.message).toBe(status)
const notice=f.translated.find((el)=>el.dataset.t === "concurrencyHelp")
expect(notice.textContent).toBe(f.i18n.messages.en.concurrencyHelp)
expect(notice.textContent).toMatch(/another editor saving at the same moment can still overwrite/)
}
})
test("secret controls keep, replace and clear the saved value", async () => {
const f=await pageFixture({apiKey:"saved_secret",apiKeyEnv:"NMEM_API_KEY",future:{x:1}}),e=f.elements
await e.configure.onclick()
expect(e.key.value).toBe("")
expect(e.key.placeholder).toBe("Saved")
expect(e["key-clear"].hidden).toBe(false)
e["key-clear"].onclick();expect(e["key-clear"]["aria-pressed"]).toBe("true")
expect(e["key-clear"].textContent).toBe("Undo removal")
e["key-clear"].onclick();expect(e["key-clear"]["aria-pressed"]).toBe("false")
e.space.value="space-7";await f.save()
expect(f.get().apiKey).toBe("saved_secret")
e.key.value="Bearer new_secret";e.key.oninput();await f.save()
expect(f.get().apiKey).toBe("new_secret")
e["key-clear"].onclick();await f.save()
expect(f.get().apiKey).toBeUndefined()
expect(f.get().apiKeyEnv).toBe("NMEM_API_KEY")
expect(f.get().future).toEqual({x:1})
expect(e["key-clear"].hidden).toBe(true)
expect(e.key.placeholder).toBe("No saved key")
})
test("clearing a key detects a concurrent replacement and keeps the draft", async () => {
const f=await pageFixture({apiKey:"saved_secret"}),e=f.elements
await e.configure.onclick();e["key-clear"].onclick()
f.external({apiKey:"changed_elsewhere"});await f.save()
expect(e.result.dataset.message).toBe("conflict")
expect(e["key-clear"]["aria-pressed"]).toBe("true")
expect(f.get().apiKey).toBe("changed_elsewhere")
expect(f.writes()).toBe(0)
})
test("human-dialogue switch preserves filter semantics and controls Cindy", async () => {
const f=await pageFixture({captureFilter:"human",captureCindy:true}),e=f.elements
await e.configure.onclick()
expect(e["capture-filter"].checked).toBe(true)
expect(e["capture-cindy"].disabled).toBe(false)
expect(e["capture-tools"].disabled).toBe(true)
e["capture-filter"].checked=false;e["capture-filter"].onchange();e["capture-filter"].dispatchEvent({type:"change"})
expect(e["capture-cindy"].disabled).toBe(true)
expect(e["capture-tools"].disabled).toBe(false)
await f.save();expect(f.get().captureFilter).toBe("off");expect(f.get().captureCindy).toBe(true)
e["capture-filter"].checked=true;e["capture-filter"].onchange();e["capture-filter"].dispatchEvent({type:"change"})
expect(e["capture-cindy"].disabled).toBe(false)
expect(e["capture-tools"].disabled).toBe(true)
await f.save();expect(f.get().captureFilter).toBe("human")
})
test("remote recall and capture are independent and gated by their global switches", async () => {
const f=await pageFixture({apiKey:"saved",future:{keep:true}}),e=f.elements
await e.configure.onclick()
expect(e["recall-remote"].checked).toBe(false)
expect(e["capture-remote"].checked).toBe(false)
expect(e["recall-remote"].disabled).toBe(false)
expect(e["capture-remote"].disabled).toBe(true)
e["recall-remote"].checked=true;e["recall-remote"].dispatchEvent({type:"change"})
await f.save()
expect(f.get()).toEqual({apiKey:"saved",future:{keep:true},recallRemote:true})
e.capture.checked=true;e.capture.onchange();e.capture.dispatchEvent({type:"change"})
expect(e["capture-remote"].disabled).toBe(false)
e["capture-remote"].checked=true;e["capture-remote"].dispatchEvent({type:"change"})
await f.save()
expect(f.get().captureRemote).toBe(true)
expect(f.get().recallRemote).toBe(true)
e.recall.checked=false;e.recall.onchange();e.recall.dispatchEvent({type:"change"})
expect(e["recall-remote"].disabled).toBe(true)
await f.save()
expect(f.get().recall).toBe(false)
expect(f.get().recallRemote).toBe(true)
expect(f.get().captureRemote).toBe(true)
})
test("a saved remote grant stays visible while its global switch is off", async () => {
const f=await pageFixture({capture:false,captureRemote:true}),e=f.elements
await e.configure.onclick()
expect(e["capture-remote"].checked).toBe(true)
expect(e["capture-remote"].disabled).toBe(true)
e.capture.checked=true;e.capture.onchange();e.capture.dispatchEvent({type:"change"})
expect(e["capture-remote"].disabled).toBe(false)
expect(e["capture-remote"].checked).toBe(true)
await f.save()
expect(f.get().captureRemote).toBe(true)
})
test("enabling a global gate conflicts if its remote grant changed elsewhere", async () => {
for (const [field,remote] of [["recall","recallRemote"],["capture","captureRemote"]]) {
const f=await pageFixture({[field]:false,[remote]:false}),e=f.elements
await e.configure.onclick()
e[field].checked=true;e[field].onchange();e[field].dispatchEvent({type:"change"})
f.external({[field]:false,[remote]:true});await f.save()
expect(e.result.dataset.message).toBe("conflict")
expect(e[field].checked).toBe(true)
expect(f.get()[field]).toBe(false)
expect(f.writes()).toBe(0)
}
})
test("remote scope disclosure and exposure warnings exist in every language", async () => {
const f=await pageFixture({})
for (const language of ["en","zh","zh-TW","ja","de"]) {
const m=f.i18n.messages[language]
expect(m.scopeDisclosure).toContain("recallRemote")
expect(m.scopeDisclosure).toContain("captureRemote")
expect(m.recallRemoteHelp).toContain("Context Bundle")
expect(m.captureRemoteHelp.length).toBeGreaterThan(10)
}
})
test("non-local HTTP requires the explicit exception for saving and testing", async () => {
const f=await pageFixture({future:{keep:true},apiKey:"saved"}),e=f.elements
await e.configure.onclick();e.url.value="http://mem.tailnet.invalid:14242"
await f.save();expect(e.result.dataset.message).toBe("invalidUrl");expect(f.writes()).toBe(0)
e.insecure.checked=true;e.insecure.dispatchEvent({type:"change"});await f.save()
expect(f.get()).toEqual({future:{keep:true},apiKey:"saved",serverUrl:"http://mem.tailnet.invalid:14242",allowInsecureHttp:true})
e["test-saved"].onclick();expect(f.location.assigned).toBe("http://127.0.0.1:3479/test?lang=en")
e.insecure.checked=false;e.insecure.dispatchEvent({type:"change"});await f.save()
expect(e.result.dataset.message).toBe("invalidUrl")
expect(f.get().allowInsecureHttp).toBe(true)
e.url.value="https://mem.example";await f.save()
expect(f.get().allowInsecureHttp).toBe(false)
const invalid=await pageFixture({serverUrl:"http://mem.tailnet.invalid:14242"})
invalid.elements["test-saved"].onclick()
expect(invalid.location.assigned).toBeUndefined()
expect(invalid.elements.configured.dataset.message).toBe("invalidUrl")
})
test("enabling HTTP exception conflicts if the saved endpoint changed elsewhere", async () => {
const f=await pageFixture({serverUrl:"https://mem.example",apiKey:"saved"}),e=f.elements
await e.configure.onclick();e.insecure.checked=true;e.insecure.dispatchEvent({type:"change"})
f.external({serverUrl:"http://other.invalid",apiKey:"saved"});await f.save()
expect(e.result.dataset.message).toBe("conflict")
expect(f.get()).toEqual({serverUrl:"http://other.invalid",apiKey:"saved"})
expect(f.writes()).toBe(0)
})
test("settings avoid native selects and associate help with controls", async () => {
const html=await Bun.file(new URL("./page/settings.html",import.meta.url)).text()
expect(html).not.toMatch(/<select\b/i)
const legends=[...html.matchAll(/<legend>(.*?)<\/legend>/gs)]
expect(legends).toHaveLength(5)
for (const [,legend] of legends) expect(legend).toContain('<svg')
for (const [,references] of html.matchAll(/\baria-describedby="([^"]+)"/g))
for (const id of references.split(/\s+/)) expect(html).toContain(`id="${id}"`)
for (const id of ["host-agent","key-env","recall","recall-remote","context","capture","capture-remote","capture-tools","capture-filter","capture-cindy","max-memories","max-bytes","request-timeout","recall-backoff","gateway-timeout","port","insecure"])
expect(html).toMatch(new RegExp(`<input id="${id}"[^>]*aria-describedby="[^"]+"`))
})
test("key visibility resets on close while its draft remains", async () => {
const f=await pageFixture({}),e=f.elements
const html=await Bun.file(new URL("./page/settings.html",import.meta.url)).text()
expect(html).toMatch(/<svg class="eye-show"/)
expect(html).toMatch(/<svg class="eye-hide"/)
expect(html).toContain('aria-describedby="key-storage key-help"')
expect(html).toContain('data-t="keyHelp"')
await e.configure.onclick();e.key.value="synthetic_secret";e.key.oninput()
e["show-key"].onclick()
expect(e.key.type).toBe("text")
expect(e["show-key"]["aria-pressed"]).toBe("true")
e.close.onclick()
expect(e.key.type).toBe("password")
expect(e["show-key"]["aria-pressed"]).toBe("false")
await e.configure.onclick()
expect(e.key.type).toBe("password")
expect(e.key.value).toBe("synthetic_secret")
})
test("test connection opens the saved local service and language", async () => {
const f=await pageFixture({}),e=f.elements
e["test-saved"].onclick()
expect(f.location.assigned).toBe("http://127.0.0.1:3479/test?lang=en")
})
test("invalid connection values do not write and closing keeps an unsaved draft", async () => {
const f=await pageFixture({},true),e=f.elements
await e.configure.onclick();e.url.value="http://remote.example"
await f.save();expect(e.result.dataset.message).toBe("invalidUrl");expect(f.writes()).toBe(0)
e.close.onclick();await e.configure.onclick()
expect(e.url.value).toBe("http://remote.example")
e.url.value="https://mem.example";e.key.value="bad key";e.key.oninput()
await f.save();expect(e.result.dataset.message).toBe("invalidKey");expect(f.writes()).toBe(0)
})
test("settings saved through the released bridge reach the hook", async () => {
const f=await pageFixture({}),e=f.elements
await e.configure.onclick()
e.url.value="https://mem.example";e.space.value="space-7"
e.key.value="synthetic_key";e.key.oninput()
await f.save()
const originalFetch=globalThis.fetch, calls=[]
globalThis.fetch=async (url,init)=>{calls.push({url:String(url),init});return Response.json([])}
try {
reset()
await onRequest({messages:[{role:"user",content:"hello"}]},{protocol:"chat",origin:"local",query:"hello",session:"session",options:f.get(),state:{},signal:new AbortController().signal})
expect(calls[0].url).toBe("https://mem.example/memories/search")
expect(calls[0].init.headers.Authorization).toBe("Bearer synthetic_key")
expect(JSON.parse(calls[0].init.body).space_id).toBe("space-7")
} finally { globalThis.fetch=originalFetch;reset() }
})
test("released hosts keep the draft when a changed field was edited elsewhere", async () => {
const f=await pageFixture({spaceId:"original"}),e=f.elements
await e.configure.onclick();e.space.value="draft"
f.external({spaceId:"other"});await f.save()
expect(e.result.dataset.message).toBe("conflict")
expect(e.space.value).toBe("draft")
expect(f.get().spaceId).toBe("other")
expect(f.writes()).toBe(0)
expect(e.result.textContent).toContain("select Cancel, then reopen")
e.close.onclick();await e.configure.onclick();expect(e.space.value).toBe("draft")
e.cancel.onclick();await e.configure.onclick();expect(e.space.value).toBe("other")
})
test("summary capture switch saves on released hosts", async () => {
{
const f=await pageFixture({capture:false,custom:{keep:true}}),e=f.elements
expect(e["summary-capture"].disabled).toBe(false)
f.external({capture:false,custom:{keep:"updated"}})
e["summary-capture"].checked=true;await e["summary-capture"].onchange()
expect(f.get()).toEqual({capture:true,custom:{keep:"updated"}})
expect(e["capture-feedback"].dataset.message).toBe("captureEnabled")
expect(e["summary-capture"].disabled).toBe(false)
}
})
test("configuration page follows host language without losing edits", async () => {
const f=await pageFixture({serverUrl:"http://127.0.0.1:14242"}),e=f.elements
const dictionary=await Bun.file(new URL("./page/i18n.js",import.meta.url)).text()
expect(dictionary).not.toMatch(/Object\.entries\(messages\.en\).*messages\[language\]\[key\]/)
await e.configure.onclick();e.url.value="unsaved address"
await f.save();expect(e.result.dataset.message).toBe("invalidUrl")
const {messages,languageFor,languageTags}=f.i18n
for (const language of ["en","zh","zh-TW","ja","de"]) {
expect(Object.keys(messages[language]).sort()).toEqual(Object.keys(messages.en).sort())
expect(Object.values(messages[language]).every((value)=>typeof value === "string" && value.length > 0)).toBe(true)
f.magpie.theme.lang=language;f.repaint()
expect(f.document.documentElement.lang).toBe(languageTags[language])
expect(e.url.value).toBe("unsaved address")
expect(e.result.textContent).toBe(messages[language].invalidUrl)
for (const el of f.translated) expect(el.textContent).toBe(messages[language][el.dataset.t])
}
expect(languageFor("zh-Hant-TW")).toBe("zh-TW")
})
+71 -30
View File
@@ -14,15 +14,12 @@ const messages = {
"dialogTitle": "Connection settings",
"settingsIntro": "Connect Magpie to your Nowledge Mem.",
"serviceSection": "Mem service",
"urlHelp": "Local HTTP or remote HTTPS; HTTP to another machine needs the switch below. No credentials in the URL.",
"insecureHttp": "Allow HTTP to another machine",
"insecureHttpHelp": "Only on a network you trust, e.g. Tailscale. Elsewhere your conversations and API key would cross the network unencrypted.",
"urlHelp": "Local HTTP or remote HTTPS without credentials in the URL. Remote HTTP requires the advanced exception. Empty uses NMEM_API_URL or the local default.",
"spaceHelp": "Optional. Leave empty for the default Space.",
"agentHelp": "Optional. Selects the Mem agent profile used for the Context Bundle.",
"authSection": "Authentication",
"key": "API key",
"keyHelp": "Leave empty when your Mem does not require a key. Saved in Magpie’s local plugin configuration.",
"keyFallback": "With this field empty, Magpie reads the variable named in apiKeyEnv (NMEM_API_KEY by default); only NMEM_* names are accepted.",
"keyHelp": "Saved in Magpie’s local plugin configuration.",
"behaviorSection": "What Magpie sends",
"recallHelp": "Search Mem with the latest user turn and add what it recalls to the request.",
"skipAgents": "Apps without memory",
@@ -53,7 +50,7 @@ const messages = {
"notConfigured": "Not configured",
"loadFailed": "Could not load configuration. Reopen this page to retry.",
"bridgeFailed": "Magpie configuration bridge unavailable.",
"invalidUrl": "Use local HTTP or remote HTTPS (HTTP too with “Allow HTTP to another machine” on), without credentials, query or fragment.",
"invalidUrl": "Use HTTP(S) without credentials, query or fragment. Non-local HTTP requires the advanced exception.",
"invalidKey": "Enter an API key without spaces or line breaks.",
"configurationSaved": "Configuration saved",
"saveSucceeded": "Saved. Connectivity has not been checked and no conversation was written.",
@@ -75,15 +72,12 @@ const messages = {
"dialogTitle": "连接设置",
"settingsIntro": "把 Magpie 连接到你的 Nowledge Mem。",
"serviceSection": "Mem 服务",
"urlHelp": "本机用 HTTP,远端用 HTTPS;远端用 HTTP 需打开下方开关。地址里不要带凭据。",
"insecureHttp": "允许用 HTTP 连接另一台机器",
"insecureHttpHelp": "仅在你信任的网络中开启,例如 Tailscale。在其他网络中,你的对话和 API 密钥会以明文经过网络。",
"urlHelp": "本机 HTTP 或远程 HTTPS,URL 不得包含凭据。远程 HTTP 需要开启高级设置中的例外。留空使用 NMEM_API_URL 或本机默认地址。",
"spaceHelp": "可选。留空使用默认 Space。",
"agentHelp": "可选。选择 Context Bundle 使用的 Mem agent 档案。",
"authSection": "认证",
"key": "API 密钥",
"keyHelp": "Mem 不要求密钥时留空。保存在 Magpie 的本地插件配置中。",
"keyFallback": "此字段留空时,Magpie 读取 apiKeyEnv 指定的变量(默认 NMEM_API_KEY);只接受 NMEM_* 名称。",
"keyHelp": "保存在 Magpie 的本地插件配置中。",
"behaviorSection": "Magpie 会发送什么",
"recallHelp": "用最新一条用户消息搜索 Mem,并把召回内容加入请求。",
"skipAgents": "不用记忆的应用",
@@ -114,7 +108,7 @@ const messages = {
"notConfigured": "尚未配置",
"loadFailed": "无法读取配置。请重新打开此页面重试。",
"bridgeFailed": "Magpie 配置桥不可用。",
"invalidUrl": "请使用本机 HTTP 或远端 HTTPS(打开“允许用 HTTP 连接另一台机器”后也可用 HTTP),且不含凭据、查询参数或片段。",
"invalidUrl": "请使用不含凭据、查询参数或片段的 HTTP(S) 地址;非本机 HTTP 需要开启高级设置中的例外。",
"invalidKey": "请输入不含空格或换行的 API 密钥。",
"configurationSaved": "配置已保存",
"saveSucceeded": "已保存。未检测连通性,也没有写入对话。",
@@ -136,15 +130,12 @@ const messages = {
"dialogTitle": "連線設定",
"settingsIntro": "把 Magpie 連接到你的 Nowledge Mem。",
"serviceSection": "Mem 服務",
"urlHelp": "本機用 HTTP,遠端用 HTTPS;遠端用 HTTP 需開啟下方開關。位址裡不要帶憑證。",
"insecureHttp": "允許用 HTTP 連線到另一台機器",
"insecureHttpHelp": "僅在你信任的網路中開啟,例如 Tailscale。在其他網路中,你的對話和 API 金鑰會以明文經過網路。",
"urlHelp": "本機 HTTP 或遠端 HTTPS,網址不得包含憑據。遠端 HTTP 需要開啟進階設定中的例外。留空使用 NMEM_API_URL 或本機預設位址。",
"spaceHelp": "選填。留空使用預設 Space。",
"agentHelp": "選填。選擇 Context Bundle 使用的 Mem agent 設定檔。",
"authSection": "驗證",
"key": "API 金鑰",
"keyHelp": "Mem 不要求金鑰時留空。儲存在 Magpie 的本機外掛設定中。",
"keyFallback": "此欄位留空時,Magpie 讀取 apiKeyEnv 指定的變數(預設為 NMEM_API_KEY);只接受 NMEM_* 名稱。",
"keyHelp": "儲存在 Magpie 的本機外掛設定中。",
"behaviorSection": "Magpie 會傳送什麼",
"recallHelp": "用最新一則使用者訊息搜尋 Mem,並把召回內容加入請求。",
"skipAgents": "不用記憶的應用程式",
@@ -175,7 +166,7 @@ const messages = {
"notConfigured": "尚未設定",
"loadFailed": "無法讀取設定。請重新開啟此頁面重試。",
"bridgeFailed": "Magpie 設定橋不可用。",
"invalidUrl": "請使用本機 HTTP 或遠端 HTTPS(開啟「允許用 HTTP 連線到另一台機器」後也可用 HTTP),且不含憑證、查詢參數或片段。",
"invalidUrl": "請使用不含憑據、查詢參數或片段的 HTTP(S) 位址;非本機 HTTP 需要開啟進階設定中的例外。",
"invalidKey": "請輸入不含空格或換行的 API 金鑰。",
"configurationSaved": "設定已儲存",
"saveSucceeded": "已儲存。未偵測連線,也沒有寫入對話。",
@@ -197,15 +188,12 @@ const messages = {
"dialogTitle": "接続設定",
"settingsIntro": "Magpie を Nowledge Mem に接続します。",
"serviceSection": "Mem サービス",
"urlHelp": "ローカルは HTTP、リモートは HTTPS。リモートに HTTP を使うには下のスイッチを有効にします。URL に認証情報を含めないでください。",
"insecureHttp": "別のコンピューターへの HTTP を許可",
"insecureHttpHelp": "信頼できるネットワーク(Tailscale など)でのみ有効にしてください。それ以外では、会話と API キーが暗号化されずにネットワークを通ります。",
"urlHelp": "ローカル HTTP またはリモート HTTPS。URL に認証情報は含められません。リモート HTTP は詳細設定での許可が必要です。空欄では NMEM_API_URL またはローカル既定値を使います。",
"spaceHelp": "任意。空欄なら既定の Space を使います。",
"agentHelp": "任意。Context Bundle に使う Mem の agent プロファイルを選びます。",
"authSection": "認証",
"key": "API キー",
"keyHelp": "Mem がキーを要求しない場合は空欄。Magpie のローカルなプラグイン設定に保存されます。",
"keyFallback": "空欄の場合、Magpie は apiKeyEnv の変数(既定は NMEM_API_KEY)を読みます。NMEM_* の名前だけを受け付けます。",
"keyHelp": "Magpie のローカルプラグイン設定に保存されます。",
"behaviorSection": "Magpie が送るもの",
"recallHelp": "最新のユーザーの発話で Mem を検索し、呼び出した内容をリクエストに加えます。",
"skipAgents": "メモリを使わないアプリ",
@@ -236,7 +224,7 @@ const messages = {
"notConfigured": "未設定",
"loadFailed": "設定を読み込めませんでした。このページを開き直してください。",
"bridgeFailed": "Magpie の設定ブリッジを利用できません。",
"invalidUrl": "ローカル HTTP またはリモート HTTPS(「別のコンピューターへの HTTP を許可」が有効なら HTTP も可)を、認証情報・クエリ・フラグメントなしで指定してください。",
"invalidUrl": "認証情報・クエリ・フラグメントのない HTTP(S) を指定してください。ローカル以外の HTTP は詳細設定での許可が必要です。",
"invalidKey": "空白や改行を含まない API キーを入力してください。",
"configurationSaved": "設定を保存しました",
"saveSucceeded": "保存しました。接続確認はしておらず、会話も書き込んでいません。",
@@ -258,15 +246,12 @@ const messages = {
"dialogTitle": "Verbindungseinstellungen",
"settingsIntro": "Verbinde Magpie mit deiner Nowledge Mem.",
"serviceSection": "Mem-Dienst",
"urlHelp": "Lokales HTTP oder entferntes HTTPS; HTTP zu einem anderen Computer braucht den Schalter unten. Keine Zugangsdaten in der URL.",
"insecureHttp": "HTTP zu einem anderen Computer erlauben",
"insecureHttpHelp": "Nur in einem Netz, dem du vertraust, z. B. Tailscale. Anderswo gingen deine Gespräche und dein API-Schlüssel unverschlüsselt durchs Netz.",
"urlHelp": "Lokales HTTP oder entferntes HTTPS ohne Zugangsdaten in der URL. Entferntes HTTP benötigt die Ausnahme unter Erweitert. Leer verwendet NMEM_API_URL oder den lokalen Standard.",
"spaceHelp": "Optional. Leer lassen für den Standard-Space.",
"agentHelp": "Optional. Wählt das Mem-Agent-Profil für das Context Bundle.",
"authSection": "Authentifizierung",
"key": "API-Schlüssel",
"keyHelp": "Leer lassen, wenn Mem keinen Schlüssel verlangt. Wird in Magpies lokaler Plugin-Konfiguration gespeichert.",
"keyFallback": "Bei leerem Feld liest Magpie die in apiKeyEnv genannte Variable (standardmäßig NMEM_API_KEY); nur NMEM_*-Namen werden akzeptiert.",
"keyHelp": "In Magpies lokaler Plugin-Konfiguration gespeichert.",
"behaviorSection": "Was Magpie sendet",
"recallHelp": "Mem mit dem letzten Benutzerbeitrag durchsuchen und das Gefundene an die Anfrage anhängen.",
"skipAgents": "Apps ohne Gedächtnis",
@@ -297,7 +282,7 @@ const messages = {
"notConfigured": "Nicht konfiguriert",
"loadFailed": "Konfiguration konnte nicht geladen werden. Seite zum Wiederholen neu öffnen.",
"bridgeFailed": "Magpies Konfigurationsschnittstelle ist nicht verfügbar.",
"invalidUrl": "Lokales HTTP oder entferntes HTTPS (HTTP auch, wenn „HTTP zu einem anderen Computer erlauben“ an ist) ohne Zugangsdaten, Abfrage oder Fragment verwenden.",
"invalidUrl": "HTTP(S) ohne Zugangsdaten, Abfrage oder Fragment verwenden. Nichtlokales HTTP benötigt die Ausnahme unter Erweitert.",
"invalidKey": "API-Schlüssel ohne Leerzeichen oder Zeilenumbrüche eingeben.",
"configurationSaved": "Konfiguration gespeichert",
"saveSucceeded": "Gespeichert. Die Verbindung wurde nicht geprüft und kein Gespräch geschrieben.",
@@ -309,6 +294,62 @@ const messages = {
}
};
// Additional settings; missing translations fall back to English without changing locale selection.
Object.assign(messages.en, {
concurrencyHelp:"Saving merges your edits into the latest settings, but another editor saving at the same moment can still overwrite them. Use one editor at a time. Very large integers in options may be rounded.",
configure: "Settings", dialogTitle: "Nowledge Mem settings", settingsIntro: "Configure connection, recall and saving.", saveHelp: "Unchanged and unlisted options are preserved.", notConfigured: "Using the environment or local default · not tested yet",
useDefault: "Use default / inherit",
hostAgent: "Host agent ID", hostAgentHelp: "Empty derives an identity from the harness.",
keyActionHelp: "Clearing the saved value falls back to the environment variable; it does not disable it.",
keyEnv: "API key environment variable", keyEnvHelp: "Only NMEM_* names are accepted. Empty uses NMEM_API_KEY.",
filterSection: "Saving and filtering", captureTools: "Include client tool results", captureCindy: "Clean recognized Cindy wrappers in human mode",
advanced: "Advanced", maxMemories: "Maximum memories (1–20)", maxBytes: "Recall bytes (512–32768)", requestTimeout: "Request timeout ms (50–5000)", recallBackoff: "Recall backoff ms (100–300000)", gatewayTimeout: "Host hook timeout ms (100–10000)", port: "Connection-test port (1024–65535)", insecure: "Allow HTTP to a non-local server (credentials travel unencrypted)", defaultsHelp: "Empty fields inherit the environment where supported, otherwise use the shown default. Unchanged values remain as configured. The host timeout can end a request first.",
conflict:"Configuration changed elsewhere. Your draft is kept; select Cancel, then reopen Settings to load the latest values.", invalidOption: "Check the highlighted values and ranges.",
});
Object.assign(messages.zh, {
concurrencyHelp:"保存时会将你的修改合并到最新设置,但其他编辑入口同时保存仍可能覆盖更改。请一次只使用一个编辑入口。选项中的超大整数可能被舍入。",
configure: "设置", dialogTitle: "Nowledge Mem 设置", settingsIntro: "配置连接、召回与保存。", saveHelp: "未修改及未列出的选项会保留。", notConfigured: "使用环境变量或本机默认值 · 尚未测试",
useDefault: "恢复默认 / 继承",
hostAgent: "宿主 Agent ID", hostAgentHelp: "留空时从客户端类型推导。", keyActionHelp: "清除保存值后仍会继承环境变量,不会禁用环境变量。", keyEnv: "API 密钥环境变量", keyEnvHelp: "仅接受 NMEM_* 名称;留空使用 NMEM_API_KEY。",
filterSection: "保存与过滤", captureTools: "包含客户端工具结果", captureCindy: "在人类对话模式清理已识别的 Cindy 包装",
advanced: "高级设置", maxMemories: "最多召回记忆数(1–20)", maxBytes: "召回字节数(512–32768)", requestTimeout: "请求超时毫秒(50–5000)", recallBackoff: "召回退避毫秒(100–300000)", gatewayTimeout: "宿主 hook 超时毫秒(100–10000)", port: "连接测试端口(1024–65535)", insecure: "允许非本机 HTTP(凭据将明文传输)", defaultsHelp: "留空时,支持环境继承的选项使用环境值,其余使用显示的默认值。未修改的值保持原样;宿主超时可能更早结束请求。",
conflict:"配置已在其他位置更改,草稿已保留。请选择“取消”,再重新打开设置以加载最新值。", invalidOption: "请检查输入及允许范围。",
});
Object.assign(messages["zh-TW"], {
concurrencyHelp:"儲存時會將你的修改合併至最新設定,但其他編輯入口同時儲存仍可能覆蓋變更。請一次只使用一個編輯入口。選項中的超大整數可能被捨入。",
configure:"設定", dialogTitle:"Nowledge Mem 設定", settingsIntro:"設定連線、召回與儲存。", saveHelp:"未修改及未列出的選項會保留。", notConfigured:"使用環境變數或本機預設值 · 尚未測試",
useDefault:"恢復預設 / 繼承",
hostAgent:"宿主 Agent ID", hostAgentHelp:"留空時從用戶端類型推導。", keyActionHelp:"清除儲存值後仍會繼承環境變數,不會停用環境變數。", keyEnv:"API 金鑰環境變數", keyEnvHelp:"僅接受 NMEM_* 名稱;留空使用 NMEM_API_KEY。",
filterSection:"儲存與過濾", captureTools:"包含用戶端工具結果", captureCindy:"在人類對話模式清理已識別的 Cindy 包裝",
advanced:"進階設定", maxMemories:"最多召回記憶數(1–20)", maxBytes:"召回位元組數(512–32768)", requestTimeout:"請求逾時毫秒(50–5000)", recallBackoff:"召回退避毫秒(100–300000)", gatewayTimeout:"宿主 hook 逾時毫秒(100–10000)", port:"連線測試埠(1024–65535)", insecure:"允許非本機 HTTP(憑據將明文傳輸)", defaultsHelp:"留空時,支援環境繼承的選項使用環境值,其餘使用顯示的預設值。未修改的值保持原樣;宿主逾時可能更早結束請求。", conflict:"設定已在其他位置更改,草稿已保留。請選擇「取消」,再重新開啟設定以載入最新值。", invalidOption:"請檢查輸入及允許範圍。",
});
Object.assign(messages.ja, {
concurrencyHelp:"保存時に変更を最新の設定に反映しますが、別の編集画面が同時に保存すると上書きされる可能性があります。一度に一つの編集画面を使ってください。非常に大きい整数は丸められる場合があります。",
configure:"設定", dialogTitle:"Nowledge Mem の設定", settingsIntro:"接続、検索と保存を設定します。", saveHelp:"変更していない項目と一覧にない項目は保持されます。", notConfigured:"環境変数またはローカルの既定値を使用 · 未テスト",
useDefault:"既定値 / 継承に戻す", hostAgent:"ホスト Agent ID", hostAgentHelp:"空欄の場合はハーネスから導出します。", keyActionHelp:"保存値を消すと環境変数にフォールバックします。環境変数は無効になりません。", keyEnv:"API キーの環境変数", keyEnvHelp:"NMEM_* のみ。空欄では NMEM_API_KEY を使用します。",
filterSection:"保存とフィルター", captureTools:"クライアントのツール結果を含める", captureCindy:"人間の会話モードで既知の Cindy 包装を整理", advanced:"詳細設定", maxMemories:"記憶の最大数(1–20)", maxBytes:"検索のバイト数(512–32768)", requestTimeout:"リクエスト時間制限 ms(50–5000)", recallBackoff:"検索の再試行待ち ms(100–300000)", gatewayTimeout:"ホスト hook の時間制限 ms(100–10000)", port:"接続テストのポート(1024–65535)", insecure:"ローカル以外の HTTP を許可(認証情報は平文で送信)", defaultsHelp:"空欄は対応する環境変数、それ以外は表示された既定値を使用します。未変更の値は保持されます。ホストの時間制限が先に切れる場合があります。", conflict:"設定が別の場所で変更されました。下書きは保持されています。「キャンセル」を選び、設定を開き直してください。", invalidOption:"入力と範囲を確認してください。",
});
Object.assign(messages.de, {
concurrencyHelp:"Beim Speichern werden deine Änderungen in die aktuellen Einstellungen übernommen; ein anderer gleichzeitig speichernder Editor kann sie dennoch überschreiben. Bitte nur einen Editor zugleich verwenden. Sehr große Ganzzahlen können gerundet werden.",
configure:"Einstellungen", dialogTitle:"Nowledge Mem Einstellungen", settingsIntro:"Verbindung, Abruf und Speichern konfigurieren.", saveHelp:"Unveränderte und nicht aufgeführte Optionen bleiben erhalten.", notConfigured:"Umgebung oder lokaler Standard · noch nicht getestet",
useDefault:"Standard / Erben", hostAgent:"Host-Agent-ID", hostAgentHelp:"Leer leitet die Identität aus dem Harness ab.", keyActionHelp:"Nach dem Löschen gilt weiterhin die Umgebungsvariable; sie wird nicht deaktiviert.", keyEnv:"Umgebungsvariable für API-Schlüssel", keyEnvHelp:"Nur NMEM_*; leer verwendet NMEM_API_KEY.",
filterSection:"Speichern und filtern", captureTools:"Client-Tool-Ergebnisse einschließen", captureCindy:"Erkannte Cindy-Hüllen im Dialogmodus bereinigen", advanced:"Erweitert", maxMemories:"Maximale Erinnerungen (1–20)", maxBytes:"Abruf-Bytes (512–32768)", requestTimeout:"Anfrage-Timeout ms (50–5000)", recallBackoff:"Abruf-Wartezeit ms (100–300000)", gatewayTimeout:"Host-Hook-Timeout ms (100–10000)", port:"Verbindungstest-Port (1024–65535)", insecure:"HTTP zu fremdem Server erlauben (Zugangsdaten unverschlüsselt)", defaultsHelp:"Leer verwendet die Umgebung, wo unterstützt, sonst den angezeigten Standard. Unveränderte Werte bleiben erhalten. Das Host-Timeout kann früher enden.", conflict:"Die Konfiguration wurde anderswo geändert. Der Entwurf bleibt erhalten. Wähle „Abbrechen“ und öffne die Einstellungen erneut.", invalidOption:"Eingaben und Wertebereiche prüfen.",
});
Object.assign(messages.en, {keySaved:"Saved",keyNotSet:"No saved key",keyRemove:"Remove saved key",keyUndo:"Undo removal",humanOnly:"Only human dialogue",filterHelp:"Exclude tool results from saved conversations.",cindyHelp:"Available when only human dialogue is enabled.",captureToolsHelp:"Used only when the human-dialogue filter is off.",insecureHelp:"Use only on a trusted network."});
Object.assign(messages.zh, {keySaved:"已保存",keyNotSet:"未保存密钥",keyRemove:"清除已保存的密钥",keyUndo:"撤销清除",humanOnly:"仅保存人类对话",filterHelp:"保存对话时排除工具结果。",cindyHelp:"仅在人类对话模式开启时可用。",captureToolsHelp:"仅在“仅保存人类对话”关闭时生效。",insecureHelp:"仅在可信网络中使用。"});
Object.assign(messages["zh-TW"], {keySaved:"已儲存",keyNotSet:"未儲存金鑰",keyRemove:"清除已儲存的金鑰",keyUndo:"復原清除",humanOnly:"僅儲存人類對話",filterHelp:"儲存對話時排除工具結果。",cindyHelp:"僅在人類對話模式開啟時可用。",captureToolsHelp:"僅在「僅儲存人類對話」關閉時生效。",insecureHelp:"僅在可信任的網路中使用。"});
Object.assign(messages.ja, {keySaved:"保存済み",keyNotSet:"保存したキーなし",keyRemove:"保存したキーを削除",keyUndo:"削除を取り消す",humanOnly:"人間の対話のみ",filterHelp:"保存する会話からツール結果を除きます。",cindyHelp:"人間の対話のみが有効なときに使用できます。",captureToolsHelp:"人間の対話のみがオフのときに適用されます。",insecureHelp:"信頼できるネットワークでのみ使用してください。"});
Object.assign(messages.de, {keySaved:"Gespeichert",keyNotSet:"Kein gespeicherter Schlüssel",keyRemove:"Gespeicherten Schlüssel entfernen",keyUndo:"Entfernen rückgängig",humanOnly:"Nur menschlicher Dialog",filterHelp:"Tool-Ergebnisse aus gespeicherten Gesprächen ausschließen.",cindyHelp:"Nur verfügbar, wenn menschlicher Dialog aktiviert ist.",captureToolsHelp:"Gilt nur, wenn der Filter für menschlichen Dialog aus ist.",insecureHelp:"Nur in einem vertrauenswürdigen Netzwerk verwenden."});
Object.assign(messages.en,{recallRemote:"Recall for remote and other gateway keys",recallRemoteHelp:"Requires recall. May share the configured Mem memories and Context Bundle with all such clients. This is not tenant isolation.",captureRemote:"Save remote and other gateway conversations",captureRemoteHelp:"Requires saving conversations. Saves conversations from all such clients to this Mem."});
Object.assign(messages.zh,{recallRemote:"允许远端和其他网关密钥召回",recallRemoteHelp:"需要开启记忆召回。可能向所有此类客户端提供所配置 Mem 的记忆和 Context Bundle。这不是租户隔离。",captureRemote:"保存远端和其他网关密钥的对话",captureRemoteHelp:"需要开启保存对话。会将所有此类客户端的对话保存到此 Mem。"});
Object.assign(messages["zh-TW"],{recallRemote:"允許遠端與其他閘道金鑰召回",recallRemoteHelp:"需要開啟記憶召回。可能向所有此類用戶端提供所設定 Mem 的記憶與 Context Bundle。這不是租戶隔離。",captureRemote:"儲存遠端與其他閘道金鑰的對話",captureRemoteHelp:"需要開啟儲存對話。會將所有此類用戶端的對話儲存到此 Mem。"});
Object.assign(messages.ja,{recallRemote:"リモートと他のゲートウェイキーの検索を許可",recallRemoteHelp:"記憶の検索が必要です。設定した Mem の記憶と Context Bundle を該当する全クライアントに共有する可能性があります。テナント分離ではありません。",captureRemote:"リモートと他のゲートウェイキーの会話を保存",captureRemoteHelp:"会話の保存が必要です。該当する全クライアントの会話をこの Mem に保存します。"});
Object.assign(messages.de,{recallRemote:"Abruf für entfernte und andere Gateway-Schlüssel",recallRemoteHelp:"Erfordert den Erinnerungsabruf. Kann Erinnerungen und Context Bundle des konfigurierten Mem mit allen solchen Clients teilen. Dies ist keine Mandantentrennung.",captureRemote:"Entfernte und andere Gateway-Gespräche speichern",captureRemoteHelp:"Erfordert das Speichern von Gesprächen. Speichert Gespräche aller solchen Clients in diesem Mem."});
const languageTags = {en: 'en', zh: 'zh-CN', 'zh-TW': 'zh-TW', ja: 'ja-JP', de: 'de-DE'};
function languageFor(value = '') {
+34 -11
View File
@@ -2,42 +2,65 @@
<html lang="en">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Nowledge Mem</title><link rel="stylesheet" href="style.css">
<script src="_magpie/bridge.js" defer></script><script src="i18n.js" defer></script><script src="settings.js" defer></script></head>
<script src="_magpie/bridge.js" defer></script><script src="i18n.js" defer></script><script src="validate.js" defer></script><script src="settings.js" defer></script></head>
<body><main>
<header class="page-head"><img class="brand" src="icon.svg" width="30" height="30" alt=""><div><h1>Nowledge Mem</h1><p data-t="intro">Recall your Mem memory in every agent behind Magpie.</p></div><div class="header-actions"><button id="configure" type="button" disabled data-t="configure">Configure connection</button><button id="test-saved" class="secondary" type="button" disabled data-t="testConnection">Test connection</button></div></header>
<header class="page-head"><img class="brand" src="icon.svg" width="30" height="30" alt=""><div><h1>Nowledge Mem</h1><p data-t="intro">Recall your Mem memory in every agent behind Magpie.</p></div><div class="header-actions"><button id="configure" type="button" disabled data-t="configure">Settings</button><button id="test-saved" class="secondary" type="button" disabled data-t="testConnection">Test connection</button></div></header>
<section class="panel"><div class="section-heading"><h2 data-t="connection">Connection</h2><span id="configured" role="status"></span></div>
<dl class="connection-summary"><div><dt data-t="url">Server URL</dt><dd id="summary-url">—</dd></div><div><dt data-t="space">Space ID</dt><dd id="summary-space">—</dd></div><div><dt data-t="recall">Memory recall</dt><dd id="summary-recall">—</dd></div><div><dt data-t="skipAgents">Apps without memory</dt><dd id="summary-skip">—</dd></div><div><dt id="summary-capture-label" data-t="capture">Save conversations</dt><dd class="capture-status"><input id="summary-capture" class="slide-switch" type="checkbox" role="switch" disabled aria-labelledby="summary-capture-label" aria-describedby="capture-feedback"><span id="capture-state"></span></dd></div></dl>
<p id="capture-feedback" role="status" aria-live="polite" hidden></p></section>
<dialog id="settings" aria-labelledby="dialog-title" aria-describedby="dialog-description">
<div class="dialog-head">
<img class="brand" src="icon.svg" width="24" height="24" alt="">
<div><h2 id="dialog-title" data-t="dialogTitle">Connection settings</h2><p id="dialog-description" data-t="settingsIntro">Connect Magpie to your Nowledge Mem.</p></div>
<div><h2 id="dialog-title" data-t="dialogTitle">Nowledge Mem settings</h2><p id="dialog-description" data-t="settingsIntro">Configure connection, recall and saving.</p></div>
<button id="close" class="icon-button" type="button" aria-label="Close">×</button>
</div>
<form id="form" novalidate><div class="dialog-body">
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3" y="4" width="18" height="6" rx="2"/><rect x="3" y="14" width="18" height="6" rx="2"/><path d="M7 7h.01M7 17h.01M16 7h2M16 17h2"/></svg><span data-t="serviceSection">Mem service</span></legend>
<div class="fields">
<label for="url"><span data-t="url">Server URL</span><input id="url" type="url" placeholder="http://127.0.0.1:14242" autocomplete="off" spellcheck="false" aria-describedby="url-help"><small id="url-help" data-t="urlHelp">Local HTTP or remote HTTPS; HTTP to another machine needs the switch below. No credentials in the URL.</small></label>
<label class="switch-field" for="insecure-http"><input id="insecure-http" type="checkbox" role="switch"><span><strong data-t="insecureHttp">Allow HTTP to another machine</strong><small data-t="insecureHttpHelp">Only on a network you trust, e.g. Tailscale. Elsewhere your conversations and API key would cross the network unencrypted.</small></span></label>
<label for="url"><span data-t="url">Server URL</span><input id="url" type="url" placeholder="http://127.0.0.1:14242" autocomplete="off" spellcheck="false" aria-describedby="url-help"><small id="url-help" data-t="urlHelp">Local HTTP or remote HTTPS without credentials in the URL. Remote HTTP requires the advanced exception. Empty uses NMEM_API_URL or the local default.</small></label>
<label for="space"><span data-t="space">Space ID</span><input id="space" placeholder="default" autocomplete="off" spellcheck="false" aria-describedby="space-help"><small id="space-help" data-t="spaceHelp">Optional. Leave empty for the default Space.</small></label>
<label for="agent"><span data-t="agent">Agent ID</span><input id="agent" placeholder="default" autocomplete="off" spellcheck="false" aria-describedby="agent-help"><small id="agent-help" data-t="agentHelp">Optional. Selects an agent profile and its default Space in Mem.</small></label>
<label for="host-agent"><span data-t="hostAgent">Host agent ID</span><input id="host-agent" autocomplete="off" aria-describedby="host-agent-help"><small id="host-agent-help" data-t="hostAgentHelp">Empty derives an identity from the harness.</small></label>
</div></fieldset>
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="9" r="5"/><path d="m12 12 8 8h2v-4h-3v-3h-3"/></svg><span data-t="authSection">Authentication</span></legend>
<label for="key"><span data-t="key">API key</span></label><div class="secret-input"><input id="key" type="password" autocomplete="off" spellcheck="false" autocapitalize="off" aria-describedby="key-help"><button id="show-key" type="button" class="secret-toggle" aria-controls="key" aria-pressed="false" aria-label="Show key" title="Show key"><svg class="eye-show" viewBox="0 0 24 24" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg><svg class="eye-hide" viewBox="0 0 24 24" aria-hidden="true"><path d="m3 3 18 18M10.6 5.1A12 12 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.1 4.1M6.5 6.5A20 20 0 0 0 2 12s3.5 7 10 7a12 12 0 0 0 5.5-1.5M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg></button></div><small id="key-help" data-t="keyHelp">Leave empty when your Mem does not require a key. Saved in Magpie’s local plugin configuration.</small><small data-t="keyFallback">With this field empty, Magpie reads the variable named in apiKeyEnv (NMEM_API_KEY by default).</small>
<label for="key"><span data-t="key">API key</span></label>
<div class="secret-input"><input id="key" type="password" autocomplete="off" spellcheck="false" autocapitalize="off" aria-describedby="key-storage key-help"><button id="show-key" type="button" class="secret-toggle" aria-controls="key" aria-pressed="false" aria-label="Show key" title="Show key"><svg class="eye-show" viewBox="0 0 24 24" aria-hidden="true"><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg><svg class="eye-hide" viewBox="0 0 24 24" aria-hidden="true"><path d="m3 3 18 18M10.6 5.1A12 12 0 0 1 12 5c6.5 0 10 7 10 7a17 17 0 0 1-3.1 4.1M6.5 6.5A20 20 0 0 0 2 12s3.5 7 10 7a12 12 0 0 0 5.5-1.5M9.9 9.9a3 3 0 0 0 4.2 4.2"/></svg></button></div>
<button id="key-clear" type="button" class="secondary key-clear" aria-pressed="false" hidden>Remove saved key</button>
<small id="key-storage" data-t="keyHelp">Saved in Magpie’s local plugin configuration.</small>
<small id="key-help" data-t="keyActionHelp">Clearing the saved value falls back to the environment variable; it does not disable it.</small>
<label for="key-env"><span data-t="keyEnv">API key environment variable</span><input id="key-env" placeholder="NMEM_API_KEY" aria-describedby="key-env-help"><small id="key-env-help" data-t="keyEnvHelp">Only NMEM_* names are accepted. Empty uses NMEM_API_KEY.</small></label>
</fieldset>
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 3v4M12 17v4M4.9 4.9l2.8 2.8M16.3 16.3l2.8 2.8M3 12h4M17 12h4M4.9 19.1l2.8-2.8M16.3 7.7l2.8-2.8"/></svg><span data-t="behaviorSection">What Magpie sends</span></legend>
<label class="switch-field" for="recall"><input id="recall" type="checkbox" role="switch"><span><strong data-t="recall">Memory recall</strong><small data-t="recallHelp">Search Mem with the latest user turn and add what it recalls to the request.</small></span></label>
<label class="switch-field" for="context"><input id="context" type="checkbox" role="switch"><span><strong data-t="contextLabel">Context Bundle</strong><small data-t="contextHelp">On a session’s first turn, also send your profile, rules and Working Memory.</small></span></label>
<label class="switch-field" for="recall"><input id="recall" type="checkbox" role="switch" aria-describedby="recall-help"><span><strong data-t="recall">Memory recall</strong><small id="recall-help" data-t="recallHelp">Search Mem with the latest user turn and add what it recalls to the request.</small></span></label>
<label class="switch-field" for="recall-remote"><input id="recall-remote" type="checkbox" role="switch" aria-describedby="recall-remote-help"><span><strong data-t="recallRemote">Recall for remote and other gateway keys</strong><small id="recall-remote-help" data-t="recallRemoteHelp">Requires recall. May share the configured Mem memories and Context Bundle with all such clients. This is not tenant isolation.</small></span></label>
<label class="switch-field" for="context"><input id="context" type="checkbox" role="switch" aria-describedby="context-help"><span><strong data-t="contextLabel">Context Bundle</strong><small id="context-help" data-t="contextHelp">On a session’s first turn, also send your profile, rules and Working Memory.</small></span></label>
<label for="skip-agents"><span data-t="skipAgents">Apps without memory</span><input id="skip-agents" placeholder="Mozilla" autocomplete="off" spellcheck="false" aria-describedby="skip-agents-help"><small id="skip-agents-help" data-t="skipAgentsHelp">Optional. App names as Magpie’s Usage page shows them, separated by commas. Their requests get no recall and are never saved.</small></label>
<label class="switch-field" for="capture"><input id="capture" type="checkbox" role="switch"><span><strong data-t="capture">Save conversations</strong><small data-t="captureHelp">Off by default. Import completed conversations as Mem Threads, which Mem distills into Memory.</small></span></label>
<label class="switch-field" for="capture"><input id="capture" type="checkbox" role="switch" aria-describedby="capture-help"><span><strong data-t="capture">Save conversations</strong><small id="capture-help" data-t="captureHelp">Off by default. Import completed conversations as Mem Threads, which Mem distills into Memory.</small></span></label>
<label class="switch-field" for="capture-remote"><input id="capture-remote" type="checkbox" role="switch" aria-describedby="capture-remote-help"><span><strong data-t="captureRemote">Save remote and other gateway conversations</strong><small id="capture-remote-help" data-t="captureRemoteHelp">Requires saving conversations. Saves conversations from all such clients to this Mem.</small></span></label>
</fieldset>
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 5h16l-6 7v5l-4 2v-7z"/></svg><span data-t="filterSection">Saving and filtering</span></legend><div class="fields">
<label class="switch-field" for="capture-tools"><input id="capture-tools" type="checkbox" aria-describedby="capture-tools-help"><span><strong data-t="captureTools">Include client tool results</strong><small id="capture-tools-help" data-t="captureToolsHelp">Used only when the human-dialogue filter is off.</small></span></label>
<label class="switch-field" for="capture-filter"><input id="capture-filter" type="checkbox" role="switch" aria-describedby="filter-help"><span><strong data-t="humanOnly">Only human dialogue</strong><small id="filter-help" data-t="filterHelp">Exclude tool results from saved conversations.</small></span></label>
<label class="switch-field" for="capture-cindy"><input id="capture-cindy" type="checkbox" aria-describedby="cindy-help"><span><strong data-t="captureCindy">Clean recognized Cindy wrappers in human mode</strong><small id="cindy-help" data-t="cindyHelp">Available when only human dialogue is enabled.</small></span></label>
</div></fieldset>
<fieldset class="settings-section"><legend><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 7h16M4 17h16M8 4v6M16 14v6"/></svg><span data-t="advanced">Advanced</span></legend><div class="fields">
<label for="max-memories"><span data-t="maxMemories">Maximum memories (1–20)</span><input id="max-memories" aria-describedby="defaults-help" type="number" min="1" max="20" placeholder="5"></label>
<label for="max-bytes"><span data-t="maxBytes">Recall bytes (512–32768)</span><input id="max-bytes" aria-describedby="defaults-help" type="number" min="512" max="32768" placeholder="6000"></label>
<label for="request-timeout"><span data-t="requestTimeout">Request timeout ms (50–5000)</span><input id="request-timeout" aria-describedby="defaults-help" type="number" min="50" max="5000" placeholder="1500"></label>
<label for="recall-backoff"><span data-t="recallBackoff">Recall backoff ms (100–300000)</span><input id="recall-backoff" aria-describedby="defaults-help" type="number" min="100" max="300000" placeholder="30000"></label>
<label for="gateway-timeout"><span data-t="gatewayTimeout">Host hook timeout ms (100–10000)</span><input id="gateway-timeout" aria-describedby="defaults-help" type="number" min="100" max="10000" placeholder="1000"></label>
<label for="port"><span data-t="port">Connection-test port (1024–65535)</span><input id="port" aria-describedby="defaults-help" type="number" min="1024" max="65535" placeholder="3479"></label>
<label class="switch-field" for="insecure"><input id="insecure" type="checkbox" aria-describedby="insecure-help"><span><strong data-t="insecure">Allow HTTP to a non-local server (credentials travel unencrypted)</strong><small id="insecure-help" data-t="insecureHelp">Use only on a trusted network.</small></span></label>
<small id="defaults-help" data-t="defaultsHelp">Empty fields inherit the environment where supported, otherwise use the shown default. Unchanged values remain as configured. The host timeout can end a request first.</small>
</div></fieldset>
<small data-t="concurrencyHelp">Saving merges your edits into the latest settings, but another editor saving at the same moment can still overwrite them. Use one editor at a time. Very large integers in options may be rounded.</small>
<p id="result" role="status" aria-live="polite" hidden></p>
</div><footer><span data-t="saveHelp">Advanced options are preserved.</span><div class="actions"><button id="cancel" class="secondary" type="button" data-t="cancel">Cancel</button><button id="save" type="button" disabled data-t="save">Save configuration</button></div></footer>
</div><footer><span><span data-t="saveHelp">Unchanged and unlisted options are preserved.</span></span><div class="actions"><button id="cancel" class="secondary" type="button" data-t="cancel">Cancel</button><button id="save" type="button" disabled data-t="save">Save configuration</button></div></footer>
</form></dialog>
<section class="panel tools-panel" aria-labelledby="tools-title">
<h2 id="tools-title" data-t="toolsTitle">Memory tools</h2>
<p data-t="toolsIntro">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.</p>
</section>
<section class="data-notice" aria-labelledby="data-title"><h2 id="data-title" data-t="dataTitle">What is sent</h2><p data-t="recallDisclosure">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.</p><p data-t="captureDisclosure">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.</p>
<p data-t="scopeDisclosure">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.</p></section>
<p data-t="scopeDisclosure">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.</p></section>
</main></body></html>
+252 -137
View File
@@ -1,168 +1,283 @@
// Only the official configuration bridge is used. The connection test is a
// local loopback page the frame navigates to, because the page's sandbox has
// no network (connect-src 'none'). It tests the saved options; the language
// travels in the query and the test page's Back button uses history.back().
// Released hosts use a best-effort field merge; read/modify/write is not
// atomic across processes.
const {languageFor, languageTags, translate} = nowledgeMemI18n;
const validateExplicitOptions = globalThis.__nowledgeMemValidateOptions;
const $ = (id) => document.getElementById(id);
let language = 'en', busy = false, savedOptions = null, pendingCapture = null;
const t = (key, parameters) => translate(language, key, parameters);
let language = 'en', busy = false, savedOptions = null, draftOptions = null, baseline = null, draftOpen = false, clearKey = false;
const resets = new Set(), resetButtons = new Map();
const t = (key) => translate(language, key);
function message(id, key, error = false) {
const el = $(id);
el.dataset.message = key;
el.textContent = t(key);
el.dataset.error = String(error);
el.hidden = false;
const el = $(id); el.dataset.message = key; el.textContent = t(key); el.dataset.error = String(error); el.hidden = false;
}
const result = (key, error = false) => message("result", key, error);
const result = (key, error = false) => message('result', key, error);
const fields = [
['url','serverUrl','text'], ['space','spaceId','text'], ['agent','agentId','text'], ['host-agent','hostAgentId','text'], ['key-env','apiKeyEnv','text'],
['skip-agents','skipAgents','list'],
['recall','recall','bool',true], ['recall-remote','recallRemote','bool',false], ['context','contextBundle','bool',true], ['capture','capture','bool',false], ['capture-remote','captureRemote','bool',false],
['capture-tools','captureTools','bool',true], ['capture-filter','captureFilter','filter','off'], ['capture-cindy','captureCindy','bool',false],
['max-memories','maxMemories','number',5,1,20], ['max-bytes','maxBytes','number',6000,512,32768],
['request-timeout','requestTimeoutMs','number',1500,50,5000], ['recall-backoff','recallBackoffMs','number',30000,100,300000],
['gateway-timeout','gatewayTimeoutMs','number',1000,100,10000], ['port','port','number',3479,1024,65535], ['insecure','allowInsecureHttp','bool',false],
];
function summary() {
if (!savedOptions) return;
$("summary-url").textContent = savedOptions.serverUrl || t("localDefault");
$("summary-space").textContent = savedOptions.spaceId || t("defaultSpace");
$("summary-recall").textContent = savedOptions.recall === false ? t("off") : t("on");
$("summary-skip").textContent = skipList(savedOptions.skipAgents).join(", ") || t("none");
const capture = $("summary-capture");
capture.checked = pendingCapture ?? savedOptions.capture === true;
$("capture-state").textContent = savedOptions.capture === true ? t("on") : t("off");
capture.title = t("captureHelp");
$('summary-url').textContent = savedOptions.serverUrl || t('localDefault');
$('summary-space').textContent = savedOptions.spaceId || t('defaultSpace');
$('summary-recall').textContent = savedOptions.recall === false ? t('off') : t('on');
$('summary-skip').textContent = skipList(savedOptions.skipAgents).join(', ') || t('none');
$('summary-capture').checked = savedOptions.capture === true;
$('summary-capture').disabled = busy;
$('capture-state').textContent = savedOptions.capture === true ? t('on') : t('off');
}
// skipAgents is kept as a list; one typed by hand may be a single string.
function skipList(value) {
const names = Array.isArray(value) ? value : typeof value === "string" ? value.split(/[,,\n]/) : [];
return names.filter((name) => typeof name === "string").map((name) => name.trim()).filter(Boolean);
const names = Array.isArray(value) ? value : typeof value === 'string' ? value.split(/[,,\n]/) : [];
return names.filter((name) => typeof name === 'string').map((name) => name.trim()).filter(Boolean);
}
// The same rule as mem.mjs: plain HTTP to another machine only with
// allowInsecureHttp, as on a tailnet, whose link is already encrypted.
function validUrl(raw, insecure = false) {
let url;
try { url = new URL(raw); } catch { return null }
const loopback = ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname);
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password || url.search || url.hash || (url.protocol === "http:" && !loopback && insecure !== true)) return null;
return url;
}
function formUrl(fallback = "") {
return validUrl($("url").value.trim() || fallback, $("insecure-http").checked);
function validUrl(raw, insecure) {
let url; try { url = new URL(raw); } catch { return false }
const local = ['localhost','127.0.0.1','[::1]'].includes(url.hostname);
return ['http:','https:'].includes(url.protocol) && !url.username && !url.password && !url.search && !url.hash && (url.protocol !== 'http:' || local || insecure);
}
function testService() {
const service = window.magpie?.service;
if (typeof service === "string" && /^https?:\/\//.test(service)) return service.replace(/\/+$/, "");
if (typeof service === 'string' && /^https?:\/\//.test(service)) return service.replace(/\/+$/, '');
const port = Number(savedOptions?.port);
return `http://127.0.0.1:${Number.isInteger(port) && port > 0 ? port : 3479}`;
}
function valueOf(id, kind) { return kind === 'bool' ? $(id).checked : kind === 'filter' ? $(id).checked ? 'human' : 'off' : $(id).value; }
function snapshotForm() { return Object.fromEntries(fields.map(([id,,kind]) => [id, valueOf(id, kind)])); }
function paintReset(id, name) {
const entry = resetButtons.get(id); if (!entry || !draftOptions) return;
entry.button.hidden = resets.has(id) || !Object.hasOwn(draftOptions, name);
entry.button.disabled = $(id).disabled;
const fieldName = entry.label.querySelector?.('strong')?.textContent || entry.label.querySelector?.('span')?.textContent || id;
const label = `${t('useDefault')}: ${fieldName}`;
entry.button.setAttribute('aria-label',label); entry.button.setAttribute('title',label);
}
function attachOrigins() {
for (const [id,name,kind,fallback] of fields) {
if (resetButtons.has(id)) continue;
const input = $(id), label = input.closest?.('label'); if (!label) continue;
const wrapper = element('div'), reset = element('button');
wrapper.className = 'field-wrap'; label.before(wrapper); wrapper.append(label,reset);
reset.type = 'button'; reset.className = 'option-reset'; reset.textContent = '×';
reset.onclick = () => {
resets.add(id);
if (kind === 'bool') input.checked = fallback;
else if (kind === 'filter') input.checked = fallback === 'human';
else input.value = '';
if (id === 'capture-filter') syncFilter();
if (id === 'recall' || id === 'capture') syncRemote();
paintReset(id,name); input.focus();
};
const edited = () => {
resets.delete(id);
paintReset(id,name);
};
input.addEventListener('input',edited); input.addEventListener('change',edited);
resetButtons.set(id,{button:reset,label});
}
}
function element(tag, key) {
const el = document.createElement(tag);
if (key) { el.dataset.t = key; el.textContent = t(key); }
return el;
}
function fill(options) {
$("url").value = options.serverUrl || "";
$("space").value = options.spaceId || "";
$("agent").value = options.agentId || "";
$("skip-agents").value = skipList(options.skipAgents).join(", ");
$("key").value = (options.apiKey || "").replace(/^Bearer\s+/i, "");
$("key").type = "password";
$("insecure-http").checked = options.allowInsecureHttp === true;
$("recall").checked = options.recall !== false;
$("context").checked = options.contextBundle !== false;
$("capture").checked = options.capture === true;
paintSecret();
resets.clear(); attachOrigins();
for (const [id,name,kind,fallback] of fields) {
if (kind === 'bool') $(id).checked = options[name] ?? fallback;
else if (kind === 'list') $(id).value = skipList(options[name]).join(', ');
else if (kind === 'filter') $(id).checked = (options[name] ?? fallback) === 'human';
else $(id).value = options[name] == null ? '' : String(options[name]);
}
clearKey = false; $('key').value = ''; $('key').type = 'password';
baseline = {fields:snapshotForm()};
for (const [id,name] of fields) paintReset(id,name);
syncFilter(); syncRemote(); paintSecret(); paintKeyAction();
}
function paintSecret() {
const visible = $("key").type === "text";
const label = t(visible ? "hideKey" : "showKey");
$("show-key").setAttribute("aria-label", label);
$("show-key").setAttribute("title", label);
$("show-key").setAttribute("aria-pressed", String(visible));
const visible = $('key').type === 'text', label = t(visible ? 'hideKey' : 'showKey');
$('show-key').setAttribute('aria-label',label); $('show-key').setAttribute('title',label); $('show-key').setAttribute('aria-pressed',String(visible));
}
$("show-key").onclick = () => { $("key").type = $("key").type === "password" ? "text" : "password"; paintSecret(); };
$("settings").onclose = () => { $("key").value = ""; $("key").type = "password"; paintSecret(); };
function close() { if (!busy) $("settings").close(); }
$("configure").onclick = () => { fill(savedOptions); $("result").hidden = true; $("settings").showModal(); };
$("close").onclick = close;
$("cancel").onclick = close;
$("settings").oncancel = (event) => { if (busy) event.preventDefault(); };
$('show-key').onclick = () => { $('key').type = $('key').type === 'password' ? 'text' : 'password'; paintSecret(); };
$('settings').onclose = () => { $('key').type = 'password'; paintSecret(); };
function paintKeyAction() {
const present = typeof draftOptions?.apiKey === 'string' && !!draftOptions.apiKey.trim();
$('key').placeholder = t(present && !clearKey ? 'keySaved' : 'keyNotSet');
$('key-clear').hidden = !present;
$('key-clear').textContent = t(clearKey ? 'keyUndo' : 'keyRemove');
$('key-clear').setAttribute('aria-pressed',String(clearKey));
}
$('key-clear').onclick = () => { clearKey = !clearKey; if (clearKey) $('key').value = ''; paintKeyAction(); };
$('key').oninput = () => { if ($('key').value) clearKey = false; paintKeyAction(); };
function syncFilter() {
$('capture-cindy').disabled = !$('capture-filter').checked;
$('capture-tools').disabled = $('capture-filter').checked;
paintReset('capture-cindy','captureCindy');
paintReset('capture-tools','captureTools');
}
$('capture-filter').onchange = syncFilter;
function syncRemote() {
$('recall-remote').disabled = !$('recall').checked;
$('capture-remote').disabled = !$('capture').checked;
paintReset('recall-remote','recallRemote');
paintReset('capture-remote','captureRemote');
}
$('recall').onchange = syncRemote;
$('capture').onchange = syncRemote;
function close() { if (!busy) $('settings').close(); }
$('configure').onclick = async () => {
if (busy || !savedOptions) return;
if (!draftOpen) {
try {
const snap = {options:await magpie.options.get()};
if (!snap || !snap.options) throw new Error('missing options');
draftOptions = snap.options; savedOptions = snap.options; $('result').hidden = true; fill(draftOptions); summary(); draftOpen = true;
$('save').disabled = false;
} catch { message('configured','loadFailed',true); return; }
}
$('settings').showModal();
};
$('close').onclick = close;
$('cancel').onclick = () => { if (!busy) { draftOpen = false; $('key').value = ''; close(); } };
$('settings').oncancel = (event) => { if (busy) event.preventDefault(); };
function paint() {
language = languageFor(magpie.theme?.lang || navigator.language);
document.documentElement.lang = languageTags[language];
$("close").setAttribute("aria-label", t("close"));
$("show-key").setAttribute("aria-label", t("showKey"));
paintSecret();
summary();
document.querySelectorAll("[data-message]").forEach((el) => { el.textContent = t(el.dataset.message); });
document.querySelectorAll("[data-t]").forEach((el) => { el.textContent = t(el.dataset.t); });
language = languageFor(magpie.theme?.lang || navigator.language); document.documentElement.lang = languageTags[language];
$('close').setAttribute('aria-label',t('close')); paintSecret(); summary();
document.querySelectorAll('[data-message]').forEach((el) => { el.textContent = t(el.dataset.message); });
document.querySelectorAll('[data-t]').forEach((el) => { el.textContent = t(el.dataset.t); });
if (draftOptions) { paintKeyAction(); for (const [id,name] of fields) paintReset(id,name); }
}
magpie.ready.then(async () => {
paint();
magpie.onTheme(paint);
paint(); magpie.onTheme(paint);
try {
const options = await magpie.options.get();
savedOptions = options; fill(options); summary();
message("configured", options.serverUrl ? "loaded" : "notConfigured");
$("save").disabled = false; $("configure").disabled = false; $("test-saved").disabled = false; $("summary-capture").disabled = false;
} catch { message("configured", "loadFailed", true); }
}).catch(() => { paint(); message("configured", "bridgeFailed", true); });
const save = async (event) => {
event.preventDefault(); if (busy) return;
const url = formUrl();
if (!url) { result("invalidUrl", true); $("url").focus(); return }
const space = $("space").value.trim();
const agent = $("agent").value.trim();
const skip = skipList($("skip-agents").value);
const key = $("key").value.trim().replace(/^Bearer\s+/i, "");
if (key && /[\s\u0000-\u001f\u007f]/.test(key)) {
result("invalidKey", true); $("key").focus(); return;
savedOptions = await magpie.options.get(); summary();
message('configured', savedOptions.serverUrl ? 'loaded' : 'notConfigured');
$('configure').disabled = false; $('test-saved').disabled = false;
} catch { message('configured','loadFailed',true); }
}).catch(() => { paint(); message('configured','bridgeFailed',true); });
function nextOptions() {
const next = {...draftOptions};
for (const [id,name,kind,,min,max] of fields) {
const current = valueOf(id,kind);
if (resets.has(id)) { delete next[name]; continue; }
if (current === baseline.fields[id]) continue;
if (kind === 'bool' || kind === 'filter') next[name] = current;
else if (kind === 'list') {
const names = skipList(current);
if (names.length) next[name] = names; else delete next[name];
}
else if (kind === 'number') {
if (current === '') delete next[name];
else { const n = Number(current); if (!Number.isInteger(n) || n < min || n > max) throw new Error('invalidOption'); next[name] = n; }
} else if (current.trim()) next[name] = current.trim(); else delete next[name];
}
busy = true; $("save").disabled = true; $("close").disabled = true; $("cancel").disabled = true;
if (next.serverUrl && !validUrl(next.serverUrl, next.allowInsecureHttp === true)) throw new Error('invalidUrl');
if (next.apiKeyEnv && !/^NMEM_[A-Za-z0-9_]+$/.test(next.apiKeyEnv)) throw new Error('invalidOption');
if (clearKey) delete next.apiKey;
else if ($('key').value) {
const key = $('key').value.trim().replace(/^Bearer\s+/i,'');
if (!key || /[\s\u0000-\u001f\u007f]/.test(key)) throw new Error('invalidKey');
next.apiKey = key;
}
// Validate the explicit values before saving; environment values are
// resolved separately by the hook.
validateExplicitOptions(next);
for (const [name,min,max] of [['gatewayTimeoutMs',100,10000],['port',1024,65535]]) {
const v = next[name];
if (v != null && (!Number.isInteger(name === 'port' ? Number(v) : v) || Number(v) < min || Number(v) > max)) throw new Error('invalidOption');
}
if (next.allowInsecureHttp !== undefined && typeof next.allowInsecureHttp !== 'boolean') throw new Error('invalidOption');
return next;
}
function optionChanges(next) {
const changes = [], same = (a,b) => JSON.stringify(a) === JSON.stringify(b);
const change = (path, value, present) => changes.push(present ? {path,value} : {path,remove:true});
for (const name of [...fields.map(([,name])=>name), 'apiKey']) {
const before = Object.hasOwn(draftOptions,name), after = Object.hasOwn(next,name);
if (before !== after || (after && !same(draftOptions[name],next[name]))) change([name],next[name],after);
}
return changes;
}
async function save(event) {
event.preventDefault(); if (busy || !draftOptions) return;
let next; try { next = nextOptions(); } catch (err) { result(err.message || 'invalidOption',true); return; }
busy = true; $('save').disabled = true; $('close').disabled = true; $('cancel').disabled = true;
try {
const previous = await magpie.options.get();
// Read again before merging to preserve options not exposed by this form.
const next = {...previous, serverUrl: url.href, recall: $("recall").checked, contextBundle: $("context").checked, capture: $("capture").checked};
if (space) next.spaceId = space;
else delete next.spaceId;
if (agent) next.agentId = agent;
else delete next.agentId;
if (skip.length) next.skipAgents = skip;
else delete next.skipAgents;
if (key) next.apiKey = key;
else delete next.apiKey;
if ($("insecure-http").checked) next.allowInsecureHttp = true;
else delete next.allowInsecureHttp;
await magpie.options.set(next);
savedOptions = next; summary();
message("configured", "configurationSaved");
result("saveSucceeded");
} catch { result("saveFailed", true); }
finally { busy = false; $("save").disabled = false; $("close").disabled = false; $("cancel").disabled = false; }
};
$("test-saved").onclick = () => {
if (!savedOptions) return;
const url = validUrl(savedOptions.serverUrl || "http://127.0.0.1:14242", savedOptions.allowInsecureHttp === true);
if (!url) { message("configured", "invalidUrl", true); return }
const target = new URL(testService() + "/test");
target.searchParams.set("lang", language);
location.assign(target.href);
};
$("save").onclick = save;
$("form").onsubmit = (event) => event.preventDefault();
$("form").onkeydown = (event) => {
if (event.key === "Enter" && event.target.tagName === "INPUT" && event.target.type !== "checkbox") save(event);
};
$("summary-capture").onchange = async () => {
const changes = optionChanges(next);
const current = await magpie.options.get();
// This detects changes since opening the draft, but the subsequent set is
// not atomic with this read on released hosts.
if (changes.some(({path}) => !sameAtPath(draftOptions,current,path))) { result('conflict',true); return; }
// Enabling a gate must not silently activate a newly changed remote grant
// or send credentials to a newly changed HTTP endpoint.
const dependencies = [];
if (next.recall !== false && draftOptions.recall === false) dependencies.push(['recallRemote']);
if (next.capture === true && draftOptions.capture !== true) dependencies.push(['captureRemote']);
if (next.allowInsecureHttp === true && draftOptions.allowInsecureHttp !== true) dependencies.push(['serverUrl']);
if (dependencies.some((path) => !sameAtPath(draftOptions,current,path))) { result('conflict',true); return; }
const merged = applyChanges(current,changes);
validateExplicitOptions(merged);
await magpie.options.set(merged);
savedOptions = merged; draftOptions = merged; fill(draftOptions); summary();
message('configured','configurationSaved'); result('saveSucceeded');
} catch { result('saveFailed',true); }
finally { busy = false; $('save').disabled = false; $('close').disabled = false; $('cancel').disabled = false; summary(); }
}
function valueAtPath(root,path) {
let value = root;
for (const key of path) {
if (!value || typeof value !== 'object' || !Object.hasOwn(value,key)) return {present:false};
value = value[key];
}
return {present:true,value};
}
function sameAtPath(a,b,path) {
const x = valueAtPath(a,path), y = valueAtPath(b,path);
return x.present === y.present && (!x.present || JSON.stringify(x.value) === JSON.stringify(y.value));
}
function applyChanges(current,changes) {
const out = {...current};
for (const {path,value,remove} of changes) {
let target = out;
for (const key of path.slice(0,-1)) {
const existing = Object.hasOwn(target,key) && target[key] && typeof target[key] === 'object' ? target[key] : {};
const copy = {...existing};
Object.defineProperty(target,key,{value:copy,writable:true,enumerable:true,configurable:true});
target = copy;
}
const key = path.at(-1);
if (remove) delete target[key];
else Object.defineProperty(target,key,{value,writable:true,enumerable:true,configurable:true});
}
return out;
}
$('summary-capture').onchange = async () => {
if (busy || !savedOptions) return;
const enabled = $("summary-capture").checked;
pendingCapture = enabled;
busy = true;
$("summary-capture").disabled = true; $("configure").disabled = true;
message("capture-feedback", "saving");
const enabled = $('summary-capture').checked;
busy = true; $('summary-capture').disabled = true; $('configure').disabled = true;
message('capture-feedback','saving');
try {
const previous = await magpie.options.get();
const next = {...previous, capture: enabled};
await magpie.options.set(next);
savedOptions = next;
message("capture-feedback", enabled ? "captureEnabled" : "captureDisabled");
const current = await magpie.options.get();
const next = {...current,capture:enabled};
await magpie.options.set(next); savedOptions = next;
message('capture-feedback',enabled ? 'captureEnabled' : 'captureDisabled');
} catch {
// A rejected bridge response may follow a completed write; reconcile when possible.
try { savedOptions = await magpie.options.get(); } catch { /* Retain the last confirmed configuration. */ }
message("capture-feedback", "captureFailed", true);
try { savedOptions = await magpie.options.get(); } catch { /* keep the last confirmed value */ }
message('capture-feedback','captureFailed',true);
} finally {
pendingCapture = null; summary(); busy = false;
$("summary-capture").disabled = false; $("configure").disabled = false;
busy = false; $('configure').disabled = false; summary();
}
};
$('test-saved').onclick = () => {
if (!savedOptions) return;
if (!validUrl(savedOptions.serverUrl || 'http://127.0.0.1:14242', savedOptions.allowInsecureHttp === true)) {
message('configured','invalidUrl',true); return;
}
const target = new URL(testService() + '/test'); target.searchParams.set('lang',language); location.assign(target.href);
};
$('save').onclick = save;
$('form').onsubmit = (event) => event.preventDefault();
$('form').onkeydown = (event) => { if (event.key === 'Enter' && event.target.tagName === 'INPUT' && event.target.type !== 'checkbox') save(event); };
$('save').disabled = false;
+13 -3
View File
@@ -86,6 +86,14 @@ input:not([type=checkbox]):focus {
border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent);
}
input::placeholder { color: var(--muted); opacity: .7; }
.field-wrap { position: relative; min-width: 0; }
.field-wrap > label > span:first-child { padding-right: 28px; }
.field-wrap > label.switch-field > span { padding-right: 28px; }
button.option-reset { position: absolute; right: 0; top: 0; min-height: 22px; padding: 0 6px; border: 0; border-radius: 4px; background: transparent; color: var(--muted); font-size: 16px; }
button.option-reset:hover { background: var(--accent-soft); color: var(--accent); filter: none; }
button.option-reset[hidden], .key-clear[hidden] { display: none; }
.key-clear { margin-top: 6px; font-size: 11px; }
#key-help + label, #key-help + .field-wrap { margin-top: 12px; }
small { display: block; color: var(--muted); font-size: 11px; line-height: 1.6; margin-top: 5px; }
.secret-input { position: relative; }
.secret-input input { padding-right: 34px; }
@@ -105,6 +113,8 @@ small { display: block; color: var(--muted); font-size: 11px; line-height: 1.6;
.switch-field input[type=checkbox]::before { content: ""; position: absolute; width: 12px; height: 12px; top: 2px; left: 2px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px #0002; }
.switch-field input[type=checkbox]:checked { background: var(--accent); border-color: var(--accent); }
.switch-field input[type=checkbox]:checked::before { left: 14px; }
.switch-field input[type=checkbox]:disabled { opacity: .45; cursor: not-allowed; }
.switch-field input[type=checkbox]:disabled + span { opacity: .6; }
.slide-switch { appearance: none; -webkit-appearance: none; position: relative; flex: none; width: 30px; height: 18px; margin: 0; border-radius: 10px; border: 1px solid var(--line); background: var(--muted); cursor: pointer; }
.slide-switch::before { content: ""; position: absolute; width: 12px; height: 12px; top: 2px; left: 2px; border-radius: 50%; background: #fff; box-shadow: 0 1px 2px #0002; }
.slide-switch:checked { background: var(--accent); border-color: var(--accent); }
@@ -112,9 +122,9 @@ small { display: block; color: var(--muted); font-size: 11px; line-height: 1.6;
#result { margin: 0 0 14px; padding: 8px 10px; border-radius: 7px; background: var(--accent-soft); color: var(--fg); font-size: 12px; }
#result[data-error=true] { background: color-mix(in srgb, var(--magpie-red, #d70015) 12%, var(--card)); color: var(--magpie-red, #d70015); }
#capture-feedback { margin: 9px 0 0; font-size: 11.5px; }
dialog footer { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 18px; border-top: 1px solid var(--line); flex: none; }
dialog footer > span { color: var(--muted); font-size: 11.5px; }
dialog footer .actions { display: flex; gap: 8px; }
dialog footer { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 18px; border-top: 1px solid var(--line); flex: none; }
dialog footer > span { flex: 1 1 180px; min-width: 0; overflow-wrap: anywhere; color: var(--muted); font-size: 11.5px; }
dialog footer .actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px; min-width: 0; margin-left: auto; }
.brand { flex: none; }
@media (max-width: 620px) {
.connection-summary { grid-template-columns: 1fr; }
+33
View File
@@ -0,0 +1,33 @@
// Shared by the gateway hook and the sandboxed settings page. This classic
// script validates explicit settings; the hook resolves environment fallback.
// Keep the global available for later importers: ES modules are cached.
globalThis.__nowledgeMemValidateOptions = (raw = {}) => {
const fail = () => { throw new Error('invalidOption'); };
const text = (name) => {
const v = raw[name];
if (v === undefined || v === null || v === '') return undefined;
if (typeof v !== 'string' || !v.trim()) fail();
return v;
};
for (const name of ['spaceId','agentId','hostAgentId']) text(name);
const skip = raw.skipAgents;
if (skip != null && typeof skip !== 'string' && (!Array.isArray(skip) || skip.some((name) => typeof name !== 'string'))) fail();
for (const name of ['recall','contextBundle','capture','recallRemote','captureRemote','captureTools','captureCindy'])
if (raw[name] !== undefined && typeof raw[name] !== 'boolean') fail();
for (const [name,fallback,min,max] of [['maxMemories',5,1,20],['maxBytes',6000,512,32768],['requestTimeoutMs',1500,50,5000],['recallBackoffMs',30000,100,300000]]) {
const n = raw[name] ?? fallback;
if (!Number.isInteger(n) || n < min || n > max) fail();
}
if (raw.captureFilter !== undefined && raw.captureFilter !== 'off' && raw.captureFilter !== 'human') fail();
const endpoint = text('serverUrl');
if (endpoint) {
let u; try { u = new URL(endpoint); } catch { throw new Error('invalidUrl'); }
const local = ['localhost','127.0.0.1','[::1]'].includes(u.hostname);
if (!['http:','https:'].includes(u.protocol) || u.username || u.password || u.search || u.hash || (u.protocol === 'http:' && !local && raw.allowInsecureHttp !== true)) throw new Error('invalidUrl');
}
const env = text('apiKeyEnv') ?? 'NMEM_API_KEY';
if (!/^NMEM_[A-Za-z0-9_]+$/.test(env)) fail();
const secret = text('apiKey');
const key = secret?.replace(/^Bearer\s+/i,'').trim();
if (key && /[\s\u0000-\u001f\u007f]/.test(key)) throw new Error('invalidKey');
};