From 2b2ee49dedaa0cc6f2cc939fe3dadfe470888137 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 23:33:14 +0800 Subject: [PATCH] gui: the Library's Memory tab MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tab after Instructions lists what the agents remember, in use, to review (what an agent only guessed) and archived, pinned first then newest; searches it, narrows it by where it applies, and adds, edits, pins, keeps, archives and deletes memories (Delete asks with a second click). Kind and scope are picked from the app's menu, never a + function menuButton(text, cls, onclick) { + const b = el("button", "sess-pick lib-menu " + cls); + b.type = "button"; + b.setAttribute("aria-haspopup", "menu"); + b.append(el("span", "", text), svg(CHEV, 11, 1.6)); + b.onclick = (e) => { e.stopPropagation(); onclick(e); }; + return b; + } + const memTags = (s) => s.split(/[,,]/).map((x) => x.trim()).filter(Boolean); + function openMemory(m) { + memRemoving = null; + if (!m) { memOpen = "new"; memDraft = { text: "", why: "", tags: "", kind: "preference", scope: memScope || "global" }; return; } + memOpen = m.id; + memDraft = { text: m.text, why: m.why || "", tags: (m.tags || []).join(", "), kind: m.kind, scope: m.scope }; + } + async function saveMemory() { + if (!memDraft || !memDraft.text.trim()) return; + const isNew = memOpen === "new"; + const body = { text: memDraft.text.trim(), why: memDraft.why.trim(), tags: memTags(memDraft.tags), kind: memDraft.kind, scope: memDraft.scope }; + if (!isNew) body.id = memOpen; + if (await memChange("memory", body, isNew ? t("Remembered") : t("Saved"))) { memOpen = null; memDraft = null; render(); } + } + // every scope a memory is kept in, and the places one can be put + function memScopes(withAgents) { + const out = ["global"]; + for (const k of Object.keys(mem.projects || {})) out.push("project:" + k); + for (const m of mem.memories) if (!out.includes(m.scope) && (withAgents || !m.scope.startsWith("agent:"))) out.push(m.scope); + if (withAgents) for (const a of shownAgents()) if (!out.includes("agent:" + a.id.split("@")[0])) out.push("agent:" + a.id.split("@")[0]); + return out; + } + function renderMemory(body) { + body.append(intro(t("What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it."))); + if (!mem) { + loadMemory(); + body.append(skeleton("memory").lastChild); + return; + } + const card = el("div", "list lib-list lib-memcard"); + const row = el("div", "row lib-row"); + const who = el("div", "who"); + who.append(el("div", "name", t("In the agents' instructions"))); + who.append(el("div", "sub", mem.agents.length ? mem.agents.map(nameOf).join(", ") : t("No agent is switched on under Instructions"))); + const sw = toggle(mem.digest, t("In the agents' instructions"), (on) => memChange("memory/digest", { on }, on ? t("The agents read the memories' summary") : t("The memories' summary is taken out of the agents' instructions"))); + row.append(glyph(GLYPH.doc), who, sw); + card.append(row); + if (!lib.servers.some((s) => s.name === "magpie-memory")) { + const r = el("div", "row lib-row lib-memtools"); + const w = el("div", "who"); + w.append(el("div", "name", "Magpie Memory"), el("div", "sub", t("Add it for agents to search and save memories"))); + r.append(glyph(GLYPH.search), w, button(t("Add"), "action", () => change("market/server", { id: "magpie-memory", values: {} }, t("{name} is in the library now", { name: "Magpie Memory" })))); + card.append(r); + } + body.append(card); + + const all = mem.memories; + const count = (st) => all.filter((m) => st === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === st).length; + const bar = el("div", "lib-membar"); + const q = input(memQ, t("Search memories")); + q.type = "search"; + q.className = "lib-memq"; + q.dataset.lib = "memq"; + q.oninput = () => { memQ = q.value; render(); }; + q.onkeydown = (e) => e.stopPropagation(); + const sugg = count("candidate"); + const st = segs([ + ["active", t("In use") + (count("active") ? " · " + count("active") : "")], + ...(sugg || memStatus === "candidate" ? [["candidate", t("To review") + (sugg ? " · " + sugg : "")]] : []), + ["archived", t("Archived") + (count("archived") ? " · " + count("archived") : "")], + ], memStatus, (v) => { memStatus = v; memOpen = null; render(); }); + st.classList.add("lib-memstatus"); + const sc = menuButton(memScope ? scopeName(memScope) : t("All"), "lib-memscope", () => openProtoMenu(sc, [{ v: "", name: t("Everywhere and every project"), literalName: true, note: "" }, ...memScopes(true).filter((s) => all.some((m) => m.scope === s)).map((s) => ({ v: s, name: scopeName(s), literalName: true, note: "" }))], memScope, (v) => { memScope = v; render(); }, "Where it applies")); + bar.append(q, sc, st, el("span", "grow"), button("+ " + t("Add"), "action lib-memadd", () => { openMemory(null); render(); })); + body.append(bar); + + const words = memQ.trim().toLowerCase().split(/\s+/).filter(Boolean); + const shown = all.filter((m) => (memStatus === "archived" ? m.status === "archived" || m.status === "superseded" : m.status === memStatus) + && (!memScope || m.scope === memScope) + && words.every((w) => [m.text, m.why || "", ...(m.tags || []), kindName(m.kind), scopeName(m.scope)].join(" ").toLowerCase().includes(w))) + .sort((a, b) => (!!b.pinned - !!a.pinned) || (b.updated > a.updated ? 1 : b.updated < a.updated ? -1 : 0)); + const list = el("div", "list lib-list lib-mems"); + if (memOpen === "new") list.append(memDetail(null)); + for (const m of shown) list.append(...memRow(m)); + if (!shown.length && memOpen !== "new") { + list.append(el("div", "lib-none", words.length || memScope ? t("No memory matches.") + : memStatus === "candidate" ? t("Nothing to review.") + : memStatus === "archived" ? t("Nothing archived.") + : t("Nothing remembered yet. Tell an agent “remember that…”, or add one here."))); + } + body.append(list); + } + function memRow(m) { + const isOpen = memOpen === m.id; + const row = el("div", "row lib-row click lib-mem" + (isOpen ? " open" : "")); + row.dataset.id = m.id; + const who = el("div", "who"); + who.append(el("div", "name", m.text)); + const sub = [scopeName(m.scope), ...(m.tags || []).map((x) => "#" + x)]; + const from = m.origin === "agent" || m.origin === "inferred" ? (m.sources || []).find((s) => s.agent)?.agent : ""; + if (from) sub.push(t("from {agent}", { agent: nameOf(from) })); + who.append(el("div", "sub", sub.join(" · "))); + const tags = el("div", "lib-tags"); + if (m.pinned) tags.append(tag(t("Pinned"), "", t("Given to the agents first"))); + tags.append(tag(kindName(m.kind))); + const chev = el("span", "chev"); + chev.append(svg(CHEV_R, 11, 1.7)); + row.append(who, tags, chev); + row.onclick = () => { if (isOpen) { memOpen = null; memDraft = null; } else openMemory(m); render(); }; + return isOpen ? [row, memDetail(m)] : [row]; + } + function memDetail(m) { + const d = memDraft; + const det = el("div", "lib-detail lib-memdetail"); + const ta = el("textarea", "lib-text small"); + ta.dataset.lib = "mem:" + (m ? m.id : "new"); + ta.value = d.text; + ta.placeholder = t("What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo"); + ta.oninput = () => { d.text = ta.value; }; + ta.onkeydown = (e) => { e.stopPropagation(); if ((e.metaKey || e.ctrlKey) && (e.key === "s" || e.key === "Enter")) { e.preventDefault(); saveMemory(); } }; + autosize(ta, 52); + if (!m) queueMicrotask(() => ta.focus()); + const pick = (label, value, opts, head, set) => { + const b = menuButton(label(value), "lib-mempick", () => openProtoMenu(b, opts.map((v) => ({ v, name: label(v), literalName: true, note: "" })), value, (v) => { set(v); render(); }, head)); + return b; + }; + const line = el("div", "lib-memline"); + line.append(pick(kindName, d.kind, MEM_KINDS, "Kind", (v) => { d.kind = v; }), pick(scopeName, d.scope, memScopes(true), "Where it applies", (v) => { d.scope = v; })); + const tg = input(d.tags, t("Tags, separated by commas")); + tg.className = "lib-memtags grow"; + tg.dataset.lib = "memtags:" + (m ? m.id : "new"); + tg.oninput = () => { d.tags = tg.value; }; + tg.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Enter") saveMemory(); }; + line.append(tg); + const why = input(d.why, t("Why (optional)")); + why.className = "lib-memwhy"; + why.dataset.lib = "memwhy:" + (m ? m.id : "new"); + why.oninput = () => { d.why = why.value; }; + why.onkeydown = tg.onkeydown; + det.append(ta, line, why); + const acts = el("div", "lib-acts"); + if (m) { + acts.append(button(m.pinned ? t("Unpin") : t("Pin"), "action", () => memChange("memory", { id: m.id, pinned: !m.pinned }))); + if (m.status === "candidate") acts.append(button(t("Keep"), "action", () => memChange("memory", { id: m.id, status: "active" }, t("Kept")))); + else if (m.status === "active") acts.append(button(t("Archive"), "action", () => { memOpen = null; memChange("memory", { id: m.id, status: "archived" }, t("Archived")); })); + else acts.append(button(t("Restore"), "action", () => { memOpen = null; memChange("memory", { id: m.id, status: "active" }, t("Restored")); })); + const sure = memRemoving === m.id; + acts.append(button(sure ? t("Delete for good") : t("Delete"), sure ? "primary danger-fill" : "action danger", () => { + if (!sure) { memRemoving = m.id; render(); return; } + memRemoving = null; memOpen = null; memDraft = null; + memChange("memory/remove", { ids: [m.id] }, t("Deleted")); + })); + } + acts.append(el("span", "grow"), button(t("Cancel"), "", () => { memOpen = null; memDraft = null; memRemoving = null; render(); }), button(m ? t("Save") : t("Remember"), "primary", saveMemory)); + det.append(acts); + det.onclick = (e) => e.stopPropagation(); + return det; + } + // ---------- RTK ---------- // RTK (rtk-ai.app) cuts down what the shell commands an agent runs print, @@ -1475,6 +1702,7 @@ magpie.plugin("library", (ctx) => { } async function discard(force = false) { if (force !== true && dirty() && !(await confirmDiscard())) return; + if (force === true) { memOpen = null; memDraft = null; } for (const k of Object.keys(texts)) delete texts[k]; for (const k of Object.keys(extras)) delete extras[k]; render(); @@ -6968,7 +7196,9 @@ magpie.plugin("library", (ctx) => { // unsaved text, or a lookup under way. // What changed there changes what the market calls added, too: take asks it again. async function quietLoad() { - if (page.hidden || modal || dirty() || probing) return; + if (page.hidden || modal || dirty() || memDirty() || probing) return; + // what agents saved meanwhile + if (tab === "memory" && mem) loadMemory(); await load(true); } const shelf = () => JSON.stringify([lib?.servers?.map((x) => x.name), lib?.skills?.map((x) => x.name)]); @@ -6988,7 +7218,7 @@ magpie.plugin("library", (ctx) => { if (!confirmationPending && modal && e.key === "Escape") { e.preventDefault(); e.stopImmediatePropagation(); closeLibModal(); } }, true); // leaving the page with the shared text not saved asks first - window.addEventListener("beforeunload", (e) => { if (lib && dirty()) e.preventDefault(); }); + window.addEventListener("beforeunload", (e) => { if (lib && (dirty() || memDirty())) e.preventDefault(); }); page.addEventListener("scroll", () => page.querySelector(".lib-head")?.classList.toggle("stuck", page.scrollTop > 0), { passive: true }); document.addEventListener("visibilitychange", () => { if (!document.hidden) quietLoad(); }); window.addEventListener("focus", quietLoad); @@ -7016,7 +7246,7 @@ magpie.plugin("library", (ctx) => { redraw: () => { if (lib) render(); }, // the reader leaving the page: its dialog closed, and what isn't saved close: () => { if (modal) closeLibModal(true); else closeModal(); }, - dirty: () => !!lib && dirty(), + dirty: () => !!lib && (dirty() || memDirty()), discard: () => discard(true), }); }); diff --git a/internal/gui/assets/plugins/library/i18n.js b/internal/gui/assets/plugins/library/i18n.js index 31b074f70..07e512d15 100644 --- a/internal/gui/assets/plugins/library/i18n.js +++ b/internal/gui/assets/plugins/library/i18n.js @@ -2,6 +2,29 @@ // kernel adds them to i18n.js's (magpie.strings). magpie.strings({ zh: { + "What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Agent 们对你和你的项目的了解,所有 Agent 共用。它们通过 Magpie Memory 搜索和保存记忆;在「指令」中开启的 Agent 还会读到记忆摘要。", + "In the agents' instructions": "写入 Agent 的指令", + "No agent is switched on under Instructions": "「指令」中没有开启任何 Agent", + "The agents read the memories' summary": "Agent 现在会读到记忆摘要", + "The memories' summary is taken out of the agents' instructions": "已从 Agent 的指令中移除记忆摘要", + "Add it for agents to search and save memories": "添加后,Agent 才能搜索和保存记忆", + "Search memories": "搜索记忆", + "To review": "待确认", + "Everywhere and every project": "全部范围和项目", + "Where it applies": "适用范围", + "Only {agent}": "仅 {agent}", + "About you": "关于你", + "How-to": "做法", + "No memory matches.": "没有匹配的记忆。", + "Nothing to review.": "没有待确认的记忆。", + "Nothing archived.": "没有归档的记忆。", + "Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "还没有记忆。对 Agent 说「记住……」,或在这里添加。", + "Given to the agents first": "优先提供给 Agent", + "What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "用一句话写下要记住的内容,例如:这个仓库用 pnpm,不用 npm", + "Tags, separated by commas": "标签,用逗号分隔", + "Why (optional)": "原因(可选)", + "Unpin": "取消置顶", + "Delete for good": "永久删除", "Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agent 会自己直接调用它,与 magpie 的联网搜索各管各的,magpie 的联网搜索不会用到它。", "As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "若在 设置 → 模型 → 联网搜索 中把 {name} 添加为搜索 API,它会为所有模型搜索,无需添加服务器。", "Skill router": "Skill 路由", @@ -845,6 +868,29 @@ magpie.strings({ "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已复制到 {agent}:Pi 下次启动或 /reload 时加载它", }, "zh-TW": { + "What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Agent 們對你和你的專案的了解,所有 Agent 共用。它們透過 Magpie Memory 搜尋和儲存記憶;在「指令」中開啟的 Agent 還會讀到記憶摘要。", + "In the agents' instructions": "寫入 Agent 的指令", + "No agent is switched on under Instructions": "「指令」中沒有開啟任何 Agent", + "The agents read the memories' summary": "Agent 現在會讀到記憶摘要", + "The memories' summary is taken out of the agents' instructions": "已從 Agent 的指令中移除記憶摘要", + "Add it for agents to search and save memories": "新增後,Agent 才能搜尋和儲存記憶", + "Search memories": "搜尋記憶", + "To review": "待確認", + "Everywhere and every project": "全部範圍和專案", + "Where it applies": "適用範圍", + "Only {agent}": "僅 {agent}", + "About you": "關於你", + "How-to": "做法", + "No memory matches.": "沒有符合的記憶。", + "Nothing to review.": "沒有待確認的記憶。", + "Nothing archived.": "沒有封存的記憶。", + "Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "還沒有記憶。對 Agent 說「記住……」,或在這裡新增。", + "Given to the agents first": "優先提供給 Agent", + "What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "用一句話寫下要記住的內容,例如:這個儲存庫用 pnpm,不用 npm", + "Tags, separated by commas": "標籤,用逗號分隔", + "Why (optional)": "原因(選填)", + "Unpin": "取消置頂", + "Delete for good": "永久刪除", "Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agent 會自己直接呼叫它,與 magpie 的聯網搜尋各自獨立,magpie 的聯網搜尋不會用到它。", "As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "若在 設定 → 模型 → 聯網搜尋 中把 {name} 新增為搜尋 API,它會為所有模型搜尋,無需新增伺服器。", "Skill router": "Skill 路由", @@ -1688,6 +1734,29 @@ magpie.strings({ "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} 已複製到 {agent}:Pi 下次啟動或 /reload 時載入它", }, ja: { + "What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "エージェントが知っているあなたとプロジェクトのこと。すべてのエージェントで共有されます。エージェントは Magpie Memory で検索・保存し、「指示」でオンにしたエージェントはその要約も読みます。", + "In the agents' instructions": "エージェントの指示に含める", + "No agent is switched on under Instructions": "「指示」でオンのエージェントはありません", + "The agents read the memories' summary": "エージェントが記憶の要約を読むようになりました", + "The memories' summary is taken out of the agents' instructions": "記憶の要約をエージェントの指示から外しました", + "Add it for agents to search and save memories": "追加すると、エージェントが記憶を検索・保存できます", + "Search memories": "記憶を検索", + "To review": "確認待ち", + "Everywhere and every project": "すべての範囲とプロジェクト", + "Where it applies": "適用範囲", + "Only {agent}": "{agent} のみ", + "About you": "あなたについて", + "How-to": "手順", + "No memory matches.": "一致する記憶はありません。", + "Nothing to review.": "確認待ちの記憶はありません。", + "Nothing archived.": "アーカイブ済みの記憶はありません。", + "Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "まだ記憶はありません。エージェントに「…を覚えて」と伝えるか、ここで追加してください。", + "Given to the agents first": "エージェントに優先して渡されます", + "What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "覚えておくことを一文で — 例:このリポジトリでは npm ではなく pnpm を使う", + "Tags, separated by commas": "タグ(カンマ区切り)", + "Why (optional)": "理由(任意)", + "Unpin": "ピン留めを外す", + "Delete for good": "完全に削除", "Agents call it themselves, beside magpie's web search, which doesn't use it.": "エージェントが自分で直接呼び出します。magpie のウェブ検索とは別のもので、magpie のウェブ検索はこれを使いません。", "As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "設定 → モデル → ウェブ検索 で {name} を検索 API として追加すると、すべてのモデルのために検索し、サーバーを追加する必要はありません。", "Skill router": "スキルルーター", @@ -2531,6 +2600,29 @@ magpie.strings({ "{name} is copied to {agent}: Pi loads it when it next starts, or at /reload": "{name} を {agent} にコピーしました。Pi は次回起動時か /reload で読み込みます", }, de: { + "What your agents know about you and your projects, shared by all of them. They search it and save to it with Magpie Memory, and the agents switched on under Instructions read a summary of it.": "Was Ihre Agenten über Sie und Ihre Projekte wissen, von allen geteilt. Sie durchsuchen und speichern es mit Magpie Memory, und die unter Anweisungen eingeschalteten Agenten lesen eine Zusammenfassung davon.", + "In the agents' instructions": "In den Anweisungen der Agenten", + "No agent is switched on under Instructions": "Unter Anweisungen ist kein Agent eingeschaltet", + "The agents read the memories' summary": "Die Agenten lesen jetzt die Zusammenfassung der Erinnerungen", + "The memories' summary is taken out of the agents' instructions": "Die Zusammenfassung wurde aus den Anweisungen der Agenten entfernt", + "Add it for agents to search and save memories": "Hinzufügen, damit Agenten Erinnerungen suchen und speichern können", + "Search memories": "Erinnerungen durchsuchen", + "To review": "Zu prüfen", + "Everywhere and every project": "Überall und jedes Projekt", + "Where it applies": "Wo es gilt", + "Only {agent}": "Nur {agent}", + "About you": "Über Sie", + "How-to": "Anleitung", + "No memory matches.": "Keine passende Erinnerung.", + "Nothing to review.": "Nichts zu prüfen.", + "Nothing archived.": "Nichts archiviert.", + "Nothing remembered yet. Tell an agent “remember that…”, or add one here.": "Noch keine Erinnerungen. Sagen Sie einem Agenten „merk dir…“, oder fügen Sie hier eine hinzu.", + "Given to the agents first": "Wird den Agenten zuerst gegeben", + "What to remember, in a sentence — e.g. Use pnpm, never npm, in this repo": "Was gemerkt werden soll, in einem Satz – z. B. In diesem Repo pnpm statt npm verwenden", + "Tags, separated by commas": "Tags, durch Kommas getrennt", + "Why (optional)": "Warum (optional)", + "Unpin": "Lösen", + "Delete for good": "Endgültig löschen", "Agents call it themselves, beside magpie's web search, which doesn't use it.": "Agenten rufen ihn selbst auf, neben magpies Websuche, die ihn nicht nutzt.", "As a search API in Settings → Models → Web search, {name} searches for every model, with no server to add.": "Als Such-API unter Einstellungen → Modelle → Websuche sucht {name} für jedes Modell, ohne einen Server hinzuzufügen.", "Skill router": "Skill-Router", diff --git a/internal/gui/assets/plugins/library/library.css b/internal/gui/assets/plugins/library/library.css index b229ebb7f..35b0c5cf1 100644 --- a/internal/gui/assets/plugins/library/library.css +++ b/internal/gui/assets/plugins/library/library.css @@ -861,3 +861,20 @@ body.window .lib-list .lib-row { --lib-indent: 38px; } .lib-pi-head > .lib-path { flex: 0 1 auto; min-width: 0; } .lib-pi-row > .lib-pi-copy { flex: none; } .lib-pi + .lib-pi-head { margin-top: 18px; } + +/* Memory: the digest switch, a search with its filters, and the memories */ +.lib-memcard { margin-bottom: 12px; } +.lib-membar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0 2px 8px; } +.lib-membar .lib-memq { flex: 1 1 180px; min-width: 0; max-width: 320px; height: 28px; } +.lib-membar .lib-menu { height: 28px; max-width: 220px; color: var(--fg); } +.lib-membar .lib-menu > span:first-child, .lib-memline .lib-menu > span:first-child { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lib-mems .lib-mem > .who .name { display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; font-weight: 400; } +.lib-mems .lib-mem.open > .who .name { -webkit-line-clamp: unset; } +.lib-mems .lib-mem > .who .sub { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.lib-memdetail { padding-left: 12px; } +.lib-memline { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; } +.lib-memline .lib-menu { height: 28px; max-width: 220px; color: var(--fg); } +.lib-memline .lib-memtags { flex: 1 1 160px; min-width: 0; height: 28px; } +.lib-memdetail .lib-memwhy { height: 28px; } +input.lib-memq, input.lib-memtags, input.lib-memwhy { padding: 0 9px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font-size: 12.5px; outline: none; box-sizing: border-box; transition: border-color .12s, box-shadow .12s; } +input.lib-memq:focus, input.lib-memtags:focus, input.lib-memwhy:focus { border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 22%, transparent); } diff --git a/internal/gui/library.go b/internal/gui/library.go index 57d79e840..10f87a9b9 100644 --- a/internal/gui/library.go +++ b/internal/gui/library.go @@ -175,6 +175,7 @@ func revealable(v *library.View) []string { func libraryRoutes(mux *http.ServeMux, w Windows) { browserRoutes(mux, w) + memoryRoutes(mux) mux.HandleFunc("GET /api/library", func(rw http.ResponseWriter, r *http.Request) { v, err := libraryRead(nil, r.URL.Query().Get("glance") == "1") if err != nil { diff --git a/internal/gui/memory.go b/internal/gui/memory.go new file mode 100644 index 000000000..08f390672 --- /dev/null +++ b/internal/gui/memory.go @@ -0,0 +1,123 @@ +package gui + +import ( + "encoding/json" + "errors" + "net/http" + + "github.com/yetone/magpie/internal/library" + "github.com/yetone/magpie/internal/memory" +) + +// memoryView is the Library's Memory tab: every memory, newest change +// first, the projects they are kept for, and whether the agents ticked +// for instructions are given the digest. +type memoryView struct { + Memories []*memory.Memory `json:"memories"` + Projects map[string]*memory.Project `json:"projects"` + Digest bool `json:"digest"` + Agents []string `json:"agents"` // ticked for instructions +} + +func readMemory() (*memoryView, error) { + ms, ps, err := memory.All() + if err != nil { + return nil, err + } + on, agents, err := library.MemoryInInstructions() + if err != nil { + return nil, err + } + if ms == nil { + ms = []*memory.Memory{} + } + if ps == nil { + ps = map[string]*memory.Project{} + } + return &memoryView{Memories: ms, Projects: ps, Digest: on, Agents: agents}, nil +} + +// memoryChanged publishes the user's change to the agents' instructions +// and answers with the tab as it is now. A publish that fails is the +// change kept and not yet given out, said beside it. +func memoryChanged(rw http.ResponseWriter) { + _, perr := library.PublishMemory(false) + v, err := readMemory() + if err != nil { + fail(rw, err) + return + } + if perr != nil { + writeJSON(rw, struct { + *memoryView + Problem string `json:"problem"` + }{v, perr.Error()}) + return + } + writeJSON(rw, v) +} + +func memoryRoutes(mux *http.ServeMux) { + mux.HandleFunc("GET /api/memory", func(rw http.ResponseWriter, r *http.Request) { + v, err := readMemory() + if err != nil { + fail(rw, err) + return + } + writeJSON(rw, v) + }) + // a memory added, or one changed by its id: the user's own from then on + mux.HandleFunc("POST /api/memory", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + ID string `json:"id"` + memory.Input + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + var err error + if in.ID != "" { + _, err = memory.Edit(in.ID, in.Input, true) + } else { + _, _, err = memory.Save(in.Input, memory.FromUser, nil, nil) + } + if err != nil { + fail(rw, err) + return + } + memoryChanged(rw) + }) + mux.HandleFunc("POST /api/memory/remove", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + IDs []string `json:"ids"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if len(in.IDs) == 0 { + fail(rw, errors.New("name the memories to remove")) + return + } + if err := memory.Remove(in.IDs...); err != nil { + fail(rw, err) + return + } + memoryChanged(rw) + }) + mux.HandleFunc("POST /api/memory/digest", func(rw http.ResponseWriter, r *http.Request) { + var in struct { + On bool `json:"on"` + } + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { + fail(rw, err) + return + } + if _, err := library.SetMemoryInInstructions(in.On); err != nil { + fail(rw, err) + return + } + memoryChanged(rw) + }) +} diff --git a/internal/gui/tests/library-memory.test.cjs b/internal/gui/tests/library-memory.test.cjs new file mode 100644 index 000000000..e4984cfd1 --- /dev/null +++ b/internal/gui/tests/library-memory.test.cjs @@ -0,0 +1,191 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// The Library's Memory tab (internal/memory, /api/memory): the switch that +// gives the agents ticked for instructions the memories' summary, the +// Magpie Memory server offered while it isn't in the library, the memories +// in use pinned first, a search, the ones an agent only guessed waiting +// under To review, and a memory added, edited through the app's menu (never +// a