fix(ui): separate global, project, and settings surfaces

This commit is contained in:
newbie 2026-11-26 16:53:07 +08:00
parent 81074c99f4
commit 7d306e77ad
28 changed files with 859 additions and 1110 deletions

View File

@ -9,8 +9,11 @@
同步云端技能中心与本机技能目录。
当前版本 **0.10.1**,含宿主端与浏览器端两部分:宿主端负责活动上报、
记忆工具注册与技能同步,`client/index.js` 提供「设置 → 插件 → 云端记忆」
配置卡片。
记忆工具注册与技能同步。浏览器 UI 有三个入口:
- 左侧栏 **Brain** 展示全局运行状态,管理全局记忆与部门。
- Better Sidebar 的 **项目记忆** 使用当前会话的项目目录,管理该项目的记忆、文档与部门。
- **设置 → 云端记忆** 提供完整配置,包括连接与上报、技能管理和 MCP 管理。
## 它做什么
@ -21,7 +24,7 @@
| 失败重试 | 网络错误与 5xx 进入待重试队列(上限 200 条),每 30 秒补发一次;4xx 不重试。切换账号或换服务地址后,旧队列条目会被丢弃,不会发到新账号。 |
| 记忆工具 | `memory_search`、`memory_read`、`memory_add`、`memory_list`、`memory_projects` 五个工具实时读写云端记忆库。 |
| 技能同步 | 云端技能中心 ↔ 本机技能目录双向同步,冲突按内容与时间自动取较新(详见「技能同步」)。 |
| 配置页 | `GET /dsh-brain` 提供完整配置界面(本 profile 关闭了原生设置页,所以自带页面)。 |
| 配置页 | 设置中的「云端记忆」提供完整配置,另有独立页面 `GET /dsh-brain`。 |
**上传范围(如实说明)**:活动上报只上传上表 6 个元数据字段,不含提示词
正文。**可选的摘要功能**(`summaryToken`)开启时,会把结束回合的对话文本
@ -46,7 +49,7 @@
- 共享服务(设置、客户端、同步引擎)由进程级内核统一构造,关掉再开不会
重复实例;设置持久化在 `$DSH_HOME/dsh-brain.json`(侧车文件为权威,
插件行的 config 只作首次种子)。
- 根导出 `.` 仍是兼容组合器:老的单行 profile 升级后行为不变。
- UI 子插件以包根名 `dsh-brain` 注册,供 DSH 发现浏览器端入口;该子插件行传入 `entry: ui`。旧的单行 profile 继续通过根导出加载全部子插件。
- 0.11.0 起第五个子插件行 id 从 `dsh-brain-settings-ui` 改为 `dsh-brain-ui`(package exports 保留 `./settings-ui` 别名指向同一入口)。若 profile 里还留有旧 id 的禁用/配置行,请到「设置 → 插件」对 `dsh-brain-ui` 重新设置;插件不会自动改写宿主配置文件。
## 安装
@ -57,8 +60,8 @@ dsh plugin --profile desktop add dsh-brain
```
装好后确认 profile 的 `package.json` 依赖里有 `dsh-brain`。重启 DSH,在
「设置 → 插件 → 云端记忆」里配置(备用入口:
`http://127.0.0.1:<当次端口>/dsh-brain`,旧 `/cloud-memory` 路由保留为别名)。
「设置 → 云端记忆」里配置。也可从插件详情的配置入口或
`http://127.0.0.1:<当次端口>/dsh-brain` 使用完整配置,旧 `/cloud-memory` 路由保留为别名。
> `baseUrl` 默认是占位符 `https://your-memory-host/api/longmemory`。
> **首次使用必须先把它改成你自己的 LongMemory 服务地址**(配置页里填,

File diff suppressed because it is too large Load Diff

View File

@ -33,4 +33,7 @@
- id: dsh-brain-mcp
name: dsh-brain/mcp
- id: dsh-brain-ui
name: dsh-brain/ui
# DSH discovers browser bundles from bare package names.
name: dsh-brain
config:
entry: ui

View File

@ -7,8 +7,12 @@ import * as ui from "./entries/ui.js";
export const name = 'dsh-brain';
/** Services required before `apply` runs. */
export const inject = ['webServer'];
/** Register the plugin with the host: all five sub-entries at once. */
/** Mount the discoverable UI row or the legacy all-in-one plugin. */
export function apply(ctx, config) {
if (config !== null && typeof config === 'object' && 'entry' in config && config.entry === 'ui') {
ui.apply(ctx, config);
return;
}
cloudsync.apply(ctx, config);
memory.apply(ctx, config);
skills.apply(ctx, config);

View File

@ -47,8 +47,10 @@ export class DepartmentManager {
return global;
return (await this.registry('project').read()).departments.find((item) => item.id === id);
}
async required(id) {
const department = await this.find(id);
async required(id, scope) {
const department = scope === undefined
? await this.find(id)
: (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope);
if (department === undefined)
throw new Error('department_not_found');
return department;
@ -88,8 +90,8 @@ export class DepartmentManager {
const files = await Promise.all(scopes.map((item) => this.registry(item).read()));
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id));
}
async update(id, patch, expectedRevision) {
const current = await this.required(id);
async update(id, patch, expectedRevision, scope) {
const current = await this.required(id, scope);
if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict');
if (patch.role !== undefined && containsSecret(patch.role))
@ -162,8 +164,8 @@ export class DepartmentManager {
});
return { ...reference, hostSessionId: externalId };
}
async checkpoint(id, input, expectedRevision) {
const current = await this.required(id);
async checkpoint(id, input, expectedRevision, scope) {
const current = await this.required(id, scope);
if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict');
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000);
@ -204,12 +206,17 @@ export class DepartmentManager {
});
}
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
async recall(id, query, k = 5, workspace) {
const department = await this.required(id);
async recall(id, query, k = 5, workspace, scope) {
const department = await this.required(id, scope);
const limit = limitOf(k);
const privateHits = await this.store(department).search(query, limit);
const shared = [];
if (department.memory.readProject && department.memory.readGlobal) {
if (scope !== undefined) {
const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject;
if (readShared)
shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope));
}
else if (department.memory.readProject && department.memory.readGlobal) {
shared.push(...await this.memory.searchHits(query, limit * 2, workspace));
}
else if (department.memory.readGlobal) {
@ -234,8 +241,8 @@ export class DepartmentManager {
}).slice(0, limit);
}
/** Disable without deleting private memories or allowing automatic session recovery. */
async disable(id, expectedRevision) {
const current = await this.required(id);
async disable(id, expectedRevision, scope) {
const current = await this.required(id, scope);
if (expectedRevision !== undefined && current.revision !== expectedRevision)
throw new Error('revision_conflict');
const store = this.store(current);

View File

@ -107,6 +107,9 @@ export class LocalMemoryManager {
get projectRoot() { return this.projectRootFor(); }
get globalStore() { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global'); }
projectStoreFor(workspace) { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))); }
scopedStore(scope, workspace) {
return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace);
}
async storeFor(scope, workspace) {
if (scope === 'global')
return this.globalStore;
@ -251,21 +254,24 @@ export class LocalMemoryManager {
return false; seen.add(record.id); return true; })
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt));
}
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId) {
async searchHits(query, k = this.settingsOf().localMemoryK ?? 5, workspace, projectId, scope) {
const startedAt = Date.now();
const hits = await this.collectHits(query, workspace, projectId);
const limit = Math.max(1, Math.min(100, Math.trunc(k)));
const result = hits.slice(0, limit);
const result = scope === undefined
? (await this.collectHits(query, workspace, projectId)).slice(0, limit)
: await this.scopedStore(scope, workspace).search(query, limit);
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: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } });
this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : 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) {
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record);
}
async list(options = {}, workspace, projectId) {
if (options.scope !== undefined)
return this.scopedStore(options.scope, workspace).list(options);
const projectStore = await this.ensureProject(workspace);
const records = [...(await this.globalStore.records()), ...(await projectStore.records())];
const scoped = records.filter((record) => {
@ -283,19 +289,24 @@ export class LocalMemoryManager {
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)));
return { items: ordered.slice(offset, offset + limit), total: ordered.length };
}
async forget(id, expectedRevision, workspace) {
const globalRecord = await this.globalStore.read(id);
await this.markProjectionDirty();
if (globalRecord !== undefined) {
const removed = await this.globalStore.forget(id, expectedRevision);
await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } });
return removed;
async forget(id, expectedRevision, workspace, scope) {
const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global');
const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace);
if (scopedStore !== undefined) {
const record = await scopedStore.read(id);
if (record === undefined)
throw new Error('memory_not_found');
if (expectedRevision !== undefined && record.revision !== expectedRevision)
throw new Error('revision_conflict');
}
const store = await this.ensureProject(workspace);
// The runtime projections are built exclusively from the global store.
if (scope !== 'project')
await this.markProjectionDirty();
const store = scopedStore ?? await this.storeFor(targetScope, workspace);
const removed = await store.forget(id, expectedRevision);
await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } });
if (scope !== 'project')
await this.tryRegenerateProjections();
this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } });
return removed;
}
async projects(workspace) {
@ -317,11 +328,21 @@ export class LocalMemoryManager {
throw new Error('local_documents_unavailable');
return documents.add(input);
}
async storageStatus(workspace) {
const projectRoot = this.projectRootFor(workspace);
const global = await this.globalStore.spaceMeta();
const project = await this.projectStoreFor(workspace).spaceMeta();
return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false };
async storageStatus(workspace, scope) {
const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace);
const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta();
const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta();
return {
provider: 'local',
...(scope === 'project' ? {} : { globalRoot: this.globalRoot }),
...(projectRoot === undefined ? {} : { projectRoot }),
spaces: {
...(scope === 'project' ? {} : { global: global ?? null }),
...(scope === 'global' ? {} : { project: project ?? null }),
},
cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true,
localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false,
};
}
/** Return the compact per-turn projection used by the system prompt. */
projectionText(limit = 2000) {

View File

@ -168,12 +168,28 @@ async function serveLocalMemory(deps, req, res) {
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 (suffix === '' || suffix === '/' || suffix === '/status' || suffix === '/memories') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) });
const scope = url.searchParams.get('scope') ?? undefined;
if (scope !== undefined && scope !== 'global' && scope !== 'project') {
fail(res, 400, 'invalid-scope');
return;
}
if (scope === 'project' && workspace === undefined) {
fail(res, 400, 'workspace-required');
return;
}
if (suffix !== '/memories') {
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) });
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, scope }, 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;
}
if (suffix === '/spaces') {
@ -189,18 +205,16 @@ async function serveLocalMemory(deps, req, res) {
fail(res, 405, 'method-not-allowed');
return;
}
json(res, 200, { ok: true, documents: await manager.documents(workspace) });
return;
}
if (suffix === '/memories') {
if (req.method !== 'GET') {
fail(res, 405, 'method-not-allowed');
const scope = url.searchParams.get('scope');
if (scope !== null && scope !== 'project') {
fail(res, 400, 'invalid-scope');
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 }, 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 })) });
if (scope === 'project' && workspace === undefined) {
fail(res, 400, 'workspace-required');
return;
}
json(res, 200, { ok: true, documents: await manager.documents(workspace) });
return;
}
if (suffix === '/forget') {
@ -232,7 +246,31 @@ async function serveLocalMemory(deps, req, res) {
}
const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined;
const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined;
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) });
const scope = input.scope;
if (scope !== undefined && scope !== 'global' && scope !== 'project') {
fail(res, 400, 'invalid-scope');
return;
}
if (scope === 'project' && targetWorkspace === undefined) {
fail(res, 400, 'workspace-required');
return;
}
try {
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace, scope) });
}
catch (error) {
if (scope === undefined || !(error instanceof Error))
throw error;
if (error.message === 'memory_not_found') {
fail(res, 404, error.message);
return;
}
if (error.message === 'revision_conflict') {
fail(res, 409, error.message);
return;
}
throw error;
}
return;
}
if (suffix === '/search') {

View File

@ -7,6 +7,8 @@ function errorStatus(message) {
return 409;
if (message === 'department_disabled')
return 409;
if (message === 'invalid-scope' || message === 'workspace-required')
return 400;
if (message === 'department_required_field' || message === 'department_invalid_host' || message === 'secret_not_allowed')
return 400;
return undefined;
@ -37,6 +39,15 @@ async function bodyObject(req, res) {
}
function stringField(value) { return typeof value === 'string' ? value : undefined; }
function revisionField(value) { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined; }
function requestScope(value, workspace) {
if (value === undefined)
return undefined;
if (value !== 'global' && value !== 'project')
throw new Error('invalid-scope');
if (value === 'project' && workspace === undefined)
throw new Error('workspace-required');
return value;
}
export async function serveDepartments(deps, req, res) {
const manager = deps.departments;
if (manager === undefined) {
@ -48,6 +59,7 @@ export async function serveDepartments(deps, req, res) {
return;
}
const withWorkspace = (workspace, job) => deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job);
const withScope = (scope, workspace, job) => scope === undefined ? withWorkspace(workspace, job) : manager.memory.withWorkspace(scope === 'project' ? workspace : undefined, job);
const url = new URL(req.url ?? '/', 'http://localhost');
const marker = '/departments';
const at = url.pathname.indexOf(marker);
@ -112,6 +124,7 @@ export async function serveDepartments(deps, req, res) {
return;
}
const expectedRevision = revisionField(body.expectedRevision);
const scope = suffix === '/resume' ? undefined : requestScope(body.scope, workspace);
if (suffix === '/update') {
const patch = {
...(stringField(body.name) === undefined ? {} : { name: stringField(body.name) }),
@ -121,11 +134,11 @@ export async function serveDepartments(deps, req, res) {
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
};
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) });
json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.update(id, patch, expectedRevision, scope)) });
return;
}
if (suffix === '/disable') {
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) });
json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.disable(id, expectedRevision, scope)) });
return;
}
if (suffix === '/checkpoint') {
@ -133,7 +146,7 @@ export async function serveDepartments(deps, req, res) {
...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }),
...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }),
};
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) });
json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.checkpoint(id, input, expectedRevision, scope)) });
return;
}
const host = stringField(body.host)?.trim() || 'dsh';
@ -158,7 +171,8 @@ export async function serveDepartments(deps, req, res) {
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10);
const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5;
const workspace = url.searchParams.get('workspace')?.trim() || undefined;
const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace));
const scope = requestScope(url.searchParams.get('scope') ?? undefined, workspace);
const hits = await withScope(scope, workspace, () => manager.recall(id, query, k, workspace, scope));
json(res, 200, { ok: true, hits: hits.map((hit) => ({ ...hit, content: hit.record.content, contentSnippet: departmentSnippet(hit.record.content) })) });
return;
}

