Files
memoryweave/plugins/obsidian/src/MemoryView.ts
T
xiaowei 2a350cf781 fix(distill): max_tokens 800→1200 — Agnes推理token预算不足
Agnes 2.0-flash是推理模型,推理token占大量预算。
800仍不够→JSON截断(parse error: unexpected end of JSON input)。
1200确保推理+正文都够用。
2026-08-20 01:13:06 +08:00

349 lines
18 KiB
TypeScript
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.
import { ItemView, WorkspaceLeaf, Modal, TFile } from "obsidian";
import {
fetchMemories,
fetchDistillStatus,
fetchDistillQuota,
fetchCategories,
writeMemory,
getRuntimeNamespace,
type MemoryRecord,
} from "./api";
export const MEMORY_VIEW_TYPE = "zhiyi-memory-view";
const PAGE_SIZE = 30;
export class MemoryView extends ItemView {
private memories: MemoryRecord[] = [];
private currentPage = 0;
private totalMemories = 0;
private status_interval: number | null = null;
private categories: string[] = [];
private activeCategory = "";
private expandedId: string | null = null;
constructor(leaf: WorkspaceLeaf) {
super(leaf);
}
getViewType() { return MEMORY_VIEW_TYPE; }
getDisplayText() { return "织忆记忆"; }
async onOpen() {
this.render();
this.startStatusPoll();
}
async onClose() {
if (this.status_interval !== null) {
(window as unknown as { clearInterval: (n: number) => void }).clearInterval(this.status_interval);
}
}
private startStatusPoll() {
const id = (window as unknown as { setInterval: (fn: () => void, ms: number) => number }).setInterval(
() => this.renderDistillBanner(),
30000
);
this.status_interval = id;
}
private async renderDistillBanner() {
const banner = this.container.querySelector(".zhiyi-distill-banner") as HTMLElement;
if (!banner) return;
try {
const [status, quota] = await Promise.all([fetchDistillStatus(), fetchDistillQuota()]);
if (status.queue_len > 0) {
banner.innerHTML = `<span class="zhiyi-warn">⚠️ 蒸馏队列: ${status.queue_len} 条</span>`;
banner.style.display = "block";
} else {
banner.style.display = "none";
}
} catch (_) {}
}
private async loadCategories() {
try {
this.categories = await fetchCategories();
} catch {
this.categories = [];
}
}
async render() {
this.container.empty();
this.container.createEl("style", { text: `
.zhiyi-memory-view { height: 100%; display: flex; flex-direction: column; font-size: 13px; }
.zhiyi-header { padding: 8px 12px 4px; border-bottom: 1px solid var(--background-modifier-border); }
.zhiyi-header-row1 { display: flex; align-items: center; gap: 6px; }
.zhiyi-header h1 { font-size: 14px; font-weight: 600; margin: 0; flex: 1; }
.zhiyi-stats { color: var(--text-muted); font-size: 11px; margin: 3px 0 0; }
.zhiyi-toolbar { display: flex; gap: 4px; padding: 4px 12px; border-bottom: 1px solid var(--background-modifier-border); flex-wrap: wrap; align-items: center; }
.zhiyi-toolbar select { background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal); font-size: 11px; padding: 2px 4px; max-width: 120px; }
.zhiyi-filter-chip { padding: 2px 8px; border-radius: 10px; font-size: 10px; border: 1px solid var(--background-modifier-border); background: var(--background-secondary); color: var(--text-muted); cursor: pointer; white-space: nowrap; }
.zhiyi-filter-chip:hover { background: var(--background-modifier-hover); }
.zhiyi-filter-chip.active { background: var(--text-accent); color: var(--bg-on-accent, #fff); border-color: var(--text-accent); }
.zhiyi-btn-icon { padding: 2px 6px; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; cursor: pointer; color: var(--text-muted); font-size: 11px; }
.zhiyi-btn-icon:hover { background: var(--background-modifier-hover); color: var(--text-normal); }
.zhiyi-distill-banner { display: none; background: #c44; color: white; padding: 4px 12px; font-size: 12px; font-weight: 600; cursor: pointer; }
.zhiyi-body { flex: 1; overflow-y: auto; }
.zhiyi-item { padding: 8px 12px; border-bottom: 1px solid var(--background-modifier-border); cursor: pointer; }
.zhiyi-item:hover { background: var(--background-modifier-hover); }
.zhiyi-item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 3px; }
.zhiyi-item-cat { font-size: 10px; color: var(--text-muted); background: var(--background-secondary); padding: 1px 5px; border-radius: 2px; }
.zhiyi-item-right { display: flex; align-items: center; gap: 6px; }
.zhiyi-quality-bar { width: 40px; height: 4px; background: var(--background-modifier-border); border-radius: 2px; overflow: hidden; }
.zhiyi-quality-fill { height: 100%; border-radius: 2px; }
.zhiyi-item-content { font-size: 12px; color: var(--text-normal); line-height: 1.4; }
.zhiyi-item-footer { display: flex; justify-content: space-between; align-items: center; margin-top: 3px; }
.zhiyi-item-time { font-size: 10px; color: var(--text-muted); }
.zhiyi-item-meta { font-size: 10px; color: var(--text-faint); font-family: monospace; }
.zhiyi-item-actions { display: flex; gap: 6px; opacity: 0; transition: opacity 0.15s; }
.zhiyi-item:hover .zhiyi-item-actions { opacity: 1; }
.zhiyi-action-btn { font-size: 10px; color: var(--text-accent); cursor: pointer; background: none; border: none; padding: 0; }
.zhiyi-action-btn:hover { text-decoration: underline; }
.zhiyi-pagination { display: flex; gap: 6px; padding: 8px 12px; border-top: 1px solid var(--background-modifier-border); align-items: center; }
.zhiyi-pagination button { padding: 4px 10px; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; cursor: pointer; font-size: 11px; }
.zhiyi-pagination button:disabled { opacity: 0.4; cursor: not-allowed; }
.zhiyi-pagination .page-info { flex: 1; text-align: center; font-size: 11px; color: var(--text-muted); }
.zhiyi-loading { padding: 30px; text-align: center; color: var(--text-muted); }
.zhiyi-empty { padding: 30px; text-align: center; color: var(--text-muted); }
/* Modal */
.zhiyi-detail-modal { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 1000; display: flex; align-items: center; justify-content: center; }
.zhiyi-detail-box { background: var(--modal-background); border: 1px solid var(--background-modifier-border); border-radius: 8px; max-width: 600px; width: 90%; max-height: 80vh; display: flex; flex-direction: column; box-shadow: 0 8px 32px rgba(0,0,0,0.4); }
.zhiyi-detail-header { display: flex; justify-content: space-between; align-items: center; padding: 12px 16px; border-bottom: 1px solid var(--background-modifier-border); }
.zhiyi-detail-header h3 { margin: 0; font-size: 14px; font-weight: 600; }
.zhiyi-detail-close { background: none; border: none; cursor: pointer; color: var(--text-muted); font-size: 18px; padding: 0; }
.zhiyi-detail-body { flex: 1; overflow-y: auto; padding: 16px; }
.zhiyi-detail-meta { display: flex; gap: 12px; margin-bottom: 12px; flex-wrap: wrap; }
.zhiyi-detail-meta span { font-size: 11px; color: var(--text-muted); background: var(--background-secondary); padding: 2px 6px; border-radius: 3px; }
.zhiyi-detail-content { font-size: 13px; line-height: 1.6; color: var(--text-normal); white-space: pre-wrap; word-break: break-word; }
.zhiyi-detail-footer { padding: 10px 16px; border-top: 1px solid var(--background-modifier-border); display: flex; gap: 8px; justify-content: flex-end; }
.zhiyi-detail-footer button { padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 12px; }
/* Write dialog */
.zhiyi-write-section { padding: 8px 12px; border-bottom: 1px solid var(--background-modifier-border); }
.zhiyi-write-input { width: 100%; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal); padding: 6px 8px; font-size: 12px; resize: vertical; min-height: 50px; box-sizing: border-box; }
.zhiyi-write-input:focus { outline: none; border-color: var(--text-accent); }
.zhiyi-write-meta { display: flex; gap: 6px; margin-top: 4px; align-items: center; }
.zhiyi-write-meta select { background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; color: var(--text-normal); font-size: 11px; padding: 2px 4px; }
.zhiyi-write-meta button { padding: 3px 10px; background: var(--text-accent); color: var(--bg-on-accent, #fff); border: none; border-radius: 4px; cursor: pointer; font-size: 11px; }
.zhiyi-write-meta button:disabled { opacity: 0.5; cursor: not-allowed; }
.zhiyi-write-hint { font-size: 10px; color: var(--text-faint); margin-left: auto; }
` });
const root = this.container.createEl("div", { cls: "zhiyi-memory-view" });
root.append(
this.container.createEl("div", { cls: "zhiyi-distill-banner" }),
this.container.createEl("div", { cls: "zhiyi-header" }).append(
Object.assign(this.container.createEl("div", { cls: "zhiyi-header-row1" }), {
innerHTML: `<h1>🧠 织忆记忆</h1>`
}) as unknown as Node,
this.container.createEl("p", { cls: "zhiyi-stats", text: "加载中..." })
),
this.container.createEl("div", { cls: "zhiyi-toolbar" }),
this.container.createEl("div", { cls: "zhiyi-body" }),
this.container.createEl("div", { cls: "zhiyi-pagination" })
);
await this.loadCategories();
await this.loadMemories();
await this.renderDistillBanner();
}
private async loadMemories() {
const body = this.container.querySelector(".zhiyi-body") as HTMLElement;
const stats = this.container.querySelector(".zhiyi-stats") as HTMLElement;
const toolbar = this.container.querySelector(".zhiyi-toolbar") as HTMLElement;
body.innerHTML = '<div class="zhiyi-loading">加载中…</div>';
try {
const ns = getRuntimeNamespace();
const data = await fetchMemories({
namespace: ns,
limit: PAGE_SIZE,
offset: this.currentPage * PAGE_SIZE,
category: this.activeCategory || undefined,
});
this.memories = data.memories || [];
this.totalMemories = data.total || 0;
stats.setText(`${this.totalMemories} 条记忆 · 第 ${this.currentPage + 1} 页 · ${ns}`);
this.renderToolbar(toolbar);
this.renderList();
} catch (e) {
body.innerHTML = `<div class="zhiyi-empty">加载失败: ${(e as Error).message}</div>`;
}
}
private renderToolbar(toolbar: HTMLElement) {
toolbar.empty();
// Namespace 切换
const nsSelect = toolbar.createEl("select");
nsSelect.createEl("option", { value: "hermes-main", text: "hermes-main" });
nsSelect.createEl("option", { value: "openclaw", text: "openclaw" });
nsSelect.value = getRuntimeNamespace();
nsSelect.onchange = () => {
const val = nsSelect.value;
(window as unknown as Record<string, string>)["zhiyi_namespace"] = val;
this.currentPage = 0;
this.loadMemories();
};
// 分类筛选 chip
const allChip = toolbar.createEl("span", { cls: "zhiyi-filter-chip" + (this.activeCategory === "" ? " active" : ""), text: "全部" });
allChip.onclick = () => { this.activeCategory = ""; this.currentPage = 0; this.loadMemories(); };
for (const cat of this.categories.slice(0, 8)) {
const chip = toolbar.createEl("span", {
cls: "zhiyi-filter-chip" + (this.activeCategory === cat ? " active" : ""),
text: cat,
});
chip.onclick = () => { this.activeCategory = cat; this.currentPage = 0; this.loadMemories(); };
}
// 刷新
const refreshBtn = toolbar.createEl("button", { cls: "zhiyi-btn-icon", text: "↻ 刷新" });
refreshBtn.onclick = () => { this.currentPage = 0; this.loadMemories(); };
// 写记忆
const writeBtn = toolbar.createEl("button", { cls: "zhiyi-btn-icon", text: "+ 写记忆" });
writeBtn.onclick = () => this.showWriteSection(toolbar);
}
private showWriteSection(toolbar: HTMLElement) {
// 避免重复
const existing = toolbar.querySelector(".zhiyi-write-section");
if (existing) { existing.remove(); return; }
const section = toolbar.createEl("div", { cls: "zhiyi-write-section" });
const textarea = section.createEl("textarea", {
cls: "zhiyi-write-input",
attr: { placeholder: "输入记忆内容,按 Enter 或点击「写入」提交…" }
}) as HTMLTextAreaElement;
const metaRow = section.createEl("div", { cls: "zhiyi-write-meta" });
const catSel = metaRow.createEl("select");
catSel.createEl("option", { value: "normal", text: "分类" });
for (const c of this.categories) {
catSel.createEl("option", { value: c, text: c });
}
const hint = metaRow.createEl("span", { cls: "zhiyi-write-hint", text: "Enter 写入 · Esc 取消" });
const submitBtn = metaRow.createEl("button", { text: "写入" });
const doWrite = async () => {
const content = textarea.value.trim();
if (!content) return;
submitBtn.setAttr("disabled", "true");
try {
await writeMemory(content, catSel.value || "normal");
textarea.value = "";
section.remove();
this.currentPage = 0;
await this.loadCategories();
await this.loadMemories();
} catch (e) {
hint.setText(`失败: ${(e as Error).message}`);
}
submitBtn.removeAttr("disabled");
};
submitBtn.onclick = doWrite;
textarea.onkeydown = (e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); doWrite(); }
if (e.key === "Escape") section.remove();
};
textarea.focus();
}
private renderList() {
const body = this.container.querySelector(".zhiyi-body") as HTMLElement;
const pag = this.container.querySelector(".zhiyi-pagination") as HTMLElement;
body.empty();
if (this.memories.length === 0) {
body.createEl("div", { cls: "zhiyi-empty", text: "暂无记忆" });
}
for (const mem of this.memories) {
const item = body.createEl("div", { cls: "zhiyi-item" });
const header = item.createEl("div", { cls: "zhiyi-item-header" });
header.createEl("span", { cls: "zhiyi-item-cat", text: mem.category || "normal" });
const right = header.createEl("div", { cls: "zhiyi-item-right" });
// 质量分条
const q = mem.quality_score ?? 0;
const qColor = q > 0.7 ? "#34c759" : q > 0.4 ? "#f6c945" : "#ff6b6b";
const barWrap = right.createEl("div", { cls: "zhiyi-quality-bar" });
const barFill = barWrap.createEl("div", { cls: "zhiyi-quality-fill" });
barFill.style.width = `${Math.round(q * 100)}%`;
barFill.style.background = qColor;
right.createEl("span", { cls: "zhiyi-item-score", text: (q * 100).toFixed(0) + "%" });
item.createEl("div", { cls: "zhiyi-item-content", text: this.truncate(mem.content, 160) });
const footer = item.createEl("div", { cls: "zhiyi-item-footer" });
footer.createEl("span", { cls: "zhiyi-item-time", text: this.formatTime(mem.created_at) });
const meta = footer.createEl("span", { cls: "zhiyi-item-meta", text: mem.id.slice(0, 16) });
const actions = footer.createEl("div", { cls: "zhiyi-item-actions" });
actions.createEl("button", { cls: "zhiyi-action-btn", text: "展开" }).onclick = (e) => {
e.stopPropagation();
this.showDetail(mem);
};
actions.createEl("button", { cls: "zhiyi-action-btn", text: "复制" }).onclick = (e) => {
e.stopPropagation();
navigator.clipboard.writeText(mem.content).catch(() => {});
};
item.onclick = () => this.showDetail(mem);
}
const totalPages = Math.ceil(this.totalMemories / PAGE_SIZE) || 1;
pag.empty();
const prev = pag.createEl("button", { text: "◀" });
prev.setAttr("disabled", this.currentPage === 0 ? "true" : "");
prev.onclick = () => { this.currentPage--; this.loadMemories(); };
pag.createEl("span", { cls: "page-info", text: `${this.currentPage + 1} / ${totalPages}` });
const next = pag.createEl("button", { text: "▶" });
next.setAttr("disabled", this.currentPage >= totalPages - 1 ? "true" : "");
next.onclick = () => { this.currentPage++; this.loadMemories(); };
}
private showDetail(mem: MemoryRecord) {
const modal = this.container.createEl("div", { cls: "zhiyi-detail-modal" });
const box = modal.createEl("div", { cls: "zhiyi-detail-box" });
const header = box.createEl("div", { cls: "zhiyi-detail-header" });
header.createEl("h3", { text: "记忆详情" });
const closeBtn = header.createEl("button", { cls: "zhiyi-detail-close", text: "×" });
closeBtn.onclick = () => modal.remove();
modal.onclick = (e) => { if (e.target === modal) modal.remove(); };
const body = box.createEl("div", { cls: "zhiyi-detail-body" });
const meta = body.createEl("div", { cls: "zhiyi-detail-meta" });
meta.createEl("span", { text: `分类: ${mem.category || "normal"}` });
meta.createEl("span", { text: `质量: ${((mem.quality_score ?? 0) * 100).toFixed(1)}%` });
meta.createEl("span", { text: `Namespace: ${mem.namespace}` });
meta.createEl("span", { text: `时间: ${this.formatTime(mem.created_at)}` });
if (mem.recall_count !== undefined) meta.createEl("span", { text: `召回: ${mem.recall_count}` });
body.createEl("div", { cls: "zhiyi-detail-content", text: mem.content });
const footer = box.createEl("div", { cls: "zhiyi-detail-footer" });
footer.createEl("button", { text: "复制内容", attr: { style: "background:var(--background-secondary);border:1px solid var(--background-modifier-border);color:var(--text-normal)" } }).onclick = () => {
navigator.clipboard.writeText(mem.content).catch(() => {});
};
footer.createEl("button", { text: "关闭", attr: { style: "background:var(--text-accent);border:none;color:var(--bg-on-accent,#fff)" } }).onclick = () => modal.remove();
}
private truncate(s: string, max: number) {
if (!s) return "";
return s.length > max ? s.slice(0, max) + "…" : s;
}
private formatTime(iso: string) {
if (!iso) return "";
try {
const d = new Date(iso);
return d.toLocaleString("zh-CN", { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
} catch { return iso; }
}
}