diff --git a/client/index.js b/client/index.js index 5a2984f..21d61ed 100644 --- a/client/index.js +++ b/client/index.js @@ -4190,7 +4190,7 @@ window.__ModuleLoader__.load({ d: path }))); } - // \0dsh-brain-css:C:\Users\qyh15\dsh-brain\src-client\panel\BrainPanel.module.css.mjs + // \0dsh-brain-css:src-client/panel/BrainPanel.module.css.mjs const css$1 = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_1xedgey.dshbrain_holtzx (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_1y11fqi {\n box-sizing: border-box;\n position: relative;\n z-index: 2;\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n padding-block-start: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_1y11fqi > * {\n min-width: 0;\n flex: 1 1 auto;\n}\n\n.dshbrain_131vunv {\n position: absolute;\n inset: 0 0 auto;\n height: var(--dsh-frame-top-clearance, 0px);\n}\n\n.dshbrain_oyvdy4 {\n display: flex;\n flex-direction: column;\n gap: 14px;\n padding: 18px 20px 24px;\n overflow: auto;\n font-size: 13px;\n line-height: 1.55;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_of3f1r {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 12px;\n flex-wrap: wrap;\n}\n\n.dshbrain_vnw8w9 {\n display: flex;\n flex-direction: column;\n gap: 2px;\n min-width: 0;\n}\n\n.dshbrain_g8fis8 {\n margin: 0;\n font-size: 16px;\n font-weight: 650;\n letter-spacing: 0.01em;\n}\n\n.dshbrain_1milhhm {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_xnx8bm {\n display: flex;\n gap: 4px;\n padding: 3px;\n border-radius: 13px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n background: var(--dsw-alias-bg-subtle, rgba(127,127,127,0.06));\n flex-wrap: wrap;\n}\n\n.dshbrain_7mndvh {\n flex: 1 1 auto;\n min-width: 88px;\n font: inherit;\n font-size: 12.5px;\n padding: 7px 12px;\n border-radius: 10px;\n border: 1px solid transparent;\n background: transparent;\n color: inherit;\n cursor: pointer;\n white-space: nowrap;\n}\n\n.dshbrain_rvx7lj {\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));\n background: var(--dsw-alias-interactive-bg-hover, rgba(127,127,127,0.14));\n box-shadow: 0 1px 3px rgba(0,0,0,0.10);\n font-weight: 600;\n}\n\n.dshbrain_1rfmkcf {\n display: flex;\n flex-direction: column;\n gap: 12px;\n min-width: 0;\n}\n\n.dshbrain_1wofcsb {\n display: flex;\n flex-direction: column;\n align-items: center;\n justify-content: center;\n gap: 8px;\n padding: 48px 16px;\n border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));\n border-radius: 16px;\n opacity: 0.65;\n}\n\n.dshbrain_3omakb {\n margin: 0;\n font-size: 14px;\n font-weight: 600;\n}\n\n.dshbrain_j3tuu2 {\n margin: 0;\n font-size: 12px;\n}\n\n.dshbrain_c36neh {\n display: flex;\n flex-direction: column;\n gap: 12px;\n}\n\n.dshbrain_1a7ley4 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.22));\n border-radius: 16px;\n padding: 16px 18px;\n min-width: 0;\n}\n\n.dshbrain_1f1qv8u {\n display: flex;\n align-items: center;\n justify-content: space-between;\n gap: 10px;\n flex-wrap: wrap;\n}\n\n.dshbrain_1t5691m {\n margin: 0;\n font-size: 13.5px;\n font-weight: 650;\n}\n\n.dshbrain_updgou {\n display: flex;\n flex-wrap: wrap;\n gap: 8px;\n}\n\n.dshbrain_xwrsl5 {\n display: inline-flex;\n align-items: center;\n gap: 6px;\n padding: 3px 10px;\n border-radius: 999px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.35));\n font-size: 12px;\n white-space: nowrap;\n}\n\n.dshbrain_mvsf69 {\n opacity: 0.75;\n}\n\n.dshbrain_1xby9uu {\n font-weight: 600;\n}\n\n.dshbrain_1bzyta0 { border-color: rgba(22,163,74,0.55); background: rgba(22,163,74,0.12); }\n.dshbrain_1hx5ob5 { border-color: rgba(220,38,38,0.55); background: rgba(220,38,38,0.12); }\n.dshbrain_amukxq { border-color: rgba(217,119,6,0.55); background: rgba(217,119,6,0.12); }\n.dshbrain_uf6ztt { }\n\n.dshbrain_1vi102j {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_qmj948 {\n padding: 10px 13px;\n border-radius: 11px;\n border: 1px solid rgba(220,38,38,0.55);\n background: rgba(220,38,38,0.12);\n font-size: 12.5px;\n}\n\n.dshbrain_1ex8b80 {\n display: flex;\n align-items: baseline;\n flex-wrap: wrap;\n}\n\n.dshbrain_1048ygk {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n padding-right: 18px;\n margin-right: 18px;\n border-right: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.20));\n}\n\n.dshbrain_1bvujjo {\n display: inline-flex;\n align-items: baseline;\n gap: 6px;\n}\n\n.dshbrain_d75ahw {\n font-size: 17px;\n font-weight: 700;\n}\n"; const tagId$1 = "src-client/panel/BrainPanel.module.css"; if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") { @@ -4397,18 +4397,41 @@ window.__ModuleLoader__.load({ }) }; } + // src-client/panel/workspace.ts + function resolveWorkspace(ctx) { + try { + const sessions = ctx !== void 0 && ctx !== null && typeof ctx.get === "function" ? ctx.get("sessions") : void 0; + if (sessions === void 0 || sessions === null) return void 0; + const current = typeof sessions.current === "function" ? sessions.current() : sessions.current; + const candidates = [ + current?.cwd, + current?.header?.cwd, + current?.session?.cwd, + current?.session?.header?.cwd, + typeof sessions.cwd === "function" ? sessions.cwd() : void 0 + ]; + for (const candidate of candidates) if (typeof candidate === "string" && candidate.trim() !== "") return candidate; + } catch {} + } + function workspaceQuery(workspace) { + return workspace === void 0 ? "" : "?workspace=" + encodeURIComponent(workspace); + } // src-client/panel/MemoryTab.tsx const h$4 = react.createElement; const PAGE_SIZE = 50; + function workspaceSuffix(workspace) { + return workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace); + } function MemoryTab(props) { const active = props.active !== false; + const workspace = props.workspace; const [offset, setOffset] = react.useState(0); const [search, setSearch] = react.useState(""); const [notice, setNotice] = react.useState(null); const [pendingForget, setPendingForget] = react.useState(null); const [busy, setBusy] = react.useState(""); const status = useApi(async () => { - const result = await request("/dsh-brain/local-memory/status"); + const result = await request("/dsh-brain/local-memory/status" + workspaceQuery(workspace)); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取本地记忆状态失败")); return result.body; }, { @@ -4416,7 +4439,7 @@ window.__ModuleLoader__.load({ pollMs: 15e3 }); const memories = useApi(async () => { - const result = await request("/dsh-brain/local-memory/memories?limit=" + String(PAGE_SIZE) + "&offset=" + String(offset)); + const result = await request("/dsh-brain/local-memory/memories?limit=" + String(PAGE_SIZE) + "&offset=" + String(offset) + workspaceSuffix(workspace)); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取记忆列表失败")); return result.body; }, { @@ -4424,7 +4447,7 @@ window.__ModuleLoader__.load({ deps: [offset] }); const documents = useApi(async () => { - const result = await request("/dsh-brain/local-memory/documents"); + const result = await request("/dsh-brain/local-memory/documents" + workspaceQuery(workspace)); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取文档列表失败")); return result.body; }, { visible: active }); @@ -4444,7 +4467,8 @@ window.__ModuleLoader__.load({ try { const result = await postJson("/dsh-brain/local-memory/forget", { id: item.id, - expectedRevision: item.revision + expectedRevision: item.revision, + workspace }); if (result.status !== 200 || result.body === null || result.body.ok !== true) setNotice({ tone: "bad", @@ -4590,25 +4614,6 @@ window.__ModuleLoader__.load({ tone: "muted" }))), h$4("div", { style: styles.clamp2 }, String(doc.content ?? ""))))))); } - // src-client/panel/workspace.ts - function resolveWorkspace(ctx) { - try { - const sessions = ctx !== void 0 && ctx !== null && typeof ctx.get === "function" ? ctx.get("sessions") : void 0; - if (sessions === void 0 || sessions === null) return void 0; - const current = typeof sessions.current === "function" ? sessions.current() : sessions.current; - const candidates = [ - current?.cwd, - current?.header?.cwd, - current?.session?.cwd, - current?.session?.header?.cwd, - typeof sessions.cwd === "function" ? sessions.cwd() : void 0 - ]; - for (const candidate of candidates) if (typeof candidate === "string" && candidate.trim() !== "") return candidate; - } catch {} - } - function workspaceQuery(workspace) { - return workspace === void 0 ? "" : "?workspace=" + encodeURIComponent(workspace); - } // src-client/panel/DepartmentTab.tsx const h$3 = react.createElement; const EMPTY_CREATE = { @@ -4994,11 +4999,14 @@ window.__ModuleLoader__.load({ let content; if (tab === "overview") content = h$2(Overview, { active }); else if (tab === "connection") content = h$2(SettingsCard, null); - else if (tab === "memory") content = h$2(MemoryTab, { - ctx: props.ctx, - active - }); - else if (tab === "departments") content = h$2(DepartmentTab, { + else if (tab === "memory") { + const workspace = resolveWorkspace(props.ctx); + content = h$2(MemoryTab, { + key: workspace ?? "", + workspace, + active + }); + } else if (tab === "departments") content = h$2(DepartmentTab, { ctx: props.ctx, active }); @@ -5089,7 +5097,7 @@ window.__ModuleLoader__.load({ stopNative = void 0; }; } - // \0dsh-brain-css:C:\Users\qyh15\dsh-brain\src-client\sidebar\ProjectMemory.module.css.mjs + // \0dsh-brain-css:src-client/sidebar/ProjectMemory.module.css.mjs const css = "/* Adapted from dsh-mnemon MnemonWorkspace.dshbrain_6gleqm.dshbrain_tp0sjt (MIT), see vendor/dsh-mnemon/LICENSE. */\n.dshbrain_ty34oh {\n display: flex;\n width: 100%;\n height: 100%;\n min-width: 0;\n min-height: 0;\n overflow: hidden;\n flex: 1 1 auto;\n color: var(--dsw-alias-label-primary, inherit);\n}\n\n.dshbrain_5jq582 {\n display: flex;\n flex-direction: column;\n gap: 10px;\n width: 100%;\n min-width: 0;\n padding: 12px;\n overflow: auto;\n font-size: 12.5px;\n line-height: 1.5;\n}\n\n.dshbrain_1h1jxwb {\n display: flex;\n align-items: flex-start;\n justify-content: space-between;\n gap: 8px;\n flex-wrap: wrap;\n}\n\n.dshbrain_y21ms {\n margin: 0;\n font-size: 13.5px;\n font-weight: 650;\n}\n\n.dshbrain_11or5iu {\n margin: 0;\n font-size: 12.5px;\n font-weight: 600;\n}\n\n.dshbrain_1feix73 {\n margin: 0;\n font-size: 11.5px;\n opacity: 0.58;\n}\n\n.dshbrain_21cgfy {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n\n.dshbrain_1qwoelq {\n display: flex;\n flex-direction: column;\n gap: 5px;\n border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));\n border-radius: 10px;\n padding: 8px 10px;\n min-width: 0;\n}\n\n.dshbrain_8p16nn {\n display: flex;\n flex-wrap: wrap;\n gap: 6px;\n}\n\n.dshbrain_gp5jh {\n display: -webkit-box;\n -webkit-line-clamp: 3;\n -webkit-box-orient: vertical;\n overflow: hidden;\n overflow-wrap: anywhere;\n}\n\n.dshbrain_11ef887 {\n height: 1px;\n background: var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));\n margin: 2px 0;\n}\n\n.dshbrain_mkopal {\n display: flex;\n flex-direction: column;\n gap: 8px;\n}\n"; const tagId = "src-client/sidebar/ProjectMemory.module.css"; if (typeof document !== "undefined" && typeof document.querySelector === "function" && typeof document.createElement === "function") { @@ -5137,7 +5145,7 @@ window.__ModuleLoader__.load({ const [recallBusy, setRecallBusy] = react.useState(false); const [notice, setNotice] = react.useState(null); const status = useApi(async () => { - const result = await request("/dsh-brain/local-memory/status"); + const result = await request("/dsh-brain/local-memory/status" + workspaceQuery(workspace)); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取本地记忆状态失败")); return result.body; }, { @@ -5145,7 +5153,7 @@ window.__ModuleLoader__.load({ pollMs: 15e3 }); const memories = useApi(async () => { - const result = await request("/dsh-brain/local-memory/memories?limit=50&offset=0"); + const result = await request("/dsh-brain/local-memory/memories?limit=50&offset=0" + (workspace === void 0 ? "" : "&workspace=" + encodeURIComponent(workspace))); if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, "读取记忆列表失败")); return result.body; }, { @@ -5278,6 +5286,7 @@ window.__ModuleLoader__.load({ order: 60, single: true, component: ({ scope, visible }) => react.createElement(ProjectMemoryView, { + key: scope?.cwd ?? "", ctx, scope, visible diff --git a/lib/diagnostics.js b/lib/diagnostics.js index 509421d..9de4a07 100644 --- a/lib/diagnostics.js +++ b/lib/diagnostics.js @@ -21,7 +21,7 @@ function sanitizeValue(value) { if (typeof value === 'string') { if (containsSecret(value)) return '[redacted]'; - return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS) + '…' : value; + return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS - 1) + '…' : value; } if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value; @@ -81,7 +81,7 @@ export class BrainLogger { if (detail !== undefined && Object.keys(detail).length > 0) record.detail = detail; if (event.err !== undefined) { - const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS) + '…' : event.err; + const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS - 1) + '…' : event.err; record.err = err; } const line = JSON.stringify(record) + '\n'; diff --git a/lib/local-memory/manager.js b/lib/local-memory/manager.js index d97b569..981add1 100644 --- a/lib/local-memory/manager.js +++ b/lib/local-memory/manager.js @@ -259,7 +259,7 @@ export class LocalMemoryManager { const sources = {}; for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1; - this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace, detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }); + this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }); return result; } async search(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) { @@ -295,7 +295,7 @@ export class LocalMemoryManager { const store = await this.ensureProject(workspace); const removed = await store.forget(id, expectedRevision); await this.tryRegenerateProjections(); - this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } }); + this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } }); return removed; } async projects(workspace) { diff --git a/lib/routes.js b/lib/routes.js index 5df888f..873abdb 100644 --- a/lib/routes.js +++ b/lib/routes.js @@ -164,6 +164,7 @@ async function serveLocalMemory(deps, req, res) { return; } const url = new URL(req.url ?? '/', 'http://localhost'); + const workspace = url.searchParams.get('workspace')?.trim() || undefined; const marker = '/local-memory'; const markerAt = url.pathname.indexOf(marker); const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length); @@ -172,7 +173,7 @@ async function serveLocalMemory(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, ...(await manager.storageStatus()) }); + json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) }); return; } if (suffix === '/spaces') { @@ -180,7 +181,7 @@ async function serveLocalMemory(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, spaces: await manager.projects() }); + json(res, 200, { ok: true, spaces: await manager.projects(workspace) }); return; } if (suffix === '/documents') { @@ -188,7 +189,7 @@ async function serveLocalMemory(deps, req, res) { fail(res, 405, 'method-not-allowed'); return; } - json(res, 200, { ok: true, documents: await manager.documents() }); + json(res, 200, { ok: true, documents: await manager.documents(workspace) }); return; } if (suffix === '/memories') { @@ -198,7 +199,7 @@ async function serveLocalMemory(deps, req, res) { } const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)); const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0); - const page = await manager.list({ limit, offset }); + const page = await manager.list({ limit, offset }, workspace); json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }); return; } @@ -230,7 +231,8 @@ async function serveLocalMemory(deps, req, res) { return; } const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined; - json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision) }); + const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined; + json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) }); return; } if (suffix === '/search') { @@ -245,7 +247,7 @@ async function serveLocalMemory(deps, req, res) { } const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10); const k = Number.isFinite(requested) ? Math.max(1, Math.min(100, requested)) : 5; - const records = await manager.search(query, k); + const records = await manager.search(query, k, workspace); json(res, 200, { ok: true, query, count: records.length, matches: records.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }); return; } diff --git a/src-client/api.ts b/src-client/api.ts index 4ca3dd1..0a4d7c1 100644 --- a/src-client/api.ts +++ b/src-client/api.ts @@ -92,4 +92,3 @@ export function pickSettings(settings) { export function emptyTokens() { return { activity: '', memory: '', summary: '' } } - diff --git a/src-client/format.ts b/src-client/format.ts index b3aa7c4..466ac1b 100644 --- a/src-client/format.ts +++ b/src-client/format.ts @@ -95,4 +95,3 @@ export const MCP_STATE_LABELS = { unknown: '未知', needs_auth: '待授权', } - diff --git a/src-client/panel/BrainPanel.tsx b/src-client/panel/BrainPanel.tsx index 2c83d5c..6a25d8f 100644 --- a/src-client/panel/BrainPanel.tsx +++ b/src-client/panel/BrainPanel.tsx @@ -3,6 +3,7 @@ import * as React from 'react' import { Overview } from './Overview' import { MemoryTab } from './MemoryTab' import { DepartmentTab } from './DepartmentTab' +import { resolveWorkspace } from './workspace' import { SettingsCard } from '../SettingsCard' import styles from './BrainPanel.module.css' @@ -32,7 +33,10 @@ export function BrainPanel(props: { ctx?: any; panelId?: string; usePanelInfo?: let content: any if (tab === 'overview') content = h(Overview, { active }) else if (tab === 'connection') content = h(SettingsCard, null) - else if (tab === 'memory') content = h(MemoryTab, { ctx: props.ctx, active }) + else if (tab === 'memory') { + const workspace = resolveWorkspace(props.ctx) + content = h(MemoryTab, { key: workspace ?? '', workspace, active }) + } else if (tab === 'departments') content = h(DepartmentTab, { ctx: props.ctx, active }) else if (tab === 'skills') content = h(Placeholder, { title: '技能' }) else content = h(Placeholder, { title: 'MCP' }) diff --git a/src-client/panel/MemoryTab.tsx b/src-client/panel/MemoryTab.tsx index 00e6fa4..eca1358 100644 --- a/src-client/panel/MemoryTab.tsx +++ b/src-client/panel/MemoryTab.tsx @@ -5,6 +5,7 @@ import { formatIso, formatTime } from '../format' import { styles } from '../styles' import { Banner, Btn, Field, Pill, Section } from '../components' import { useApi } from './useApi' +import { workspaceQuery } from './workspace' const h = React.createElement const PAGE_SIZE = 50 @@ -13,8 +14,9 @@ function workspaceSuffix(workspace: string | undefined): string { return workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace) } -export function MemoryTab(props: { ctx?: any; active?: boolean }): any { +export function MemoryTab(props: { workspace?: string; active?: boolean }): any { const active = props.active !== false + const workspace = props.workspace const [offset, setOffset] = React.useState(0) const [search, setSearch] = React.useState('') const [notice, setNotice] = React.useState(null) @@ -22,19 +24,19 @@ export function MemoryTab(props: { ctx?: any; active?: boolean }): any { const [busy, setBusy] = React.useState('') const status = useApi(async () => { - const result = await request('/dsh-brain/local-memory/status') + const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace)) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取本地记忆状态失败')) return result.body }, { visible: active, pollMs: 15000 }) const memories = useApi(async () => { - const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset)) + const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset) + workspaceSuffix(workspace)) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败')) return result.body }, { visible: active, deps: [offset] }) const documents = useApi(async () => { - const result = await request('/dsh-brain/local-memory/documents') + const result = await request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace)) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取文档列表失败')) return result.body }, { visible: active }) @@ -50,7 +52,7 @@ export function MemoryTab(props: { ctx?: any; active?: boolean }): any { const forget = async (item: any): Promise => { setBusy(item.id) try { - const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision }) + const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, workspace }) if (result.status !== 200 || result.body === null || result.body.ok !== true) { setNotice({ tone: 'bad', text: bodyError(result, '删除失败') }) } else { diff --git a/src-client/sections/ImportSection.tsx b/src-client/sections/ImportSection.tsx index ae71434..48d963b 100644 --- a/src-client/sections/ImportSection.tsx +++ b/src-client/sections/ImportSection.tsx @@ -298,4 +298,3 @@ export function ImportSection(props) { s.notice === null ? null : h(Banner, { tone: s.notice.tone }, s.notice.text), ) } - diff --git a/src-client/sections/McpCustomSection.tsx b/src-client/sections/McpCustomSection.tsx index 829a97c..3bc042f 100644 --- a/src-client/sections/McpCustomSection.tsx +++ b/src-client/sections/McpCustomSection.tsx @@ -96,4 +96,3 @@ export function McpCustomSection(props) { ) : null, ) } - diff --git a/src-client/sections/SyncResolveSection.tsx b/src-client/sections/SyncResolveSection.tsx index 04cb5eb..6d1e78c 100644 --- a/src-client/sections/SyncResolveSection.tsx +++ b/src-client/sections/SyncResolveSection.tsx @@ -115,4 +115,3 @@ export function SyncResolveSection(props) { // method answers 405 on current dsh-mcp-connector builds, so the card only // rendered an error banner. Discover/install stays in the host's own // plugin market instead of a broken embedded panel. - diff --git a/src-client/sidebar/ProjectMemoryView.tsx b/src-client/sidebar/ProjectMemoryView.tsx index 39a2250..7eabc4d 100644 --- a/src-client/sidebar/ProjectMemoryView.tsx +++ b/src-client/sidebar/ProjectMemoryView.tsx @@ -5,6 +5,7 @@ import { formatIso } from '../format' import { styles } from '../styles' import { Banner, Btn, Field, Pill } from '../components' import { useApi } from '../panel/useApi' +import { workspaceQuery } from '../panel/workspace' import styles2 from './ProjectMemory.module.css' const h = React.createElement @@ -29,13 +30,14 @@ export function ProjectMemoryView(props: { ctx?: any; scope?: { cwd?: string; se const [notice, setNotice] = React.useState(null) const status = useApi(async () => { - const result = await request('/dsh-brain/local-memory/status') + const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace)) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取本地记忆状态失败')) return result.body }, { visible, pollMs: 15000 }) const memories = useApi(async () => { - const result = await request('/dsh-brain/local-memory/memories?limit=50&offset=0') + const suffix = workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace) + const result = await request('/dsh-brain/local-memory/memories?limit=50&offset=0' + suffix) if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败')) return result.body }, { visible, pollMs: 30000 }) diff --git a/src-client/sidebar/register.ts b/src-client/sidebar/register.ts index df3af74..b9d92fc 100644 --- a/src-client/sidebar/register.ts +++ b/src-client/sidebar/register.ts @@ -45,7 +45,7 @@ export function mountBrainSidebarTab(ctx: any): () => void { icon: (size: number) => React.createElement(BrainIcon, { size }), order: 60, single: true, - component: ({ scope, visible }: BetterSidebarTabProps) => React.createElement(ProjectMemoryView, { ctx, scope, visible }), + component: ({ scope, visible }: BetterSidebarTabProps) => React.createElement(ProjectMemoryView, { key: scope?.cwd ?? '', ctx, scope, visible }), }) current = { service, dispose } } diff --git a/src-client/styles.ts b/src-client/styles.ts index 62638c6..0499396 100644 --- a/src-client/styles.ts +++ b/src-client/styles.ts @@ -365,4 +365,3 @@ export const styles = { overflowWrap: 'anywhere', }, } - diff --git a/src/diagnostics.ts b/src/diagnostics.ts index 45f692e..0104181 100644 --- a/src/diagnostics.ts +++ b/src/diagnostics.ts @@ -46,7 +46,7 @@ function dateStamp(date: Date): string { return String(date.getFullYear()) + '-' function sanitizeValue(value: unknown): unknown { if (typeof value === 'string') { if (containsSecret(value)) return '[redacted]' - return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS) + '…' : value + return value.length > MAX_FIELD_CHARS ? value.slice(0, MAX_FIELD_CHARS - 1) + '…' : value } if (typeof value === 'number' || typeof value === 'boolean' || value === null) return value if (Array.isArray(value)) return value.slice(0, 20).map((item) => sanitizeValue(item)) @@ -101,7 +101,7 @@ export class BrainLogger { const detail = sanitizeDetail(event.detail) if (detail !== undefined && Object.keys(detail).length > 0) record.detail = detail if (event.err !== undefined) { - const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS) + '…' : event.err + const err = containsSecret(event.err) ? '[redacted]' : event.err.length > MAX_ERR_CHARS ? event.err.slice(0, MAX_ERR_CHARS - 1) + '…' : event.err record.err = err } const line = JSON.stringify(record) + '\n' diff --git a/src/local-memory/manager.ts b/src/local-memory/manager.ts index 65d89a1..faa2713 100644 --- a/src/local-memory/manager.ts +++ b/src/local-memory/manager.ts @@ -230,7 +230,7 @@ export class LocalMemoryManager { const result = hits.slice(0, limit) const sources: Record = {} for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1 - this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace, detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }) + this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } }) return result } async search(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise { @@ -263,7 +263,7 @@ export class LocalMemoryManager { const store = await this.ensureProject(workspace) const removed = await store.forget(id, expectedRevision) await this.tryRegenerateProjections() - this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace, detail: { recordId: id, revision: removed.revision } }) + this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } }) return removed } async projects(workspace?: string): Promise<{ id: string; name: string }[]> { diff --git a/src/routes.ts b/src/routes.ts index bf21a5d..28a69c1 100644 --- a/src/routes.ts +++ b/src/routes.ts @@ -262,29 +262,30 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv return } const url = new URL(req.url ?? '/', 'http://localhost') + const workspace = url.searchParams.get('workspace')?.trim() || undefined const marker = '/local-memory' const markerAt = url.pathname.indexOf(marker) const suffix = markerAt < 0 ? '' : url.pathname.slice(markerAt + marker.length) if (suffix === '' || suffix === '/' || suffix === '/status') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } - json(res, 200, { ok: true, ...(await manager.storageStatus()) }) + json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) }) return } if (suffix === '/spaces') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } - json(res, 200, { ok: true, spaces: await manager.projects() }) + json(res, 200, { ok: true, spaces: await manager.projects(workspace) }) return } if (suffix === '/documents') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } - json(res, 200, { ok: true, documents: await manager.documents() }) + json(res, 200, { ok: true, documents: await manager.documents(workspace) }) return } if (suffix === '/memories') { if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return } const limit = Math.max(1, Math.min(1000, Number.parseInt(url.searchParams.get('limit') ?? '50', 10) || 50)) const offset = Math.max(0, Number.parseInt(url.searchParams.get('offset') ?? '0', 10) || 0) - const page = await manager.list({ limit, offset }) + const page = await manager.list({ limit, offset }, workspace) json(res, 200, { ok: true, total: page.total, items: page.items.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }) return } @@ -298,7 +299,8 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv const id = typeof input.id === 'string' ? input.id.trim() : '' if (id === '') { fail(res, 400, 'id-required'); return } const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined - json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision) }) + const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined + json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) }) return } if (suffix === '/search') { @@ -307,7 +309,7 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv if (query === '') { fail(res, 400, 'query-required'); return } const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10) const k = Number.isFinite(requested) ? Math.max(1, Math.min(100, requested)) : 5 - const records = await manager.search(query, k) + const records = await manager.search(query, k, workspace) json(res, 200, { ok: true, query, count: records.length, matches: records.map((record) => ({ id: record.id, scope: record.scope, content: record.content, category: record.category, tags: record.tags, source: record.source, revision: record.revision, updatedAt: record.updatedAt })) }) return } diff --git a/tsdown.config.ts b/tsdown.config.ts index cced56e..add5a29 100644 --- a/tsdown.config.ts +++ b/tsdown.config.ts @@ -22,11 +22,12 @@ function brainCssPlugin(): TsdownPlugin { resolveId(source: string, importer: string | undefined) { if (!source.endsWith('.module.css')) return null const absolute = importer === undefined ? source : resolvePath(dirname(importer), source) - return CSS_VIRTUAL_PREFIX + absolute + CSS_VIRTUAL_SUFFIX + const rel = relative(process.cwd(), absolute).replaceAll('\\', '/') + return CSS_VIRTUAL_PREFIX + rel + CSS_VIRTUAL_SUFFIX }, async load(virtualId: string) { if (!virtualId.startsWith(CSS_VIRTUAL_PREFIX)) return null - const fileId = virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length) + const fileId = resolvePath(process.cwd(), virtualId.slice(CSS_VIRTUAL_PREFIX.length, -CSS_VIRTUAL_SUFFIX.length)) this.addWatchFile(fileId) const source = await readFile(fileId, 'utf8') const filename = relative(process.cwd(), fileId).replaceAll('\\', '/') diff --git a/verify-client-build.mjs b/verify-client-build.mjs index bc42cbc..fa2cf27 100644 --- a/verify-client-build.mjs +++ b/verify-client-build.mjs @@ -3,7 +3,12 @@ // legacy hand-written file, and registers the same settings seats. // U1: the Brain panel registers on both native seats (main + sidebar.panellist) // and degrades silently when a seat is missing. +import { once } from 'node:events' import { existsSync, readFileSync } from 'node:fs' +import { mkdir, mkdtemp, rm } from 'node:fs/promises' +import { createServer } from 'node:http' +import { tmpdir } from 'node:os' +import { join } from 'node:path' import { createRequire } from 'node:module' import vm from 'node:vm' @@ -19,6 +24,9 @@ function check(name, ok, detail = '') { const bundle = readFileSync(new URL('./client/index.js', import.meta.url), 'utf8') check('client bundle uses the __ModuleLoader__ contract', bundle.includes('__ModuleLoader__.load')) check('client bundle id stays dsh-brain', /id:\s*['"]dsh-brain['"]/.test(bundle)) +const cssModuleIds = [...bundle.matchAll(/^\s*\/\/ \S*?dsh-brain-css:(\S+)$/gm)].map((match) => match[1]) +check('client CSS module comments use portable repository paths', + cssModuleIds.length === 2 && cssModuleIds.every((id) => /^src-client\/.*\.module\.css\.mjs$/.test(id))) for (const seat of ['settings.section', 'plugins.bundle.config', 'sidebar.panellist']) { check('client bundle registers ' + seat, bundle.includes(seat)) } @@ -158,5 +166,62 @@ if (existsSync(legacyFile)) { console.log('SKIP legacy comparison (artifacts/analysis/client-legacy.js missing)') } +// Keep the static request checks local to each consumer, so the presence of a +// workspace parameter elsewhere in the bundle cannot satisfy them. +const memoryTab = readFileSync(new URL('./src-client/panel/MemoryTab.tsx', import.meta.url), 'utf8') +const sidebar = readFileSync(new URL('./src-client/sidebar/ProjectMemoryView.tsx', import.meta.url), 'utf8') +check('memory tab scopes status, memories and documents to the active workspace', + memoryTab.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") && + memoryTab.includes("'&offset=' + String(offset) + workspaceSuffix(workspace)") && + memoryTab.includes("request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace))")) +check('sidebar scopes status and memories to its workspace', + sidebar.includes('props.scope?.cwd') && + sidebar.includes("request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))") && + sidebar.includes("'&workspace=' + encodeURIComponent(workspace)") && + sidebar.includes("request('/dsh-brain/local-memory/memories?limit=50&offset=0' + suffix)")) + +const root = await mkdtemp(join(tmpdir(), 'brain-ui-workspace-')) +try { + const [projectA, projectB] = [join(root, 'project a'), join(root, 'project b')] + await Promise.all([mkdir(projectA), mkdir(projectB)]) + const { LocalMemoryManager, projectBrainRoot } = await import('./lib/local-memory/index.js') + const { createCoreRoutes, ROUTES } = await import('./lib/routes.js') + const localMemory = new LocalMemoryManager({ cwd: () => projectA, globalRoot: join(root, 'global') }) + const a = await localMemory.withWorkspace(projectA, () => localMemory.remember({ scope: 'project', content: 'workspace A sample' })) + const b = await localMemory.withWorkspace(projectB, () => localMemory.remember({ scope: 'project', content: 'workspace B sample' })) + const documentB = await localMemory.addDocument({ title: 'Workspace B document', content: 'workspace B sample document' }, projectB) + const route = createCoreRoutes({ localMemory }).find((entry) => entry.path === ROUTES.localMemory) + const server = createServer((req, res) => { + void route.handler(req, res).catch(() => { res.statusCode = 500; res.end() }) + }) + server.listen(0, '127.0.0.1') + try { + await once(server, 'listening') + const origin = 'http://127.0.0.1:' + server.address().port + const base = origin + ROUTES.localMemory + const workspace = '?workspace=' + encodeURIComponent(projectB) + const getJson = async (suffix) => { + const response = await fetch(base + suffix) + if (!response.ok) throw new Error(suffix + ': HTTP ' + response.status) + return response.json() + } + const [defaultPage, scopedPage, status, documents] = await Promise.all([ + getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace), + ]) + check('omitting workspace still lists the default project', defaultPage.total === 1 && defaultPage.items[0]?.id === a.record.id) + check('workspace query lists only the selected project fixture', scopedPage.total === 1 && scopedPage.items[0]?.id === b.record.id) + check('status and documents read the selected project', status.projectRoot === projectBrainRoot(projectB) && documents.documents[0]?.id === documentB.id) + const forget = await fetch(base + '/forget', { + method: 'POST', headers: { origin, 'content-type': 'application/json' }, + body: JSON.stringify({ id: b.record.id, expectedRevision: b.record.revision, workspace: projectB }), + }) + check('forget uses the target workspace and preserves the default project', forget.ok && (await getJson('/memories' + workspace)).total === 0 && (await getJson('/memories')).items[0]?.id === a.record.id) + } finally { + await new Promise((resolve) => server.close(resolve)) + } +} finally { + await rm(root, { recursive: true, force: true }) +} + console.log('\n' + (results.every((result) => result.ok) ? 'ALL ' + results.length + ' CHECKS PASSED' : results.filter((result) => !result.ok).length + ' FAILED')) process.exit(results.every((result) => result.ok) ? 0 : 1) diff --git a/verify-diagnostics.mjs b/verify-diagnostics.mjs index c3edae7..08fed13 100644 --- a/verify-diagnostics.mjs +++ b/verify-diagnostics.mjs @@ -44,11 +44,21 @@ const record = await memory.remember({ content: '项目 A 使用 pnpm 管理依 await memory.search('pnpm') await memory.forget(record.record.id) await memory.remember({ content: '全局 TypeScript 经验', category: 'fact', scope: 'global' }) +const queryB = 'project-b-search-fixture' +await memory.withWorkspace(projectB, async () => { + const saved = await memory.remember({ content: queryB, scope: 'project' }) + await memory.search(queryB) + await memory.forget(saved.record.id) +}) await logger.flush() const projectLogs = readLogs(projectBrainRoot(projectA)) const globalLogs = readLogs(globalBrainRoot()) check('project operations write a project JSONL file', projectLogs.files.length > 0) +const projectBLogs = readLogs(projectBrainRoot(projectB)).entries +const isProjectBSearch = (entry) => entry.event === 'memory.search' && entry.detail?.query === queryB +check('context-only search logs in project B and stays out of project A', projectBLogs.some((entry) => isProjectBSearch(entry) && entry.detail.hits === 1) && !projectLogs.entries.some(isProjectBSearch)) +check('context-only forget logs in project B', projectBLogs.some((entry) => entry.event === 'memory.forget') && projectLogs.entries.filter((entry) => entry.event === 'memory.forget').length === 1) const projectEvents = projectLogs.entries.map((entry) => entry.event) for (const event of ['memory.ensure', 'memory.remember', 'memory.search', 'memory.forget']) { check('project log contains ' + event, projectEvents.includes(event), JSON.stringify(projectEvents)) @@ -60,11 +70,13 @@ check('memory.remember carries structured detail only', rememberEntry !== undefi // ── 2/3. secret redaction and content truncation ───────────────────────── logger.log({ event: 'test.secret', detail: { note: 'api_key: sk-abcdef1234567890' } }) -logger.log({ event: 'test.long', detail: { content: 'x'.repeat(700) } }) +logger.log({ event: 'test.long', detail: { content: 'x'.repeat(130) }, err: 'y'.repeat(310) }) await logger.flush() const afterSpecial = readLogs(globalBrainRoot()).text check('secret-like detail is redacted', !afterSpecial.includes('sk-abcdef1234567890') && afterSpecial.includes('[redacted]')) -check('long detail is truncated at 120 chars', !afterSpecial.includes('x'.repeat(121))) +const truncated = readLogs(globalBrainRoot()).entries.find((entry) => entry.event === 'test.long') +check('long detail is truncated at 120 chars including ellipsis', truncated?.detail?.content === 'x'.repeat(119) + '…') +check('long error is truncated at 300 chars including ellipsis', truncated?.err === 'y'.repeat(299) + '…') // ── 4. rotation and retention ──────────────────────────────────────────── const rotationRoot = join(home, 'rotation')