View File

@ -1,64 +0,0 @@
// Slim settings card: status summary + a jump into the Brain total panel.
import * as React from 'react'
import { API, request, messageOf } from './api'
import { styles } from './styles'
import { Pill, Banner, Btn } from './components'
const h = React.createElement
export function SettingsSummaryCard(props: { ctx?: any }): any {
const [status, setStatus] = React.useState<any>(null)
const [error, setError] = React.useState<string | null>(null)
React.useEffect(() => {
let cancelled = false
const load = (): void => {
request(API.status).then(
(result) => {
if (cancelled) return
if (result.status === 200 && result.body !== null && result.body.ok === true) {
setStatus(result.body)
setError(null)
} else {
setError('读取状态失败(HTTP ' + String(result.status) + ')')
}
},
(failure) => { if (!cancelled) setError(messageOf(failure)) },
)
}
load()
const timer = setInterval(load, 15000)
return () => {
cancelled = true
clearInterval(timer)
}
}, [])
function openPanel(): void {
const ctx = props.ctx
const layout = ctx === undefined || ctx === null ? undefined : ctx.layout
if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') {
layout.selectPanel('dsh-brain')
return
}
if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain')
}
const settings = status?.settings ?? {}
return h('div', { style: styles.root, 'data-dsh-plugin': 'dsh-brain' },
h('div', { style: styles.sectionHead },
h('h4', { style: styles.sectionTitle }, '云端记忆'),
h('div', { style: styles.actions },
h(Btn, { variant: 'primary', label: '打开总面板', onClick: openPanel }),
),
),
h('p', { style: styles.hint }, '设置与连接内容已收进左侧栏 Brain 总面板的「连接与上报」页签。这里保留状态摘要和快捷入口。'),
error === null ? null : h(Banner, { tone: 'bad' }, error),
status === null ? h('p', { style: styles.hint }, '正在读取状态…') : h('div', { style: styles.pills },
h(Pill, { label: '服务', value: settings.baseUrlConfigured === false ? '未配置' : '已配置', tone: settings.baseUrlConfigured === false ? 'warn' : 'ok' }),
h(Pill, { label: '上报', value: settings.activityEnabled === true ? '开' : '关', tone: settings.activityEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '本地记忆', value: settings.localMemoryEnabled === false ? '关' : '开', tone: settings.localMemoryEnabled === false ? 'muted' : 'ok' }),
),
)
}

View File

