Files
plugins/packages/nowledge-mem/page/settings.js
T
yetone debc0f7b53 nowledge-mem 0.1.4: a tailnet HTTP server from the page, and recallRemote/captureRemote opt-ins (#608)
pluoki (on X) runs Mem on a Mac Studio reached over Tailscale. Two limits:

- page/settings.js validUrl() refused any http: URL to a non-loopback host
  whatever allowInsecureHttp said, while mem.mjs honoured it, so
  http://mac-studio.tailnet.ts.net:14242 could only be set by hand in
  Options JSON and the page's Save and Test refused it. The dialog now has
  an "Allow HTTP to another machine" switch (Mem service section, same
  switch-field component as the others; help text: only on a network you
  trust, e.g. Tailscale) that reads and writes allowInsecureHttp, and
  validUrl follows it exactly as mem.mjs does; Test checks the saved
  option. Turning it off removes the option. All five languages (en, zh,
  zh-TW, ja, de) get the new strings; urlHelp and invalidUrl name the
  switch.
- The hook took only origin local / magpie-key. recallRemote and
  captureRemote (default false, typed booleans, in package.json's options
  and the README) let remote and gateway-key requests in, each on its own,
  as powercontext's do: captureRemote saves the conversation but recalls
  nothing, and neither turns capture on. Unlike powercontext's, a missing
  or unknown origin stays out even with both on. powercontext's page has
  no switches for these, so this page doesn't either; its "What is sent"
  text names the options. Sticky blocks were already keyed by origin.

Run (mote, at this tree on origin/main 53e3820):
- HOME=$(mktemp -d) bun test: 4557 pass, 0 fail, 9 skip (live checks).
- bun scripts/check.mjs: ok.
- The page in Playwright 1.62 chromium and webkit, served over local HTTP
  with a stub bridge, in en/zh/zh-TW/ja/de: the tailnet URL is refused
  with the switch off and saved with allowInsecureHttp: true with it on;
  screenshots checked (en webkit, de chromium).
- Broken by hand, each red then green: validUrl ignoring the option, and
  the page never writing it (tailnet page test red); captureRemote
  granting recall, the old local-only line, unknown origins counted as
  remote (new origin test red); both opt-ins on by default (new test plus
  "remote and unknown origins stay out" and the gateway-key test red).
Not tried: a real Mem over a real tailnet, or in the real magpie app; the
hook is driven as magpie's host calls it, and the page through its test
and the Playwright stub.
2026-11-02 02:38:06 +08:00

169 lines
7.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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().
const {languageFor, languageTags, translate} = nowledgeMemI18n;
const $ = (id) => document.getElementById(id);
let language = 'en', busy = false, savedOptions = null, pendingCapture = null;
const t = (key, parameters) => translate(language, key, parameters);
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 result = (key, error = false) => message("result", key, error);
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");
}
// 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);
}
// 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 testService() {
const service = window.magpie?.service;
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 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();
}
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));
}
$("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(); };
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); });
}
magpie.ready.then(async () => {
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;
}
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 () => {
if (busy || !savedOptions) return;
const enabled = $("summary-capture").checked;
pendingCapture = enabled;
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");
} 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);
} finally {
pendingCapture = null; summary(); busy = false;
$("summary-capture").disabled = false; $("configure").disabled = false;
}
};