chore: package dsh-workspace-groups v0.1.0 for GitHub distribution
- MIT license, README with install/uninstall + screenshot, .gitignore - keywords + docs for dsh-plugin topic collection - commit lib/ so git install needs no build scripts
This commit is contained in:
commit
b56507bcf1
|
|
@ -0,0 +1,3 @@
|
|||
node_modules/
|
||||
*.log
|
||||
.DS_Store
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 zcol
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
|
@ -0,0 +1,174 @@
|
|||
# dsh-workspace-groups
|
||||
|
||||

|
||||

|
||||
|
||||
> **DeepSeek Harness(DSH)Web 客户端插件**:把 GUI 侧边栏的工作区列表从两层
|
||||
> 「项目 → 会话」变成三层 **「分类文件夹 → 项目文件夹 → 会话」**。
|
||||
|
||||
典型场景:多个 DSH 插件项目(SkillsManagePlugins / Documentation-Driven AI Coding /
|
||||
DeepSeek峰谷小组件 等)归入一个「DSH 插件」分类文件夹,点开是各项目,再点开是各自会话。
|
||||
|
||||
## 截图
|
||||
|
||||

|
||||
|
||||
## 特性
|
||||
|
||||
- **三层侧边栏**:分类文件夹(可折叠)→ 项目文件夹(可折叠)→ 会话行
|
||||
- **sidecar 配置**:分类规则写在 `~/.dsh/workspace-groups.yaml`,改配置即可增删分类 /
|
||||
调整归类,无需改代码、无需重启(刷新页面生效)
|
||||
- **树形搜索**:搜索命中后仍保留三层树结构(分类 → 项目 → 命中会话),命中行高亮并
|
||||
显示内容摘要,而不是扁平的结果列表
|
||||
- **零侵入**:不修改 `~/.dsh/storages/workspace.json`、不修改会话落盘结构、
|
||||
不修改官方 `@deepseek-ai/dsh-client-ui-workspace` 包
|
||||
- **功能不退化**:打开/新建/搜索会话、Add Workspace、项目重命名/删除、
|
||||
会话重命名/派生/归档、展开状态持久化(独立 key,重启保留)
|
||||
- **产物自包含**:`lib/` 已构建并随仓库分发,Git 安装无需执行任何依赖脚本
|
||||
|
||||
## 工作原理
|
||||
|
||||
- 本插件是 **client 插件**,注册进官方 sidebar shell 声明的 `sidebar.workspaces`
|
||||
slot(`kind: 'single'`),以 `priority: -1` 顶替官方默认 WorkspaceBrowser
|
||||
(官方以 priority 0 注册;single 槽位最低 priority 胜出)。
|
||||
- 数据源全部复用运行时 API:`useWorkspaces` / `useSessions` 全局 hooks 与
|
||||
`ctx.workspaces.*` / `ctx.sessions.*`,分类只是**展示层变换**。
|
||||
- host 半只做一件事:把 sidecar YAML 解析为 JSON,经
|
||||
`/workspace-groups/config` 路由(`Cache-Control: no-cache`)供 client 获取。
|
||||
|
||||
## 安装(GitHub 分发)
|
||||
|
||||
> 前置:已安装 [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness)
|
||||
> (`dsh` 命令可用),并已初始化好目标 profile(如内置 `web`)。
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web add github:z-col/dsh-workspace-groups
|
||||
```
|
||||
|
||||
这会自动:
|
||||
|
||||
1. 在 `~/.dsh/profiles/web/package.json` 的 `dependencies` 加入
|
||||
`"dsh-workspace-groups": "github:z-col/dsh-workspace-groups"`(含版本/commit)
|
||||
2. 在 `dsh.profile.bundles` 末尾追加 `"dsh-workspace-groups"`
|
||||
3. 运行 pnpm 安装并校验 bundle 层
|
||||
|
||||
**安装后重启 web profile**(bundle 与 host 半只有在重启后才会被加载):
|
||||
|
||||
```sh
|
||||
# 停止现有 dsh web 进程后重新启动,例如:
|
||||
dsh web
|
||||
```
|
||||
|
||||
验证安装:
|
||||
|
||||
```sh
|
||||
dsh --profile web --dump-config | grep -A3 workspace-groups
|
||||
# 应出现 - id: workspace-groups / name: dsh-workspace-groups / config: {}
|
||||
curl http://127.0.0.1:3080/workspace-groups/config
|
||||
# 应返回 sidecar YAML 解析后的 JSON
|
||||
```
|
||||
|
||||
## 卸载
|
||||
|
||||
```sh
|
||||
dsh plugin --profile web remove dsh-workspace-groups
|
||||
```
|
||||
|
||||
这会自动从 `dependencies` 删除该依赖并从 `dsh.profile.bundles` 移除对应行。
|
||||
同样需要**重启 web profile** 后生效。
|
||||
|
||||
> 手动等价做法(任选其一,不要重复):编辑 `~/.dsh/profiles/web/package.json`,
|
||||
> 从 `dependencies` 删除 `dsh-workspace-groups` 行、从 `dsh.profile.bundles`
|
||||
> 删除 `"dsh-workspace-groups"`,然后在该目录 `pnpm install`。
|
||||
|
||||
## 分类配置(sidecar)
|
||||
|
||||
默认位置 `~/.dsh/workspace-groups.yaml`(也可用 `$DSH_HOME` 环境变量覆盖家目录)。
|
||||
模板见仓库根目录 `workspace-groups.example.yaml`。
|
||||
|
||||
```yaml
|
||||
categories:
|
||||
- name: DSH 插件
|
||||
rules:
|
||||
- pathPrefix: /Users/zcol/Project/SkillsManagePlugins
|
||||
- nameContains: 插件
|
||||
- basenameContains: plugin
|
||||
- name: 个人项目
|
||||
rules:
|
||||
- pathPrefix: /Users/zcol/Project/yeluzi
|
||||
```
|
||||
|
||||
规则字段(每个 rule 是 OR 关系,任一命中即归类;分类按序匹配,先到先得):
|
||||
|
||||
| 字段 | 含义 |
|
||||
|---|---|
|
||||
| `pathPrefix` | 项目绝对路径前缀 |
|
||||
| `pathExact` | 项目绝对路径精确匹配 |
|
||||
| `nameContains` | 项目显示标题包含(忽略大小写) |
|
||||
| `basenameContains` | 项目目录名包含(忽略大小写) |
|
||||
|
||||
未命中任何分类的项目进入「未分类」桶,不会被隐藏。
|
||||
|
||||
## 收录标签(topics)
|
||||
|
||||
本仓库面向 DSH 插件生态的自动收录(社区市场靠 GitHub topic 扫描发现),已设置:
|
||||
|
||||
- `dsh-plugin`(核心标签,[1024Store](https://github.com/imsai-sh/awesome-deepseek-harness-plugins)
|
||||
等市场定时按此 topic 自动发现,并校验 `package.json` + `dsh.bundle.patch` 字段)
|
||||
- `deepseek-harness` / `deepseek-harness-plugin` / `dsh`
|
||||
- `sidebar` / `workspace` / `workspace-groups`
|
||||
|
||||
`package.json` 同时提供 `keywords` 便于 npm/搜索索引。
|
||||
|
||||
## 开发
|
||||
|
||||
```sh
|
||||
pnpm install
|
||||
pnpm typecheck # host + client 双 program 类型检查
|
||||
pnpm test # 核心规则与配置解析单测
|
||||
pnpm build # 构建 lib/(node 半 + client bundle)
|
||||
pnpm watch # tsdown 监听(client HMR)
|
||||
```
|
||||
|
||||
产物契约(与官方 client 包一致):
|
||||
|
||||
- `lib/index.js` —— host 半(ESM;读取 sidecar + `/workspace-groups/config` 路由,
|
||||
js-yaml 已内联,无运行时依赖)
|
||||
- `lib/client.js` —— browser 半(`window.__ModuleLoader__.load({id, factory})`;
|
||||
仅 require 平台 seed:react / react/jsx-runtime / @deepseek-ai/dsh-client-runtime/client /
|
||||
@deepseek-ai/dsh-client-ui-primitives;跨插件值 import 在构建期被 purity 门拒绝)
|
||||
- `lib/types/**` —— 声明文件
|
||||
|
||||
> 发布策略说明:`lib/` 构建产物随仓库提交(无 `prepare` 脚本),因此
|
||||
> `dsh plugin add github:...` 全程无需执行第三方构建脚本,安装即用。
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
src/
|
||||
index.ts # host 半:config 路由
|
||||
host-config.ts # sidecar YAML 读取/校验
|
||||
context-types.ts # host 侧 cordis 服务结构类型
|
||||
core/
|
||||
types.ts # 配置类型(两半共享)
|
||||
matcher.ts # 分类规则纯函数(两半共享)
|
||||
client/
|
||||
index.ts # apply:注册 sidebar.workspaces(priority -1)
|
||||
contract.ts # 注入面类型
|
||||
stores.ts # 展开状态 store(persist: dsh.workspace.groups.view.v1)
|
||||
tree.ts # 三层树派生 + 树形搜索派生
|
||||
GroupsBrowser.tsx # 浏览区域组件
|
||||
rows.tsx # 分类/项目/会话/搜索结果行
|
||||
locales.ts # 中英文案
|
||||
styles.css # 内联样式
|
||||
tests/
|
||||
core.test.ts # 分类规则 + 配置解析单测
|
||||
```
|
||||
|
||||
## 验证记录
|
||||
|
||||
见 `docs/verification.md`(真实组合验证:headless Chrome + CDP 实操记录)。
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
# dsh-workspace-groups bundle patch
|
||||
#
|
||||
# This file is the `dsh.bundle.patch` layer of the package: when the plugin is
|
||||
# installed through the official CLI —
|
||||
#
|
||||
# dsh plugin --profile <name> add dsh-workspace-groups
|
||||
#
|
||||
# — the command reconciles `dsh.profile.bundles` against installed packages
|
||||
# and, seeing this declaration, appends `dsh-workspace-groups` to the bundle
|
||||
# stack. The profile boot then merges THIS patch (a single `insert` of the
|
||||
# plugin row) exactly like a manual cordis.patch.yml mount line.
|
||||
#
|
||||
# The row uses a stable `id` (configuration-tree line identity), a `name` the
|
||||
# host Loader resolves as a package, and a `config` the host half consumes.
|
||||
- insert:
|
||||
- id: workspace-groups
|
||||
name: 'dsh-workspace-groups'
|
||||
config: {}
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
# 真实组合验证记录(dsh-workspace-groups)
|
||||
|
||||
验证日期:2026-08-21
|
||||
验证对象:`dsh-workspace-groups@0.1.0`(link 安装于 `~/.dsh/profiles/web`)
|
||||
运行环境:`dsh web`(PID 90954),GUI http://127.0.0.1:3080,官方 dsh 0.1.1-rc.2
|
||||
|
||||
## 1. 安装与组合层验证
|
||||
|
||||
| 检查项 | 结果 |
|
||||
|---|---|
|
||||
| `dsh plugin --profile web add` 自动对账 bundles | ✅ 追加 `dsh-workspace-groups` 至 `dsh.profile.bundles` |
|
||||
| `dsh --profile web --dump-config` 出现插件层 | ✅ `- id: workspace-groups / name: dsh-workspace-groups / config: {}` |
|
||||
| 重启后 boot manifest 含插件 client 行 | ✅ `dsh-workspace-groups` 出现于 `__DSH_BOOT__.entries` |
|
||||
| client bundle 可服务 | ✅ `/plugins/dsh-workspace-groups/client.js` 返回 ModuleLoader 包装 |
|
||||
| host config 路由 | ✅ `GET /workspace-groups/config` 200,返回 sidecar JSON |
|
||||
|
||||
## 2. 顶替与数据链路(最小验证先行,三项全绿)
|
||||
|
||||
1. **顶替默认 WorkspaceBrowser**:侧边栏渲染 `.wgRoot` 树(非官方浏览器);
|
||||
CDP 断言 `officialBrowser: false`、`wgRoot: true` ✅
|
||||
2. **useWorkspaces 数据完整**:6 个工作区全部可见并按 sidecar 归类 ✅
|
||||
3. **一层树渲染**:分类 → 项目 → 会话三层结构渲染成功 ✅
|
||||
|
||||
## 3. 分类结果(sidecar 实际生效)
|
||||
|
||||
```
|
||||
DSH 插件 (4) ← pathPrefix 规则命中
|
||||
├── DSH-工作区分组
|
||||
├── DeepSeek峰谷小组件
|
||||
├── Documentation-Driven AI Coding
|
||||
└── SkillsManagePlugins
|
||||
个人项目 (2)
|
||||
├── 闲谝
|
||||
└── yeluzi
|
||||
```
|
||||
|
||||
计数与 `~/.dsh/storages/workspace.json` 的 6 个工作区精确一致。
|
||||
|
||||
## 4. 交互验证(headless Chrome + CDP 实操)
|
||||
|
||||
| 操作 | 结果 |
|
||||
|---|---|
|
||||
| 点击分类「个人项目」 | ✅ 展开,显示闲谝 / yeluzi 项目 |
|
||||
| 刷新页面 | ✅ 展开状态保留(store `dsh.workspace.groups.view.v1` 持久化) |
|
||||
| 点击会话 `Docs AI Coding` | ✅ 选中态迁移到该会话(`.wgSelected`),打开生效 |
|
||||
| 搜索「DSH」 | ✅ 返回 `Docs AI Coding · DSH-工作区分组`(workspace 归属保留) |
|
||||
| 清除搜索 | ✅ 恢复三层树 |
|
||||
|
||||
## 5. 存储零侵入断言
|
||||
|
||||
| 检查项 | 结果 |
|
||||
|---|---|
|
||||
| `workspace.json` 结构 | ✅ 无 `category` 字段,unit.version=2 不变,workspace 计数 6 |
|
||||
| 会话落盘 | ✅ 未新增/改动任何 session 文件 |
|
||||
| 官方 view store | ✅ `dsh.workspace.view.v5` 未被触碰(仅新增独立 key `dsh.workspace.groups.view.v1`) |
|
||||
| host 暴露面 | ✅ 仅一个只读 GET 路由 `/workspace-groups/config`(no-cache) |
|
||||
|
||||
## 6. 构建与质量门
|
||||
|
||||
| 检查项 | 结果 |
|
||||
|---|---|
|
||||
| `pnpm typecheck`(host + client 双 program) | ✅ 0 错误 |
|
||||
| `pnpm test` | ✅ 12/12 通过(分类规则、配置解析) |
|
||||
| `pnpm build` | ✅ lib/index.js(96KB,js-yaml 内联)+ lib/client.js(56KB)+ types |
|
||||
| client bundle purity | ✅ 仅 require 平台 seed(react / runtime/client / primitives),跨插件值 import 被拒 |
|
||||
| host bundle 自包含 | ✅ 零外部运行时 require(js-yaml 已内联) |
|
||||
|
||||
## 7. 已知限制(非缺陷)
|
||||
|
||||
- 会话拖拽排序未实现(当前行交互为打开/重命名/派生/归档;官方浏览器同样具备的
|
||||
拖拽排序在 v0.1 未移植)。项目拖拽排序同样未移植。
|
||||
- 分类/项目的折叠状态自动展开当前会话所在分类与项目(与官方行为一致)。
|
||||
- Add Workspace 使用原生目录选择器(`ctx.workspaces.pickDirectory`),
|
||||
无官方 WorkspacePickFlow 的菜单选择既有工作区功能 —— 已在功能上等价覆盖
|
||||
(既有工作区在树中始终可见)。
|
||||
|
||||
## 8. 缺陷修复记录(2026-08-21 二轮验证)
|
||||
|
||||
**Bug:当前分类/项目无法收缩**(用户报告)
|
||||
|
||||
- 现象:包含当前会话的「DSH 插件」分类与其下「DSH-工作区分组」项目无法折叠,
|
||||
其他节点正常。
|
||||
- 根因:store 折叠用 `delete` 删 key + auto-expand effect 用 `!expansion[key]`
|
||||
守卫 —— 折叠后 key 缺失 → effect 重新展开。
|
||||
- 修复:折叠改写入 `false`(key 保留,同官方 `setGroupExpanded` 语义);
|
||||
auto-expand 守卫改 `Object.hasOwn`(仅从未操作过的 key 自动展开)。
|
||||
- 验证(CDP 实操,全新 profile):
|
||||
| 操作 | 结果 |
|
||||
|---|---|
|
||||
| 收缩「DSH 插件」(当前分类) | ✅ 折叠,2s 后不反弹,store `{"DSH 插件": false}` |
|
||||
| 再展开「DSH 插件」 | ✅ 恢复正常 |
|
||||
| 折叠后刷新 | ✅ 折叠状态持久保留 |
|
||||
| 收缩「DSH-工作区分组」(当前项目)后刷新 | ✅ 保持折叠(sessions 隐藏) |
|
||||
- 回归:`pnpm typecheck` 0 错误;`pnpm test` 18/18(新增 6 个 store 语义测试)。
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,7 @@
|
|||
import type { GroupsBrowserProps } from './contract.ts';
|
||||
/**
|
||||
* Render the browsing region.
|
||||
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||
* @returns the region element tree.
|
||||
*/
|
||||
export declare function GroupsBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, searchSessions, searchResultLimit, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
/**
|
||||
* Registrant-private injected share for the workspace-groups browser entry.
|
||||
* Mirrors the official ui-workspace browser inject (same runtime calls), with
|
||||
* two differences: no directory-flow hole dependency (Add Workspace is
|
||||
* self-contained via `pickDirectory`), and no locale-keyed naming collision.
|
||||
*/
|
||||
import type { PropsHooks, PropsLocale, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { HostDescriptionSource } from '@deepseek-ai/dsh-client-connection/client';
|
||||
import type { SessionId, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import type { createGroupsViewStore } from './stores.ts';
|
||||
/** Injected share (arrives via the register inject factory). */
|
||||
export type GroupsBrowserInjected = {
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void;
|
||||
/** Search current visible conversation messages. */
|
||||
searchSessions: (query: string, signal: AbortSignal) => Promise<{
|
||||
items: readonly SessionSearchResultItem[];
|
||||
hasMore: boolean;
|
||||
}>;
|
||||
/** Maximum number of merged rows rendered for one search. */
|
||||
searchResultLimit: number;
|
||||
/** Rename a Session (resolves on host acceptance). */
|
||||
renameSession: (sessionId: SessionId, title: string) => Promise<void>;
|
||||
/** Fork a Session at its last completed turn and open the child. */
|
||||
forkSession: (sessionId: SessionId) => void;
|
||||
/** Rename a Host Workspace (rejects on name conflict). */
|
||||
renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise<void>;
|
||||
/** Delete only a Host Workspace registration; directory and Session logs remain. */
|
||||
deleteWorkspace: (workspaceId: WorkspaceId) => Promise<void>;
|
||||
/** Reorder a Workspace in the durable registry display order (omitted anchor appends). */
|
||||
insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise<void>;
|
||||
/** Archive a Session into the registry-global set (hidden from grouping surfaces). */
|
||||
archiveSession: (sessionId: SessionId) => Promise<void>;
|
||||
/** Reorder a session inside its Workspace account. */
|
||||
insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise<void>;
|
||||
/** Adopt a picked host directory as a real Workspace before targeting a Session. */
|
||||
createWorkspace: (input: {
|
||||
path: string;
|
||||
}) => Promise<WorkspaceView>;
|
||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||
pickDirectory: () => Promise<string | null>;
|
||||
/** Browser-private injected hooks (host description; bound by the slot renderer). */
|
||||
hooks: {
|
||||
/** Current generation's Host description. */
|
||||
hostDescription: HostDescriptionSource;
|
||||
};
|
||||
};
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + locale seat. */
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsStore<ReturnType<typeof createGroupsViewStore>> & Omit<GroupsBrowserInjected, 'hooks'> & PropsHooks<GroupsBrowserInjected['hooks']> & PropsLocale<'workspaceGroups'>;
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
* dsh-workspace-groups client half: registers the three-level grouped
|
||||
* workspace browser into the `sidebar.workspaces` slot, shadowing the
|
||||
* official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.
|
||||
*/
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import { type WorkspaceGroupsKey } from './locales.ts';
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey;
|
||||
}
|
||||
}
|
||||
/** Required services (cordis fiber inject). */
|
||||
export declare const inject: string[];
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export declare function apply(ctx: ClientContext): void;
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
/**
|
||||
* Locale dictionaries for the workspace-groups browser. The namespace is
|
||||
* `workspaceGroups` (independent from ui-workspace's `workspace` namespace).
|
||||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey = 'section.workspaces' | 'section.sessions' | 'search' | 'search.placeholder' | 'search.clear' | 'search.noMatches' | 'search.unavailable' | 'search.pending' | 'search.hasMore' | 'search.results.aria' | 'workspace.add' | 'workspace.addBusy' | 'workspace.addError' | 'workspace.addErrorTitle' | 'workspace.rename' | 'workspace.delete' | 'workspace.deleteTitle' | 'workspace.deleteConfirm' | 'workspace.deleteCancel' | 'workspace.renaming' | 'workspace.deleting' | 'workspace.renameTitle' | 'workspace.renamePlaceholder' | 'workspace.renameConfirm' | 'workspace.renameCancel' | 'session.new' | 'session.rename' | 'session.archive' | 'session.fork' | 'session.renameTitle' | 'session.renamePlaceholder' | 'session.renameConfirm' | 'session.renameCancel' | 'session.renaming' | 'uncategorized' | 'empty.none' | 'empty.noWorkspaces' | 'close' | 'cancel' | 'confirm' | 'retry' | 'configUnavailable' | 'collapse' | 'expandMore' | 'newSession';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
/** English dictionary. */
|
||||
export declare const en: WorkspaceGroupsDict;
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
|
||||
type T = TranslateNS<'workspaceGroups'>;
|
||||
/** Primary status dot state for a session row. */
|
||||
export declare function sessionDotState(node: Pick<SessionNode, 'pendingInteraction' | 'running' | 'runningSubagentCount' | 'completed'>): StateDotState;
|
||||
/** Compact relative time ("now"/"5min"/"3h"/"2d"/"4mo"/"1y"). */
|
||||
export declare function relativeTimeLabel(updatedAt: number, now: number): string;
|
||||
/** One category folder row. */
|
||||
export declare function CategoryRow({ node, t, onToggle }: {
|
||||
node: CategoryNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
}): import("react").JSX.Element;
|
||||
/** One workspace folder row inside a category. */
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }: {
|
||||
node: WorkspaceGroupNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
onNewSession: () => void;
|
||||
onRename: () => void;
|
||||
onDelete: () => void;
|
||||
}): import("react").JSX.Element;
|
||||
/** One session leaf row. */
|
||||
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
node: SessionNode;
|
||||
currentId: string | undefined;
|
||||
now: number;
|
||||
t: T;
|
||||
onOpen: (id: SessionNode['id']) => void;
|
||||
onRename: (id: SessionNode['id'], currentTitle: string) => void;
|
||||
onFork: (id: SessionNode['id']) => void;
|
||||
onArchive: (id: SessionNode['id']) => void;
|
||||
}): import("react").JSX.Element;
|
||||
export type { T };
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* Pure expansion-state transforms for the workspace-groups store. Kept free
|
||||
* of any runtime import so both the store (which binds them via defineStore)
|
||||
* and unit tests (which exercise them directly) share one implementation.
|
||||
*
|
||||
* Expansion semantics follow the official ui-workspace store: collapse
|
||||
* WRITES `false` (never deletes the key). The browser's auto-expand guard
|
||||
* uses `Object.hasOwn` — a present `false` means "user deliberately
|
||||
* collapsed this" and must NOT be re-expanded; only a fully absent key means
|
||||
* "never touched" and may auto-expand. (Earlier versions deleted the key on
|
||||
* collapse, which made the current category/workspace impossible to fold.)
|
||||
*/
|
||||
/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */
|
||||
export interface GroupsViewState {
|
||||
/** Category folder expansion keyed by category label (absent = never touched). */
|
||||
categoryExpansion: Record<string, boolean>;
|
||||
/** Workspace folder expansion keyed by workspace id (absent = never touched). */
|
||||
workspaceExpansion: Record<string, boolean>;
|
||||
}
|
||||
/** Collapse writes `false` (key retained); expand writes `true`. */
|
||||
export declare function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void;
|
||||
/** Collapse writes `false` (key retained); expand writes `true`. */
|
||||
export declare function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void;
|
||||
/** Drop expansion keys that no longer exist (renames/deletes/config edits). */
|
||||
export declare function retainKeysImpl(state: GroupsViewState, categoryKeys: readonly string[], workspaceKeys: readonly string[]): void;
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
/**
|
||||
* The workspace-groups viewing store: category / workspace folder expansion,
|
||||
* persisted across reloads under an independent key (the official
|
||||
* ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch
|
||||
* it). Module level exports the factory only (a module-level handle would pin
|
||||
* the store identity across plugin reloads); register() receives the factory
|
||||
* and the browser derives its PropsStore share from the return type.
|
||||
*
|
||||
* The action implementations live in `store-core.ts` (pure, runtime-free) so
|
||||
* unit tests exercise the real semantics without a browser module loader;
|
||||
* this file only binds them through defineStore.
|
||||
*/
|
||||
import { type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import { retainKeysImpl, setCategoryExpandedImpl, setWorkspaceExpandedImpl, type GroupsViewState } from './store-core.ts';
|
||||
/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */
|
||||
type GroupsViewActions = {
|
||||
setCategoryExpanded: typeof setCategoryExpandedImpl;
|
||||
setWorkspaceExpanded: typeof setWorkspaceExpandedImpl;
|
||||
retainKeys: typeof retainKeysImpl;
|
||||
};
|
||||
/**
|
||||
* Create the workspace-groups viewing store handle.
|
||||
* @returns the store handle (spec + type + identity + factory in one).
|
||||
*/
|
||||
export declare function createGroupsViewStore(): EngineStoreHandle<GroupsViewState, GroupsViewActions>;
|
||||
export type { GroupsViewState } from './store-core.ts';
|
||||
|
|
@ -0,0 +1,106 @@
|
|||
/**
|
||||
* Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →
|
||||
* 会话行. Pure derivation — all inputs are snapshots; the renderer never
|
||||
* scans. Session visibility rules mirror the official ui-workspace tree
|
||||
* (blank rows only when current, archived excluded, subagent rows excluded).
|
||||
*/
|
||||
import { type PendingInteractionStatus, type SessionId, type SessionListState, type SessionSearchResultItem, type WorkspaceId, type WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client';
|
||||
import { type GroupsConfig } from '../core/types.ts';
|
||||
/** One top-level session row inside a workspace folder. */
|
||||
export interface SessionNode {
|
||||
id: SessionId;
|
||||
/** Stored display title; blank rows show the localized New Session label. */
|
||||
title: string;
|
||||
/** The provisional blank session (renderer shows the localized New Session title). */
|
||||
blank: boolean;
|
||||
pendingInteraction?: PendingInteractionStatus;
|
||||
running: boolean;
|
||||
/** Running descendants connected through uninterrupted subagent-origin lineage. */
|
||||
runningSubagentCount: number;
|
||||
/** Finished running while not selected and not yet opened (the green "done" reminder dot). */
|
||||
completed: boolean;
|
||||
updatedAt: number;
|
||||
/** Search-hit marker (rendered with a highlighted tint in search mode). */
|
||||
matched?: boolean;
|
||||
/** Content-match snippet from the Host search (search mode only). */
|
||||
snippet?: string;
|
||||
}
|
||||
/** One workspace folder row inside a category folder. */
|
||||
export interface WorkspaceGroupNode {
|
||||
workspaceId: WorkspaceId;
|
||||
/** Canonical host directory path. */
|
||||
path: string;
|
||||
/** Display title. */
|
||||
label: string;
|
||||
/** Workspace creation time (epoch ms). */
|
||||
createdAt: number;
|
||||
/** Total visible sessions in the folder. */
|
||||
sessionCount: number;
|
||||
expanded: boolean;
|
||||
/** The folder contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean;
|
||||
/** Visible session rows (empty while the folder is folded). */
|
||||
sessions: readonly SessionNode[];
|
||||
}
|
||||
/** One category folder at the top of the tree. */
|
||||
export interface CategoryNode {
|
||||
/** Stable category key: the configured label, or the uncategorized bucket. */
|
||||
key: string;
|
||||
/** Display label. */
|
||||
label: string;
|
||||
expanded: boolean;
|
||||
/** The category contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean;
|
||||
/** Workspace folders in host order. */
|
||||
workspaces: readonly WorkspaceGroupNode[];
|
||||
}
|
||||
/** Viewing state consumed by the derivation. */
|
||||
export interface GroupsTreeView {
|
||||
expandedCategories: readonly string[];
|
||||
expandedWorkspaces: readonly string[];
|
||||
}
|
||||
/** Key of the uncategorized bucket (matches the config fallback label). */
|
||||
export declare const UNCATEGORIZED_KEY = "\u672A\u5206\u7C7B";
|
||||
/** Directory display label: basename of the path (both separators accepted). */
|
||||
export declare function workspaceLabel(cwd: string | undefined): string;
|
||||
/**
|
||||
* Derive the three-level tree.
|
||||
* @param list - sessions list snapshot (`current` feeds containsCurrent).
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param config - sidecar grouping config.
|
||||
* @param view - local expansion arrays.
|
||||
* @returns category sections in render order (configured categories first, uncategorized last).
|
||||
*/
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView): CategoryNode[];
|
||||
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
|
||||
export interface SearchMatchSet {
|
||||
/** Session ids that matched (local metadata hits + Host content hits). */
|
||||
matchedIds: ReadonlySet<SessionId>;
|
||||
/** Content-match snippets keyed by session id (Host search only). */
|
||||
snippetsBySession: ReadonlyMap<SessionId, string>;
|
||||
hasMore: boolean;
|
||||
}
|
||||
/**
|
||||
* Compute the matched-session set: immediate title/Workspace substring matches
|
||||
* from the local list, merged with ranked Host content matches. The consumer
|
||||
* (SearchBody) derives the pruned three-level tree from these ids.
|
||||
*/
|
||||
export declare function deriveSearchMatches(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, query: string, archivedSessionIds: readonly SessionId[], content: {
|
||||
items: readonly SessionSearchResultItem[];
|
||||
hasMore: boolean;
|
||||
}, limit: number): SearchMatchSet;
|
||||
/**
|
||||
* Build a three-level search tree containing ONLY the branches that hold a
|
||||
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
|
||||
* session carries `matched: true` so rows render with the search-hit tint.
|
||||
*
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param config - sidecar grouping config.
|
||||
* @param matchedIds - set of session ids that matched the query.
|
||||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @returns categories in render order, pruned to matched branches only.
|
||||
*/
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], snippetsBySession?: ReadonlyMap<SessionId, string>): CategoryNode[];
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* Structural types for the cordis services this plugin consumes. A third-party
|
||||
* plugin resolves outside the DSH monorepo's single cordis instance, so the
|
||||
* upstream `declare module` augmentations do not reach this Context — the
|
||||
* members below mirror the actual runtime shapes this plugin touches:
|
||||
* - webServer: @deepseek-ai/dsh-host-webserver (the WebServer)
|
||||
* - effect: the DSH-vendored cordis lifecycle helper
|
||||
* Drift from upstream is contained to this file.
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
/** One named webserver route (mirror of the host-webserver WebRoute). */
|
||||
export interface GroupsWebRoute {
|
||||
kind: 'exact' | 'prefix';
|
||||
path: string;
|
||||
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>;
|
||||
}
|
||||
/** The webServer service face this plugin uses. */
|
||||
export interface GroupsWebServer {
|
||||
register(route: GroupsWebRoute): () => void;
|
||||
}
|
||||
/** Cordis Context augmented with the services this plugin needs. */
|
||||
export interface GroupsContext extends Context {
|
||||
webServer: GroupsWebServer;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/**
|
||||
* Pure classification logic: decides which category a workspace belongs to.
|
||||
* Shared by the host half (validation) and the client half (tree derivation),
|
||||
* so the rule semantics can never drift between the config surface and the
|
||||
* rendered tree.
|
||||
*/
|
||||
import { type GroupCategory } from './types.ts';
|
||||
/**
|
||||
* Classify a workspace into its category.
|
||||
* @param categories - configured categories, in render order.
|
||||
* @param path - workspace canonical directory path.
|
||||
* @param title - workspace display title.
|
||||
* @returns the matching category, or undefined when no rule matches.
|
||||
*/
|
||||
export declare function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined;
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
/**
|
||||
* Shared config types for dsh-workspace-groups. Pure types (zero runtime
|
||||
* deps) so both halves — the node half (sidecar YAML reading) and the
|
||||
* browser half (tree derivation) — compile against the same contract.
|
||||
*/
|
||||
/** One classification rule: any rule that matches places the workspace in the category. */
|
||||
export interface GroupRule {
|
||||
/** Absolute path prefix match (normalized, case-sensitive). */
|
||||
pathPrefix?: string;
|
||||
/** Case-insensitive substring match against the workspace display title. */
|
||||
nameContains?: string;
|
||||
/** Case-insensitive substring match against the workspace directory basename. */
|
||||
basenameContains?: string;
|
||||
/** Exact absolute path match (normalized). */
|
||||
pathExact?: string;
|
||||
}
|
||||
/** One category folder in the sidebar tree. */
|
||||
export interface GroupCategory {
|
||||
/** Display label of the category folder. */
|
||||
name: string;
|
||||
/** Rules; a workspace is classified here when ANY rule matches. */
|
||||
rules: GroupRule[];
|
||||
}
|
||||
/** The full sidecar configuration (mirrors workspace-groups.yaml). */
|
||||
export interface GroupsConfig {
|
||||
/** Category folders, in render order. First match wins. */
|
||||
categories: GroupCategory[];
|
||||
}
|
||||
/** The label of the fallback bucket for unmatched workspaces. */
|
||||
export declare const UNCATEGORIZED_LABEL = "\u672A\u5206\u7C7B";
|
||||
/** Normalize a path for prefix matching: trailing slashes stripped. */
|
||||
export declare function normalizePath(path: string): string;
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
import { classify } from './core/matcher.ts';
|
||||
import type { GroupsConfig } from './core/types.ts';
|
||||
/** Default sidecar location: `$DSH_HOME/workspace-groups.yaml` (DSH_HOME falls back to ~/.dsh). */
|
||||
export declare function defaultConfigPath(): string;
|
||||
/** Parse + validate a raw sidecar document into a GroupsConfig (throws on malformed input). */
|
||||
export declare function parseGroupsConfig(raw: unknown): GroupsConfig;
|
||||
/**
|
||||
* Read + parse the sidecar config file. A missing file yields an empty config
|
||||
* (all workspaces fall into the uncategorized bucket); malformed YAML throws
|
||||
* so the operator sees the problem instead of silently ungrouping everything.
|
||||
*/
|
||||
export declare function readGroupsConfig(path: string): Promise<GroupsConfig>;
|
||||
export { classify };
|
||||
export type { GroupsConfig, GroupCategory, GroupRule } from './core/types.ts';
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { GroupsContext } from './context-types.ts';
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export declare const name = "dsh-workspace-groups";
|
||||
/** Services required before mounting: the webserver route. */
|
||||
export declare const inject: string[];
|
||||
/** Plugin body: mount the config route. */
|
||||
export declare function apply(ctx: GroupsContext): void;
|
||||
|
|
@ -0,0 +1,107 @@
|
|||
{
|
||||
"name": "dsh-workspace-groups",
|
||||
"version": "0.1.0",
|
||||
"description": "DSH web client plugin: group sidebar workspaces into configurable category folders (分类 → 项目 → 会话 three-level tree). Sidecar YAML rules, no core storage changes.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
"deepseek-harness",
|
||||
"deepseek-harness-plugin",
|
||||
"dsh-plugin",
|
||||
"plugin",
|
||||
"sidebar",
|
||||
"workspace",
|
||||
"workspace-groups",
|
||||
"client-plugin"
|
||||
],
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/z-col/dsh-workspace-groups"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib",
|
||||
"cordis.patch.yml",
|
||||
"README.md"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"dsh": {
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-runtime",
|
||||
"@deepseek-ai/dsh-client-locale",
|
||||
"@deepseek-ai/dsh-client-ui-slots"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"build": "rm -rf lib && pnpm build:types && tsdown",
|
||||
"build:types": "tsc -p tsconfig.build.json --noEmit false --declaration --emitDeclarationOnly --outDir lib/types",
|
||||
"watch": "tsdown --watch",
|
||||
"typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tsconfig.client.json --noEmit",
|
||||
"verify": "pnpm typecheck && pnpm test",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"@deepseek-ai/dsh-client-connection": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-locale": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-host-webserver": "^0.1.1-rc.2",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"react-dom": {
|
||||
"optional": true
|
||||
}
|
||||
},
|
||||
"dependencies": {
|
||||
"js-yaml": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "^4.0.1",
|
||||
"@deepseek-ai/dsh-client-connection": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-locale": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-sidebar": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.1.1-rc.2",
|
||||
"@deepseek-ai/dsh-host-webserver": "^0.1.1-rc.2",
|
||||
"@types/js-yaml": "^4.0.9",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/react": "~18.3.1",
|
||||
"@types/react-dom": "~18.3.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jsdom": "^30.0.1",
|
||||
"lightningcss": "^1.32.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"tsdown": "^0.22.2",
|
||||
"typescript": "^5.6.0",
|
||||
"vitest": "^4.1.8"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
|
|
@ -0,0 +1,649 @@
|
|||
/**
|
||||
* The workspace-groups browsing region filling the sidebar shell's
|
||||
* `sidebar.workspaces` hole: section header (title + right-aligned search +
|
||||
* add workspace), the three-level tree (category → workspace → session),
|
||||
* and the workspace/session dialogs. Wide state renders the full browser;
|
||||
* rail state renders the two region icons (search / add workspace) as 36px
|
||||
* controls on the shell's shared rail entry path, each requesting expansion
|
||||
* through the owner share.
|
||||
*
|
||||
* Data: workspaces/sessions via the framework global hooks; grouping config
|
||||
* via the host half's `/workspace-groups/config` route (refetched on mount).
|
||||
*/
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import {
|
||||
Button,
|
||||
IconCloseFill14,
|
||||
IconProjectAddOutline16,
|
||||
IconSearchOutline16,
|
||||
Modal,
|
||||
Tooltip,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { SessionId, SessionListState, SessionSearchResultItem, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { classify } from '../core/matcher.ts'
|
||||
import type { GroupsConfig } from '../core/types.ts'
|
||||
import type { GroupsBrowserProps } from './contract.ts'
|
||||
import { deriveGroups, deriveSearchGroups, deriveSearchMatches, type CategoryNode } from './tree.ts'
|
||||
import { CategoryRow, SessionRow, WorkspaceRow } from './rows.tsx'
|
||||
import css from './styles.css?inline'
|
||||
|
||||
const SEARCH_DEBOUNCE_MS = 250
|
||||
const SEARCH_QUERY_MAX_CODE_UNITS = 500
|
||||
|
||||
function sanitizeSearchQuery(value: string): string {
|
||||
const withoutNul = value.replaceAll('\0', '')
|
||||
if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul
|
||||
return withoutNul.slice(0, SEARCH_QUERY_MAX_CODE_UNITS)
|
||||
}
|
||||
|
||||
/** Immutable membership toggle for the local expand-all array. */
|
||||
function toggled(list: readonly string[], key: string): string[] {
|
||||
return list.includes(key) ? list.filter(k => k !== key) : [...list, key]
|
||||
}
|
||||
|
||||
interface RemoteSearchState {
|
||||
query: string
|
||||
status: 'idle' | 'loading' | 'ready' | 'error'
|
||||
items: readonly SessionSearchResultItem[]
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
/** Minimal fetch of the grouping config (host route; no-cache revalidation). */
|
||||
async function fetchGroupsConfig(): Promise<GroupsConfig> {
|
||||
const response = await fetch('/workspace-groups/config', { cache: 'no-cache' })
|
||||
if (!response.ok) throw new Error(`config request failed: ${response.status}`)
|
||||
const body = (await response.json()) as GroupsConfig
|
||||
return Array.isArray(body.categories) ? body : { categories: [] }
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the browsing region.
|
||||
* @param props - composed slot props (shell owner share + store + injected actions).
|
||||
* @returns the region element tree.
|
||||
*/
|
||||
export function GroupsBrowser({
|
||||
wide,
|
||||
expandSidebar,
|
||||
useSessions,
|
||||
useWorkspaces,
|
||||
useStore,
|
||||
actions,
|
||||
startSession,
|
||||
open,
|
||||
renameSession,
|
||||
forkSession,
|
||||
renameWorkspace,
|
||||
deleteWorkspace,
|
||||
insertWorkspaceBefore,
|
||||
archiveSession,
|
||||
insertSessionBefore,
|
||||
createWorkspace,
|
||||
pickDirectory,
|
||||
searchSessions,
|
||||
searchResultLimit,
|
||||
t,
|
||||
}: GroupsBrowserProps) {
|
||||
// Inject the stylesheet once per fiber; dispose removes it (HMR safe).
|
||||
useEffect(() => {
|
||||
const style = document.createElement('style')
|
||||
style.setAttribute('data-plugin', 'dsh-workspace-groups')
|
||||
style.textContent = css
|
||||
document.head.append(style)
|
||||
return () => { style.remove() }
|
||||
}, [])
|
||||
|
||||
// Grouping config from the host route.
|
||||
const [config, setConfig] = useState<GroupsConfig>({ categories: [] })
|
||||
const [configError, setConfigError] = useState<string | null>(null)
|
||||
const reloadConfig = () => {
|
||||
setConfigError(null)
|
||||
fetchGroupsConfig().then(setConfig).catch((reason: unknown) => {
|
||||
setConfigError(reason instanceof Error ? reason.message : String(reason))
|
||||
})
|
||||
}
|
||||
useEffect(() => { reloadConfig() }, [])
|
||||
|
||||
const workspaces = useWorkspaces(state => state.items)
|
||||
const workspacePhase = useWorkspaces(state => state.phase)
|
||||
const archivedSessionIds = useWorkspaces(state => state.archivedSessionIds)
|
||||
const categoryExpansion = useStore(s => s.categoryExpansion)
|
||||
const workspaceExpansion = useStore(s => s.workspaceExpansion)
|
||||
|
||||
const list = useSessions(s => s)
|
||||
const current = list.current
|
||||
const currentWorkspaceKey = current === undefined
|
||||
? undefined
|
||||
: (workspaces.find(w => w.sessionIds.includes(current as SessionId))?.workspaceId as string | undefined)
|
||||
|
||||
// Auto-expand the category + workspace containing the current session, but
|
||||
// ONLY when the user has never touched that key (`Object.hasOwn`): a
|
||||
// present `false` is a deliberate collapse and must stay folded. Without
|
||||
// this guard the effect re-expands the just-collapsed current category on
|
||||
// every store change (the reported "cannot collapse" bug).
|
||||
useEffect(() => {
|
||||
if (current === undefined || currentWorkspaceKey === undefined) return
|
||||
const category = categoriesForCurrent(config, workspaces, current)
|
||||
if (category !== undefined && !Object.hasOwn(categoryExpansion, category)) {
|
||||
actions.setCategoryExpanded(category, true)
|
||||
}
|
||||
if (!Object.hasOwn(workspaceExpansion, currentWorkspaceKey)) {
|
||||
actions.setWorkspaceExpanded(currentWorkspaceKey, true)
|
||||
}
|
||||
}, [current, currentWorkspaceKey, config, workspaces, categoryExpansion, workspaceExpansion, actions])
|
||||
|
||||
// Drop expansion keys that no longer exist (config edits / workspace deletion).
|
||||
useEffect(() => {
|
||||
if (workspacePhase !== 'ready') return
|
||||
actions.retainKeys(
|
||||
config.categories.map(c => c.name),
|
||||
workspaces.map(w => w.workspaceId as string),
|
||||
)
|
||||
}, [actions, config, workspacePhase, workspaces])
|
||||
|
||||
const [query, setQuery] = useState('')
|
||||
const [searchExpanded, setSearchExpanded] = useState(false)
|
||||
const normalizedQuery = sanitizeSearchQuery(query).trim()
|
||||
const [remoteSearch, setRemoteSearch] = useState<RemoteSearchState>({
|
||||
query: '', status: 'idle', items: [], hasMore: false,
|
||||
})
|
||||
const searchInput = useRef<HTMLInputElement | null>(null)
|
||||
const searchRoot = useRef<HTMLDivElement | null>(null)
|
||||
|
||||
// Search debounce + abort, same posture as the official browser.
|
||||
useEffect(() => {
|
||||
if (normalizedQuery === '') {
|
||||
setRemoteSearch({ query: '', status: 'idle', items: [], hasMore: false })
|
||||
return
|
||||
}
|
||||
const controller = new AbortController()
|
||||
setRemoteSearch({ query: normalizedQuery, status: 'loading', items: [], hasMore: false })
|
||||
const timer = window.setTimeout(() => {
|
||||
searchSessions(normalizedQuery, controller.signal).then((result) => {
|
||||
if (controller.signal.aborted) return
|
||||
setRemoteSearch({ query: normalizedQuery, status: 'ready', items: result.items, hasMore: result.hasMore })
|
||||
}).catch(() => {
|
||||
if (controller.signal.aborted) return
|
||||
setRemoteSearch({ query: normalizedQuery, status: 'error', items: [], hasMore: false })
|
||||
})
|
||||
}, SEARCH_DEBOUNCE_MS)
|
||||
return () => {
|
||||
window.clearTimeout(timer)
|
||||
controller.abort()
|
||||
}
|
||||
}, [normalizedQuery, searchSessions])
|
||||
|
||||
// Outside-click dismissal of the search box.
|
||||
useEffect(() => {
|
||||
if (!wide || !searchExpanded) return
|
||||
const onClick = (event: MouseEvent): void => {
|
||||
if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return
|
||||
searchInput.current?.blur()
|
||||
if (normalizedQuery !== '') return
|
||||
setSearchExpanded(false)
|
||||
}
|
||||
document.addEventListener('click', onClick)
|
||||
return () => { document.removeEventListener('click', onClick) }
|
||||
}, [normalizedQuery, wide, searchExpanded])
|
||||
|
||||
const expandedCategories = useMemo(
|
||||
() => Object.entries(categoryExpansion).filter(([, v]) => v).map(([k]) => k),
|
||||
[categoryExpansion],
|
||||
)
|
||||
const expandedWorkspaces = useMemo(
|
||||
() => Object.entries(workspaceExpansion).filter(([, v]) => v).map(([k]) => k),
|
||||
[workspaceExpansion],
|
||||
)
|
||||
const groups = useMemo(
|
||||
() => deriveGroups(list, workspaces, archivedSessionIds, config, {
|
||||
expandedCategories,
|
||||
expandedWorkspaces,
|
||||
}),
|
||||
[list, workspaces, archivedSessionIds, config, expandedCategories, expandedWorkspaces],
|
||||
)
|
||||
|
||||
// Add workspace flow: self-contained (no directory-flow hole dependency).
|
||||
const [adding, setAdding] = useState(false)
|
||||
const [addError, setAddError] = useState<string | null>(null)
|
||||
const [addErrorOpen, setAddErrorOpen] = useState(false)
|
||||
const addWorkspace = async (): Promise<void> => {
|
||||
if (adding) return
|
||||
setAdding(true)
|
||||
setAddError(null)
|
||||
setAddErrorOpen(false)
|
||||
try {
|
||||
const path = await pickDirectory()
|
||||
if (path === null) return // cancelled
|
||||
const workspace = await createWorkspace({ path })
|
||||
startSession(workspace.workspaceId)
|
||||
} catch (reason) {
|
||||
const message = reason instanceof Error ? reason.message : String(reason)
|
||||
setAddError(message)
|
||||
setAddErrorOpen(true)
|
||||
} finally {
|
||||
setAdding(false)
|
||||
}
|
||||
}
|
||||
|
||||
// Workspace rename dialog.
|
||||
const [renameTarget, setRenameTarget] = useState<{ workspaceId: WorkspaceId; currentTitle: string } | null>(null)
|
||||
const [renameDraft, setRenameDraft] = useState('')
|
||||
const [renaming, setRenaming] = useState(false)
|
||||
const [renameError, setRenameError] = useState<string | null>(null)
|
||||
const renameTrimmed = renameDraft.trim()
|
||||
const renameDuplicate = renameTarget !== null && renameTrimmed !== '' && renameTrimmed !== renameTarget.currentTitle
|
||||
&& workspaces.some(w => w.title === renameTrimmed)
|
||||
const renameBlocked = renaming || renameTrimmed === '' || renameTarget === null
|
||||
|| renameTrimmed === renameTarget.currentTitle || renameDuplicate
|
||||
const confirmRename = () => {
|
||||
if (renameBlocked || renameTarget === null) return
|
||||
setRenaming(true)
|
||||
setRenameError(null)
|
||||
renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {
|
||||
setRenaming(false)
|
||||
setRenameTarget(null)
|
||||
}).catch((reason: unknown) => {
|
||||
setRenaming(false)
|
||||
setRenameError(reason instanceof Error ? reason.message : String(reason))
|
||||
})
|
||||
}
|
||||
|
||||
// Workspace delete dialog.
|
||||
const [deleteTarget, setDeleteTarget] = useState<{ workspaceId: WorkspaceId; title: string } | null>(null)
|
||||
const [deleting, setDeleting] = useState(false)
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null)
|
||||
const confirmDelete = () => {
|
||||
if (deleting || deleteTarget === null) return
|
||||
setDeleting(true)
|
||||
setDeleteError(null)
|
||||
deleteWorkspace(deleteTarget.workspaceId).then(() => {
|
||||
setDeleting(false)
|
||||
setDeleteTarget(null)
|
||||
}).catch((reason: unknown) => {
|
||||
setDeleting(false)
|
||||
setDeleteError(reason instanceof Error ? reason.message : String(reason))
|
||||
})
|
||||
}
|
||||
|
||||
// Session rename dialog.
|
||||
const [sessionRenameTarget, setSessionRenameTarget] = useState<{ sessionId: SessionId; currentTitle: string } | null>(null)
|
||||
const [sessionRenameDraft, setSessionRenameDraft] = useState('')
|
||||
const [sessionRenaming, setSessionRenaming] = useState(false)
|
||||
const [sessionRenameError, setSessionRenameError] = useState<string | null>(null)
|
||||
const sessionRenameTrimmed = sessionRenameDraft.trim()
|
||||
const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === '' || sessionRenameTarget === null
|
||||
const confirmSessionRename = () => {
|
||||
if (sessionRenameBlocked || sessionRenameTarget === null) return
|
||||
setSessionRenaming(true)
|
||||
setSessionRenameError(null)
|
||||
renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {
|
||||
setSessionRenaming(false)
|
||||
setSessionRenameTarget(null)
|
||||
}).catch((reason: unknown) => {
|
||||
setSessionRenaming(false)
|
||||
setSessionRenameError(reason instanceof Error ? reason.message : String(reason))
|
||||
})
|
||||
}
|
||||
const onSessionRename = (sessionId: SessionId, currentTitle: string) => {
|
||||
setSessionRenameTarget({ sessionId, currentTitle })
|
||||
setSessionRenameDraft(currentTitle)
|
||||
setSessionRenameError(null)
|
||||
}
|
||||
|
||||
const onSessionArchive = (sessionId: SessionId) => {
|
||||
archiveSession(sessionId).catch((reason: unknown) => {
|
||||
console.warn('session archive rejected:', reason)
|
||||
})
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
|
||||
return (
|
||||
<div className={`wgRoot${wide ? '' : ' wgRail'}`}>
|
||||
<div className="wgSectionHeader">
|
||||
{wide && <span className="wgSectionLabel">{t('section.workspaces')}</span>}
|
||||
{wide && (
|
||||
<div className={`wgSearch${searchExpanded ? ' wgSearchExpanded' : ''}`} ref={searchRoot}>
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={t('search')}
|
||||
onClick={() => { setSearchExpanded(true) }}
|
||||
>
|
||||
<IconSearchOutline16 size={searchExpanded ? 11 : 14} />
|
||||
</button>
|
||||
{searchExpanded && (
|
||||
<input
|
||||
ref={searchInput}
|
||||
className="wgSearchInput"
|
||||
type="text"
|
||||
placeholder={t('search.placeholder')}
|
||||
maxLength={SEARCH_QUERY_MAX_CODE_UNITS}
|
||||
value={query}
|
||||
autoFocus
|
||||
onChange={(e) => { setQuery(sanitizeSearchQuery(e.target.value)) }}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key !== 'Escape') return
|
||||
setQuery('')
|
||||
setSearchExpanded(false)
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{searchExpanded && (
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={t('search.clear')}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation()
|
||||
setQuery('')
|
||||
setSearchExpanded(false)
|
||||
}}
|
||||
>
|
||||
<IconCloseFill14 />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<Tooltip label={t('workspace.add')} side="bottom" delayMs={500}>
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={t('workspace.add')}
|
||||
disabled={adding}
|
||||
onClick={addWorkspace}
|
||||
>
|
||||
<IconProjectAddOutline16 size={wide ? 16 : 18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
|
||||
{!wide && (
|
||||
<div className="wgSectionHeader">
|
||||
<Tooltip label={t('search')}>
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={t('search')}
|
||||
onClick={() => { setSearchExpanded(true); expandSidebar() }}
|
||||
>
|
||||
<IconSearchOutline16 size={18} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="wgTreeBody">
|
||||
{configError !== null && (
|
||||
<div className="wgSearchStatus" role="status">{t('configUnavailable')}</div>
|
||||
)}
|
||||
{wide && normalizedQuery !== '' ? (
|
||||
<SearchBody
|
||||
list={list}
|
||||
workspaces={workspaces}
|
||||
config={config}
|
||||
archivedSessionIds={archivedSessionIds}
|
||||
query={normalizedQuery}
|
||||
remote={remoteSearch}
|
||||
resultLimit={searchResultLimit}
|
||||
current={current}
|
||||
now={now}
|
||||
open={open}
|
||||
t={t}
|
||||
/>
|
||||
) : (
|
||||
<div className="wgList" role="tree" aria-label={t('section.workspaces')}>
|
||||
{groups.length === 0 && (
|
||||
<div className="wgEmpty">{workspacePhase === 'ready' ? t('empty.noWorkspaces') : t('empty.none')}</div>
|
||||
)}
|
||||
{groups.map((category) => (
|
||||
<CategorySection
|
||||
key={category.key}
|
||||
category={category}
|
||||
current={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onToggleCategory={() => { actions.setCategoryExpanded(category.key, !category.expanded) }}
|
||||
onToggleWorkspace={(key) => { actions.setWorkspaceExpanded(key, !workspaceExpansion[key]) }}
|
||||
onNewSession={startSession}
|
||||
onOpen={open}
|
||||
onRenameRequest={(workspaceId, title) => {
|
||||
setRenameTarget({ workspaceId, currentTitle: title })
|
||||
setRenameDraft(title)
|
||||
setRenameError(null)
|
||||
}}
|
||||
onDeleteRequest={(workspaceId, title) => {
|
||||
setDeleteTarget({ workspaceId, title })
|
||||
setDeleteError(null)
|
||||
}}
|
||||
onSessionRename={onSessionRename}
|
||||
onSessionArchive={onSessionArchive}
|
||||
onFork={forkSession}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Workspace rename dialog */}
|
||||
<Modal
|
||||
open={renameTarget !== null}
|
||||
onClose={() => { setRenameTarget(null) }}
|
||||
closeLabel={t('close')}
|
||||
title={t('workspace.renameTitle')}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="outline" onClick={() => { setRenameTarget(null) }}>{t('cancel')}</Button>
|
||||
<Button variant="primary" disabled={renameBlocked} onClick={confirmRename}>{t('workspace.renameConfirm')}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<input
|
||||
className="wgRenameInput"
|
||||
value={renameDraft}
|
||||
aria-label={t("workspace.renamePlaceholder")}
|
||||
autoFocus
|
||||
onChange={(e) => { setRenameDraft(e.target.value) }}
|
||||
onKeyDown={(e) => { if (e.key === "Enter") confirmRename() }}
|
||||
/>
|
||||
{renameError !== null && <div className="wgAddError" role="alert">{renameError}</div>}
|
||||
</Modal>
|
||||
|
||||
{/* Workspace delete dialog */}
|
||||
<Modal
|
||||
open={deleteTarget !== null}
|
||||
onClose={() => { setDeleteTarget(null) }}
|
||||
closeLabel={t('close')}
|
||||
title={t('workspace.deleteTitle')}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="outline" onClick={() => { setDeleteTarget(null) }}>{t('workspace.deleteCancel')}</Button>
|
||||
<Button variant="outline" disabled={deleting} onClick={confirmDelete}>{t('workspace.delete')}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<div className="wgAddError">{t('workspace.deleteConfirm')}</div>
|
||||
{deleteError !== null && <div className="wgAddError" role="alert">{deleteError}</div>}
|
||||
</Modal>
|
||||
|
||||
{/* Session rename dialog */}
|
||||
<Modal
|
||||
open={sessionRenameTarget !== null}
|
||||
onClose={() => { setSessionRenameTarget(null) }}
|
||||
closeLabel={t('close')}
|
||||
title={t('session.renameTitle')}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="outline" onClick={() => { setSessionRenameTarget(null) }}>{t('session.renameCancel')}</Button>
|
||||
<Button variant="primary" disabled={sessionRenameBlocked} onClick={confirmSessionRename}>{t('session.renameConfirm')}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<input
|
||||
className="wgRenameInput"
|
||||
value={sessionRenameDraft}
|
||||
aria-label={t("session.renamePlaceholder")}
|
||||
autoFocus
|
||||
onChange={(e) => { setSessionRenameDraft(e.target.value) }}
|
||||
onKeyDown={(e) => { if (e.key === "Enter") confirmSessionRename() }}
|
||||
/>
|
||||
{sessionRenameError !== null && <div className="wgAddError" role="alert">{sessionRenameError}</div>}
|
||||
</Modal>
|
||||
|
||||
{/* Add workspace error dialog */}
|
||||
<Modal
|
||||
open={addErrorOpen}
|
||||
onClose={() => { setAddErrorOpen(false) }}
|
||||
closeLabel={t('close')}
|
||||
title={t('workspace.addErrorTitle')}
|
||||
footer={(
|
||||
<>
|
||||
<Button variant="outline" onClick={() => { setAddErrorOpen(false) }}>{t('close')}</Button>
|
||||
<Button variant="primary" onClick={addWorkspace}>{t('retry')}</Button>
|
||||
</>
|
||||
)}
|
||||
>
|
||||
<div className="wgAddError" role="alert">{addError}</div>
|
||||
</Modal>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Resolve the category label containing the current session (auto-expand helper). */
|
||||
function categoriesForCurrent(
|
||||
config: GroupsConfig,
|
||||
workspaces: readonly WorkspaceView[],
|
||||
current: SessionId,
|
||||
): string | undefined {
|
||||
const workspace = workspaces.find(w => w.sessionIds.includes(current))
|
||||
if (workspace === undefined) return undefined
|
||||
return classify(config.categories, workspace.path, workspace.title)?.name
|
||||
}
|
||||
|
||||
/** One category section: header row + expanded workspace folders. */
|
||||
function CategorySection({ category, current, now, t, onToggleCategory, onToggleWorkspace, onNewSession, onOpen, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, onFork }: {
|
||||
category: CategoryNode
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
t: GroupsBrowserProps['t']
|
||||
onToggleCategory: () => void
|
||||
onToggleWorkspace: (key: string) => void
|
||||
onNewSession: (workspaceId?: WorkspaceId) => void
|
||||
onOpen: (sessionId: SessionId) => void
|
||||
onRenameRequest: (workspaceId: WorkspaceId, currentTitle: string) => void
|
||||
onDeleteRequest: (workspaceId: WorkspaceId, title: string) => void
|
||||
onSessionRename: (sessionId: SessionId, currentTitle: string) => void
|
||||
onSessionArchive: (sessionId: SessionId) => void
|
||||
onFork: (sessionId: SessionId) => void
|
||||
}) {
|
||||
return (
|
||||
<div role="group">
|
||||
<CategoryRow node={category} t={t} onToggle={onToggleCategory} />
|
||||
{category.expanded && (
|
||||
<div role="group">
|
||||
{category.workspaces.map((workspace) => (
|
||||
<div key={workspace.workspaceId} role="group">
|
||||
<WorkspaceRow
|
||||
node={workspace}
|
||||
t={t}
|
||||
onToggle={() => { onToggleWorkspace(workspace.workspaceId as string) }}
|
||||
onNewSession={() => { onNewSession(workspace.workspaceId) }}
|
||||
onRename={() => { onRenameRequest(workspace.workspaceId, workspace.label) }}
|
||||
onDelete={() => { onDeleteRequest(workspace.workspaceId, workspace.label) }}
|
||||
/>
|
||||
{workspace.expanded && workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={onOpen}
|
||||
onRename={onSessionRename}
|
||||
onFork={onFork}
|
||||
onArchive={onSessionArchive}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Search body rendered as a three-level tree pruned to matched branches:
|
||||
* 分类文件夹 → 项目文件夹 → 命中会话行. Reuses the same row components as
|
||||
* the idle tree, so search keeps the same folder hierarchy the user is used to.
|
||||
*/
|
||||
function SearchBody({ list, workspaces, config, archivedSessionIds, query, remote, resultLimit, current, now, open, t }: {
|
||||
list: SessionListState
|
||||
workspaces: readonly WorkspaceView[]
|
||||
config: GroupsConfig
|
||||
archivedSessionIds: readonly SessionId[]
|
||||
query: string
|
||||
remote: RemoteSearchState
|
||||
resultLimit: number
|
||||
current: SessionId | undefined
|
||||
now: number
|
||||
open: (sessionId: SessionId) => void
|
||||
t: GroupsBrowserProps['t']
|
||||
}) {
|
||||
const currentRemote = remote.query === query ? remote : { query, status: 'loading' as const, items: [], hasMore: false }
|
||||
const matches = useMemo(
|
||||
() => deriveSearchMatches(list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit),
|
||||
[list, workspaces, config, query, archivedSessionIds, currentRemote, resultLimit],
|
||||
)
|
||||
const groups = useMemo(
|
||||
() => deriveSearchGroups(list, workspaces, config, matches.matchedIds, archivedSessionIds, matches.snippetsBySession),
|
||||
[list, workspaces, config, matches, archivedSessionIds],
|
||||
)
|
||||
const pending = currentRemote.status === 'loading'
|
||||
const failed = currentRemote.status === 'error'
|
||||
return (
|
||||
<div className="wgList" role="tree" aria-label={t('search.results.aria')}>
|
||||
{groups.map((category) => (
|
||||
<div key={category.key} role="group">
|
||||
<CategoryRow node={category} t={t} onToggle={() => {}} />
|
||||
<div role="group">
|
||||
{category.workspaces.map((workspace) => (
|
||||
<div key={workspace.workspaceId} role="group">
|
||||
<WorkspaceRow
|
||||
node={workspace}
|
||||
t={t}
|
||||
onToggle={() => {}}
|
||||
onNewSession={() => {}}
|
||||
onRename={() => {}}
|
||||
onDelete={() => {}}
|
||||
/>
|
||||
<div role="group">
|
||||
{workspace.sessions.map((session) => (
|
||||
<SessionRow
|
||||
key={session.id}
|
||||
node={session}
|
||||
currentId={current}
|
||||
now={now}
|
||||
t={t}
|
||||
onOpen={open}
|
||||
onRename={() => {}}
|
||||
onFork={() => {}}
|
||||
onArchive={() => {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{pending && <div className="wgSearchStatus" role="status">{t('search.pending')}</div>}
|
||||
{failed && <div className="wgSearchStatus" role="status">{t('search.unavailable')}</div>}
|
||||
{!pending && groups.length === 0 && (
|
||||
<div className="wgEmpty">{t('search.noMatches')}</div>
|
||||
)}
|
||||
{matches.hasMore && (
|
||||
<div className="wgSearchStatus">{t('search.hasMore')}</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
/**
|
||||
* Registrant-private injected share for the workspace-groups browser entry.
|
||||
* Mirrors the official ui-workspace browser inject (same runtime calls), with
|
||||
* two differences: no directory-flow hole dependency (Add Workspace is
|
||||
* self-contained via `pickDirectory`), and no locale-keyed naming collision.
|
||||
*/
|
||||
import type {
|
||||
PropsHooks,
|
||||
PropsLocale,
|
||||
PropsRuntime,
|
||||
PropsStore,
|
||||
} from '@deepseek-ai/dsh-client-ui-slots'
|
||||
// Type-only: pulls the sidebar shell's SlotMap merge (sidebar.workspaces).
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client'
|
||||
import type { HostDescriptionSource } from '@deepseek-ai/dsh-client-connection/client'
|
||||
import type {
|
||||
SessionId,
|
||||
SessionSearchResultItem,
|
||||
WorkspaceId,
|
||||
WorkspaceView,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { createGroupsViewStore } from './stores.ts'
|
||||
|
||||
/** Injected share (arrives via the register inject factory). */
|
||||
export type GroupsBrowserInjected = {
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void
|
||||
/** Open a real Session. */
|
||||
open: (sessionId: SessionId) => void
|
||||
/** Search current visible conversation messages. */
|
||||
searchSessions: (query: string, signal: AbortSignal) => Promise<{
|
||||
items: readonly SessionSearchResultItem[]
|
||||
hasMore: boolean
|
||||
}>
|
||||
/** Maximum number of merged rows rendered for one search. */
|
||||
searchResultLimit: number
|
||||
/** Rename a Session (resolves on host acceptance). */
|
||||
renameSession: (sessionId: SessionId, title: string) => Promise<void>
|
||||
/** Fork a Session at its last completed turn and open the child. */
|
||||
forkSession: (sessionId: SessionId) => void
|
||||
/** Rename a Host Workspace (rejects on name conflict). */
|
||||
renameWorkspace: (workspaceId: WorkspaceId, title: string) => Promise<void>
|
||||
/** Delete only a Host Workspace registration; directory and Session logs remain. */
|
||||
deleteWorkspace: (workspaceId: WorkspaceId) => Promise<void>
|
||||
/** Reorder a Workspace in the durable registry display order (omitted anchor appends). */
|
||||
insertWorkspaceBefore: (workspaceId: WorkspaceId, beforeWorkspaceId?: WorkspaceId) => Promise<void>
|
||||
/** Archive a Session into the registry-global set (hidden from grouping surfaces). */
|
||||
archiveSession: (sessionId: SessionId) => Promise<void>
|
||||
/** Reorder a session inside its Workspace account. */
|
||||
insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise<void>
|
||||
/** Adopt a picked host directory as a real Workspace before targeting a Session. */
|
||||
createWorkspace: (input: { path: string }) => Promise<WorkspaceView>
|
||||
/** Ask the local Host to open its native single-directory chooser (self-contained Add Workspace). */
|
||||
pickDirectory: () => Promise<string | null>
|
||||
/** Browser-private injected hooks (host description; bound by the slot renderer). */
|
||||
hooks: {
|
||||
/** Current generation's Host description. */
|
||||
hostDescription: HostDescriptionSource
|
||||
}
|
||||
}
|
||||
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + locale seat. */
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> &
|
||||
PropsStore<ReturnType<typeof createGroupsViewStore>> &
|
||||
Omit<GroupsBrowserInjected, 'hooks'> &
|
||||
PropsHooks<GroupsBrowserInjected['hooks']> &
|
||||
PropsLocale<'workspaceGroups'>
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
/**
|
||||
* dsh-workspace-groups client half: registers the three-level grouped
|
||||
* workspace browser into the `sidebar.workspaces` slot, shadowing the
|
||||
* official ui-workspace browser.
|
||||
*
|
||||
* Shadowing mechanics (SlotCore semantics):
|
||||
* - `sidebar.workspaces` is a `single`/`root` slot. The official browser
|
||||
* registers at priority 0; this entry registers at priority -1, and the
|
||||
* single-cell shadow rule makes the LOWEST priority the winner — the
|
||||
* sidebar renders this browser instead of the official one.
|
||||
* - This entry deliberately declares NO child slots: the official entry
|
||||
* already declared `sidebar.workspaces.directoryFlow` (a second declaration
|
||||
* of an occupied child key throws). Add Workspace is therefore self-
|
||||
* contained — `ctx.workspaces.pickDirectory()` + `create()`, no hole.
|
||||
*/
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
|
||||
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
|
||||
import type {} from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type { GroupsBrowserInjected } from './contract.ts'
|
||||
import { createGroupsViewStore } from './stores.ts'
|
||||
import { GroupsBrowser } from './GroupsBrowser.tsx'
|
||||
import { en, zh, type WorkspaceGroupsKey } from './locales.ts'
|
||||
|
||||
declare module '@deepseek-ai/dsh-client-ui-slots' {
|
||||
interface LocaleNamespaceMap {
|
||||
/** The workspace-groups browsing region copy. */
|
||||
workspaceGroups: WorkspaceGroupsKey
|
||||
}
|
||||
}
|
||||
|
||||
/** Dictionary namespace owned by this plugin. */
|
||||
const NS = 'workspaceGroups'
|
||||
|
||||
/** Required services (cordis fiber inject). */
|
||||
export const inject = ['slots', 'sessions', 'workspaces', 'locale', 'connection']
|
||||
|
||||
/**
|
||||
* Register the grouped browser once the sidebar slot declaration is on the
|
||||
* ledger. Inject factory returns plain callbacks; data reads use the
|
||||
* framework's global hooks.
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-workspace-groups: dictionaries')
|
||||
|
||||
const searchSessions: GroupsBrowserInjected['searchSessions'] = async (query, signal) => {
|
||||
const result = await ctx.sessions.search(query, signal)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
return result.value
|
||||
}
|
||||
|
||||
const browserInjected = (): GroupsBrowserInjected => ({
|
||||
startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },
|
||||
open: (sessionId) => { ctx.sessions.open(sessionId) },
|
||||
searchSessions,
|
||||
searchResultLimit: ctx.sessions.searchResultLimit,
|
||||
renameSession: async (sessionId, title) => {
|
||||
const session = ctx.sessions.binding(sessionId)?.session
|
||||
if (session === undefined) throw new Error(`unknown session "${sessionId}"`)
|
||||
const result = await session.rename(title)
|
||||
if (!result.ok) throw new Error(result.error.message)
|
||||
},
|
||||
forkSession: (sessionId) => {
|
||||
ctx.sessions.fork({ sessionId, increaseTitle: true })
|
||||
.then((childId) => { ctx.sessions.open(childId) })
|
||||
.catch(() => {})
|
||||
},
|
||||
renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },
|
||||
deleteWorkspace: async (workspaceId) => { await ctx.workspaces.delete(workspaceId) },
|
||||
insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
|
||||
await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId)
|
||||
},
|
||||
archiveSession: async (sessionId) => { await ctx.workspaces.archiveSession(sessionId) },
|
||||
insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {
|
||||
await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId)
|
||||
},
|
||||
createWorkspace: input => ctx.workspaces.create(input),
|
||||
pickDirectory: () => ctx.workspaces.pickDirectory(),
|
||||
hooks: {
|
||||
hostDescription: (ctx.get('connection') as ConnectionHandle).hostDescription,
|
||||
},
|
||||
})
|
||||
|
||||
// priority: -1 — lower than the official browser's default 0, so the
|
||||
// single-slot shadow rule elects this entry. No children declaration: the
|
||||
// official entry already owns `sidebar.workspaces.directoryFlow`.
|
||||
ctx.slots.inject('sidebar.workspaces', () => ctx.slots.register(
|
||||
{
|
||||
name: 'sidebar.workspaces',
|
||||
priority: -1,
|
||||
store: createGroupsViewStore(),
|
||||
inject: browserInjected,
|
||||
locale: NS,
|
||||
registrant: 'dsh-workspace-groups',
|
||||
},
|
||||
GroupsBrowser,
|
||||
))
|
||||
}
|
||||
|
|
@ -0,0 +1,153 @@
|
|||
/**
|
||||
* Locale dictionaries for the workspace-groups browser. The namespace is
|
||||
* `workspaceGroups` (independent from ui-workspace's `workspace` namespace).
|
||||
*/
|
||||
import type { LocaleDictOf } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
|
||||
/** Dictionary keys of the workspaceGroups namespace (single source of truth). */
|
||||
export type WorkspaceGroupsKey =
|
||||
| 'section.workspaces'
|
||||
| 'section.sessions'
|
||||
| 'search'
|
||||
| 'search.placeholder'
|
||||
| 'search.clear'
|
||||
| 'search.noMatches'
|
||||
| 'search.unavailable'
|
||||
| 'search.pending'
|
||||
| 'search.hasMore'
|
||||
| 'search.results.aria'
|
||||
| 'workspace.add'
|
||||
| 'workspace.addBusy'
|
||||
| 'workspace.addError'
|
||||
| 'workspace.addErrorTitle'
|
||||
| 'workspace.rename'
|
||||
| 'workspace.delete'
|
||||
| 'workspace.deleteTitle'
|
||||
| 'workspace.deleteConfirm'
|
||||
| 'workspace.deleteCancel'
|
||||
| 'workspace.renaming'
|
||||
| 'workspace.deleting'
|
||||
| 'workspace.renameTitle'
|
||||
| 'workspace.renamePlaceholder'
|
||||
| 'workspace.renameConfirm'
|
||||
| 'workspace.renameCancel'
|
||||
| 'session.new'
|
||||
| 'session.rename'
|
||||
| 'session.archive'
|
||||
| 'session.fork'
|
||||
| 'session.renameTitle'
|
||||
| 'session.renamePlaceholder'
|
||||
| 'session.renameConfirm'
|
||||
| 'session.renameCancel'
|
||||
| 'session.renaming'
|
||||
| 'uncategorized'
|
||||
| 'empty.none'
|
||||
| 'empty.noWorkspaces'
|
||||
| 'close'
|
||||
| 'cancel'
|
||||
| 'confirm'
|
||||
| 'retry'
|
||||
| 'configUnavailable'
|
||||
| 'collapse'
|
||||
| 'expandMore'
|
||||
| 'newSession'
|
||||
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>
|
||||
|
||||
/** Simplified Chinese dictionary. */
|
||||
export const zh: WorkspaceGroupsDict = {
|
||||
'section.workspaces': '工作区',
|
||||
'section.sessions': '会话',
|
||||
search: '搜索',
|
||||
'search.placeholder': '搜索会话…',
|
||||
'search.clear': '清除',
|
||||
'search.noMatches': '没有匹配的会话',
|
||||
'search.unavailable': '搜索不可用',
|
||||
'search.pending': '搜索中…',
|
||||
'search.hasMore': '结果过多,请细化关键词',
|
||||
'search.results.aria': '搜索结果',
|
||||
'workspace.add': '添加工作区',
|
||||
'workspace.addBusy': '正在添加…',
|
||||
'workspace.addError': '添加失败',
|
||||
'workspace.addErrorTitle': '无法添加工作区',
|
||||
'workspace.rename': '重命名',
|
||||
'workspace.delete': '删除',
|
||||
'workspace.deleteTitle': '删除工作区',
|
||||
'workspace.deleteConfirm': '仅删除注册信息,目录与会话日志保留。确定删除?',
|
||||
'workspace.deleteCancel': '取消删除',
|
||||
'workspace.renaming': '重命名中…',
|
||||
'workspace.deleting': '删除中…',
|
||||
'workspace.renameTitle': '重命名工作区',
|
||||
'workspace.renamePlaceholder': '工作区名称',
|
||||
'workspace.renameConfirm': '重命名',
|
||||
'workspace.renameCancel': '取消',
|
||||
'session.new': '新建会话',
|
||||
'session.rename': '重命名会话',
|
||||
'session.archive': '归档',
|
||||
'session.fork': '派生',
|
||||
'session.renameTitle': '重命名会话',
|
||||
'session.renamePlaceholder': '会话名称',
|
||||
'session.renameConfirm': '重命名',
|
||||
'session.renameCancel': '取消',
|
||||
'session.renaming': '重命名中…',
|
||||
uncategorized: '未分类',
|
||||
'empty.none': '暂无内容',
|
||||
'empty.noWorkspaces': '还没有工作区',
|
||||
close: '关闭',
|
||||
cancel: '取消',
|
||||
confirm: '确定',
|
||||
retry: '重试',
|
||||
configUnavailable: '分组配置不可用',
|
||||
collapse: '折叠',
|
||||
expandMore: '展开全部',
|
||||
newSession: '新建会话',
|
||||
}
|
||||
|
||||
/** English dictionary. */
|
||||
export const en: WorkspaceGroupsDict = {
|
||||
'section.workspaces': 'Workspaces',
|
||||
'section.sessions': 'Sessions',
|
||||
search: 'Search',
|
||||
'search.placeholder': 'Search sessions…',
|
||||
'search.clear': 'Clear',
|
||||
'search.noMatches': 'No matching sessions',
|
||||
'search.unavailable': 'Search unavailable',
|
||||
'search.pending': 'Searching…',
|
||||
'search.hasMore': 'Too many results — refine the query',
|
||||
'search.results.aria': 'Search results',
|
||||
'workspace.add': 'Add workspace',
|
||||
'workspace.addBusy': 'Adding…',
|
||||
'workspace.addError': 'Add failed',
|
||||
'workspace.addErrorTitle': 'Could not add workspace',
|
||||
'workspace.rename': 'Rename',
|
||||
'workspace.delete': 'Delete',
|
||||
'workspace.deleteTitle': 'Delete workspace',
|
||||
'workspace.deleteConfirm': 'Only the registration is removed; the directory and session logs stay. Delete?',
|
||||
'workspace.deleteCancel': 'Cancel delete',
|
||||
'workspace.renaming': 'Renaming…',
|
||||
'workspace.deleting': 'Deleting…',
|
||||
'workspace.renameTitle': 'Rename workspace',
|
||||
'workspace.renamePlaceholder': 'Workspace name',
|
||||
'workspace.renameConfirm': 'Rename',
|
||||
'workspace.renameCancel': 'Cancel',
|
||||
'session.new': 'New Session',
|
||||
'session.rename': 'Rename session',
|
||||
'session.archive': 'Archive',
|
||||
'session.fork': 'Fork',
|
||||
'session.renameTitle': 'Rename session',
|
||||
'session.renamePlaceholder': 'Session name',
|
||||
'session.renameConfirm': 'Rename',
|
||||
'session.renameCancel': 'Cancel',
|
||||
'session.renaming': 'Renaming…',
|
||||
uncategorized: 'Uncategorized',
|
||||
'empty.none': 'Nothing here',
|
||||
'empty.noWorkspaces': 'No workspaces yet',
|
||||
close: 'Close',
|
||||
cancel: 'Cancel',
|
||||
confirm: 'Confirm',
|
||||
retry: 'Retry',
|
||||
configUnavailable: 'Grouping config unavailable',
|
||||
collapse: 'Collapse',
|
||||
expandMore: 'Show all',
|
||||
newSession: 'New Session',
|
||||
}
|
||||
|
|
@ -0,0 +1,217 @@
|
|||
/**
|
||||
* Row components for the workspace-groups tree. Kept dependency-light: they
|
||||
* consume only React, primitives (StateDot/Menu/icons), and the shared CSS
|
||||
* string. Each row owns its hover actions menu; dialogs live in the browser
|
||||
* root so they survive row unmounts during collapse.
|
||||
*/
|
||||
import { useState } from 'react'
|
||||
import {
|
||||
IconArchiveOutline20,
|
||||
IconBranchOutline16,
|
||||
IconEditOutline16,
|
||||
IconEllipsisOutline16,
|
||||
IconFolderClose16,
|
||||
IconFolderOpen16,
|
||||
IconPlusOutline16,
|
||||
IconTriangleRightFill14,
|
||||
IconTrashOutline16,
|
||||
Menu,
|
||||
StateDot,
|
||||
type StateDotState,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { WorkspaceGroupsKey } from './locales.ts'
|
||||
import type { CategoryNode, SessionNode, WorkspaceGroupNode } from './tree.ts'
|
||||
|
||||
type T = TranslateNS<'workspaceGroups'>
|
||||
|
||||
/** Pending interaction status → primitives StateDot state. */
|
||||
function pendingState(status: SessionNode['pendingInteraction']): StateDotState | undefined {
|
||||
switch (status) {
|
||||
case 'approval':
|
||||
case 'plan-review':
|
||||
case 'question':
|
||||
return 'warning'
|
||||
default:
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** Primary status dot state for a session row. */
|
||||
export function sessionDotState(node: Pick<SessionNode, 'pendingInteraction' | 'running' | 'runningSubagentCount' | 'completed'>): StateDotState {
|
||||
if (pendingState(node.pendingInteraction) !== undefined) return 'warning'
|
||||
if (node.running || node.runningSubagentCount > 0) return 'ongoing'
|
||||
return node.completed ? 'done' : 'done'
|
||||
}
|
||||
|
||||
/** Compact relative time ("now"/"5min"/"3h"/"2d"/"4mo"/"1y"). */
|
||||
export function relativeTimeLabel(updatedAt: number, now: number): string {
|
||||
const diff = Math.max(0, now - updatedAt)
|
||||
const MIN = 60_000
|
||||
const HOUR = 3_600_000
|
||||
const DAY = 86_400_000
|
||||
if (diff < MIN) return 'now'
|
||||
if (diff < HOUR) return `${Math.floor(diff / MIN)}min`
|
||||
if (diff < DAY) return `${Math.floor(diff / HOUR)}h`
|
||||
if (diff < 30 * DAY) return `${Math.floor(diff / DAY)}d`
|
||||
if (diff < 365 * DAY) return `${Math.floor(diff / (30 * DAY))}mo`
|
||||
return `${Math.floor(diff / (365 * DAY))}y`
|
||||
}
|
||||
|
||||
/** One category folder row. */
|
||||
export function CategoryRow({ node, t, onToggle }: {
|
||||
node: CategoryNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
}) {
|
||||
const count = node.workspaces.length
|
||||
return (
|
||||
<div
|
||||
className="wgCategoryRow"
|
||||
role="treeitem"
|
||||
aria-expanded={node.expanded}
|
||||
aria-label={t('section.workspaces')}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
</span>
|
||||
<span className="wgCategoryIcon">
|
||||
{node.expanded ? <IconFolderOpen16 /> : <IconFolderClose16 />}
|
||||
</span>
|
||||
<span className="wgCategoryLabel">{node.label}</span>
|
||||
<span className="wgCategoryCount">{count}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One workspace folder row inside a category. */
|
||||
export function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete }: {
|
||||
node: WorkspaceGroupNode
|
||||
t: T
|
||||
onToggle: () => void
|
||||
onNewSession: () => void
|
||||
onRename: () => void
|
||||
onDelete: () => void
|
||||
}) {
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const menuItems = [
|
||||
{ id: 'rename', label: t('workspace.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'delete', label: t('workspace.delete'), icon: <IconTrashOutline16 />, danger: true },
|
||||
]
|
||||
return (
|
||||
<div
|
||||
className={`wgProjectRow${node.containsCurrent ? ' wgProjectActive' : ''}`}
|
||||
role="treeitem"
|
||||
aria-expanded={node.expanded}
|
||||
onClick={onToggle}
|
||||
>
|
||||
<span className={`wgChevron${node.expanded ? ' wgChevronOpen' : ''}`}>
|
||||
<IconTriangleRightFill14 />
|
||||
</span>
|
||||
<span className="wgCategoryIcon">
|
||||
{node.expanded ? <IconFolderOpen16 /> : <IconFolderClose16 />}
|
||||
</span>
|
||||
<span className="wgProjectLabel" title={node.path}>{node.label}</span>
|
||||
<span className="wgRowActions">
|
||||
<Menu
|
||||
open={menuOpen}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
items={menuItems}
|
||||
onSelect={(id) => {
|
||||
setMenuOpen(false)
|
||||
if (id === 'rename') onRename()
|
||||
if (id === 'delete') onDelete()
|
||||
}}
|
||||
portal
|
||||
closeOnPointerLeave
|
||||
anchor={(
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={`${t('workspace.rename')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutline16 />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={`${t('session.new')} ${node.label}`}
|
||||
onClick={(e) => { e.stopPropagation(); onNewSession() }}
|
||||
>
|
||||
<IconPlusOutline16 />
|
||||
</button>
|
||||
</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** One session leaf row. */
|
||||
export function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive }: {
|
||||
node: SessionNode
|
||||
currentId: string | undefined
|
||||
now: number
|
||||
t: T
|
||||
onOpen: (id: SessionNode['id']) => void
|
||||
onRename: (id: SessionNode['id'], currentTitle: string) => void
|
||||
onFork: (id: SessionNode['id']) => void
|
||||
onArchive: (id: SessionNode['id']) => void
|
||||
}) {
|
||||
const selected = node.id === currentId
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const showStatus = true
|
||||
const menuItems = [
|
||||
{ id: 'rename', label: t('session.rename'), icon: <IconEditOutline16 /> },
|
||||
{ id: 'fork', label: t('session.fork'), icon: <IconBranchOutline16 /> },
|
||||
{ id: 'archive', label: t('session.archive'), icon: <IconArchiveOutline20 size={16} /> },
|
||||
]
|
||||
return (
|
||||
<div
|
||||
className={`wgSessionRow${selected ? ' wgSelected' : ''}${node.matched === true ? ' wgMatched' : ''}`}
|
||||
role="treeitem"
|
||||
aria-selected={selected}
|
||||
onClick={() => { onOpen(node.id) }}
|
||||
>
|
||||
<span className="wgStatusSlot">
|
||||
{showStatus && <StateDot state={sessionDotState(node)} />}
|
||||
</span>
|
||||
<span className="wgSessionTitle">{node.title}</span>
|
||||
{!node.blank && <span className="wgSessionTime">{relativeTimeLabel(node.updatedAt, now)}</span>}
|
||||
{node.snippet !== undefined && (
|
||||
<span className="wgSessionSnippet" title={node.snippet}>{node.snippet}</span>
|
||||
)}
|
||||
{!node.blank && (
|
||||
<span className="wgRowActions">
|
||||
<Menu
|
||||
open={menuOpen}
|
||||
onClose={() => { setMenuOpen(false) }}
|
||||
items={menuItems}
|
||||
onSelect={(id) => {
|
||||
setMenuOpen(false)
|
||||
if (id === 'rename') onRename(node.id, node.title)
|
||||
if (id === 'fork') onFork(node.id)
|
||||
if (id === 'archive') onArchive(node.id)
|
||||
}}
|
||||
portal
|
||||
closeOnPointerLeave
|
||||
anchor={(
|
||||
<button
|
||||
type="button"
|
||||
className="wgIconButton"
|
||||
aria-label={`${t('session.rename')} ${node.title}`}
|
||||
onClick={(e) => { e.stopPropagation(); setMenuOpen(v => !v) }}
|
||||
>
|
||||
<IconEllipsisOutline16 />
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type { T }
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* Pure expansion-state transforms for the workspace-groups store. Kept free
|
||||
* of any runtime import so both the store (which binds them via defineStore)
|
||||
* and unit tests (which exercise them directly) share one implementation.
|
||||
*
|
||||
* Expansion semantics follow the official ui-workspace store: collapse
|
||||
* WRITES `false` (never deletes the key). The browser's auto-expand guard
|
||||
* uses `Object.hasOwn` — a present `false` means "user deliberately
|
||||
* collapsed this" and must NOT be re-expanded; only a fully absent key means
|
||||
* "never touched" and may auto-expand. (Earlier versions deleted the key on
|
||||
* collapse, which made the current category/workspace impossible to fold.)
|
||||
*/
|
||||
|
||||
/** Workspace-groups browser viewing state persisted across surface remounts and reloads. */
|
||||
export interface GroupsViewState {
|
||||
/** Category folder expansion keyed by category label (absent = never touched). */
|
||||
categoryExpansion: Record<string, boolean>
|
||||
/** Workspace folder expansion keyed by workspace id (absent = never touched). */
|
||||
workspaceExpansion: Record<string, boolean>
|
||||
}
|
||||
|
||||
/** Collapse writes `false` (key retained); expand writes `true`. */
|
||||
export function setCategoryExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {
|
||||
state.categoryExpansion[key] = expanded
|
||||
}
|
||||
|
||||
/** Collapse writes `false` (key retained); expand writes `true`. */
|
||||
export function setWorkspaceExpandedImpl(state: GroupsViewState, key: string, expanded: boolean): void {
|
||||
state.workspaceExpansion[key] = expanded
|
||||
}
|
||||
|
||||
/** Drop expansion keys that no longer exist (renames/deletes/config edits). */
|
||||
export function retainKeysImpl(
|
||||
state: GroupsViewState,
|
||||
categoryKeys: readonly string[],
|
||||
workspaceKeys: readonly string[],
|
||||
): void {
|
||||
state.categoryExpansion = Object.fromEntries(
|
||||
Object.entries(state.categoryExpansion).filter(([key]) => categoryKeys.includes(key)),
|
||||
)
|
||||
state.workspaceExpansion = Object.fromEntries(
|
||||
Object.entries(state.workspaceExpansion).filter(([key]) => workspaceKeys.includes(key)),
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
/**
|
||||
* The workspace-groups viewing store: category / workspace folder expansion,
|
||||
* persisted across reloads under an independent key (the official
|
||||
* ui-workspace store keeps its own `dsh.workspace.view.v5` — we never touch
|
||||
* it). Module level exports the factory only (a module-level handle would pin
|
||||
* the store identity across plugin reloads); register() receives the factory
|
||||
* and the browser derives its PropsStore share from the return type.
|
||||
*
|
||||
* The action implementations live in `store-core.ts` (pure, runtime-free) so
|
||||
* unit tests exercise the real semantics without a browser module loader;
|
||||
* this file only binds them through defineStore.
|
||||
*/
|
||||
import { defineStore, type EngineStoreHandle } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import {
|
||||
retainKeysImpl,
|
||||
setCategoryExpandedImpl,
|
||||
setWorkspaceExpandedImpl,
|
||||
type GroupsViewState,
|
||||
} from './store-core.ts'
|
||||
|
||||
/** Annotation twin of the actions literal below (structural type, satisfies `ActionsDecl`). */
|
||||
type GroupsViewActions = {
|
||||
setCategoryExpanded: typeof setCategoryExpandedImpl
|
||||
setWorkspaceExpanded: typeof setWorkspaceExpandedImpl
|
||||
retainKeys: typeof retainKeysImpl
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the workspace-groups viewing store handle.
|
||||
* @returns the store handle (spec + type + identity + factory in one).
|
||||
*/
|
||||
export function createGroupsViewStore(): EngineStoreHandle<GroupsViewState, GroupsViewActions> {
|
||||
return defineStore({
|
||||
init: () => ({ categoryExpansion: {}, workspaceExpansion: {} }),
|
||||
persist: 'dsh.workspace.groups.view.v1',
|
||||
actions: {
|
||||
setCategoryExpanded: setCategoryExpandedImpl,
|
||||
setWorkspaceExpanded: setWorkspaceExpandedImpl,
|
||||
retainKeys: retainKeysImpl,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export type { GroupsViewState } from './store-core.ts'
|
||||
|
|
@ -0,0 +1,317 @@
|
|||
/* dsh-workspace-groups browser styles. Plain CSS injected by the plugin's
|
||||
apply (via the ?inline virtual module) — no CSS Modules toolchain needed. */
|
||||
|
||||
.wgRoot {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.wgSectionHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 0 12px;
|
||||
height: 36px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.wgSectionLabel {
|
||||
flex: none;
|
||||
max-width: 45%;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
}
|
||||
|
||||
.wgIconButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border: none;
|
||||
background: transparent;
|
||||
border-radius: 6px;
|
||||
color: var(--dsw-fg-2, inherit);
|
||||
cursor: pointer;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.wgIconButton:hover {
|
||||
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
}
|
||||
|
||||
.wgIconButton:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.wgSearch {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
max-width: 28px;
|
||||
margin-left: auto;
|
||||
transition: max-width 180ms ease;
|
||||
}
|
||||
|
||||
/* Search expanded: the slot grows to fill the header so the input widens
|
||||
(mirrors the official ui-workspace searchSlot idle/expanded swap). */
|
||||
.wgSearchExpanded {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.wgSearchInput {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
border: none;
|
||||
background: transparent;
|
||||
outline: none;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.wgTreeBody {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 0 8px 8px;
|
||||
}
|
||||
|
||||
.wgList {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.wgEmpty {
|
||||
padding: 16px 8px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
}
|
||||
|
||||
/* Category row: top-level folder. */
|
||||
.wgCategoryRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
padding: 0 4px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.wgCategoryRow:hover {
|
||||
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
|
||||
}
|
||||
|
||||
.wgChevron {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex: none;
|
||||
transition: transform 120ms ease;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
}
|
||||
|
||||
.wgChevronOpen {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.wgCategoryIcon {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: none;
|
||||
color: var(--dsw-fg-2, inherit);
|
||||
}
|
||||
|
||||
.wgCategoryLabel {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
}
|
||||
|
||||
.wgCategoryCount {
|
||||
flex: none;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
}
|
||||
|
||||
/* Workspace row: project folder under a category. */
|
||||
.wgProjectRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
padding: 0 4px 0 20px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.wgProjectRow:hover {
|
||||
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
|
||||
}
|
||||
|
||||
.wgProjectActive {
|
||||
color: var(--dsw-accent, #4a90d9);
|
||||
}
|
||||
|
||||
.wgProjectLabel {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
}
|
||||
|
||||
.wgRowActions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex: none;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.wgProjectRow:hover .wgRowActions,
|
||||
.wgProjectRow:focus-within .wgRowActions {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
/* Session row: leaf under a workspace folder. */
|
||||
.wgSessionRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
height: 30px;
|
||||
padding: 0 4px 0 40px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.wgSessionRow:hover {
|
||||
background: var(--dsw-bg-hover, rgba(127, 127, 127, 0.12));
|
||||
}
|
||||
|
||||
.wgSessionRow:hover .wgRowActions,
|
||||
.wgSessionRow:focus-within .wgRowActions {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wgSelected {
|
||||
background: var(--dsw-bg-selected, rgba(74, 144, 217, 0.18));
|
||||
}
|
||||
|
||||
.wgStatusSlot {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.wgSessionTitle {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 12px;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
}
|
||||
|
||||
.wgSessionTime {
|
||||
flex: none;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
}
|
||||
|
||||
.wgVisuallyHidden {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
margin: -1px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
clip: rect(0 0 0 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
/* Search: the idle tree is re-rendered pruned to matched branches; matched
|
||||
session rows get a tint, and content hits show a snippet line. */
|
||||
.wgMatched {
|
||||
background: var(--dsw-bg-selected, rgba(74, 144, 217, 0.18));
|
||||
}
|
||||
|
||||
.wgSessionSnippet {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
}
|
||||
|
||||
.wgSearchStatus {
|
||||
padding: 8px;
|
||||
font-size: 11px;
|
||||
color: var(--dsw-fg-3, rgba(127, 127, 127, 0.8));
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wgRail {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.wgAddError {
|
||||
font-size: 12px;
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
max-height: 200px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.wgRenameInput {
|
||||
width: 100%;
|
||||
border: 1px solid var(--dsw-border, rgba(127, 127, 127, 0.3));
|
||||
border-radius: 6px;
|
||||
background: var(--dsw-bg-1, transparent);
|
||||
color: var(--dsw-fg-1, inherit);
|
||||
font-size: 13px;
|
||||
padding: 6px 8px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.wgRenameInput:focus {
|
||||
border-color: var(--dsw-accent, #4a90d9);
|
||||
}
|
||||
|
|
@ -0,0 +1,357 @@
|
|||
/**
|
||||
* Derives the three-level workspace-groups tree: 分类文件夹 → 项目文件夹 →
|
||||
* 会话行. Pure derivation — all inputs are snapshots; the renderer never
|
||||
* scans. Session visibility rules mirror the official ui-workspace tree
|
||||
* (blank rows only when current, archived excluded, subagent rows excluded).
|
||||
*/
|
||||
import {
|
||||
indexSubagentDescendants,
|
||||
type PendingInteractionStatus,
|
||||
type SessionId,
|
||||
type SessionListState,
|
||||
type SessionSearchResultItem,
|
||||
type SessionSummary,
|
||||
type SubagentDescendantSummary,
|
||||
type WorkspaceId,
|
||||
type WorkspaceView,
|
||||
} from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { classify } from '../core/matcher.ts'
|
||||
import { UNCATEGORIZED_LABEL, type GroupsConfig } from '../core/types.ts'
|
||||
|
||||
/** One top-level session row inside a workspace folder. */
|
||||
export interface SessionNode {
|
||||
id: SessionId
|
||||
/** Stored display title; blank rows show the localized New Session label. */
|
||||
title: string
|
||||
/** The provisional blank session (renderer shows the localized New Session title). */
|
||||
blank: boolean
|
||||
pendingInteraction?: PendingInteractionStatus
|
||||
running: boolean
|
||||
/** Running descendants connected through uninterrupted subagent-origin lineage. */
|
||||
runningSubagentCount: number
|
||||
/** Finished running while not selected and not yet opened (the green "done" reminder dot). */
|
||||
completed: boolean
|
||||
updatedAt: number
|
||||
/** Search-hit marker (rendered with a highlighted tint in search mode). */
|
||||
matched?: boolean
|
||||
/** Content-match snippet from the Host search (search mode only). */
|
||||
snippet?: string
|
||||
}
|
||||
|
||||
/** One workspace folder row inside a category folder. */
|
||||
export interface WorkspaceGroupNode {
|
||||
workspaceId: WorkspaceId
|
||||
/** Canonical host directory path. */
|
||||
path: string
|
||||
/** Display title. */
|
||||
label: string
|
||||
/** Workspace creation time (epoch ms). */
|
||||
createdAt: number
|
||||
/** Total visible sessions in the folder. */
|
||||
sessionCount: number
|
||||
expanded: boolean
|
||||
/** The folder contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean
|
||||
/** Visible session rows (empty while the folder is folded). */
|
||||
sessions: readonly SessionNode[]
|
||||
}
|
||||
|
||||
/** One category folder at the top of the tree. */
|
||||
export interface CategoryNode {
|
||||
/** Stable category key: the configured label, or the uncategorized bucket. */
|
||||
key: string
|
||||
/** Display label. */
|
||||
label: string
|
||||
expanded: boolean
|
||||
/** The category contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean
|
||||
/** Workspace folders in host order. */
|
||||
workspaces: readonly WorkspaceGroupNode[]
|
||||
}
|
||||
|
||||
/** Viewing state consumed by the derivation. */
|
||||
export interface GroupsTreeView {
|
||||
expandedCategories: readonly string[]
|
||||
expandedWorkspaces: readonly string[]
|
||||
}
|
||||
|
||||
/** Key of the uncategorized bucket (matches the config fallback label). */
|
||||
export const UNCATEGORIZED_KEY = UNCATEGORIZED_LABEL
|
||||
|
||||
/** Directory display label: basename of the path (both separators accepted). */
|
||||
export function workspaceLabel(cwd: string | undefined): string {
|
||||
if (cwd === undefined || cwd === '') return UNCATEGORIZED_LABEL
|
||||
const base = cwd.replace(/[/\\]+$/, '').split(/[/\\]/).pop()
|
||||
return base !== undefined && base !== '' ? base : cwd
|
||||
}
|
||||
|
||||
/** Ordinary sessions are visible; blank only when current; archived/subagent never. */
|
||||
function sessionVisible(session: SessionSummary, current: SessionId | undefined, archived: ReadonlySet<SessionId>): boolean {
|
||||
return session.origin !== 'subagent'
|
||||
&& !archived.has(session.id)
|
||||
&& (!session.blank || session.id === current)
|
||||
}
|
||||
|
||||
/** Blank rows display the localized New Session label (never enters search). */
|
||||
function sessionTitle(session: SessionSummary): string {
|
||||
return session.blank ? 'New Session' : session.displayTitle
|
||||
}
|
||||
|
||||
function sessionNode(
|
||||
s: SessionSummary,
|
||||
descendants: ReadonlyMap<SessionId, SubagentDescendantSummary>,
|
||||
): SessionNode {
|
||||
return {
|
||||
id: s.id,
|
||||
title: sessionTitle(s),
|
||||
blank: s.blank,
|
||||
running: s.running,
|
||||
runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,
|
||||
completed: s.completed === true,
|
||||
updatedAt: s.updatedAt,
|
||||
...(s.pendingInteraction === undefined ? {} : { pendingInteraction: s.pendingInteraction }),
|
||||
}
|
||||
}
|
||||
|
||||
/** Visible sessions of one workspace in its stored account order. */
|
||||
function workspaceSessions(
|
||||
list: SessionListState,
|
||||
workspace: WorkspaceView,
|
||||
archived: ReadonlySet<SessionId>,
|
||||
descendants: ReadonlyMap<SessionId, SubagentDescendantSummary>,
|
||||
): SessionNode[] {
|
||||
const nodes: SessionNode[] = []
|
||||
for (const id of workspace.sessionIds) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined) continue // account may lead the list pull; appears when the summary lands
|
||||
if (!sessionVisible(summary, list.current, archived)) continue
|
||||
nodes.push(sessionNode(summary, descendants))
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the three-level tree.
|
||||
* @param list - sessions list snapshot (`current` feeds containsCurrent).
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param config - sidecar grouping config.
|
||||
* @param view - local expansion arrays.
|
||||
* @returns category sections in render order (configured categories first, uncategorized last).
|
||||
*/
|
||||
export function deriveGroups(
|
||||
list: SessionListState,
|
||||
workspaces: readonly WorkspaceView[],
|
||||
archivedSessionIds: readonly SessionId[],
|
||||
config: GroupsConfig,
|
||||
view: GroupsTreeView,
|
||||
): CategoryNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const expandedCategories = new Set(view.expandedCategories)
|
||||
const expandedWorkspaces = new Set(view.expandedWorkspaces)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
||||
// Bucket workspaces by category, preserving host order inside each bucket.
|
||||
const byCategory = new Map<string, WorkspaceView[]>()
|
||||
const categorized = new Set<WorkspaceId>()
|
||||
for (const category of config.categories) {
|
||||
byCategory.set(category.name, [])
|
||||
}
|
||||
for (const workspace of workspaces) {
|
||||
const category = classify(config.categories, workspace.path, workspace.title)
|
||||
const key = category !== undefined ? category.name : UNCATEGORIZED_KEY
|
||||
if (!byCategory.has(key)) byCategory.set(key, [])
|
||||
byCategory.get(key)!.push(workspace)
|
||||
categorized.add(workspace.workspaceId)
|
||||
}
|
||||
|
||||
const currentWorkspaceId = list.current === undefined
|
||||
? undefined
|
||||
: workspaces.find(w => w.sessionIds.includes(list.current as SessionId))?.workspaceId
|
||||
|
||||
const nodes: CategoryNode[] = []
|
||||
for (const [key, bucket] of byCategory) {
|
||||
if (bucket.length === 0) continue
|
||||
const expanded = expandedCategories.has(key)
|
||||
const workspaceNodes: WorkspaceGroupNode[] = []
|
||||
let containsCurrent = false
|
||||
for (const workspace of bucket) {
|
||||
const sessions = workspaceSessions(list, workspace, archived, descendants)
|
||||
const wsExpanded = expandedWorkspaces.has(workspace.workspaceId as string)
|
||||
const wsContainsCurrent = workspace.workspaceId === currentWorkspaceId
|
||||
if (wsContainsCurrent) containsCurrent = true
|
||||
workspaceNodes.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
label: workspace.title,
|
||||
createdAt: Date.parse(workspace.createdAt),
|
||||
sessionCount: sessions.length,
|
||||
expanded: wsExpanded,
|
||||
containsCurrent: wsContainsCurrent,
|
||||
sessions: wsExpanded ? sessions : [],
|
||||
})
|
||||
}
|
||||
nodes.push({
|
||||
key,
|
||||
label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,
|
||||
expanded,
|
||||
containsCurrent,
|
||||
workspaces: workspaceNodes,
|
||||
})
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
/** Recency comparator: newest first, id as the deterministic tiebreak. */
|
||||
function byRecency(a: SessionSummary, b: SessionSummary): number {
|
||||
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt
|
||||
return a.id < b.id ? -1 : 1
|
||||
}
|
||||
|
||||
/** Bounded set of matched sessions plus content snippets (feeds the search tree). */
|
||||
export interface SearchMatchSet {
|
||||
/** Session ids that matched (local metadata hits + Host content hits). */
|
||||
matchedIds: ReadonlySet<SessionId>
|
||||
/** Content-match snippets keyed by session id (Host search only). */
|
||||
snippetsBySession: ReadonlyMap<SessionId, string>
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Compute the matched-session set: immediate title/Workspace substring matches
|
||||
* from the local list, merged with ranked Host content matches. The consumer
|
||||
* (SearchBody) derives the pruned three-level tree from these ids.
|
||||
*/
|
||||
export function deriveSearchMatches(
|
||||
list: SessionListState,
|
||||
workspaces: readonly WorkspaceView[],
|
||||
config: GroupsConfig,
|
||||
query: string,
|
||||
archivedSessionIds: readonly SessionId[],
|
||||
content: { items: readonly SessionSearchResultItem[]; hasMore: boolean },
|
||||
limit: number,
|
||||
): SearchMatchSet {
|
||||
const q = query.trim().toLowerCase()
|
||||
if (q === '') return { matchedIds: new Set(), snippetsBySession: new Map(), hasMore: false }
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
||||
const workspaceBySession = new Map<SessionId, WorkspaceView>()
|
||||
for (const workspace of workspaces) {
|
||||
for (const sessionId of workspace.sessionIds) {
|
||||
if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace)
|
||||
}
|
||||
}
|
||||
const labelOf = (summary: SessionSummary): string =>
|
||||
workspaceBySession.get(summary.id)?.title ?? workspaceLabel(summary.cwd)
|
||||
|
||||
const local: SessionSummary[] = []
|
||||
for (const id of list.ids) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined || summary.blank || !sessionVisible(summary, list.current, archived)) continue
|
||||
if (
|
||||
sessionTitle(summary).toLowerCase().includes(q)
|
||||
|| labelOf(summary).toLowerCase().includes(q)
|
||||
) {
|
||||
local.push(summary)
|
||||
}
|
||||
}
|
||||
local.sort(byRecency)
|
||||
|
||||
const ordered: SessionSummary[] = []
|
||||
const included = new Set<SessionId>()
|
||||
const include = (summary: SessionSummary): void => {
|
||||
if (included.has(summary.id)) return
|
||||
included.add(summary.id)
|
||||
ordered.push(summary)
|
||||
}
|
||||
for (const summary of local) include(summary)
|
||||
for (const item of content.items) {
|
||||
const summary = list.byId[item.sessionId]
|
||||
if (summary !== undefined && !summary.blank && sessionVisible(summary, list.current, archived)) include(summary)
|
||||
}
|
||||
|
||||
const snippets = new Map<SessionId, string>()
|
||||
for (const item of content.items) {
|
||||
if (item.snippet !== undefined) snippets.set(item.sessionId, item.snippet)
|
||||
}
|
||||
|
||||
return {
|
||||
matchedIds: ordered.slice(0, limit).reduce((set, summary) => { set.add(summary.id); return set }, new Set<SessionId>()),
|
||||
snippetsBySession: snippets,
|
||||
hasMore: content.hasMore || ordered.length > limit,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a three-level search tree containing ONLY the branches that hold a
|
||||
* matched session: 分类文件夹 → 项目文件夹 → 命中会话行. Every matched
|
||||
* session carries `matched: true` so rows render with the search-hit tint.
|
||||
*
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param config - sidecar grouping config.
|
||||
* @param matchedIds - set of session ids that matched the query.
|
||||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @returns categories in render order, pruned to matched branches only.
|
||||
*/
|
||||
export function deriveSearchGroups(
|
||||
list: SessionListState,
|
||||
workspaces: readonly WorkspaceView[],
|
||||
config: GroupsConfig,
|
||||
matchedIds: ReadonlySet<SessionId>,
|
||||
archivedSessionIds: readonly SessionId[],
|
||||
snippetsBySession?: ReadonlyMap<SessionId, string>,
|
||||
): CategoryNode[] {
|
||||
const archived = new Set(archivedSessionIds)
|
||||
const descendants = indexSubagentDescendants(list.byId)
|
||||
|
||||
const byCategory = new Map<string, WorkspaceGroupNode[]>()
|
||||
for (const category of config.categories) byCategory.set(category.name, [])
|
||||
|
||||
for (const workspace of workspaces) {
|
||||
// Only sessions that matched the query and are visible in this folder.
|
||||
const nodes: SessionNode[] = []
|
||||
for (const id of workspace.sessionIds) {
|
||||
const summary = list.byId[id]
|
||||
if (summary === undefined || !matchedIds.has(id)) continue
|
||||
if (!sessionVisible(summary, list.current, archived)) continue
|
||||
const node = sessionNode(summary, descendants)
|
||||
const snippet = snippetsBySession?.get(id)
|
||||
nodes.push({
|
||||
...node,
|
||||
matched: true,
|
||||
...(snippet === undefined ? {} : { snippet }),
|
||||
})
|
||||
}
|
||||
if (nodes.length === 0) continue
|
||||
|
||||
const category = classify(config.categories, workspace.path, workspace.title)
|
||||
const key = category !== undefined ? category.name : UNCATEGORIZED_KEY
|
||||
if (!byCategory.has(key)) byCategory.set(key, [])
|
||||
byCategory.get(key)!.push({
|
||||
workspaceId: workspace.workspaceId,
|
||||
path: workspace.path,
|
||||
label: workspace.title,
|
||||
createdAt: Date.parse(workspace.createdAt),
|
||||
sessionCount: nodes.length,
|
||||
expanded: true,
|
||||
containsCurrent: false,
|
||||
sessions: nodes,
|
||||
})
|
||||
}
|
||||
|
||||
const categories: CategoryNode[] = []
|
||||
for (const [key, workspaceNodes] of byCategory) {
|
||||
if (workspaceNodes.length === 0) continue
|
||||
categories.push({
|
||||
key,
|
||||
label: key === UNCATEGORIZED_KEY ? UNCATEGORIZED_LABEL : key,
|
||||
expanded: true,
|
||||
containsCurrent: false,
|
||||
workspaces: workspaceNodes,
|
||||
})
|
||||
}
|
||||
return categories
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
/**
|
||||
* Structural types for the cordis services this plugin consumes. A third-party
|
||||
* plugin resolves outside the DSH monorepo's single cordis instance, so the
|
||||
* upstream `declare module` augmentations do not reach this Context — the
|
||||
* members below mirror the actual runtime shapes this plugin touches:
|
||||
* - webServer: @deepseek-ai/dsh-host-webserver (the WebServer)
|
||||
* - effect: the DSH-vendored cordis lifecycle helper
|
||||
* Drift from upstream is contained to this file.
|
||||
*/
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http'
|
||||
import type { Context } from '@deepseek-ai/cordis'
|
||||
|
||||
/** One named webserver route (mirror of the host-webserver WebRoute). */
|
||||
export interface GroupsWebRoute {
|
||||
kind: 'exact' | 'prefix'
|
||||
path: string
|
||||
handler: (req: IncomingMessage, res: ServerResponse) => void | Promise<void>
|
||||
}
|
||||
|
||||
/** The webServer service face this plugin uses. */
|
||||
export interface GroupsWebServer {
|
||||
register(route: GroupsWebRoute): () => void
|
||||
}
|
||||
|
||||
/** Cordis Context augmented with the services this plugin needs. */
|
||||
export interface GroupsContext extends Context {
|
||||
webServer: GroupsWebServer
|
||||
}
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* Pure classification logic: decides which category a workspace belongs to.
|
||||
* Shared by the host half (validation) and the client half (tree derivation),
|
||||
* so the rule semantics can never drift between the config surface and the
|
||||
* rendered tree.
|
||||
*/
|
||||
import { normalizePath, type GroupCategory, type GroupRule } from './types.ts'
|
||||
|
||||
/** One rule match against a workspace's path and title. */
|
||||
function ruleMatches(rule: GroupRule, path: string, title: string): boolean {
|
||||
const normalized = normalizePath(path)
|
||||
if (rule.pathPrefix !== undefined && normalized.startsWith(normalizePath(rule.pathPrefix))) return true
|
||||
if (rule.pathExact !== undefined && normalized === normalizePath(rule.pathExact)) return true
|
||||
if (rule.nameContains !== undefined && title.toLowerCase().includes(rule.nameContains.toLowerCase())) return true
|
||||
if (rule.basenameContains !== undefined) {
|
||||
const base = path.replace(/[/\\]+$/, '').split(/[/\\]/).pop() ?? ''
|
||||
if (base.toLowerCase().includes(rule.basenameContains.toLowerCase())) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify a workspace into its category.
|
||||
* @param categories - configured categories, in render order.
|
||||
* @param path - workspace canonical directory path.
|
||||
* @param title - workspace display title.
|
||||
* @returns the matching category, or undefined when no rule matches.
|
||||
*/
|
||||
export function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined {
|
||||
for (const category of categories) {
|
||||
if (category.rules.some(rule => ruleMatches(rule, path, title))) return category
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
/**
|
||||
* Shared config types for dsh-workspace-groups. Pure types (zero runtime
|
||||
* deps) so both halves — the node half (sidecar YAML reading) and the
|
||||
* browser half (tree derivation) — compile against the same contract.
|
||||
*/
|
||||
|
||||
/** One classification rule: any rule that matches places the workspace in the category. */
|
||||
export interface GroupRule {
|
||||
/** Absolute path prefix match (normalized, case-sensitive). */
|
||||
pathPrefix?: string
|
||||
/** Case-insensitive substring match against the workspace display title. */
|
||||
nameContains?: string
|
||||
/** Case-insensitive substring match against the workspace directory basename. */
|
||||
basenameContains?: string
|
||||
/** Exact absolute path match (normalized). */
|
||||
pathExact?: string
|
||||
}
|
||||
|
||||
/** One category folder in the sidebar tree. */
|
||||
export interface GroupCategory {
|
||||
/** Display label of the category folder. */
|
||||
name: string
|
||||
/** Rules; a workspace is classified here when ANY rule matches. */
|
||||
rules: GroupRule[]
|
||||
}
|
||||
|
||||
/** The full sidecar configuration (mirrors workspace-groups.yaml). */
|
||||
export interface GroupsConfig {
|
||||
/** Category folders, in render order. First match wins. */
|
||||
categories: GroupCategory[]
|
||||
}
|
||||
|
||||
/** The label of the fallback bucket for unmatched workspaces. */
|
||||
export const UNCATEGORIZED_LABEL = '未分类'
|
||||
|
||||
/** Normalize a path for prefix matching: trailing slashes stripped. */
|
||||
export function normalizePath(path: string): string {
|
||||
return path.replace(/[/\\]+$/, '')
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
/** Type declaration for the `*.css?inline` virtual module (compiled CSS text). */
|
||||
declare module '*.css?inline' {
|
||||
const css: string
|
||||
export default css
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
/**
|
||||
* Sidecar config reading for dsh-workspace-groups. The classification rules
|
||||
* live in a user-editable YAML file (default `~/.dsh/workspace-groups.yaml`),
|
||||
* read and validated on the host, served to the browser half as JSON. The
|
||||
* core workspace.json and session storage are never touched.
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { resolve } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import { load as parseYaml } from 'js-yaml'
|
||||
import { classify } from './core/matcher.ts'
|
||||
import type { GroupsConfig, GroupCategory } from './core/types.ts'
|
||||
|
||||
/** Default sidecar location: `$DSH_HOME/workspace-groups.yaml` (DSH_HOME falls back to ~/.dsh). */
|
||||
export function defaultConfigPath(): string {
|
||||
const home = process.env.DSH_HOME !== undefined && process.env.DSH_HOME !== ''
|
||||
? process.env.DSH_HOME
|
||||
: resolve(homedir(), '.dsh')
|
||||
return resolve(home, 'workspace-groups.yaml')
|
||||
}
|
||||
|
||||
/** Parse + validate a raw sidecar document into a GroupsConfig (throws on malformed input). */
|
||||
export function parseGroupsConfig(raw: unknown): GroupsConfig {
|
||||
if (raw === undefined || raw === null) return { categories: [] }
|
||||
if (typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
throw new Error('workspace-groups.yaml: top-level value must be a mapping')
|
||||
}
|
||||
const categoriesValue = (raw as { categories?: unknown }).categories
|
||||
const categories: GroupCategory[] = []
|
||||
if (categoriesValue === undefined) return { categories: [] }
|
||||
if (!Array.isArray(categoriesValue)) {
|
||||
throw new Error('workspace-groups.yaml: categories must be a list')
|
||||
}
|
||||
for (const entry of categoriesValue) {
|
||||
if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
|
||||
throw new Error('workspace-groups.yaml: each category must be a mapping')
|
||||
}
|
||||
const name = (entry as { name?: unknown }).name
|
||||
if (typeof name !== 'string' || name.trim() === '') {
|
||||
throw new Error('workspace-groups.yaml: each category needs a non-empty name')
|
||||
}
|
||||
const rulesValue = (entry as { rules?: unknown }).rules
|
||||
if (rulesValue === undefined) {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" needs a rules list`)
|
||||
}
|
||||
if (!Array.isArray(rulesValue)) {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" rules must be a list`)
|
||||
}
|
||||
const rules: GroupCategory['rules'] = []
|
||||
for (const rule of rulesValue) {
|
||||
if (typeof rule !== 'object' || rule === null || Array.isArray(rule)) {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" rule must be a mapping`)
|
||||
}
|
||||
const r = rule as Record<string, unknown>
|
||||
const normalized: GroupCategory['rules'][number] = {}
|
||||
for (const key of ['pathPrefix', 'nameContains', 'basenameContains', 'pathExact'] as const) {
|
||||
const value = r[key]
|
||||
if (value !== undefined) {
|
||||
if (typeof value !== 'string' || value === '') {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" rule ${key} must be a non-empty string`)
|
||||
}
|
||||
normalized[key] = value
|
||||
}
|
||||
}
|
||||
if (Object.keys(normalized).length === 0) {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" has a rule with no matchers`)
|
||||
}
|
||||
rules.push(normalized)
|
||||
}
|
||||
if (rules.length === 0) {
|
||||
throw new Error(`workspace-groups.yaml: category "${name}" needs at least one rule`)
|
||||
}
|
||||
categories.push({ name: name.trim(), rules })
|
||||
}
|
||||
return { categories }
|
||||
}
|
||||
|
||||
/**
|
||||
* Read + parse the sidecar config file. A missing file yields an empty config
|
||||
* (all workspaces fall into the uncategorized bucket); malformed YAML throws
|
||||
* so the operator sees the problem instead of silently ungrouping everything.
|
||||
*/
|
||||
export async function readGroupsConfig(path: string): Promise<GroupsConfig> {
|
||||
let text: string
|
||||
try {
|
||||
text = await readFile(path, 'utf8')
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return { categories: [] }
|
||||
throw error
|
||||
}
|
||||
const raw = parseYaml(text)
|
||||
return parseGroupsConfig(raw)
|
||||
}
|
||||
|
||||
export { classify }
|
||||
export type { GroupsConfig, GroupCategory, GroupRule } from './core/types.ts'
|
||||
|
|
@ -0,0 +1,55 @@
|
|||
/**
|
||||
* dsh-workspace-groups host half: serves the sidecar grouping config to the
|
||||
* browser half over a single fenced GET route (`/workspace-groups/config`).
|
||||
*
|
||||
* The route is a read-only snapshot endpoint: the browser half fetches it on
|
||||
* load (and refetches on demand), the classification rules stay operator-
|
||||
* editable in the YAML file, and no core workspace.json / session storage is
|
||||
* touched. Static content — the config is small and operator-owned — uses
|
||||
* `Cache-Control: no-cache` so a page reload revalidates against the file
|
||||
* without the browser serving a stale grouping.
|
||||
*/
|
||||
import type { ServerResponse } from 'node:http'
|
||||
import type { GroupsContext } from './context-types.ts'
|
||||
import { defaultConfigPath, readGroupsConfig, type GroupsConfig } from './host-config.ts'
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = 'dsh-workspace-groups'
|
||||
|
||||
/** Services required before mounting: the webserver route. */
|
||||
export const inject = ['webServer']
|
||||
|
||||
/** Write a plain-text error response with the given status. */
|
||||
function writeError(res: ServerResponse, status: number, message: string): void {
|
||||
res.writeHead(status, { 'Content-Type': 'text/plain; charset=utf-8' })
|
||||
res.end(message)
|
||||
}
|
||||
|
||||
/** Plugin body: mount the config route. */
|
||||
export function apply(ctx: GroupsContext): void {
|
||||
const configPath = defaultConfigPath()
|
||||
ctx.effect(() => ctx.webServer.register({
|
||||
kind: 'exact',
|
||||
path: '/workspace-groups/config',
|
||||
handler: async (req, res) => {
|
||||
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
||||
writeError(res, 405, 'method not allowed')
|
||||
return
|
||||
}
|
||||
let config: GroupsConfig
|
||||
try {
|
||||
config = await readGroupsConfig(configPath)
|
||||
} catch (error) {
|
||||
writeError(res, 500, `workspace-groups: failed to read config: ${error instanceof Error ? error.message : String(error)}`)
|
||||
return
|
||||
}
|
||||
const body = JSON.stringify(config)
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
})
|
||||
res.end(req.method === 'HEAD' ? undefined : body)
|
||||
},
|
||||
}), 'dsh-workspace-groups: /workspace-groups/config route')
|
||||
}
|
||||
|
|
@ -0,0 +1,96 @@
|
|||
/**
|
||||
* Pure-logic tests: classification rules (the matcher) and config parsing.
|
||||
* These are the plugin's business rules — no DOM, no cordis runtime.
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { classify } from '../src/core/matcher.ts'
|
||||
import { parseGroupsConfig } from '../src/host-config.ts'
|
||||
import type { GroupsConfig } from '../src/core/types.ts'
|
||||
|
||||
const CONFIG: GroupsConfig = {
|
||||
categories: [
|
||||
{
|
||||
name: 'DSH 插件',
|
||||
rules: [
|
||||
{ pathPrefix: '/Users/zcol/Project/SkillsManagePlugins' },
|
||||
{ nameContains: '峰谷' },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: '文档',
|
||||
rules: [{ basenameContains: 'docs' }],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
describe('classify', () => {
|
||||
it('matches by path prefix', () => {
|
||||
const category = classify(CONFIG.categories, '/Users/zcol/Project/SkillsManagePlugins', 'SkillsManagePlugins')
|
||||
expect(category?.name).toBe('DSH 插件')
|
||||
})
|
||||
|
||||
it('matches by name substring', () => {
|
||||
const category = classify(CONFIG.categories, '/Users/zcol/Project/DeepSeek峰谷小组件', 'DeepSeek峰谷小组件')
|
||||
expect(category?.name).toBe('DSH 插件')
|
||||
})
|
||||
|
||||
it('matches by basename substring', () => {
|
||||
const category = classify(CONFIG.categories, '/Users/zcol/Project/SomeDocs', 'SomeDocs')
|
||||
expect(category?.name).toBe('文档')
|
||||
})
|
||||
|
||||
it('first match wins across categories', () => {
|
||||
const config: GroupsConfig = {
|
||||
categories: [
|
||||
{ name: 'A', rules: [{ nameContains: 'common' }] },
|
||||
{ name: 'B', rules: [{ nameContains: 'common' }] },
|
||||
],
|
||||
}
|
||||
const category = classify(config.categories, '/p/x', 'common-project')
|
||||
expect(category?.name).toBe('A')
|
||||
})
|
||||
|
||||
it('returns undefined when nothing matches', () => {
|
||||
const category = classify(CONFIG.categories, '/tmp/random', 'Random')
|
||||
expect(category).toBeUndefined()
|
||||
})
|
||||
|
||||
it('path prefix matching strips trailing slashes', () => {
|
||||
const category = classify(CONFIG.categories, '/Users/zcol/Project/SkillsManagePlugins/sub', 'Sub')
|
||||
expect(category?.name).toBe('DSH 插件')
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseGroupsConfig', () => {
|
||||
it('parses a valid document', () => {
|
||||
const parsed = parseGroupsConfig({
|
||||
categories: [
|
||||
{ name: 'X', rules: [{ pathPrefix: '/a' }] },
|
||||
],
|
||||
})
|
||||
expect(parsed.categories).toHaveLength(1)
|
||||
expect(parsed.categories[0]?.name).toBe('X')
|
||||
})
|
||||
|
||||
it('empty document yields empty categories', () => {
|
||||
expect(parseGroupsConfig(undefined).categories).toEqual([])
|
||||
expect(parseGroupsConfig({}).categories).toEqual([])
|
||||
})
|
||||
|
||||
it('rejects a category without a name', () => {
|
||||
expect(() => parseGroupsConfig({ categories: [{ rules: [] }] })).toThrow(/name/)
|
||||
})
|
||||
|
||||
it('rejects a rule with no matchers', () => {
|
||||
expect(() => parseGroupsConfig({ categories: [{ name: 'X', rules: [{}] }] })).toThrow(/no matchers/)
|
||||
})
|
||||
|
||||
it('rejects a non-list categories value', () => {
|
||||
expect(() => parseGroupsConfig({ categories: 'nope' })).toThrow(/list/)
|
||||
})
|
||||
|
||||
it('trims category names', () => {
|
||||
const parsed = parseGroupsConfig({ categories: [{ name: ' X ', rules: [{ pathPrefix: '/a' }] }] })
|
||||
expect(parsed.categories[0]?.name).toBe('X')
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,67 @@
|
|||
/**
|
||||
* Store action tests: expansion semantics must match the official
|
||||
* ui-workspace store — a collapse writes `false` (key retained), never
|
||||
* deletes the key, so the auto-expand guard (`Object.hasOwn`) can tell
|
||||
* "user collapsed this" from "user never touched this".
|
||||
*
|
||||
* Tested against the pure action implementations (the defineStore wrapper is
|
||||
* a thin binder over these; the runtime bundle needs a browser loader we do
|
||||
* not pull into this suite).
|
||||
*/
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
retainKeysImpl,
|
||||
setCategoryExpandedImpl,
|
||||
setWorkspaceExpandedImpl,
|
||||
type GroupsViewState,
|
||||
} from '../src/client/store-core.ts'
|
||||
|
||||
function freshState(): GroupsViewState {
|
||||
return { categoryExpansion: {}, workspaceExpansion: {} }
|
||||
}
|
||||
|
||||
describe('groups view store expansion semantics', () => {
|
||||
it('setCategoryExpanded(true) stores the key as true', () => {
|
||||
const state = freshState()
|
||||
setCategoryExpandedImpl(state, 'DSH 插件', true)
|
||||
expect(state.categoryExpansion['DSH 插件']).toBe(true)
|
||||
})
|
||||
|
||||
it('setCategoryExpanded(false) retains the key with false (never deletes)', () => {
|
||||
const state = freshState()
|
||||
setCategoryExpandedImpl(state, 'DSH 插件', false)
|
||||
// The key must EXIST with false — this is what lets the auto-expand
|
||||
// guard distinguish a deliberate collapse from an untouched key.
|
||||
expect(state.categoryExpansion).toHaveProperty('DSH 插件', false)
|
||||
expect('DSH 插件' in state.categoryExpansion).toBe(true)
|
||||
})
|
||||
|
||||
it('setWorkspaceExpanded(false) retains the key with false', () => {
|
||||
const state = freshState()
|
||||
setWorkspaceExpandedImpl(state, 'ws-1', false)
|
||||
expect(state.workspaceExpansion).toHaveProperty('ws-1', false)
|
||||
expect('ws-1' in state.workspaceExpansion).toBe(true)
|
||||
})
|
||||
|
||||
it('retainKeys keeps collapsed keys (deliberate user state survives config churn)', () => {
|
||||
const state = freshState()
|
||||
setCategoryExpandedImpl(state, 'DSH 插件', true)
|
||||
setCategoryExpandedImpl(state, '个人项目', false)
|
||||
retainKeysImpl(state, ['DSH 插件', '个人项目'], [])
|
||||
expect(state.categoryExpansion).toEqual({ 'DSH 插件': true, '个人项目': false })
|
||||
})
|
||||
|
||||
it('retainKeys drops keys for removed categories', () => {
|
||||
const state = freshState()
|
||||
setCategoryExpandedImpl(state, '旧分类', true)
|
||||
retainKeysImpl(state, ['新分类'], [])
|
||||
expect(state.categoryExpansion).toEqual({})
|
||||
})
|
||||
|
||||
it('retainKeys drops workspace keys for deleted workspaces', () => {
|
||||
const state = freshState()
|
||||
setWorkspaceExpandedImpl(state, 'ws-gone', false)
|
||||
retainKeysImpl(state, [], ['ws-kept'])
|
||||
expect(state.workspaceExpansion).toEqual({})
|
||||
})
|
||||
})
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"noEmit": false,
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"jsx": "react-jsx",
|
||||
"types": ["react", "react-dom", "node"]
|
||||
},
|
||||
"include": [
|
||||
"src/client/**/*.ts",
|
||||
"src/client/**/*.tsx",
|
||||
"src/core/**/*.ts",
|
||||
"src/css-modules.d.ts"
|
||||
]
|
||||
}
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Bundler",
|
||||
"lib": ["ES2022", "DOM"],
|
||||
"strict": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true,
|
||||
"exactOptionalPropertyTypes": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"noEmit": true,
|
||||
"allowImportingTsExtensions": true,
|
||||
"jsx": "react-jsx",
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
|
|
@ -0,0 +1,150 @@
|
|||
/**
|
||||
* tsdown build for dsh-workspace-groups: the host-half lib (lib/index.js, ESM
|
||||
* node) plus one browser client bundle (lib/client.js, CJS closure factory).
|
||||
*
|
||||
* The client bundle replicates the official DSH client-bundle preset
|
||||
* (packages/client/tsdown.client.ts, same shape as dsh-better-sidebar and the
|
||||
* official ui-* client packages):
|
||||
* - externals resolve through the loader module table at runtime (the
|
||||
* PLATFORM_MODULES seed list from packages/client/web/src/platform.ts,
|
||||
* plus the runtime/client exemption),
|
||||
* - everything else is inlined into the bundle,
|
||||
* - the purity gate rejects any other @deepseek-ai value import: cross-plugin
|
||||
* collaboration goes through cordis services / slots, never value imports,
|
||||
* - CSS Modules compile to hashed class maps and inject <style data-plugin>
|
||||
* tags at factory execution,
|
||||
* - the artifact registers itself via window.__ModuleLoader__.load({id,
|
||||
* factory}) with the (require) => exports CJS closure shape.
|
||||
*
|
||||
* Types ship from lib/types (tsc -p tsconfig.build.json), not from tsdown.
|
||||
*/
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { dirname, resolve as resolvePath, isAbsolute } from 'node:path'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { builtinModules } from 'node:module'
|
||||
import type { UserConfig } from 'tsdown'
|
||||
import { transform } from 'lightningcss'
|
||||
|
||||
/** Node builtins must never survive into the browser module-loader factory. */
|
||||
const NODE_BUILTINS = new Set([
|
||||
...builtinModules,
|
||||
...builtinModules.map(id => `node:${id}`),
|
||||
])
|
||||
|
||||
/** Module specifiers the web shell shares into the frozen module table (the official PLATFORM_MODULES list, plus the runtime/client exemption). */
|
||||
const CLIENT_EXTERNALS = [
|
||||
'react',
|
||||
'react/jsx-runtime',
|
||||
'react-dom',
|
||||
'react-dom/client',
|
||||
'@deepseek-ai/cordis',
|
||||
'@deepseek-ai/dsh-client-ui-slots',
|
||||
'@deepseek-ai/dsh-client-ui-primitives',
|
||||
'@deepseek-ai/dsh-client-runtime/client',
|
||||
] as const
|
||||
|
||||
/** Requested-from-module-table specifiers (kept as imports, never inlined). */
|
||||
function isRequested(specifier: string): boolean {
|
||||
return (CLIENT_EXTERNALS as readonly string[]).includes(specifier)
|
||||
}
|
||||
|
||||
const INLINE_CSS_QUERY = '?inline'
|
||||
const CSS_VIRTUAL_PREFIX = '\0dsh-workspace-groups-inline-css:'
|
||||
const CSS_VIRTUAL_SUFFIX = '.mjs'
|
||||
|
||||
/** Resolve a relative import to a physical stylesheet (tsdown consumes src/ sources). */
|
||||
function sourceAssetPath(source: string, importer: string): string {
|
||||
const abs = resolvePath(dirname(importer), source)
|
||||
if (existsSync(abs)) return abs
|
||||
return source
|
||||
}
|
||||
|
||||
/** Node half: host plugin (reads the sidecar YAML, serves /workspace-groups config). */
|
||||
function nodeConfig(): UserConfig {
|
||||
return {
|
||||
name: 'dsh-workspace-groups',
|
||||
entry: ['src/index.ts'],
|
||||
outDir: 'lib',
|
||||
format: ['esm'],
|
||||
platform: 'node',
|
||||
target: 'es2022',
|
||||
fixedExtension: false,
|
||||
dts: false,
|
||||
clean: false,
|
||||
deps: {
|
||||
alwaysBundle: (specifier: string) => {
|
||||
// js-yaml is the one runtime dependency; bundle it so the artifact is
|
||||
// self-contained (link installs carry no node_modules guarantees).
|
||||
return !NODE_BUILTINS.has(specifier)
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** Browser half: client bundle, wrapped as __ModuleLoader__.load. */
|
||||
function clientConfig(): UserConfig {
|
||||
return {
|
||||
name: 'dsh-workspace-groups/client',
|
||||
entry: { client: 'src/client/index.ts' },
|
||||
// Shares lib/ with the node half (entryFileNames pins lib/client.js;
|
||||
// clean is off so the node output survives).
|
||||
outDir: 'lib',
|
||||
format: 'cjs',
|
||||
platform: 'browser',
|
||||
target: 'es2022',
|
||||
sourcemap: true,
|
||||
dts: false,
|
||||
clean: false,
|
||||
deps: {
|
||||
neverBundle: isRequested,
|
||||
alwaysBundle: (specifier: string) => !isRequested(specifier),
|
||||
},
|
||||
plugins: [
|
||||
{
|
||||
// Build-time purity gate (mirror of the module-table boundary):
|
||||
// @deepseek-ai/* value imports only through the module-table rows;
|
||||
// cross-plugin value imports are build errors (type-only imports are
|
||||
// erased and never reach this gate).
|
||||
name: 'dsh-workspace-groups-client-purity',
|
||||
resolveId(source: string) {
|
||||
if (!source.startsWith('@deepseek-ai/')) return null
|
||||
if (isRequested(source)) return null
|
||||
throw new Error(
|
||||
`client bundle purity: "${source}" is not a platform module — `
|
||||
+ 'cross-plugin value imports are forbidden (type-only imports are erased)',
|
||||
)
|
||||
},
|
||||
},
|
||||
{
|
||||
// `*.css?inline` -> compiled CSS text; the plugin injects/cleans it via ctx.effect.
|
||||
name: 'dsh-workspace-groups-css-inline',
|
||||
resolveId(source: string, importer: string | undefined) {
|
||||
if (!source.endsWith(`.css${INLINE_CSS_QUERY}`)) return null
|
||||
const stylesheet = source.slice(0, -INLINE_CSS_QUERY.length)
|
||||
const abs = importer !== undefined && isAbsolute(stylesheet)
|
||||
? stylesheet
|
||||
: importer !== undefined
|
||||
? sourceAssetPath(stylesheet, importer)
|
||||
: stylesheet
|
||||
return CSS_VIRTUAL_PREFIX + abs + 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)
|
||||
this.addWatchFile(fileId)
|
||||
const source = await readFile(fileId)
|
||||
const { code } = transform({ filename: fileId, code: source, minify: true })
|
||||
return `export default ${JSON.stringify(code.toString())};`
|
||||
},
|
||||
},
|
||||
],
|
||||
outputOptions: {
|
||||
entryFileNames: 'client.js',
|
||||
banner: `window.__ModuleLoader__.load({ id: "dsh-workspace-groups", factory: (require) => {`,
|
||||
footer: 'return module.exports; } });',
|
||||
intro: 'var module = { exports: {} }; var exports = module.exports;',
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export default [nodeConfig(), clientConfig()]
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
import { defineConfig } from 'vitest/config'
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
environment: 'node',
|
||||
include: ['tests/**/*.test.ts'],
|
||||
},
|
||||
})
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
# dsh-workspace-groups 侧车配置(sidecar config)
|
||||
#
|
||||
# 本文件控制侧边栏的分类规则:左侧「分类文件夹 → 项目文件夹 → 会话」三层树
|
||||
# 的分类如何划分。修改后刷新页面即可生效,无需改代码、无需重启 DSH、不触碰
|
||||
# ~/.dsh/storages/workspace.json。
|
||||
#
|
||||
# 默认路径:~/.dsh/workspace-groups.yaml
|
||||
# 规则语义:workspace 按 categories 顺序匹配,第一个命中的分类生效;
|
||||
# 未命中任何规则的 workspace 进入「未分类」桶。
|
||||
# 每个分类的 rules 是「任一规则命中即归类」的 OR 关系。
|
||||
|
||||
categories:
|
||||
# —— DSH 插件 ——
|
||||
- name: DSH 插件
|
||||
rules:
|
||||
- pathPrefix: /Users/zcol/Project/SkillsManagePlugins
|
||||
- pathPrefix: /Users/zcol/Project/Documentation-Driven AI Coding
|
||||
- pathPrefix: /Users/zcol/Project/DeepSeek峰谷小组件
|
||||
- pathPrefix: /Users/zcol/Project/DSH-工作区分组
|
||||
# 也可以按项目名包含规则归类,例如:
|
||||
# - nameContains: 插件
|
||||
# - basenameContains: plugin
|
||||
|
||||
# —— 个人项目 ——
|
||||
- name: 个人项目
|
||||
rules:
|
||||
- pathPrefix: /Users/zcol/Project/yeluzi
|
||||
- pathPrefix: /Users/zcol/Project/闲谝
|
||||
|
||||
# 未匹配任何分类的项目(例如日后新增的 /Users/zcol/Project/新项目)会
|
||||
# 自动出现在「未分类」桶中,不会被忽略。
|
||||
Loading…
Reference in New Issue