E5.1 Obsidian 插件: CORS中间件 + 记忆面板 + 图谱视图 + 搜索模态框
- 新增 CORS 中间件 (middleware/cors.go): 支持 app://obsidian.md 跨域 - 新增 Obsidian 插件: MemoryView(分页记忆列表) + GraphView(D3力导向图) + SearchModal(语义搜索) - Go API CORS: Access-Control-Allow-Origin: app://obsidian.md - Makefile 新增 build-obsidian / install-obsidian 目标 - 插件安装至 ~/.obsidian/plugins/zhiyi-memory/
This commit is contained in:
@@ -0,0 +1,328 @@
|
||||
import { ItemView, WorkspaceLeaf } from "obsidian";
|
||||
import { fetchGraphExport, fetchNeighbors, fetchByEntity, fetchPageRank, type GraphNode, type GraphEdge, type MemoryRecord } from "./api";
|
||||
|
||||
// 动态加载 D3.js(从 CDN,不打包)
|
||||
async function loadD3(): Promise<typeof import("d3")> {
|
||||
if ((window as unknown as Record<string, unknown>)["d3"]) {
|
||||
return (window as unknown as Record<string, unknown>)["d3"] as typeof import("d3");
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement("script");
|
||||
script.src = "https://cdn.jsdelivr.net/npm/d3@7/dist/d3.min.js";
|
||||
script.onload = () => resolve((window as unknown as Record<string, unknown>)["d3"] as typeof import("d3"));
|
||||
script.onerror = reject;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
export const GRAPH_VIEW_TYPE = "zhiyi-graph-view";
|
||||
|
||||
interface SimNode extends d3.SimulationNodeDatum {
|
||||
id: string;
|
||||
label: string;
|
||||
category?: string;
|
||||
weight?: number;
|
||||
isCentral?: boolean;
|
||||
}
|
||||
|
||||
interface SimLink extends d3.SimulationLinkDatum<SimNode> {
|
||||
relation: string;
|
||||
weight?: number;
|
||||
}
|
||||
|
||||
export class GraphView extends ItemView {
|
||||
private container: HTMLElement;
|
||||
private currentEntity = "";
|
||||
private d3: typeof import("d3") | null = null;
|
||||
private svg: d3.Selection<SVGSVGElement, unknown, null, undefined> | null = null;
|
||||
private simulation: d3.Simulation<SimNode, SimLink> | null = null;
|
||||
|
||||
constructor(leaf: WorkspaceLeaf) {
|
||||
super(leaf);
|
||||
this.container = this.contentEl;
|
||||
}
|
||||
|
||||
getViewType() { return GRAPH_VIEW_TYPE; }
|
||||
getDisplayText() { return "织忆图谱"; }
|
||||
|
||||
async onOpen() {
|
||||
this.render();
|
||||
}
|
||||
|
||||
async onClose() {
|
||||
this.simulation?.stop();
|
||||
}
|
||||
|
||||
async render() {
|
||||
this.container.empty();
|
||||
this.container.createEl("style", {
|
||||
text: `
|
||||
.zhiyi-graph-view { height: 100%; display: flex; flex-direction: column; }
|
||||
.zhiyi-graph-toolbar {
|
||||
display: flex; gap: 6px; padding: 6px 10px;
|
||||
border-bottom: 1px solid var(--background-modifier-border);
|
||||
align-items: center;
|
||||
}
|
||||
.zhiyi-graph-toolbar input {
|
||||
flex: 1; padding: 4px 8px; font-size: 12px;
|
||||
background: var(--background-secondary);
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
border-radius: 4px; color: var(--text-normal);
|
||||
}
|
||||
.zhiyi-graph-toolbar button {
|
||||
padding: 4px 10px; font-size: 12px; cursor: pointer;
|
||||
background: var(--background-secondary);
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
.zhiyi-graph-toolbar .info {
|
||||
font-size: 11px; color: var(--text-muted); padding: 0 6px;
|
||||
}
|
||||
.zhiyi-graph-canvas { flex: 1; position: relative; overflow: hidden; }
|
||||
.zhiyi-graph-canvas svg { width: 100%; height: 100%; }
|
||||
.zhiyi-graph-detail {
|
||||
position: absolute; bottom: 0; left: 0; right: 0;
|
||||
background: var(--background-secondary);
|
||||
border-top: 1px solid var(--background-modifier-border);
|
||||
padding: 8px 12px; font-size: 11px; max-height: 120px; overflow-y: auto;
|
||||
}
|
||||
.zhiyi-graph-detail-title { font-weight: 600; margin-bottom: 4px; }
|
||||
.zhiyi-graph-node-label { font-size: 10px; fill: var(--text-muted); pointer-events: none; }
|
||||
.zhiyi-legend { position: absolute; top: 8px; right: 8px; background: var(--background-secondary); border: 1px solid var(--background-modifier-border); border-radius: 4px; padding: 6px 8px; font-size: 10px; }
|
||||
.zhiyi-legend-item { display: flex; align-items: center; gap: 4px; margin: 2px 0; }
|
||||
.zhiyi-legend-dot { width: 8px; height: 8px; border-radius: 50%; display: inline-block; }
|
||||
.zhiyi-tooltip {
|
||||
position: absolute; background: var(--background-secondary);
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
border-radius: 4px; padding: 6px 8px; font-size: 11px;
|
||||
pointer-events: none; opacity: 0; transition: opacity 0.15s;
|
||||
max-width: 200px; z-index: 10;
|
||||
}
|
||||
`
|
||||
});
|
||||
|
||||
const root = this.container.createEl("div", { cls: "zhiyi-graph-view" });
|
||||
const toolbar = root.createEl("div", { cls: "zhiyi-graph-toolbar" });
|
||||
|
||||
const searchInput = toolbar.createEl("input", {
|
||||
attr: { placeholder: "输入实体名称,回车查看 ego-network(如: 牧尘)" }
|
||||
}) as HTMLInputElement;
|
||||
|
||||
const loadBtn = toolbar.createEl("button", { text: "加载图谱" });
|
||||
toolbar.createEl("span", { cls: "info", text: "点击节点查看详情" });
|
||||
|
||||
// 快捷入口:Top 实体
|
||||
const topBtn = toolbar.createEl("button", { text: "Top 节点" });
|
||||
|
||||
const canvas = root.createEl("div", { cls: "zhiyi-graph-canvas" });
|
||||
const tooltip = canvas.createEl("div", { cls: "zhiyi-tooltip" });
|
||||
|
||||
const legendEl = canvas.createEl("div", { cls: "zhiyi-legend" });
|
||||
legendEl.innerHTML = `
|
||||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#4a9eff"></span> 默认</div>
|
||||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#f6c945"></span> 人物</div>
|
||||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#34c759"></span> 项目</div>
|
||||
<div class="zhiyi-legend-item"><span class="zhiyi-legend-dot" style="background:#ff6b6b"></span> 事件</div>
|
||||
`;
|
||||
|
||||
const detail = root.createEl("div", { cls: "zhiyi-graph-detail", attr: { style: "display:none" } });
|
||||
const detailTitle = detail.createEl("div", { cls: "zhiyi-graph-detail-title" });
|
||||
const detailContent = detail.createEl("div", { cls: "zhiyi-graph-detail-content" });
|
||||
|
||||
// 加载 D3 并渲染全局图谱
|
||||
this.d3 = await loadD3();
|
||||
this.svg = this.d3.select(canvas.createEl("svg"));
|
||||
await this.renderGlobalGraph();
|
||||
|
||||
loadBtn.onclick = async () => {
|
||||
if (searchInput.value.trim()) {
|
||||
await this.renderEgoGraph(searchInput.value.trim(), canvas, tooltip, detail, detailTitle, detailContent);
|
||||
}
|
||||
};
|
||||
|
||||
searchInput.onkeydown = async (e) => {
|
||||
if (e.key === "Enter" && searchInput.value.trim()) {
|
||||
await this.renderEgoGraph(searchInput.value.trim(), canvas, tooltip, detail, detailTitle, detailContent);
|
||||
}
|
||||
};
|
||||
|
||||
topBtn.onclick = async () => {
|
||||
try {
|
||||
const data = await fetchPageRank(20);
|
||||
const topEntity = data.pagerank?.[0]?.entity || "牧尘";
|
||||
searchInput.value = topEntity;
|
||||
await this.renderEgoGraph(topEntity, canvas, tooltip, detail, detailTitle, detailContent);
|
||||
} catch (_) {}
|
||||
};
|
||||
}
|
||||
|
||||
private async renderGlobalGraph() {
|
||||
try {
|
||||
const data = await fetchGraphExport("hermes-main", 80);
|
||||
await this.renderD3Graph(data.nodes, data.edges, null);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
private async renderEgoGraph(
|
||||
entity: string,
|
||||
canvas: HTMLElement,
|
||||
tooltip: HTMLElement,
|
||||
detail: HTMLElement,
|
||||
detailTitle: HTMLElement,
|
||||
detailContent: HTMLElement
|
||||
) {
|
||||
this.currentEntity = entity;
|
||||
this.simulation?.stop();
|
||||
try {
|
||||
const [graphData, memData] = await Promise.all([
|
||||
fetchNeighbors(entity),
|
||||
fetchByEntity(entity),
|
||||
]);
|
||||
// 中心节点
|
||||
const central: GraphNode = { id: entity, label: entity };
|
||||
const nodes = [central, ...graphData.nodes.filter(n => n.id !== entity)];
|
||||
await this.renderD3Graph(nodes, graphData.edges, entity);
|
||||
|
||||
// 详情面板
|
||||
detail.style.display = "block";
|
||||
detailTitle.setText(`📌 ${entity}`);
|
||||
const mems = memData.memories || [];
|
||||
detailContent.innerHTML = mems.slice(0, 3).map((m: MemoryRecord) =>
|
||||
`<div style="margin:2px 0">• ${this.truncate(m.content, 100)}</div>`
|
||||
).join("") || "<div>无关联记忆</div>";
|
||||
} catch (e) {
|
||||
const errEl = canvas.createEl("div", { text: `加载失败: ${(e as Error).message}`, cls: "zhiyi-empty" });
|
||||
setTimeout(() => errEl.remove(), 3000);
|
||||
}
|
||||
}
|
||||
|
||||
private async renderD3Graph(
|
||||
nodes: GraphNode[],
|
||||
edges: GraphEdge[],
|
||||
centralId: string | null
|
||||
) {
|
||||
if (!this.d3 || !this.svg) return;
|
||||
const d3 = this.d3;
|
||||
const svg = this.svg;
|
||||
svg.selectAll("*").remove();
|
||||
|
||||
const width = svg.node()!.clientWidth || 600;
|
||||
const height = svg.node()!.clientHeight || 400;
|
||||
|
||||
const catColor: Record<string, string> = {
|
||||
"人物": "#f6c945", "人物_name": "#f6c945", "project": "#34c759",
|
||||
"项目": "#34c759", "event": "#ff6b6b", "事件": "#ff6b6b",
|
||||
"concept": "#a855f7", "概念": "#a855f7", "location": "#06b6d4",
|
||||
"distilled": "#4a9eff", "default": "#4a9eff"
|
||||
};
|
||||
|
||||
const getColor = (n: GraphNode) => {
|
||||
if (n.id === centralId) return "#ff4d4d";
|
||||
if (n.category && catColor[n.category]) return catColor[n.category];
|
||||
return catColor[n.weight !== undefined && n.weight > 5 ? "distilled" : "default"];
|
||||
};
|
||||
|
||||
const simNodes: SimNode[] = nodes.map(n => ({
|
||||
id: n.id, label: n.label || n.id,
|
||||
category: n.category, weight: n.weight,
|
||||
isCentral: n.id === centralId,
|
||||
}));
|
||||
|
||||
const nodeMap = new Map(simNodes.map(n => [n.id, n]));
|
||||
const simLinks: SimLink[] = edges
|
||||
.filter(e => nodeMap.has(e.source) && nodeMap.has(e.target))
|
||||
.map(e => ({ source: e.source, target: e.target, relation: e.relation, weight: e.weight }));
|
||||
|
||||
// 缩放
|
||||
const zoom = d3.zoom<SVGSVGElement, unknown>()
|
||||
.scaleExtent([0.2, 5])
|
||||
.on("zoom", (event) => {
|
||||
g.attr("transform", event.transform);
|
||||
});
|
||||
svg.call(zoom as unknown as (s: d3.Selection<SVGSVGElement, unknown, null, undefined>) => void);
|
||||
|
||||
const g = svg.append("g");
|
||||
svg.append("defs").append("marker")
|
||||
.attr("id", "arrowhead")
|
||||
.attr("viewBox", "-0 -5 10 10")
|
||||
.attr("refX", 15).attr("refY", 0)
|
||||
.attr("orient", "auto")
|
||||
.attr("markerWidth", 6).attr("markerHeight", 6)
|
||||
.append("path").attr("d", "M 0,-5 L 10,0 L 0,5")
|
||||
.attr("fill", "#666");
|
||||
|
||||
const link = g.append("g").selectAll("line")
|
||||
.data(simLinks)
|
||||
.enter().append("line")
|
||||
.attr("stroke", "#999").attr("stroke-opacity", 0.6)
|
||||
.attr("stroke-width", d => Math.min(2, d.weight || 1))
|
||||
.attr("marker-end", "url(#arrowhead)");
|
||||
|
||||
const node = g.append("g").selectAll("g")
|
||||
.data(simNodes)
|
||||
.enter().append("g")
|
||||
.style("cursor", "pointer");
|
||||
|
||||
node.append("circle")
|
||||
.attr("r", d => d.isCentral ? 12 : 6 + (d.weight || 1) * 0.5)
|
||||
.attr("fill", d => getColor(d as GraphNode))
|
||||
.attr("stroke", d => d.isCentral ? "#ff4d4d" : "white")
|
||||
.attr("stroke-width", d => d.isCentral ? 2 : 1.5);
|
||||
|
||||
node.append("text")
|
||||
.text(d => d.label.length > 12 ? d.label.slice(0, 12) + "…" : d.label)
|
||||
.attr("dy", -8)
|
||||
.attr("text-anchor", "middle")
|
||||
.attr("class", "zhiyi-graph-node-label")
|
||||
.style("font-size", d => d.isCentral ? "11px" : "9px")
|
||||
.style("fill", "var(--text-muted)");
|
||||
|
||||
// 拖拽
|
||||
const drag = d3.drag<SVGGElement, SimNode>()
|
||||
.on("start", (event, d) => {
|
||||
if (!event.active) this.simulation!.alphaTarget(0.3).restart();
|
||||
d.fx = d.x; d.fy = d.y;
|
||||
})
|
||||
.on("drag", (event, d) => { d.fx = event.x; d.fy = event.y; })
|
||||
.on("end", (event, d) => {
|
||||
if (!event.active) this.simulation!.alphaTarget(0);
|
||||
d.fx = null; d.fy = null;
|
||||
});
|
||||
node.call(drag as unknown as (s: d3.Selection<SVGGElement, SimNode, SVGGElement, unknown>) => void);
|
||||
|
||||
node.on("click", (_event, d) => {
|
||||
this.renderEgoGraph(d.id, canvas.parentElement!, tooltip,
|
||||
canvas.parentElement!.querySelector(".zhiyi-graph-detail") as HTMLElement,
|
||||
canvas.parentElement!.querySelector(".zhiyi-graph-detail-title") as HTMLElement,
|
||||
canvas.parentElement!.querySelector(".zhiyi-graph-detail-content") as HTMLElement);
|
||||
});
|
||||
|
||||
node.on("mouseover", (event, d) => {
|
||||
tooltip.style.opacity = "1";
|
||||
tooltip.style.left = (event.offsetX + 10) + "px";
|
||||
tooltip.style.top = (event.offsetY - 10) + "px";
|
||||
tooltip.setText(`${d.label}${d.weight !== undefined ? ` (×${d.weight})` : ""}`);
|
||||
});
|
||||
|
||||
node.on("mouseout", () => { tooltip.style.opacity = "0"; });
|
||||
|
||||
this.simulation = d3.forceSimulation(simNodes)
|
||||
.force("link", d3.forceLink<SimNode, SimLink>(simLinks).id(d => d.id).distance(80))
|
||||
.force("charge", d3.forceManyBody().strength(-200))
|
||||
.force("center", d3.forceCenter(width / 2, height / 2))
|
||||
.force("collision", d3.forceCollide(20))
|
||||
.on("tick", () => {
|
||||
link
|
||||
.attr("x1", d => (d.source as SimNode).x!)
|
||||
.attr("y1", d => (d.source as SimNode).y!)
|
||||
.attr("x2", d => (d.target as SimNode).x!)
|
||||
.attr("y2", d => (d.target as SimNode).y!);
|
||||
node.attr("transform", d => `translate(${d.x},${d.y})`);
|
||||
});
|
||||
}
|
||||
|
||||
private truncate(s: string, max: number) {
|
||||
if (!s) return "";
|
||||
return s.length > max ? s.slice(0, max) + "…" : s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
import { ItemView, WorkspaceLeaf } from "obsidian";
|
||||
import { fetchMemories, fetchDistillStatus, fetchDistillQuota, type MemoryRecord } from "./api";
|
||||
|
||||
export const MEMORY_VIEW_TYPE = "zhiyi-memory-view";
|
||||
|
||||
export class MemoryView extends ItemView {
|
||||
private container: HTMLElement;
|
||||
private memories: MemoryRecord[] = [];
|
||||
private currentPage = 0;
|
||||
private pageSize = 20;
|
||||
private totalMemories = 0;
|
||||
private status_interval: number | null = null;
|
||||
|
||||
constructor(leaf: WorkspaceLeaf) {
|
||||
super(leaf);
|
||||
this.container = this.contentEl;
|
||||
}
|
||||
|
||||
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() {
|
||||
// 轮询蒸馏状态(每 30 秒)
|
||||
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 (_) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
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: 10px 12px 6px; border-bottom: 1px solid var(--background-modifier-border); }
|
||||
.zhiyi-header h1 { font-size: 14px; font-weight: 600; margin: 0 0 4px; }
|
||||
.zhiyi-stats { color: var(--text-muted); font-size: 11px; margin: 0; }
|
||||
.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: 2px; }
|
||||
.zhiyi-item-cat { font-size: 10px; color: var(--text-muted); background: var(--background-secondary); padding: 1px 4px; border-radius: 2px; }
|
||||
.zhiyi-item-score { font-size: 10px; color: var(--text-muted); }
|
||||
.zhiyi-item-content { font-size: 12px; color: var(--text-normal); line-height: 1.4; }
|
||||
.zhiyi-item-time { font-size: 10px; color: var(--text-muted); margin-top: 2px; }
|
||||
.zhiyi-item-id { font-size: 10px; color: var(--text-faint); font-family: monospace; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.zhiyi-pagination { display: flex; gap: 6px; padding: 8px 12px; border-top: 1px solid var(--background-modifier-border); }
|
||||
.zhiyi-pagination button { flex: 1; padding: 4px; 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-loading { padding: 20px; text-align: center; color: var(--text-muted); }
|
||||
.zhiyi-empty { padding: 20px; text-align: center; color: var(--text-muted); }
|
||||
`
|
||||
});
|
||||
this.container.createEl("div", { cls: "zhiyi-memory-view" }).append(
|
||||
this.container.createEl("div", { cls: "zhiyi-distill-banner" }),
|
||||
this.container.createEl("div", { cls: "zhiyi-header" }).append(
|
||||
this.container.createEl("h1", { text: "🧠 织忆记忆" }),
|
||||
this.container.createEl("p", { cls: "zhiyi-stats", text: "加载中..." })
|
||||
),
|
||||
this.container.createEl("div", { cls: "zhiyi-body" }),
|
||||
this.container.createEl("div", { cls: "zhiyi-pagination" })
|
||||
);
|
||||
await this.loadMemories();
|
||||
await this.renderDistillBanner();
|
||||
}
|
||||
|
||||
async loadMemories() {
|
||||
const body = this.container.querySelector(".zhiyi-body") as HTMLElement;
|
||||
const stats = this.container.querySelector(".zhiyi-stats") as HTMLElement;
|
||||
body.innerHTML = '<div class="zhiyi-loading">加载中…</div>';
|
||||
try {
|
||||
const data = await fetchMemories({ namespace: "hermes-main", limit: this.pageSize, offset: this.currentPage * this.pageSize });
|
||||
this.memories = data.memories || [];
|
||||
this.totalMemories = data.total || 0;
|
||||
stats.setText(`${this.totalMemories} 条记忆 · 第 ${this.currentPage + 1} 页`);
|
||||
this.renderList();
|
||||
} catch (e) {
|
||||
body.innerHTML = `<div class="zhiyi-empty">加载失败: ${(e as Error).message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
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" });
|
||||
header.createEl("span", { cls: "zhiyi-item-score", text: `score: ${(mem.quality_score ?? 0).toFixed(2)}` });
|
||||
item.createEl("div", { cls: "zhiyi-item-content", text: this.truncate(mem.content, 120) });
|
||||
item.createEl("div", { cls: "zhiyi-item-time", text: this.formatTime(mem.created_at) });
|
||||
item.createEl("div", { cls: "zhiyi-item-id", text: mem.id });
|
||||
}
|
||||
const totalPages = Math.ceil(this.totalMemories / this.pageSize);
|
||||
pag.empty();
|
||||
if (totalPages > 1) {
|
||||
const prev = pag.createEl("button", { text: "◀ 上一页" });
|
||||
prev.setAttr("disabled", this.currentPage === 0 ? "true" : "");
|
||||
prev.onclick = () => { this.currentPage--; this.loadMemories(); };
|
||||
pag.createEl("span", { text: `${this.currentPage + 1}/${totalPages}`, cls: "zhiyi-item-cat" });
|
||||
const next = pag.createEl("button", { text: "下一页 ▶" });
|
||||
next.setAttr("disabled", this.currentPage >= totalPages - 1 ? "true" : "");
|
||||
next.onclick = () => { this.currentPage++; this.loadMemories(); };
|
||||
}
|
||||
}
|
||||
|
||||
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; }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { App, Modal, setIcon } from "obsidian";
|
||||
import { searchMemories, type RecallResult } from "./api";
|
||||
|
||||
export class SearchModal extends Modal {
|
||||
private results: RecallResult["memories"] = [];
|
||||
private inputEl: HTMLInputElement;
|
||||
private listEl: HTMLElement;
|
||||
private loading = false;
|
||||
private debounceTimer: number | null = null;
|
||||
onSelect?: (id: string, content: string) => void;
|
||||
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
}
|
||||
|
||||
onOpen() {
|
||||
this.contentEl.createEl("style", {
|
||||
text: `
|
||||
.zhiyi-search-modal { width: 600px; max-height: 80vh; display: flex; flex-direction: column; }
|
||||
.zhiyi-search-header {
|
||||
display: flex; align-items: center; gap: 8px;
|
||||
padding: 12px 16px; border-bottom: 1px solid var(--background-modifier-border);
|
||||
}
|
||||
.zhiyi-search-header h2 { margin: 0; font-size: 14px; font-weight: 600; flex: 1; }
|
||||
.zhiyi-search-input {
|
||||
flex: 1; padding: 8px 12px; font-size: 14px;
|
||||
background: var(--background-secondary);
|
||||
border: 1px solid var(--background-modifier-border);
|
||||
border-radius: 6px; color: var(--text-normal); outline: none;
|
||||
}
|
||||
.zhiyi-search-input:focus { border-color: var(--text-accent); }
|
||||
.zhiyi-search-results { flex: 1; overflow-y: auto; padding: 8px 0; }
|
||||
.zhiyi-search-result {
|
||||
padding: 10px 16px; border-bottom: 1px solid var(--background-modifier-border);
|
||||
cursor: pointer;
|
||||
}
|
||||
.zhiyi-search-result:hover { background: var(--background-modifier-hover); }
|
||||
.zhiyi-search-result-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
|
||||
.zhiyi-search-score { font-size: 10px; color: var(--text-muted); }
|
||||
.zhiyi-search-cat { font-size: 10px; background: var(--background-secondary); padding: 1px 4px; border-radius: 2px; color: var(--text-muted); }
|
||||
.zhiyi-search-content { font-size: 12px; color: var(--text-normal); line-height: 1.5; }
|
||||
.zhiyi-search-id { font-size: 10px; color: var(--text-faint); font-family: monospace; margin-top: 3px; }
|
||||
.zhiyi-search-loading { padding: 20px; text-align: center; color: var(--text-muted); }
|
||||
.zhiyi-search-empty { padding: 20px; text-align: center; color: var(--text-muted); }
|
||||
.zhiyi-search-hint { padding: 8px 16px; font-size: 11px; color: var(--text-muted); text-align: center; }
|
||||
`
|
||||
});
|
||||
|
||||
const root = this.contentEl.createEl("div", { cls: "zhiyi-search-modal" });
|
||||
const header = root.createEl("div", { cls: "zhiyi-search-header" });
|
||||
header.createEl("h2", { text: "🔍 织忆语义搜索" });
|
||||
this.inputEl = header.createEl("input", {
|
||||
cls: "zhiyi-search-input",
|
||||
attr: { placeholder: "输入关键词,语义搜索记忆…", autofocus: "true" }
|
||||
}) as HTMLInputElement;
|
||||
this.listEl = root.createEl("div", { cls: "zhiyi-search-results" });
|
||||
root.createEl("div", { cls: "zhiyi-search-hint", text: "实时搜索 · 按 Enter 选择第一条结果" });
|
||||
|
||||
this.inputEl.oninput = () => {
|
||||
if (this.debounceTimer !== null) {
|
||||
(window as unknown as { clearTimeout: (n: number) => void }).clearTimeout(this.debounceTimer);
|
||||
}
|
||||
this.debounceTimer = (window as unknown as { setTimeout: (fn: () => void, ms: number) => number }).setTimeout(
|
||||
() => this.doSearch(),
|
||||
300
|
||||
);
|
||||
};
|
||||
|
||||
this.inputEl.onkeydown = (e) => {
|
||||
if (e.key === "Enter" && this.results.length > 0) {
|
||||
this.selectResult(this.results[0]);
|
||||
}
|
||||
if (e.key === "Escape") {
|
||||
this.close();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async doSearch() {
|
||||
const query = this.inputEl.value.trim();
|
||||
if (!query) {
|
||||
this.results = [];
|
||||
this.listEl.empty();
|
||||
return;
|
||||
}
|
||||
this.listEl.innerHTML = '<div class="zhiyi-search-loading">搜索中…</div>';
|
||||
this.loading = true;
|
||||
try {
|
||||
const data = await searchMemories(query, "hermes-main");
|
||||
this.results = data.memories || [];
|
||||
this.renderResults();
|
||||
} catch (e) {
|
||||
this.listEl.innerHTML = `<div class="zhiyi-search-empty">搜索失败: ${(e as Error).message}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
private renderResults() {
|
||||
this.listEl.empty();
|
||||
if (this.results.length === 0) {
|
||||
this.listEl.createEl("div", { cls: "zhiyi-search-empty", text: "未找到结果" });
|
||||
return;
|
||||
}
|
||||
for (const r of this.results) {
|
||||
const item = this.listEl.createEl("div", { cls: "zhiyi-search-result" });
|
||||
const hdr = item.createEl("div", { cls: "zhiyi-search-result-header" });
|
||||
hdr.createEl("span", { cls: "zhiyi-search-cat", text: r.category || "normal" });
|
||||
hdr.createEl("span", { cls: "zhiyi-search-score", text: ` relevance: ${(r.score ?? 0).toFixed(3)}` });
|
||||
item.createEl("div", { cls: "zhiyi-search-content", text: this.truncate(r.content, 200) });
|
||||
item.createEl("div", { cls: "zhiyi-search-id", text: r.id });
|
||||
item.onclick = () => this.selectResult(r);
|
||||
}
|
||||
}
|
||||
|
||||
private selectResult(r: { id: string; content: string }) {
|
||||
this.onSelect?.(r.id, r.content);
|
||||
this.close();
|
||||
}
|
||||
|
||||
private truncate(s: string, max: number) {
|
||||
if (!s) return "";
|
||||
return s.length > max ? s.slice(0, max) + "…" : s;
|
||||
}
|
||||
|
||||
onClose() {
|
||||
this.listEl.empty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
|
||||
|
||||
// ─── API 客户端(调用织忆 Go API)─────────────────────────────────────────────
|
||||
|
||||
const API_BASE = "http://localhost:7821";
|
||||
const API_KEY = "zhiyi-dev-key-2026";
|
||||
|
||||
interface ApiOptions {
|
||||
method?: string;
|
||||
body?: unknown;
|
||||
}
|
||||
|
||||
async function apiCall<T = unknown>(
|
||||
path: string,
|
||||
opts: ApiOptions = {}
|
||||
): Promise<T> {
|
||||
const method = opts.method ?? "GET";
|
||||
const headers: Record<string, string> = {
|
||||
"X-API-Key": API_KEY,
|
||||
"Content-Type": "application/json",
|
||||
};
|
||||
|
||||
const init: RequestInit = { method, headers };
|
||||
if (opts.body !== undefined) {
|
||||
init.body = JSON.stringify(opts.body);
|
||||
}
|
||||
|
||||
const res = await fetch(`${API_BASE}${path}`, init);
|
||||
if (!res.ok) {
|
||||
throw new Error(`API ${path} failed: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
|
||||
// 有些端点返回空 body
|
||||
const text = await res.text();
|
||||
if (!text) return {} as T;
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
// ─── 数据类型 ────────────────────────────────────────────────────────────────
|
||||
|
||||
export interface MemoryRecord {
|
||||
id: string;
|
||||
content: string;
|
||||
category: string;
|
||||
namespace: string;
|
||||
quality_score: number;
|
||||
created_at: string;
|
||||
agent_id?: string;
|
||||
}
|
||||
|
||||
export interface GraphNode {
|
||||
id: string;
|
||||
label: string;
|
||||
category?: string;
|
||||
weight?: number;
|
||||
}
|
||||
|
||||
export interface GraphEdge {
|
||||
source: string;
|
||||
target: string;
|
||||
relation: string;
|
||||
weight?: number;
|
||||
}
|
||||
|
||||
export interface GraphNavigateResult {
|
||||
nodes: GraphNode[];
|
||||
edges: GraphEdge[];
|
||||
paths: Array<{ source: string; target: string; relation: string }>;
|
||||
}
|
||||
|
||||
export interface RecallResult {
|
||||
memories: Array<{ id: string; content: string; score: number; category: string }>;
|
||||
}
|
||||
|
||||
export interface DistillStatus {
|
||||
queue_len: number;
|
||||
daily_used: number;
|
||||
daily_limit: number;
|
||||
batch_size: number;
|
||||
last_distill?: string;
|
||||
}
|
||||
|
||||
export interface DistillQuota {
|
||||
remaining: number;
|
||||
used: number;
|
||||
limit: number;
|
||||
status: string;
|
||||
}
|
||||
|
||||
// ─── API 方法 ────────────────────────────────────────────────────────────────
|
||||
|
||||
export async function fetchStats() {
|
||||
return apiCall<{ total_memories: number; total_episodes: number; backend: string }>(
|
||||
"/api/v1/stats"
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchMemories(opts: {
|
||||
namespace?: string;
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
}): Promise<{ memories: MemoryRecord[]; total: number }> {
|
||||
const params = new URLSearchParams();
|
||||
if (opts.namespace) params.set("namespace", opts.namespace);
|
||||
if (opts.limit) params.set("limit", String(opts.limit));
|
||||
if (opts.offset !== undefined) params.set("offset", String(opts.offset));
|
||||
const qs = params.toString();
|
||||
return apiCall(`/api/v1/memories?${qs}`);
|
||||
}
|
||||
|
||||
export async function searchMemories(query: string, namespace = "hermes-main") {
|
||||
return apiCall<{ memories: RecallResult["memories"] }>("/api/v1/search/recall", {
|
||||
method: "POST",
|
||||
body: { query, namespace, top_k: 20 },
|
||||
});
|
||||
}
|
||||
|
||||
export async function fetchNeighbors(entity: string) {
|
||||
return apiCall<GraphNavigateResult>(`/api/v1/graph/navigate?entity=${encodeURIComponent(entity)}&depth=1`);
|
||||
}
|
||||
|
||||
export async function fetchGraphExport(namespace = "hermes-main", limit = 100) {
|
||||
return apiCall<{ nodes: GraphNode[]; edges: GraphEdge[] }>(
|
||||
`/api/v1/graph/export?namespace=${namespace}&limit=${limit}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchDistillStatus(): Promise<DistillStatus> {
|
||||
return apiCall("/api/v1/distill/status");
|
||||
}
|
||||
|
||||
export async function fetchDistillQuota(): Promise<DistillQuota> {
|
||||
return apiCall("/api/v1/distill/quota");
|
||||
}
|
||||
|
||||
export async function fetchPageRank(limit = 30) {
|
||||
return apiCall<{ pagerank: Array<{ entity: string; score: number }>; count: number }>(
|
||||
`/api/v1/graph/pagerank?limit=${limit}`
|
||||
);
|
||||
}
|
||||
|
||||
export async function fetchByEntity(entity: string) {
|
||||
return apiCall<{ memories: MemoryRecord[] }>(
|
||||
`/api/v1/memories/by-entity/${encodeURIComponent(entity)}`
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user