@ -3,7 +3,6 @@ import * as React from 'react'
import { messageOf } from './api'
import { CardBoundary } from './components'
import { SettingsCard } from './SettingsCard'
import { SettingsSummaryCard } from './SettingsSummaryCard'
import { registerBrainPanel } from './panel/register'
import { mountBrainSidebarTab } from './sidebar/register'
@ -12,11 +11,6 @@ const h = React.createElement
export const inject = ['slots']
export function apply(ctx: any): void {
const summaryCard = function () {
return h(CardBoundary as any, null, h(SettingsSummaryCard as any, { ctx }))
}
// The plugin bundle config page keeps the full settings card; the generic
// settings section is now only the status summary with a jump button.
const configCard = function () {
return h(CardBoundary as any, null, h(SettingsCard as any, null))
}
@ -40,7 +34,7 @@ export function apply(ctx: any): void {
label: function () {
return '云端记忆'
},
}, summaryCard)
}, configCard)
try {
if (typeof ctx.effect === 'function') ctx.effect(() => registerBrainPanel(ctx), 'dsh-brain: panel')

View File

@ -101,29 +101,6 @@
min-width: 0;
}
.placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 8px;
padding: 48px 16px;
border: 1px dashed var(--dsw-alias-border-subtle, rgba(127,127,127,0.30));
border-radius: 16px;
opacity: 0.65;
}
.placeholderTitle {
margin: 0;
font-size: 14px;
font-weight: 600;
}
.placeholderHint {
margin: 0;
font-size: 12px;
}
.overviewGrid {
display: flex;
flex-direction: column;

View File

@ -3,8 +3,6 @@ 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'
const h = React.createElement
@ -13,40 +11,24 @@ const TABS = [
{ id: 'overview', label: '概览' },
{ id: 'memory', label: '记忆' },
{ id: 'departments', label: '部门' },
{ id: 'skills', label: '技能' },
{ id: 'mcp', label: 'MCP' },
{ id: 'connection', label: '连接与上报' },
] as const
function Placeholder(props: { title: string }): any {
return h('div', { className: styles.placeholder },
h('h3', { className: styles.placeholderTitle }, props.title),
h('p', { className: styles.placeholderHint }, '即将上线'),
)
}
export function BrainPanel(props: { ctx?: any; panelId?: string; usePanelInfo?: any }): any {
export function BrainPanel(props: { panelId?: string; usePanelInfo?: any }): any {
const [tab, setTab] = React.useState('overview')
const panelId = props.panelId ?? 'dsh-brain'
const usePanelInfo = props.usePanelInfo
const active = usePanelInfo === undefined ? true : usePanelInfo((info: { activePanelId: string | null }) => info.activePanelId === panelId)
let content: any
if (tab === 'overview') content = h(Overview, { active })
else if (tab === 'connection') content = h(SettingsCard, null)
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' })
else if (tab === 'memory') content = h(MemoryTab, { scope: 'global', active })
else content = h(DepartmentTab, { scope: 'global', active })
return h('div', { className: styles.nativeWorkspace, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'brain-panel' },
h('div', { className: styles.windowDragBand, 'data-window-drag': true, 'aria-hidden': 'true' }),
h('div', { className: styles.panelInner },
h('div', { className: styles.header },
h('div', { className: styles.titleBlock },
h('h3', { className: styles.title }, 'Brain'),
h('p', { className: styles.subtitle }, '本地记忆、部门与连接的总面板'),
h('p', { className: styles.subtitle }, '全局记忆、部门与运行状态'),
),
),
h('div', { className: styles.tabBar, role: 'tablist', 'aria-label': 'Brain 面板页签' },

View File

@ -5,11 +5,11 @@ import { formatIso } from '../format'
import { styles } from '../styles'
import { Banner, Btn, Field, Pill, Section } from '../components'
import { useApi } from './useApi'
import { resolveWorkspace, workspaceQuery } from './workspace'
import { scopeParams, type BrainScope } from './workspace'
const h = React.createElement
const EMPTY_CREATE = { name: '', role: '', scope: 'project', skills: '', allowedTools: '', readGlobal: true, readProject: true }
const EMPTY_CREATE = { name: '', role: '', skills: '', allowedTools: '', readGlobal: true, readProject: true }
const ENDPOINTS = {
list: '/dsh-brain/departments/list',
@ -20,9 +20,10 @@ const ENDPOINTS = {
recall: '/dsh-brain/departments/recall',
} as const
export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
export function DepartmentTab(props: BrainScope & { active?: boolean }): any {
const active = props.active !== false
const workspace = resolveWorkspace(props.ctx)
const scope = scopeParams(props)
const scopeLabel = props.scope === 'global' ? '全局' : '项目'
const [notice, setNotice] = React.useState<any>(null)
const [busy, setBusy] = React.useState('')
const [form, setForm] = React.useState<any>({ ...EMPTY_CREATE })
@ -35,7 +36,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
const [recallBusy, setRecallBusy] = React.useState(false)
const list = useApi(async () => {
const result = await request(ENDPOINTS.list + workspaceQuery(workspace))
const result = await request(ENDPOINTS.list + '?' + scope.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取部门列表失败'))
return result.body
}, { visible: active, pollMs: 15000 })
@ -66,12 +67,11 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
const result = await postJson(ENDPOINTS.create, {
name: String(form.name).trim(),
role: String(form.role).trim() || undefined,
scope: form.scope,
skills: String(form.skills).split(/[,,\s]+/).filter((value) => value !== ''),
allowedTools: String(form.allowedTools).split(/[,,\s]+/).filter((value) => value !== ''),
readGlobal: form.readGlobal === true,
readProject: form.readProject === true,
workspace,
...Object.fromEntries(scope),
})
if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '创建部门失败'); return }
setNotice({ tone: 'ok', text: result.body.created === false ? '同名部门已存在,已复用。' : '部门已创建。' })
@ -87,7 +87,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
const mutate = async (action: 'update' | 'disable' | 'checkpoint'): Promise<void> => {
if (selected === undefined) return
setBusy(action)
const payload: any = { id: selected.id, expectedRevision: selected.revision, workspace }
const payload: any = { id: selected.id, expectedRevision: selected.revision, ...Object.fromEntries(scope) }
if (action === 'update') { payload.role = detail.role; payload.name = selected.name }
if (action === 'checkpoint') { payload.currentTask = detail.currentTask; payload.handoff = detail.handoff }
try {
@ -107,7 +107,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
setRecallBusy(true)
setRecallHits([])
try {
const query = ENDPOINTS.recall + '?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=' + encodeURIComponent(recallK) + (workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace))
const query = ENDPOINTS.recall + '?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=' + encodeURIComponent(recallK) + '&' + scope.toString()
const result = await request(query)
if (result.status !== 200 || result.body === null || result.body.ok !== true) { handleFailure(result, '召回失败'); return }
setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : [])
@ -121,7 +121,7 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
notice === null ? null : h(Banner, { tone: notice.tone }, notice.text),
list.error === null ? null : h(Banner, { tone: 'bad' }, list.error),
h(Section, { title: '部门列表', hint: '部门是本机可复用的工作身份;列表显示 scope、状态、当前任务与 revision。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => list.reload() }) },
h(Section, { title: scopeLabel + '部门列表', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => list.reload() }) },
departments.length === 0 ? h('p', { style: styles.hint }, '还没有部门。可在下方创建。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
departments.map((item) => h('div', { key: item.id, style: styles.row },
h('div', { style: styles.rowHead },
@ -152,17 +152,10 @@ export function DepartmentTab(props: { ctx?: any; active?: boolean }): any {
)),
),
),
h(Section, { title: '创建部门', hint: '同名部门会幂等复用,不会覆盖原角色。' },
h(Section, { title: '创建' + scopeLabel + '部门', hint: '同名部门会幂等复用,不会覆盖原角色。' },
h('div', { style: styles.grid },
h(Field, { label: '名称', value: form.name, onChange: (value) => setForm({ ...form, name: value }) }),
h(Field, { label: '角色', value: form.role, onChange: (value) => setForm({ ...form, role: value }) }),
h('div', { style: styles.field },
h('span', { style: styles.label }, '范围'),
h('select', { value: form.scope, style: styles.input, onChange: (event) => setForm({ ...form, scope: event.target.value }) },
h('option', { value: 'project' }, '项目'),
h('option', { value: 'global' }, '全局'),
),
),
h(Field, { label: '技能(逗号分隔)', value: form.skills, onChange: (value) => setForm({ ...form, skills: value }) }),
h(Field, { label: '允许工具(逗号分隔)', value: form.allowedTools, onChange: (value) => setForm({ ...form, allowedTools: value }) }),
),

View File

@ -1,22 +1,20 @@
// Memory tab: local-memory spaces, paged memory list, read-only documents, forget.
import * as React from 'react'
import { API, request, postJson, bodyError, messageOf } from '../api'
import { formatIso, formatTime } from '../format'
import { request, postJson, bodyError, messageOf } from '../api'
import { formatIso } from '../format'
import { styles } from '../styles'
import { Banner, Btn, Field, Pill, Section } from '../components'
import { useApi } from './useApi'
import { workspaceQuery } from './workspace'
import { scopeParams, type BrainScope } from './workspace'
const h = React.createElement
const PAGE_SIZE = 50
function workspaceSuffix(workspace: string | undefined): string {
return workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace)
}
export function MemoryTab(props: { workspace?: string; active?: boolean }): any {
export function MemoryTab(props: BrainScope & { active?: boolean }): any {
const active = props.active !== false
const workspace = props.workspace
const project = props.scope === 'project'
const scope = scopeParams(props)
const scopeLabel = project ? '项目' : '全局'
const [offset, setOffset] = React.useState(0)
const [search, setSearch] = React.useState('')
const [notice, setNotice] = React.useState<any>(null)
@ -24,22 +22,22 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any
const [busy, setBusy] = React.useState('')
const status = useApi(async () => {
const result = await request('/dsh-brain/local-memory/status' + workspaceQuery(workspace))
const result = await request('/dsh-brain/local-memory/status' + '?' + scope.toString())
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) + workspaceSuffix(workspace))
const result = await request('/dsh-brain/local-memory/memories?limit=' + String(PAGE_SIZE) + '&offset=' + String(offset) + '&' + scope.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取记忆列表失败'))
return result.body
}, { visible: active, deps: [offset] })
}, { visible: active, pollMs: project ? 30000 : undefined, deps: [offset] })
const documents = useApi(async () => {
const result = await request('/dsh-brain/local-memory/documents' + workspaceQuery(workspace))
const result = await request('/dsh-brain/local-memory/documents' + '?' + scope.toString())
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取文档列表失败'))
return result.body
}, { visible: active })
}, { visible: active && project })
const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : []
const needle = String(search).trim().toLowerCase()
@ -52,7 +50,7 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any
const forget = async (item: any): Promise<void> => {
setBusy(item.id)
try {
const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, workspace })
const result = await postJson('/dsh-brain/local-memory/forget', { id: item.id, expectedRevision: item.revision, ...Object.fromEntries(scope) })
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
setNotice({ tone: 'bad', text: bodyError(result, '删除失败') })
} else {
@ -67,21 +65,14 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any
}
}
const spaces = status.data?.spaces ?? {}
const globalSpace = spaces.global
const projectSpace = spaces.project
const space = status.data?.spaces?.[props.scope]
const root = project ? status.data?.projectRoot : status.data?.globalRoot
return h('div', { style: { display: 'flex', flexDirection: 'column', gap: '12px' } },
status.error === null ? null : h(Banner, { tone: 'bad' }, status.error),
h(Section, { title: '本地记忆空间', hint: '全局空间与当前项目空间都由本机文件保存;云同步只影响上报,不改变本地存储。', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); documents.reload() } }) },
h('div', { style: styles.pills },
h(Pill, { label: 'provider', value: status.data?.provider ?? '—', tone: 'muted' }),
h(Pill, { label: '全局空间', value: globalSpace === null || globalSpace === undefined ? '未创建' : (globalSpace.name ?? globalSpace.id ?? '就绪'), tone: globalSpace === null || globalSpace === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '项目空间', value: projectSpace === null || projectSpace === undefined ? '未创建' : (projectSpace.name ?? projectSpace.id ?? '就绪'), tone: projectSpace === null || projectSpace === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '本地记忆', value: status.data?.localMemoryEnabled === false ? '关' : '开', tone: status.data?.localMemoryEnabled === false ? 'bad' : 'ok' }),
h(Pill, { label: '云同步', value: status.data?.cloudSyncEnabled === true ? '开' : '关', tone: status.data?.cloudSyncEnabled === true ? 'ok' : 'muted' }),
),
status.data?.globalRoot === undefined ? null : h('p', { style: styles.hint }, '全局:' + String(status.data.globalRoot) + (status.data?.projectRoot === undefined ? '' : ' · 项目:' + String(status.data.projectRoot))),
h(Section, { title: scopeLabel + '记忆空间', aside: h(Btn, { label: '刷新', variant: 'small', onClick: () => { status.reload(); memories.reload(); if (project) documents.reload() } }) },
h(Pill, { label: '空间状态', value: status.status === 'loading' ? '读取中' : space?.name ?? (space ? '就绪' : '未创建'), tone: space ? 'ok' : 'muted' }),
root === undefined ? null : h('p', { style: styles.hint }, String(root)),
),
h(Section, { title: '记忆条目(' + String(total) + ')', hint: '只显示当前页;搜索只在当前页内过滤。删除需要二次确认并带 revision 校验。', aside: h('div', { style: styles.actions },
h(Field, { label: '搜索当前页', value: search, onChange: setSearch }),
@ -120,7 +111,7 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any
h(Btn, { label: '下一页', variant: 'small', disabled: offset + PAGE_SIZE >= total || memories.status === 'loading', onClick: () => setOffset(offset + PAGE_SIZE) }),
),
),
h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' },
project ? h(Section, { title: '文档(只读)', hint: '项目文档由本地记忆库维护;这里只展示标题与摘要。' },
documents.error === null ? null : h(Banner, { tone: 'bad' }, documents.error),
(documents.data?.documents ?? []).length === 0 ? h('p', { style: styles.hint }, '当前项目还没有文档。') : h('div', { style: { display: 'flex', flexDirection: 'column', gap: '8px' } },
(documents.data?.documents ?? []).map((doc: any) => h('div', { key: doc.id, style: styles.row },
@ -134,6 +125,6 @@ export function MemoryTab(props: { workspace?: string; active?: boolean }): any
h('div', { style: styles.clamp2 }, String(doc.content ?? '')),
)),
),
),
) : null,
)
}

View File

@ -45,7 +45,7 @@ export function Overview(props: { active?: boolean }): any {
const [statusResult, capabilitiesResult, memoryResult] = await Promise.all([
request(API.status),
request(API.capabilities),
request('/dsh-brain/local-memory/status'),
request('/dsh-brain/local-memory/status?scope=global'),
])
if (cancelled) return
if (statusResult.status === 200 && statusResult.body !== null && statusResult.body.ok === true) {
@ -87,7 +87,7 @@ export function Overview(props: { active?: boolean }): any {
h(Pill, { label: '记忆', value: settings.memoryEnabled === true ? '开' : '关', tone: settings.memoryEnabled === true ? 'ok' : 'muted' }),
h(Pill, { label: '诊断日志', value: settings.diagnosticsEnabled === false ? '关' : '开', tone: settings.diagnosticsEnabled === false ? 'muted' : 'ok' }),
),
h('p', { className: styles.hint }, '诊断日志位置:$DSH_HOME/brain/logs(全局)与 <项目>/.dsh/brain/logs(项目)'),
h('p', { className: styles.hint }, '全局诊断日志:$DSH_HOME/brain/logs'),
status?.lastCheck === null || status?.lastCheck === undefined ? null : h('p', { className: styles.hint }, '最近检查:' + formatTime(status.lastCheck.at) + ' · ' + String(status.lastCheck.status ?? '')),
),
h(Card, { title: '五个 bundle 开关态' },
@ -99,7 +99,6 @@ export function Overview(props: { active?: boolean }): any {
h('div', { className: styles.pills },
h(Pill, { label: '状态', value: memory === null ? '不可用' : '已启用', tone: memory === null ? 'warn' : 'ok' }),
h(Pill, { label: '全局空间', value: memorySpaces.global === null || memorySpaces.global === undefined ? '未创建' : '就绪', tone: memorySpaces.global === null || memorySpaces.global === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '项目空间', value: memorySpaces.project === null || memorySpaces.project === undefined ? '未创建' : '就绪', tone: memorySpaces.project === null || memorySpaces.project === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '云同步', value: memory?.cloudSyncEnabled === true ? '开' : '关', tone: memory?.cloudSyncEnabled === true ? 'ok' : 'muted' }),
),
memory === null ? h('p', { className: styles.hint }, '本地记忆状态路由不可用;启用「本地记忆」后此处会显示空间状态。') : null,

View File

@ -44,7 +44,7 @@ export function registerBrainPanel(ctx: any): () => void {
stopNative = ctx.slots.inject('main', () =>
ctx.slots.inject('sidebar.panellist', () => {
const usePanelInfo = makeUsePanelInfo(ctx, PANEL_ID)
const panel = (props: any) => React.createElement(BrainPanel, { ...props, ctx, panelId: PANEL_ID, usePanelInfo })
const panel = (props: any) => React.createElement(BrainPanel, { ...props, panelId: PANEL_ID, usePanelInfo })
const icon = (props: any) => React.createElement(BrainIcon, { size: props?.size ?? 18 })
const stopMain = ctx.slots.register({ name: 'main', key: PANEL_ID, inject: () => ({ panelId: PANEL_ID }) }, panel as never)
let stopIcon: (() => void) | undefined

View File

@ -1,26 +1,7 @@
// Resolve the active session workspace from the optional host sessions face.
// The probe is deliberately defensive: the panel must work without the service.
export function resolveWorkspace(ctx: any): string | undefined {
try {
const sessions = ctx !== undefined && ctx !== null && typeof ctx.get === 'function' ? ctx.get('sessions') : undefined
if (sessions === undefined || sessions === null) return undefined
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() : undefined,
]
for (const candidate of candidates) {
if (typeof candidate === 'string' && candidate.trim() !== '') return candidate
}
} catch {
/* no sessions face -> omit the workspace argument */
}
return undefined
}
export type BrainScope = { scope: 'global' } | { scope: 'project'; workspace: string }
export function workspaceQuery(workspace: string | undefined): string {
return workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace)
export function scopeParams(scope: BrainScope): URLSearchParams {
const params = new URLSearchParams({ scope: scope.scope })
if (scope.scope === 'project') params.set('workspace', scope.workspace)
return params
}

View File

@ -22,70 +22,9 @@
line-height: 1.5;
}
.header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 8px;
flex-wrap: wrap;
}
.title {
margin: 0;
font-size: 13.5px;
font-weight: 650;
}
.subtitle {
margin: 0;
font-size: 12.5px;
font-weight: 600;
}
.workspace,
.hint {
margin: 0;
font-size: 11.5px;
opacity: 0.58;
}
.list {
display: flex;
flex-direction: column;
gap: 8px;
}
.row {
display: flex;
flex-direction: column;
gap: 5px;
border: 1px solid var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));
border-radius: 10px;
padding: 8px 10px;
min-width: 0;
}
.rowMeta {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.rowText {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
color: var(--dsw-alias-label-secondary, inherit);
overflow-wrap: anywhere;
}
.divider {
height: 1px;
background: var(--dsw-alias-border-subtle, rgba(127,127,127,0.18));
margin: 2px 0;
}
.recallRow {
display: flex;
flex-direction: column;
gap: 8px;
}

View File

@ -1,122 +1,51 @@
// Read-only project-memory view for the better-sidebar tab.
import * as React from 'react'
import { request, bodyError, messageOf } from '../api'
import { formatIso } from '../format'
import { styles } from '../styles'
import { Banner, Btn, Field, Pill } from '../components'
import { postJson } from '../api'
import { Btn } from '../components'
import { useApi } from '../panel/useApi'
import { workspaceQuery } from '../panel/workspace'
import styles2 from './ProjectMemory.module.css'
import { DepartmentTab } from '../panel/DepartmentTab'
import { MemoryTab } from '../panel/MemoryTab'
import panel from '../panel/BrainPanel.module.css'
import styles from './ProjectMemory.module.css'
const h = React.createElement
const TABS = [
{ id: 'memory', label: '记忆与文档' },
{ id: 'departments', label: '部门' },
] as const
function openTotalPanel(ctx: any): void {
const layout = ctx === undefined || ctx === null ? undefined : ctx.layout
if (layout !== undefined && layout !== null && typeof layout.selectPanel === 'function') {
layout.selectPanel('dsh-brain')
return
}
if (typeof window !== 'undefined' && typeof window.open === 'function') window.open('/dsh-brain')
}
export function ProjectMemoryView(props: { ctx?: any; scope?: { cwd?: string; sessionId?: string }; visible?: boolean }): any {
const visible = props.visible !== false
const workspace = props.scope?.cwd
const [search, setSearch] = React.useState('')
const [recallId, setRecallId] = React.useState('')
const [recallQuery, setRecallQuery] = React.useState('')
const [recallHits, setRecallHits] = React.useState<any[]>([])
const [recallBusy, setRecallBusy] = React.useState(false)
const [notice, setNotice] = React.useState<any>(null)
const status = useApi(async () => {
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 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 })
const departments = useApi(async () => {
const suffix = workspace === undefined ? '' : '?workspace=' + encodeURIComponent(workspace)
const result = await request('/dsh-brain/departments/list' + suffix)
if (result.status !== 200 || result.body === null || result.body.ok !== true) throw new Error(bodyError(result, '读取部门列表失败'))
return result.body
}, { visible })
const items: any[] = Array.isArray(memories.data?.items) ? memories.data!.items : []
const needle = String(search).trim().toLowerCase()
const filtered = needle === '' ? items : items.filter((item) => String(item.content ?? '').toLowerCase().indexOf(needle) >= 0)
const departmentList: any[] = Array.isArray(departments.data?.departments) ? departments.data!.departments : []
const spaces = status.data?.spaces ?? {}
const recall = async (): Promise<void> => {
if (recallId === '') { setNotice({ tone: 'warn', text: '请选择部门。' }); return }
setRecallBusy(true)
setRecallHits([])
try {
const query = '/dsh-brain/departments/recall?id=' + encodeURIComponent(recallId) + '&query=' + encodeURIComponent(recallQuery) + '&k=5' + (workspace === undefined ? '' : '&workspace=' + encodeURIComponent(workspace))
const result = await request(query)
if (result.status !== 200 || result.body === null || result.body.ok !== true) {
setNotice({ tone: 'bad', text: bodyError(result, '召回失败') })
return
}
setRecallHits(Array.isArray(result.body.hits) ? result.body.hits : [])
} catch (failure) {
setNotice({ tone: 'bad', text: messageOf(failure) })
} finally {
setRecallBusy(false)
export function ProjectMemoryView(props: { sessionId?: string; visible?: boolean }): any {
const [tab, setTab] = React.useState<(typeof TABS)[number]['id']>('memory')
const { sessionId } = props
const directory = useApi(async () => {
const result = await postJson('/sidebar/api/session.cwd', { sessionId })
const value = result.body?.value
const cwd = typeof value?.cwd === 'string' ? value.cwd.trim() : ''
if (result.status !== 200 || result.body?.ok !== true || value?.sessionId !== sessionId || cwd === '') {
throw new Error('无法确认当前会话的项目目录。')
}
}
return h('div', { className: styles2.betterSidebarSeat, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'better-sidebar-memory' },
h('div', { className: styles2.inner },
h('div', { className: styles2.header },
h('div', null,
h('h4', { className: styles2.title }, '项目记忆'),
h('p', { className: styles2.hint }, '当前会话项目的本地记忆(只读)'),
return cwd
}, { visible: props.visible !== false && sessionId !== undefined })
const workspace = directory.error === null ? directory.data ?? undefined : undefined
return h('div', { className: styles.betterSidebarSeat, 'data-dsh-plugin': 'dsh-brain', 'data-dsh-part': 'better-sidebar-memory' },
h('div', { className: styles.inner },
workspace === undefined ? h('div', null,
h('p', { className: styles.hint }, directory.error ?? '等待当前会话的项目目录。'),
directory.error === null ? null : h(Btn, { label: '重试', variant: 'small', onClick: directory.reload }),
) : h(React.Fragment, null,
h('p', { className: styles.workspace, title: workspace }, workspace),
h('div', { className: panel.tabBar, role: 'tablist', 'aria-label': '项目记忆页签' },
TABS.map((item) => h('button', {
key: item.id,
type: 'button',
role: 'tab',
'aria-selected': tab === item.id,
className: tab === item.id ? panel.tab + ' ' + panel.tabActive : panel.tab,
onClick: () => setTab(item.id),
}, item.label)),
),
h(Btn, { label: '去总面板', variant: 'small', onClick: () => openTotalPanel(props.ctx) }),
),
status.error === null ? null : h(Banner, { tone: 'bad' }, status.error),
h('div', { style: styles.pills },
h(Pill, { label: '全局空间', value: spaces.global === null || spaces.global === undefined ? '未创建' : '就绪', tone: spaces.global === null || spaces.global === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '项目空间', value: spaces.project === null || spaces.project === undefined ? '未创建' : '就绪', tone: spaces.project === null || spaces.project === undefined ? 'muted' : 'ok' }),
h(Pill, { label: '条目', value: memories.data?.total ?? 0, tone: 'muted' }),
),
h(Field, { label: '搜索记忆', value: search, onChange: setSearch }),
notice === null ? null : h(Banner, { tone: notice.tone }, notice.text),
memories.error === null ? null : h(Banner, { tone: 'bad' }, memories.error),
filtered.length === 0 ? h('p', { className: styles2.hint }, '没有匹配的记忆条目。') : h('div', { className: styles2.list },
filtered.map((item) => h('div', { key: item.id, className: styles2.row },
h('div', { className: styles2.rowMeta },
h(Pill, { label: 'scope', value: item.scope ?? '—', tone: 'muted' }),
item.category === undefined ? null : h(Pill, { label: '分类', value: item.category, tone: 'muted' }),
h(Pill, { label: '更新', value: formatIso(item.updatedAt), tone: 'muted' }),
),
h('div', { className: styles2.rowText }, String(item.content ?? '')),
)),
),
h('div', { className: styles2.divider }),
h('h5', { className: styles2.subtitle }, '部门召回'),
h('div', { className: styles2.recallRow },
h('select', { className: styles.input, value: recallId, onChange: (event) => setRecallId(event.target.value) },
h('option', { value: '' }, '选择部门…'),
departmentList.map((item) => h('option', { key: item.id, value: item.id }, String(item.name))),
),
h(Field, { label: '查询', value: recallQuery, onChange: setRecallQuery }),
h(Btn, { label: recallBusy ? '召回中…' : '召回', disabled: recallBusy, onClick: () => { void recall() } }),
),
recallHits.length === 0 ? null : h('div', { className: styles2.list },
recallHits.map((hit: any, index: number) => h('div', { key: String(index), className: styles2.row },
h('div', { className: styles2.rowMeta }, h(Pill, { label: '来源', value: hit.origin ?? '—', tone: 'muted' })),
h('div', { className: styles2.rowText }, String(hit.contentSnippet ?? hit.content ?? '')),
)),
tab === 'memory'
? h(MemoryTab, { scope: 'project', workspace, key: workspace, active: props.visible })
: h(DepartmentTab, { scope: 'project', workspace, key: workspace, active: props.visible }),
),
),
)

View File

@ -41,11 +41,17 @@ export function mountBrainSidebarTab(ctx: any): () => void {
const dispose = service.registerTab({
id: BETTER_SIDEBAR_TAB_ID,
title: () => '项目记忆',
description: '当前会话项目的本地记忆:空间/条目/搜索/部门召回',
description: '查看和管理当前项目的记忆、文档与部门',
icon: (size: number) => React.createElement(BrainIcon, { size }),
order: 60,
single: true,
component: ({ scope, visible }: BetterSidebarTabProps) => React.createElement(ProjectMemoryView, { key: scope?.cwd ?? '', ctx, scope, visible }),
component: ({ scope, visible }: BetterSidebarTabProps) => {
const cwd = scope?.cwd?.trim()
const sessionId = cwd ? scope?.sessionId?.trim() || undefined : undefined
// Better Sidebar can first publish the saved directory before resolving a live worktree.
// Recheck with the host on mount and whenever the sidebar changes its directory hint.
return React.createElement(ProjectMemoryView, { key: JSON.stringify([sessionId, cwd]), sessionId, visible })
},
})
current = { service, dispose }
}

View File

@ -24,8 +24,12 @@ export const name = 'dsh-brain'
/** Services required before `apply` runs. */
export const inject = ['webServer']
/** Register the plugin with the host: all five sub-entries at once. */
/** Mount the discoverable UI row or the legacy all-in-one plugin. */
export function apply(ctx: CloudMemoryContext, config: unknown): void {
if (config !== null && typeof config === 'object' && 'entry' in config && config.entry === 'ui') {
ui.apply(ctx, config)
return
}
cloudsync.apply(ctx, config)
memory.apply(ctx, config)
skills.apply(ctx, config)

View File

@ -50,8 +50,10 @@ export class DepartmentManager {
if (global !== undefined) return global
return (await this.registry('project').read()).departments.find((item) => item.id === id)
}
private async required(id: string): Promise<Department> {
const department = await this.find(id)
private async required(id: string, scope?: DepartmentScope): Promise<Department> {
const department = scope === undefined
? await this.find(id)
: (await this.registry(scope).read()).departments.find((item) => item.id === id && item.scope === scope)
if (department === undefined) throw new Error('department_not_found')
return department
}
@ -91,8 +93,8 @@ export class DepartmentManager {
return files.flatMap((file) => file.departments).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id))
}
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number): Promise<Department> {
const current = await this.required(id)
async update(id: string, patch: DepartmentUpdateInput, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
if (patch.role !== undefined && containsSecret(patch.role)) throw new Error('secret_not_allowed')
return this.registry(current.scope).update(async (file) => {
@ -156,8 +158,8 @@ export class DepartmentManager {
return { ...reference, hostSessionId: externalId }
}
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number): Promise<Department> {
const current = await this.required(id)
async checkpoint(id: string, input: { currentTask?: string; handoff?: string }, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
const currentTask = input.currentTask === undefined ? undefined : text(input.currentTask, 4000)
const handoff = input.handoff === undefined ? undefined : text(input.handoff, 20000)
@ -192,12 +194,15 @@ export class DepartmentManager {
}
/** Private first on equal scores; project/global are opt-in and the total result count stays bounded. */
async recall(id: string, query: string, k = 5, workspace?: string): Promise<DepartmentRecallHit[]> {
const department = await this.required(id)
async recall(id: string, query: string, k = 5, workspace?: string, scope?: DepartmentScope): Promise<DepartmentRecallHit[]> {
const department = await this.required(id, scope)
const limit = limitOf(k)
const privateHits = await this.store(department).search(query, limit)
const shared: LocalMemorySearchHit[] = []
if (department.memory.readProject && department.memory.readGlobal) {
if (scope !== undefined) {
const readShared = scope === 'global' ? department.memory.readGlobal : department.memory.readProject
if (readShared) shared.push(...await this.memory.searchHits(query, limit, workspace, undefined, scope))
} else if (department.memory.readProject && department.memory.readGlobal) {
shared.push(...await this.memory.searchHits(query, limit * 2, workspace))
} else if (department.memory.readGlobal) {
shared.push(...await this.memory.searchHits(query, limit, workspace, 'global'))
@ -220,8 +225,8 @@ export class DepartmentManager {
}
/** Disable without deleting private memories or allowing automatic session recovery. */
async disable(id: string, expectedRevision?: number): Promise<Department> {
const current = await this.required(id)
async disable(id: string, expectedRevision?: number, scope?: DepartmentScope): Promise<Department> {
const current = await this.required(id, scope)
if (expectedRevision !== undefined && current.revision !== expectedRevision) throw new Error('revision_conflict')
const store = this.store(current)
if (await store.spaceMeta() !== undefined) await store.setActive(false)

View File

@ -107,6 +107,9 @@ export class LocalMemoryManager {
get projectRoot(): string { return this.projectRootFor() }
private get globalStore(): JsonMemoryStore { return new JsonMemoryStore(join(this.globalRoot, 'runtime'), 'global', 'global') }
private projectStoreFor(workspace?: string): JsonMemoryStore { return new JsonMemoryStore(join(this.projectRootFor(workspace), 'memory-space'), 'project', projectIdFor(this.projectRootFor(workspace))) }
private scopedStore(scope: LocalMemoryScope, workspace?: string): JsonMemoryStore {
return scope === 'global' ? this.globalStore : this.projectStoreFor(workspace)
}
private async storeFor(scope: LocalMemoryScope, workspace?: string): Promise<JsonMemoryStore> {
if (scope === 'global') return this.globalStore
return this.ensureProject(workspace)
@ -223,20 +226,22 @@ export class LocalMemoryManager {
return scoped.filter(({ record }) => { if (seen.has(record.id)) return false; seen.add(record.id); return true })
.sort((a, b) => b.score - a.score || b.record.updatedAt.localeCompare(a.record.updatedAt))
}
async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string): Promise<{ record: LocalMemoryRecord; score: number }[]> {
async searchHits(query: string, k = this.settingsOf().localMemoryK ?? 5, workspace?: string, projectId?: string, scope?: LocalMemoryScope): Promise<{ record: LocalMemoryRecord; score: number }[]> {
const startedAt = Date.now()
const hits = await this.collectHits(query, workspace, projectId)
const limit = Math.max(1, Math.min(100, Math.trunc(k)))
const result = hits.slice(0, limit)
const result = scope === undefined
? (await this.collectHits(query, workspace, projectId)).slice(0, limit)
: await this.scopedStore(scope, workspace).search(query, limit)
const sources: Record<string, number> = {}
for (const hit of result) sources[hit.record.scope] = (sources[hit.record.scope] ?? 0) + 1
this.loggerOf?.log({ event: 'memory.search', scope: 'project', workspace: this.workspacePath(workspace), detail: { query, k: limit, hits: result.length, sources, durationMs: Date.now() - startedAt } })
this.loggerOf?.log({ event: 'memory.search', scope: scope ?? 'project', workspace: scope === 'global' ? undefined : 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<LocalMemoryRecord[]> {
return (await this.searchHits(query, k, workspace, projectId)).map((hit) => hit.record)
}
async list(options: { limit?: number; offset?: number } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> {
async list(options: { limit?: number; offset?: number; scope?: LocalMemoryScope } = {}, workspace?: string, projectId?: string): Promise<{ items: LocalMemoryRecord[]; total: number }> {
if (options.scope !== undefined) return this.scopedStore(options.scope, workspace).list(options)
const projectStore = await this.ensureProject(workspace)
const records = [...(await this.globalStore.records()), ...(await projectStore.records())]
const scoped = records.filter((record) => {
@ -251,19 +256,20 @@ export class LocalMemoryManager {
const limit = Math.max(1, Math.min(1000, Math.trunc(options.limit ?? 50)))
return { items: ordered.slice(offset, offset + limit), total: ordered.length }
}
async forget(id: string, expectedRevision?: number, workspace?: string): Promise<LocalMemoryRecord> {
const globalRecord = await this.globalStore.read(id)
await this.markProjectionDirty()
if (globalRecord !== undefined) {
const removed = await this.globalStore.forget(id, expectedRevision)
await this.tryRegenerateProjections()
this.loggerOf?.log({ event: 'memory.forget', scope: 'global', detail: { recordId: id, revision: removed.revision } })
return removed
async forget(id: string, expectedRevision?: number, workspace?: string, scope?: LocalMemoryScope): Promise<LocalMemoryRecord> {
const targetScope = scope ?? ((await this.globalStore.read(id)) === undefined ? 'project' : 'global')
const scopedStore = scope === undefined ? undefined : this.scopedStore(scope, workspace)
if (scopedStore !== undefined) {
const record = await scopedStore.read(id)
if (record === undefined) throw new Error('memory_not_found')
if (expectedRevision !== undefined && record.revision !== expectedRevision) throw new Error('revision_conflict')
}
const store = await this.ensureProject(workspace)
// The runtime projections are built exclusively from the global store.
if (scope !== 'project') await this.markProjectionDirty()
const store = scopedStore ?? await this.storeFor(targetScope, workspace)
const removed = await store.forget(id, expectedRevision)
await this.tryRegenerateProjections()
this.loggerOf?.log({ event: 'memory.forget', scope: 'project', workspace: this.workspacePath(workspace), detail: { recordId: id, revision: removed.revision } })
if (scope !== 'project') await this.tryRegenerateProjections()
this.loggerOf?.log({ event: 'memory.forget', scope: targetScope, workspace: targetScope === 'project' ? this.workspacePath(workspace) : undefined, detail: { recordId: id, revision: removed.revision } })
return removed
}
async projects(workspace?: string): Promise<{ id: string; name: string }[]> {
@ -284,11 +290,21 @@ export class LocalMemoryManager {
if (documents === undefined) throw new Error('local_documents_unavailable')
return documents.add(input)
}
async storageStatus(workspace?: string): Promise<Record<string, unknown>> {
const projectRoot = this.projectRootFor(workspace)
const global = await this.globalStore.spaceMeta()
const project = await this.projectStoreFor(workspace).spaceMeta()
return { provider: 'local', globalRoot: this.globalRoot, projectRoot, spaces: { global: global ?? null, project: project ?? null }, cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true, localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false }
async storageStatus(workspace?: string, scope?: LocalMemoryScope): Promise<Record<string, unknown>> {
const projectRoot = scope === 'global' ? undefined : this.projectRootFor(workspace)
const global = scope === 'project' ? undefined : await this.globalStore.spaceMeta()
const project = scope === 'global' ? undefined : await this.projectStoreFor(workspace).spaceMeta()
return {
provider: 'local',
...(scope === 'project' ? {} : { globalRoot: this.globalRoot }),
...(projectRoot === undefined ? {} : { projectRoot }),
spaces: {
...(scope === 'project' ? {} : { global: global ?? null }),
...(scope === 'global' ? {} : { project: project ?? null }),
},
cloudSyncEnabled: this.settingsOf().cloudMemoryEnabled === true,
localMemoryEnabled: this.settingsOf().localMemoryEnabled !== false,
}
}
/** Return the compact per-turn projection used by the system prompt. */
projectionText(limit = 2000): string {

View File

@ -266,9 +266,19 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv
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 (suffix === '' || suffix === '/' || suffix === '/status' || suffix === '/memories') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace)) })
const scope = url.searchParams.get('scope') ?? undefined
if (scope !== undefined && scope !== 'global' && scope !== 'project') { fail(res, 400, 'invalid-scope'); return }
if (scope === 'project' && workspace === undefined) { fail(res, 400, 'workspace-required'); return }
if (suffix !== '/memories') {
json(res, 200, { ok: true, ...(await manager.storageStatus(workspace, scope)) })
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, scope }, 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
}
if (suffix === '/spaces') {
@ -278,17 +288,12 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv
}
if (suffix === '/documents') {
if (req.method !== 'GET') { fail(res, 405, 'method-not-allowed'); return }
const scope = url.searchParams.get('scope')
if (scope !== null && scope !== 'project') { fail(res, 400, 'invalid-scope'); return }
if (scope === 'project' && workspace === undefined) { fail(res, 400, 'workspace-required'); return }
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 }, 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
}
if (suffix === '/forget') {
if (req.method !== 'POST') { fail(res, 405, 'method-not-allowed'); return }
if (!sameOrigin(req)) { fail(res, 403, 'origin-rejected'); return }
@ -300,7 +305,17 @@ async function serveLocalMemory(deps: RouteDeps, req: IncomingMessage, res: Serv
if (id === '') { fail(res, 400, 'id-required'); return }
const expectedRevision = typeof input.expectedRevision === 'number' && Number.isFinite(input.expectedRevision) ? Math.trunc(input.expectedRevision) : undefined
const targetWorkspace = typeof input.workspace === 'string' ? input.workspace.trim() || undefined : undefined
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace) })
const scope = input.scope
if (scope !== undefined && scope !== 'global' && scope !== 'project') { fail(res, 400, 'invalid-scope'); return }
if (scope === 'project' && targetWorkspace === undefined) { fail(res, 400, 'workspace-required'); return }
try {
json(res, 200, { ok: true, record: await manager.forget(id, expectedRevision, targetWorkspace, scope) })
} catch (error) {
if (scope === undefined || !(error instanceof Error)) throw error
if (error.message === 'memory_not_found') { fail(res, 404, error.message); return }
if (error.message === 'revision_conflict') { fail(res, 409, error.message); return }
throw error
}
return
}
if (suffix === '/search') {

View File

@ -10,7 +10,7 @@ import type { SettingsStore } from '../store.ts'
import type { DepartmentManager } from '../local-memory/departments/index.ts'
import type { LocalMemoryManager } from '../local-memory/manager.ts'
import { departmentSnippet } from '../memory/departments-tools.ts'
import type { DepartmentCreateInput, DepartmentUpdateInput } from '../local-memory/departments/types.ts'
import type { DepartmentCreateInput, DepartmentScope, DepartmentUpdateInput } from '../local-memory/departments/types.ts'
import { fail, json, readBody, sameOrigin } from '../http.ts'
export interface DepartmentRouteDeps {
@ -23,6 +23,7 @@ function errorStatus(message: string): number | undefined {
if (message === 'department_not_found') return 404
if (message === 'revision_conflict') return 409
if (message === 'department_disabled') return 409
if (message === 'invalid-scope' || message === 'workspace-required') return 400
if (message === 'department_required_field' || message === 'department_invalid_host' || message === 'secret_not_allowed') return 400
return undefined
}
@ -47,12 +48,21 @@ async function bodyObject(req: IncomingMessage, res: ServerResponse): Promise<Re
function stringField(value: unknown): string | undefined { return typeof value === 'string' ? value : undefined }
function revisionField(value: unknown): number | undefined { return typeof value === 'number' && Number.isFinite(value) ? Math.trunc(value) : undefined }
function requestScope(value: unknown, workspace?: string): DepartmentScope | undefined {
if (value === undefined) return undefined
if (value !== 'global' && value !== 'project') throw new Error('invalid-scope')
if (value === 'project' && workspace === undefined) throw new Error('workspace-required')
return value
}
export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingMessage, res: ServerResponse): Promise<void> {
const manager = deps.departments
if (manager === undefined) { fail(res, 503, 'departments-unavailable'); return }
if (deps.store.settings().localMemoryEnabled === false) { fail(res, 503, 'local-memory-disabled'); return }
const withWorkspace = <T>(workspace: string | undefined, job: () => Promise<T>): Promise<T> =>
deps.localMemory === undefined ? job() : deps.localMemory.withWorkspace(workspace, job)
const withScope = <T>(scope: DepartmentScope | undefined, workspace: string | undefined, job: () => Promise<T>): Promise<T> =>
scope === undefined ? withWorkspace(workspace, job) : manager.memory.withWorkspace(scope === 'project' ? workspace : undefined, job)
const url = new URL(req.url ?? '/', 'http://localhost')
const marker = '/departments'
const at = url.pathname.indexOf(marker)
@ -92,6 +102,7 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
const id = stringField(body.id)?.trim() ?? ''
if (id === '') { fail(res, 400, 'id-required'); return }
const expectedRevision = revisionField(body.expectedRevision)
const scope = suffix === '/resume' ? undefined : requestScope(body.scope, workspace)
if (suffix === '/update') {
const patch: DepartmentUpdateInput = {
...(stringField(body.name) === undefined ? {} : { name: stringField(body.name) }),
@ -101,16 +112,16 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
...(typeof body.readGlobal === 'boolean' ? { readGlobal: body.readGlobal } : {}),
...(typeof body.readProject === 'boolean' ? { readProject: body.readProject } : {}),
}
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.update(id, patch, expectedRevision)) })
json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.update(id, patch, expectedRevision, scope)) })
return
}
if (suffix === '/disable') { json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.disable(id, expectedRevision)) }); return }
if (suffix === '/disable') { json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.disable(id, expectedRevision, scope)) }); return }
if (suffix === '/checkpoint') {
const input: { currentTask?: string; handoff?: string } = {
...(stringField(body.currentTask) === undefined ? {} : { currentTask: stringField(body.currentTask) }),
...(stringField(body.handoff) === undefined ? {} : { handoff: stringField(body.handoff) }),
}
json(res, 200, { ok: true, department: await withWorkspace(workspace, () => manager.checkpoint(id, input, expectedRevision)) })
json(res, 200, { ok: true, department: await withScope(scope, workspace, () => manager.checkpoint(id, input, expectedRevision, scope)) })
return
}
const host = stringField(body.host)?.trim() || 'dsh'
@ -129,7 +140,8 @@ export async function serveDepartments(deps: DepartmentRouteDeps, req: IncomingM
const requested = Number.parseInt(url.searchParams.get('k') ?? '5', 10)
const k = Number.isFinite(requested) ? Math.max(1, Math.min(5, requested)) : 5
const workspace = url.searchParams.get('workspace')?.trim() || undefined
const hits = await withWorkspace(workspace, () => manager.recall(id, query, k, workspace))
const scope = requestScope(url.searchParams.get('scope') ?? undefined, workspace)
const hits = await withScope(scope, workspace, () => manager.recall(id, query, k, workspace, scope))
json(res, 200, { ok: true, hits: hits.map((hit) => ({ ...hit, content: hit.record.content, contentSnippet: departmentSnippet(hit.record.content) })) })
return
}

View File

@ -166,19 +166,19 @@ 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')
// Each surface must pass an explicit scope to both management tabs.
const layout = readFileSync(new URL('./src-client/panel/BrainPanel.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 patch = readFileSync(new URL('./cordis.patch.yml', import.meta.url), 'utf8')
check('global panel binds both tabs to global data',
layout.includes("h(MemoryTab, { scope: 'global', active })") && layout.includes("h(DepartmentTab, { scope: 'global', active })"))
check('project tab waits for its workspace and scopes both tabs to it',
sidebar.includes("postJson('/sidebar/api/session.cwd', { sessionId })") && sidebar.includes('value?.sessionId !== sessionId') &&
sidebar.includes('workspace === undefined ?') && sidebar.includes("h(MemoryTab, { scope: 'project', workspace,") && sidebar.includes("h(DepartmentTab, { scope: 'project', workspace,"))
check('the UI loader row mounts at the package root for browser discovery',
/id: dsh-brain-ui\r?\n(?: *#[^\r\n]*\r?\n)* *name: dsh-brain\r?\n *config:\r?\n *entry: ui(?:\r?\n|$)/.test(patch))
check('settings section mounts the full plugin config form',
bySeat['settings.section']?.component === bySeat['plugins.bundle.config']?.component && typeof bySeat['settings.section']?.component === 'function')
const root = await mkdtemp(join(tmpdir(), 'brain-ui-workspace-'))
try {
@ -206,11 +206,15 @@ try {
return response.json()
}
const [defaultPage, scopedPage, status, documents] = await Promise.all([
getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace),
getJson('/memories'), getJson('/memories' + workspace), getJson('/status' + workspace), getJson('/documents' + workspace + '&scope=project'),
])
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 invalidDocuments = await Promise.all([
fetch(base + '/documents?scope=project'), fetch(base + '/documents' + workspace + '&scope=global'),
])
check('explicit document scope requires a project workspace', invalidDocuments.every(({ status }) => status === 400))
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 }),

View File

@ -82,6 +82,97 @@ const missingName = await request(server, 'POST', '/dsh-brain/departments/create
check('POST create rejects missing name', missingName.status === 400 && missingName.body?.error === 'name-required')
const stale = await request(server, 'POST', '/dsh-brain/departments/update', { id: sameOrigin.body.department.id, expectedRevision: 0, role: 'stale' }, 'http://127.0.0.1:' + server.address().port)
check('POST update maps revision conflict to 409', stale.status === 409 && stale.body?.error === 'revision_conflict')
// Explicit UI scopes and legacy callers share the same route table.
const memoryRoute = '/dsh-brain/local-memory'
const departmentRoute = '/dsh-brain/departments'
const workspaceA = '&workspace=' + encodeURIComponent(dualA)
const workspaceB = '&workspace=' + encodeURIComponent(dualB)
const globalMemory = (await kernel.localMemory.remember({ content: 'boundary alpha beta global shared', scope: 'global' })).record
const projectMemory = (await kernel.localMemory.withWorkspace(dualA, () => kernel.localMemory.remember({ content: 'boundary alpha project shared' }))).record
const legacyProjectMemory = (await (await kernel.localMemory.ensureProject(dualA)).add({ content: 'boundary project legacy record' })).record
const otherProjectMemory = (await kernel.localMemory.withWorkspace(dualB, () => kernel.localMemory.remember({ content: 'boundary alpha beta other workspace' }))).record
const globalStatus = await request(server, 'GET', memoryRoute + '/status?scope=global' + workspaceA)
const projectStatus = await request(server, 'GET', memoryRoute + '/status?scope=project' + workspaceA)
const combinedStatus = await request(server, 'GET', memoryRoute + '/status?' + workspaceA.slice(1))
check('memory status returns only the requested space and root with legacy flags',
globalStatus.status === 200 && globalStatus.body.globalRoot === kernel.localMemory.globalRoot && !('projectRoot' in globalStatus.body) &&
Object.keys(globalStatus.body.spaces).join() === 'global' && globalStatus.body.spaces.global.scope === 'global' &&
projectStatus.status === 200 && projectStatus.body.projectRoot === join(dualA, '.dsh', 'brain') && !('globalRoot' in projectStatus.body) &&
Object.keys(projectStatus.body.spaces).join() === 'project' && projectStatus.body.spaces.project.scope === 'project' &&
[globalStatus, projectStatus].every(({ body }) => body.localMemoryEnabled === combinedStatus.body.localMemoryEnabled && body.cloudSyncEnabled === combinedStatus.body.cloudSyncEnabled) &&
Object.keys(combinedStatus.body.spaces).sort().join() === 'global,project')
const memoryPages = await Promise.all([
request(server, 'GET', memoryRoute + '/memories?scope=global&limit=1' + workspaceA),
request(server, 'GET', memoryRoute + '/memories?scope=project&limit=1' + workspaceA),
request(server, 'GET', memoryRoute + '/memories?scope=project&limit=1&offset=1' + workspaceA),
request(server, 'GET', memoryRoute + '/memories?' + workspaceA.slice(1)),
])
const [globalPage, projectFirst, projectSecond, combinedPage] = memoryPages.map(({ body }) => body)
check('memory pagination uses one store and includes legacy project records without projectId',
memoryPages.every(({ status }) => status === 200) && globalPage.total === 1 && globalPage.items[0]?.id === globalMemory.id &&
projectFirst.total === 2 && projectSecond.total === 2 && projectFirst.items.length === 1 && projectSecond.items.length === 1 &&
[projectFirst.items[0]?.id, projectSecond.items[0]?.id].sort().join() === [projectMemory.id, legacyProjectMemory.id].sort().join() &&
legacyProjectMemory.projectId === undefined && combinedPage.total === 3 && combinedPage.items.some((item) => item.id === globalMemory.id))
for (const path of ['/status', '/memories']) {
const missing = await request(server, 'GET', memoryRoute + path + '?scope=project')
const blank = await request(server, 'GET', memoryRoute + path + '?scope=project&workspace=%20')
const invalid = await request(server, 'GET', memoryRoute + path + '?scope=other')
check('memory ' + path + ' validates explicit scope and workspace',
[missing, blank].every(({ status, body }) => status === 400 && body?.error === 'workspace-required') && invalid.status === 400 && invalid.body?.error === 'invalid-scope')
}
const forget = (body) => request(server, 'POST', memoryRoute + '/forget', body)
const blockedForgets = await Promise.all([
forget({ scope: 'global', workspace: dualA, id: projectMemory.id }),
forget({ scope: 'project', workspace: dualA, id: globalMemory.id }),
forget({ scope: 'project', workspace: dualA, id: otherProjectMemory.id }),
])
const missingForget = await forget({ scope: 'project', workspace: ' ', id: projectMemory.id })
check('scoped forget cannot fall through to another store', blockedForgets.every(({ status, body }) => status === 404 && body?.error === 'memory_not_found') && missingForget.status === 400 && missingForget.body?.error === 'workspace-required')
const projectDepartment = httpA.body.department
const globalDepartment = sameOrigin.body.department
await rememberTool.execute({ departmentId: projectDepartment.id, content: 'boundary alpha project private' }, { workspace: dualA })
await rememberTool.execute({ departmentId: globalDepartment.id, content: 'boundary global private' }, { workspace: dualA })
const recall = (id, params = '') => request(server, 'GET', departmentRoute + '/recall?query=boundary+alpha+beta&id=' + id + params)
const projectRecall = await recall(projectDepartment.id, '&scope=project' + workspaceA)
const scopedGlobalRecall = await recall(globalDepartment.id, '&scope=global' + workspaceA)
const legacyRecall = await recall(projectDepartment.id, workspaceA)
check('scoped recall ranks private records with same-scope shared memory and legacy recall still spans scopes',
projectRecall.status === 200 && projectRecall.body.hits.map((hit) => hit.origin).join() === 'department,project,project' &&
scopedGlobalRecall.status === 200 && scopedGlobalRecall.body.hits.map((hit) => hit.origin).sort().join() === 'department,global' &&
legacyRecall.status === 200 && legacyRecall.body.hits[0]?.origin === 'global')
const projectFirstHit = await request(server, 'GET', departmentRoute + '/recall?k=1&query=boundary+alpha+beta&id=' + projectDepartment.id + '&scope=project' + workspaceA)
check('scoped recall selects the same-scope candidates before limiting', projectFirstHit.status === 200 && projectFirstHit.body.hits[0]?.origin === 'department')
const blockedRecalls = await Promise.all([
recall(projectDepartment.id, '&scope=global' + workspaceA),
recall(globalDepartment.id, '&scope=project' + workspaceA),
recall(projectDepartment.id, '&scope=project' + workspaceB),
])
const missingRecall = await recall(projectDepartment.id, '&scope=project')
check('scoped recall requires the matching department scope and workspace', blockedRecalls.every(({ status, body }) => status === 404 && body?.error === 'department_not_found') && missingRecall.status === 400 && missingRecall.body?.error === 'workspace-required')
const mutate = (action, body) => request(server, 'POST', departmentRoute + '/' + action, body)
for (const action of ['update', 'checkpoint', 'disable']) {
const missing = await mutate(action, { scope: 'project', id: projectDepartment.id })
const wrongScope = await mutate(action, { scope: 'project', workspace: dualA, id: globalDepartment.id })
const wrongWorkspace = await mutate(action, { scope: 'project', workspace: dualB, id: projectDepartment.id })
check('department ' + action + ' requires the matching scope and workspace',
missing.status === 400 && missing.body?.error === 'workspace-required' &&
[wrongScope, wrongWorkspace].every(({ status, body }) => status === 404 && body?.error === 'department_not_found'))
}
const updatedProject = await mutate('update', { scope: 'project', workspace: dualA, id: projectDepartment.id, readProject: false })
const privateProject = await recall(projectDepartment.id, '&scope=project' + workspaceA)
const updatedGlobal = await mutate('update', { scope: 'global', id: globalDepartment.id, readGlobal: false })
const privateGlobal = await recall(globalDepartment.id, '&scope=global' + workspaceA)
check('scoped recall honors the same-scope read policy even when the other scope is enabled',
updatedProject.status === 200 && updatedGlobal.status === 200 && [privateProject, privateGlobal].every(({ status, body }) => status === 200 && body.hits.map((hit) => hit.origin).join() === 'department'))
const scopedCheckpoint = await mutate('checkpoint', { scope: 'project', workspace: dualA, id: projectDepartment.id, currentTask: 'scoped checkpoint' })
const scopedDisable = await mutate('disable', { scope: 'global', id: globalDepartment.id })
check('scoped checkpoint and disable update the selected department', scopedCheckpoint.status === 200 && scopedCheckpoint.body.department.currentTask === 'scoped checkpoint' && scopedDisable.status === 200 && scopedDisable.body.department.active === false)
const legacyProjectList = await request(server, 'GET', departmentRoute + '/list?scope=project')
check('legacy department project list keeps its default workspace', legacyProjectList.status === 200 && Array.isArray(legacyProjectList.body.departments))
const staleForget = await forget({ scope: 'global', id: globalMemory.id, expectedRevision: 0 })
const projectForget = await forget({ scope: 'project', workspace: dualA, id: legacyProjectMemory.id, expectedRevision: legacyProjectMemory.revision })
const legacyForget = await forget({ id: globalMemory.id, workspace: dualB })
check('scoped forget checks the revision and legacy forget still finds a global memory', staleForget.status === 409 && projectForget.status === 200 && projectForget.body.record.id === legacyProjectMemory.id && legacyForget.status === 200 && legacyForget.body.record.id === globalMemory.id)
const legacyRoutes = legacyAliases(createCoreRoutes(kernel.routeDeps()))
const legacyServer = http.createServer((req, res) => { const path = (req.url || '/').split('?')[0]; const route = legacyRoutes.find((candidate) => candidate.kind === 'prefix' ? path === candidate.path || path.startsWith(candidate.path + '/') : path === candidate.path); if (route) void route.handler(req, res); else { res.writeHead(404); res.end() } })
await new Promise((resolve) => legacyServer.listen(0, '127.0.0.1', resolve))

View File

@ -161,6 +161,13 @@ check('deactivating mcp and cloudsync gates the tab and sync flags',
&& withoutMcpOrSync.capabilities.features.syncResolve === false,
JSON.stringify(withoutMcpOrSync.capabilities.features))
// The bundle patch mounts the UI through the bare package name for browser discovery.
resetBrainKernel()
const rootUi = fakeCtx()
root.apply(rootUi.ctx, { ...SEED, entry: 'ui' })
check('package root UI mode mounts only the UI entry', rootUi.tools.length === 0
&& JSON.stringify(rootUi.routes.map((route) => `${route.kind}:${route.path}`)) === JSON.stringify(uiPaths))
// --- compat root -------------------------------------------------------------
resetBrainKernel()
const rootHost = fakeCtx()