feat: bundle the 0.14 component release
This commit is contained in:
parent
20ad551d67
commit
27a1adfe77
|
|
@ -4,10 +4,10 @@
|
|||
|
||||
| 组件 | 版本 | 干什么 |
|
||||
|---|---|---|
|
||||
| dsh-sansheng-liubu | 0.12.1 | 三省六部工作台:每项目十个独立部门会话、三层记忆、朝堂面板 |
|
||||
| dsh-brain | 0.5.1 | LongMemory 云端记忆桥:活动上报、memory 工具、Mnemon provider、技能双向同步与管理页 |
|
||||
| workspace-groups-remote | 1.0.0 | 工作区分组 + 远程 SSH(合并包,含 shell 覆盖) |
|
||||
| dsh-better-chat | 0.1.0 | 审批卡回车同意 / Esc 拒绝(自动聚焦 + 全局兜底) |
|
||||
| dsh-sansheng-liubu | 0.14.0 | 三省六部工作台:每项目十个独立部门会话、三层记忆、朝堂面板 |
|
||||
| dsh-brain | 0.9.1 | LongMemory 云端记忆桥:活动上报、memory 工具、Mnemon provider、技能双向同步与管理页 |
|
||||
| workspace-groups-remote | 1.1.0 | 工作区分组 + 远程 SSH(合并包,含 shell 覆盖) |
|
||||
| dsh-better-chat | 0.3.1 | 审批卡回车同意 / Esc 拒绝;权限 UI 只移除完全权限,不改已有会话 |
|
||||
|
||||
## 安装
|
||||
|
||||
|
|
|
|||
|
|
@ -2,33 +2,33 @@
|
|||
{
|
||||
"id": "dsh-sansheng-liubu",
|
||||
"package": "dsh-sansheng-liubu-mode",
|
||||
"version": "0.12.1",
|
||||
"version": "0.14.0",
|
||||
"sourceRepo": "DeepsSeekHarness/dsh-sansheng-liubu",
|
||||
"sourceCommit": "126f97e80887f3df1e932c5884cc96f0863e08c1",
|
||||
"sourceCommit": "efc4a32c758d1df9bb3c22bb53f1359e0d433ab1",
|
||||
"vendorPath": "vendor/dsh-sansheng-liubu"
|
||||
},
|
||||
{
|
||||
"id": "dsh-brain",
|
||||
"package": "dsh-brain",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.1",
|
||||
"sourceRepo": "DeepsSeekHarness/dsh-brain",
|
||||
"sourceCommit": "9ab2ca26d99e1d59e49acd9eae552c487de9bc08",
|
||||
"sourceCommit": "89af1f4c7c6acf65be93792f68eade383ec0d794",
|
||||
"vendorPath": "vendor/dsh-brain"
|
||||
},
|
||||
{
|
||||
"id": "workspace-groups-remote",
|
||||
"package": "workspace-groups-remote",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"sourceRepo": "DeepsSeekHarness/workspace-groups-remote",
|
||||
"sourceCommit": "96caf19f3447848f881b560fbec0d4dead70a405",
|
||||
"sourceCommit": "fb88fd2d3ed4423817cb6409491f1cbc2bc0f9f6",
|
||||
"vendorPath": "vendor/workspace-groups-remote"
|
||||
},
|
||||
{
|
||||
"id": "dsh-better-chat",
|
||||
"package": "dsh-better-chat",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.1",
|
||||
"sourceRepo": "DeepsSeekHarness/dsh-better-chat",
|
||||
"sourceCommit": "78147194df352ad7e99b3e33ca10894dd0475643",
|
||||
"sourceCommit": "f2f11528bdd8779b247265ca8ba667287af12cd7",
|
||||
"vendorPath": "vendor/dsh-better-chat"
|
||||
}
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,10 +1,12 @@
|
|||
# QQ-dsh bundle patch
|
||||
#
|
||||
# One insert row loads the bundle entry, which composes all four plugins.
|
||||
# Migration: remove the four standalone bundles (dsh-sansheng-liubu-mode /
|
||||
# dsh-sansheng-liubu-panel, dsh-brain, workspace-groups-remote,
|
||||
# dsh-better-chat) from the profile and add qq-dsh instead. Stored data is
|
||||
# kept: every component reads its own sidecars and settings namespaces.
|
||||
# Migration: remove the retired standalone panel bundles
|
||||
# (dsh-sansheng-liubu-workbench / dsh-sansheng-liubu-panel) and the four
|
||||
# independent bundles (dsh-sansheng-liubu-mode, dsh-brain,
|
||||
# workspace-groups-remote, dsh-better-chat) from the profile, then add
|
||||
# qq-dsh instead. Stored data is kept: every component reads its own
|
||||
# sidecars and settings namespaces.
|
||||
- insert:
|
||||
- id: qq-dsh
|
||||
name: 'qq-dsh'
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "qq-dsh",
|
||||
"version": "1.3.0",
|
||||
"version": "1.4.0",
|
||||
"description": "QQ-dsh — personal DSH plugin bundle: sansheng-liubu workbench + dsh-brain (LongMemory bridge, skill sync) + workspace-groups-remote (grouped workspaces + remote SSH) + dsh-better-chat (approval Enter/Esc), in one install.",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
|
|
|
|||
|
|
@ -16,7 +16,14 @@ import { dirname, join, resolve } from 'node:path'
|
|||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
const SRC = (p) => resolve(ROOT, '..', p)
|
||||
const SOURCE_ROOT = resolve(process.env.QQ_DSH_SOURCE_ROOT ?? resolve(ROOT, '..'))
|
||||
const SRC = (...candidates) => {
|
||||
for (const candidate of candidates) {
|
||||
const dir = resolve(SOURCE_ROOT, candidate)
|
||||
if (existsSync(dir)) return dir
|
||||
}
|
||||
throw new Error(`source repo not found: tried ${candidates.join(', ')} under ${SOURCE_ROOT}`)
|
||||
}
|
||||
|
||||
const COMPONENTS = [
|
||||
{
|
||||
|
|
@ -31,7 +38,7 @@ const COMPONENTS = [
|
|||
},
|
||||
{
|
||||
id: 'dsh-brain',
|
||||
sourceDir: SRC('dsh-cloud-memory'),
|
||||
sourceDir: SRC('dsh-brain', 'dsh-cloud-memory'),
|
||||
sourceRepo: 'DeepsSeekHarness/dsh-brain',
|
||||
copy: [
|
||||
{ from: 'lib', dir: true }, { from: 'client', dir: true },
|
||||
|
|
@ -41,7 +48,7 @@ const COMPONENTS = [
|
|||
},
|
||||
{
|
||||
id: 'workspace-groups-remote',
|
||||
sourceDir: SRC('dsh-workspace-groups-remote'),
|
||||
sourceDir: SRC('workspace-groups-remote', 'dsh-workspace-groups-remote'),
|
||||
sourceRepo: 'DeepsSeekHarness/workspace-groups-remote',
|
||||
copy: [
|
||||
{ from: 'lib', dir: true }, { from: 'package.json' }, { from: 'LICENSE', optional: true },
|
||||
|
|
@ -53,9 +60,9 @@ const COMPONENTS = [
|
|||
sourceDir: SRC('dsh-better-chat'),
|
||||
sourceRepo: 'DeepsSeekHarness/dsh-better-chat',
|
||||
copy: [
|
||||
{ from: 'index.js' }, { from: 'client.js' }, { from: 'package.json' }, { from: 'LICENSE', optional: true },
|
||||
{ from: 'index.js' }, { from: 'client.js' }, { from: 'lib', dir: true }, { from: 'package.json' }, { from: 'LICENSE', optional: true },
|
||||
],
|
||||
clientFile: 'client.js',
|
||||
clientFile: 'lib/client.js',
|
||||
},
|
||||
]
|
||||
|
||||
|
|
@ -76,6 +83,9 @@ function copyOne(base, item, dest) {
|
|||
}
|
||||
|
||||
const manifest = []
|
||||
const pinnedCommits = process.env.QQ_DSH_COMMITS !== undefined && process.env.QQ_DSH_COMMITS.trim() !== ''
|
||||
? JSON.parse(process.env.QQ_DSH_COMMITS)
|
||||
: null
|
||||
rmSync(join(ROOT, 'vendor'), { recursive: true, force: true })
|
||||
for (const c of COMPONENTS) {
|
||||
if (!existsSync(c.sourceDir)) throw new Error(`source repo not found: ${c.sourceDir}`)
|
||||
|
|
@ -83,7 +93,10 @@ for (const c of COMPONENTS) {
|
|||
mkdirSync(dest, { recursive: true })
|
||||
for (const item of c.copy) copyOne(c.sourceDir, item, dest)
|
||||
const pkg = JSON.parse(readFileSync(join(dest, 'package.json'), 'utf8'))
|
||||
const commit = execFileSync('git', ['-C', c.sourceDir, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
|
||||
const commit = pinnedCommits !== null
|
||||
? String(pinnedCommits[c.id] ?? '')
|
||||
: execFileSync('git', ['-C', c.sourceDir, 'rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
|
||||
if (!/^[0-9a-f]{40}$/i.test(commit)) throw new Error(`missing pinned commit for ${c.id}`)
|
||||
manifest.push({
|
||||
id: c.id, package: pkg.name, version: pkg.version,
|
||||
sourceRepo: c.sourceRepo, sourceCommit: commit, vendorPath: `vendor/${c.id}`,
|
||||
|
|
@ -92,7 +105,9 @@ for (const c of COMPONENTS) {
|
|||
}
|
||||
|
||||
// ---- cordis.patch.yml: insert row + workspace-groups-remote overrides ----
|
||||
const wgrPatch = readFileSync(join(SRC('dsh-workspace-groups-remote'), 'cordis.patch.yml'), 'utf8')
|
||||
const groupsComponent = COMPONENTS.find((component) => component.id === 'workspace-groups-remote')
|
||||
if (groupsComponent === undefined) throw new Error('workspace-groups-remote component missing')
|
||||
const wgrPatch = readFileSync(join(groupsComponent.sourceDir, 'cordis.patch.yml'), 'utf8')
|
||||
const marker = '# 自动覆盖 better-sidebar'
|
||||
const at = wgrPatch.indexOf(marker)
|
||||
if (at < 0) throw new Error('wgr patch override marker not found')
|
||||
|
|
@ -101,10 +116,12 @@ if (!overrides.includes('terminal-controller')) throw new Error('wgr overrides i
|
|||
const patch = `# QQ-dsh bundle patch
|
||||
#
|
||||
# One insert row loads the bundle entry, which composes all four plugins.
|
||||
# Migration: remove the four standalone bundles (dsh-sansheng-liubu-mode /
|
||||
# dsh-sansheng-liubu-panel, dsh-brain, workspace-groups-remote,
|
||||
# dsh-better-chat) from the profile and add qq-dsh instead. Stored data is
|
||||
# kept: every component reads its own sidecars and settings namespaces.
|
||||
# Migration: remove the retired standalone panel bundles
|
||||
# (dsh-sansheng-liubu-workbench / dsh-sansheng-liubu-panel) and the four
|
||||
# independent bundles (dsh-sansheng-liubu-mode, dsh-brain,
|
||||
# workspace-groups-remote, dsh-better-chat) from the profile, then add
|
||||
# qq-dsh instead. Stored data is kept: every component reads its own
|
||||
# sidecars and settings namespaces.
|
||||
- insert:
|
||||
- id: qq-dsh
|
||||
name: 'qq-dsh'
|
||||
|
|
|
|||
|
|
@ -1,12 +1,10 @@
|
|||
#!/usr/bin/env node
|
||||
/** QQ-dsh bundle verification: provenance, host composition, client composition, patch shape. */
|
||||
import assert from 'node:assert'
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { register } from 'node:module'
|
||||
import { dirname, join, resolve } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import vm from 'node:vm'
|
||||
|
||||
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..')
|
||||
let checks = 0
|
||||
|
|
@ -20,11 +18,7 @@ for (const c of manifest) {
|
|||
ok(pkg.version === c.version && pkg.name === c.package, `${c.id}: version ${c.version} matches`)
|
||||
}
|
||||
|
||||
// 2. syntax of the entry + client composition
|
||||
for (const f of ['index.js', 'client.js']) {
|
||||
execFileSync('node', ['--check', join(ROOT, f)])
|
||||
ok(true, `${f} parses`)
|
||||
}
|
||||
// 2. entry/client syntax is exercised by the dynamic imports below.
|
||||
|
||||
// 3. host composition: apply() mounts exactly the four component plugins
|
||||
register('./verify-loader.mjs', import.meta.url)
|
||||
|
|
@ -47,7 +41,7 @@ const loads = []
|
|||
const clientMod = await import(join(ROOT, 'client.js'))
|
||||
ok(clientMod.name === 'qq-dsh', 'client plugin name is qq-dsh')
|
||||
ok(loads.length === 3, `client registers 3 loader modules: ${loads.join(', ')}`)
|
||||
for (const id of ['workspace-groups-remote', 'dsh-brain', 'dsh-sansheng-liubu-workbench']) {
|
||||
for (const id of ['workspace-groups-remote', 'dsh-brain', 'dsh-sansheng-liubu-mode']) {
|
||||
ok(loads.includes(id), `client includes ${id}`)
|
||||
}
|
||||
const clientMounted = []
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@ function install(doc) {
|
|||
}
|
||||
|
||||
/**
|
||||
* 功能二:权限策略 —— 去掉「完全权限」选项,新会话默认「自动审查」。
|
||||
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
|
||||
*
|
||||
* 背景(DSH 0.2.2-rc.1 的权限预设,@deepseek-ai/dsh-client-ui-permission-presets):
|
||||
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
||||
|
|
@ -121,14 +121,11 @@ function install(doc) {
|
|||
* 也选不到它。宿主切换预设的通道是会话对象的 command(`/permission <值>`),
|
||||
* 带参命令直接生效、不弹风险确认。
|
||||
*
|
||||
* 本功能补两件事:
|
||||
* 1. 界面移除完全权限:观察 DOM,把选择器/菜单/设置下拉里标签为「完全
|
||||
* 权限 / Full access」的选项摘掉。只动界面——直接输入 /permission
|
||||
* danger-full-access 命令仍可达(宿主行为,不在本插件管辖内)。
|
||||
* 2. 默认自动审查:轮询会话服务,第一次见到某个会话且其权限不是 auto
|
||||
* 时,用宿主同一条命令通道切到 auto。每个会话只尝试一次:之后用户
|
||||
* 手动改走,本插件不再干预;auto 不可用(实验层没开)时命令会失败,
|
||||
* 记录一次日志便不再重试。
|
||||
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或
|
||||
* 插件重载时遍历已有会话改权限:那会把用户明确选择的只读/工作区权限
|
||||
* 覆盖成 auto,而且 handled 只在内存里,刷新后会再次执行。默认权限
|
||||
* 属于宿主的新建会话流程;本插件没有可靠的新建扩展点,因此不拿轮询
|
||||
* 去补偿,用户仍可在宿主提供的权限选择器里自行选择自动审查。
|
||||
*/
|
||||
|
||||
/** 完全权限的预设机器值。 */
|
||||
|
|
@ -200,11 +197,13 @@ export function pruneFullAccess(doc) {
|
|||
}
|
||||
|
||||
/**
|
||||
* 安装权限策略:DOM 观察(防抖扫描)+ 会话轮询(默认 auto)。
|
||||
* getSessions 每次调用现取 ctx.sessions(服务可能晚于插件就绪)。
|
||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
||||
*
|
||||
* 不接收 `getSessions`,也不启动任何会话轮询:页面加载、刷新和插件重载
|
||||
* 都不得改变已有会话的权限。新建会话的默认值由宿主自己的新建流程决定。
|
||||
* @returns 卸载函数
|
||||
*/
|
||||
export function installPermissionPolicy(doc, getSessions, timers = { setInterval, clearInterval, setTimeout, clearTimeout }) {
|
||||
export function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) {
|
||||
let disposed = false
|
||||
let scanTimer = 0
|
||||
const scheduleScan = () => {
|
||||
|
|
@ -218,39 +217,178 @@ export function installPermissionPolicy(doc, getSessions, timers = { setInterval
|
|||
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
||||
pruneFullAccess(doc)
|
||||
|
||||
const handled = new Set()
|
||||
const tick = async () => {
|
||||
if (disposed) return
|
||||
let sessions
|
||||
try { sessions = getSessions() } catch { return }
|
||||
for (const { id, live } of liveSessions(sessions)) {
|
||||
if (handled.has(id)) continue
|
||||
const preset = currentPreset(live)
|
||||
if (!shouldAutoSwitch(preset, handled.has(id))) {
|
||||
if (preset !== undefined && preset !== null) handled.add(id)
|
||||
continue
|
||||
}
|
||||
handled.add(id)
|
||||
if (typeof live.command !== 'function') continue
|
||||
try {
|
||||
const result = await live.command(`/permission ${AUTO_REVIEW_PRESET}`)
|
||||
if (!result?.ok) console.info('[dsh-better-chat] auto review not applied for session', id, result?.error?.code ?? '')
|
||||
} catch {
|
||||
console.info('[dsh-better-chat] auto review switch failed for session', id)
|
||||
}
|
||||
}
|
||||
}
|
||||
const timer = timers.setInterval(() => { void tick() }, 2500)
|
||||
void tick()
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
if (scanTimer) timers.clearTimeout(scanTimer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 功能三:插件商店「更新」按钮。
|
||||
*
|
||||
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有
|
||||
* 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮:
|
||||
* 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装
|
||||
* 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖
|
||||
* 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。
|
||||
* 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。
|
||||
*
|
||||
* 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与
|
||||
* 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效,
|
||||
* 本功能静默关闭。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
export const UPDATE_LABELS = ['有新版本', 'Update available']
|
||||
|
||||
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
|
||||
export function localizedTitle(title, lang) {
|
||||
if (typeof title === 'string') return title
|
||||
if (!title || typeof title !== 'object') return ''
|
||||
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
|
||||
for (const key of chain) {
|
||||
if (key && typeof title[key] === 'string' && title[key]) return title[key]
|
||||
}
|
||||
const values = Object.values(title)
|
||||
return typeof values[0] === 'string' ? values[0] : ''
|
||||
}
|
||||
|
||||
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
|
||||
export function pickUpdates(searchResults, lang) {
|
||||
const updates = []
|
||||
for (const result of searchResults ?? []) {
|
||||
const entries = result?.value?.entries ?? result?.entries ?? []
|
||||
for (const entry of entries) {
|
||||
if (entry?.installation?.status !== 'update-available') continue
|
||||
const versions = entry.versions ?? []
|
||||
const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0]
|
||||
const spec = version?.install?.spec
|
||||
if (!entry.name || !version?.version || !spec) continue
|
||||
updates.push({
|
||||
name: entry.name,
|
||||
title: localizedTitle(entry.title, lang) || entry.name,
|
||||
installedVersion: entry.installation.installedVersion ?? '',
|
||||
version: version.version,
|
||||
spec,
|
||||
registry: version.install.registry,
|
||||
})
|
||||
}
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
|
||||
export async function runUpdate(remote, update, makeRequestId) {
|
||||
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
|
||||
return remote.pluginManager.installBundle(update.spec, {
|
||||
enabled: true,
|
||||
requestId,
|
||||
...(update.registry ? { registry: update.registry } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
|
||||
* 同时包含插件标题、且文本总量还像一行的祖先。
|
||||
*/
|
||||
export function findUpdateRow(doc, title) {
|
||||
for (const el of doc.querySelectorAll('button')) {
|
||||
if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue
|
||||
let node = el
|
||||
for (let depth = 0; depth < 6 && node; depth++) {
|
||||
node = node.parentElement
|
||||
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
|
||||
export function makeUpdateClickHandler(doc, getRemote, update, button) {
|
||||
return async (event) => {
|
||||
event?.preventDefault?.()
|
||||
event?.stopPropagation?.()
|
||||
const view = doc.defaultView
|
||||
const ask = view?.confirm ?? globalThis.confirm
|
||||
const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
|
||||
if (ask && !ask.call(view ?? globalThis, message)) return
|
||||
button.disabled = true
|
||||
button.textContent = '更新中…'
|
||||
try {
|
||||
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined)
|
||||
if (result?.value?.application === 'applied') {
|
||||
button.textContent = '已更新,重启 DSH 后生效'
|
||||
} else {
|
||||
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
|
||||
button.disabled = false
|
||||
button.textContent = '更新失败,点此重试'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[dsh-better-chat] update failed for', update.name, error)
|
||||
button.disabled = false
|
||||
button.textContent = '更新失败,点此重试'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
|
||||
export function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) {
|
||||
let disposed = false
|
||||
let updates = []
|
||||
const decorate = () => {
|
||||
for (const update of updates) {
|
||||
const row = findUpdateRow(doc, update.title)
|
||||
if (!row || row.querySelector('[data-better-chat-update]')) continue
|
||||
const button = doc.createElement('button')
|
||||
button.type = 'button'
|
||||
button.setAttribute('data-better-chat-update', update.name)
|
||||
button.textContent = '更新到 ' + update.version
|
||||
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
|
||||
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
|
||||
row.appendChild(button)
|
||||
}
|
||||
}
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const remote = getRemote()
|
||||
if (!remote?.pluginMarket || !remote?.pluginManager) return
|
||||
const indexes = await remote.pluginMarket.listIndexes()
|
||||
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean)
|
||||
const results = []
|
||||
for (const url of urls) {
|
||||
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
|
||||
}
|
||||
if (disposed) return
|
||||
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
|
||||
decorate()
|
||||
} catch {
|
||||
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
|
||||
}
|
||||
}
|
||||
const observer = new MutationObserver(() => decorate())
|
||||
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
||||
const timer = timers.setInterval(() => { void refresh() }, 30000)
|
||||
void refresh()
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
timers.clearInterval(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
|
||||
const storeUpdatePlugin = {
|
||||
name: 'dsh-better-chat-store-update',
|
||||
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
|
||||
apply(childCtx) {
|
||||
childCtx.effect(
|
||||
() => installStoreUpdateButtons(document, () => childCtx.remote),
|
||||
'dsh-better-chat: store update buttons',
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
/** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */
|
||||
export const inject = []
|
||||
|
||||
|
|
@ -258,7 +396,12 @@ export const inject = []
|
|||
export function apply(ctx) {
|
||||
ctx.effect(() => install(document), 'dsh-better-chat: approval enter/esc routing')
|
||||
ctx.effect(
|
||||
() => installPermissionPolicy(document, () => ctx.sessions),
|
||||
'dsh-better-chat: permission policy (no full access, auto review by default)',
|
||||
() => installPermissionPolicy(document),
|
||||
'dsh-better-chat: permission policy (no full access)',
|
||||
)
|
||||
try {
|
||||
ctx.plugin(storeUpdatePlugin)
|
||||
} catch {
|
||||
// 子插件挂不上(旧宿主等)不影响主功能。
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,418 @@
|
|||
'use strict'
|
||||
/* Generated by scripts/build-client.mjs from client.js - do not edit by hand.
|
||||
The host client module loader fetches this file as a classic script and
|
||||
expects window.__ModuleLoader__.load({ id, factory }) registration. */
|
||||
;(function () {
|
||||
/**
|
||||
* dsh-better-chat 客户端:让审批卡片的回车 / Esc 不再挑焦点。
|
||||
*
|
||||
* 背景(DSH 0.2.2-rc.1 的 @deepseek-ai/dsh-client-ui-approval):
|
||||
* 官方审批卡自带键盘处理 —— Enter 批准(单次)、Esc 拒绝 —— 但它的
|
||||
* keydown 挂在卡片根节点上,且要求焦点先落在卡片内。审批弹出时焦点
|
||||
* 往往还在对话区/页面主体上,按回车毫无反应,必须先点一下卡片。
|
||||
*
|
||||
* 本模块补两件事,不改官方任何逻辑:
|
||||
* 1. 审批卡出现时,若用户没有正在别处输入,把焦点送进卡片的详情区
|
||||
* ([data-approval-scroll],本身 tabIndex=0),官方处理立即生效。
|
||||
* 2. 焦点不在卡片内时兜底路由:在 document 捕获阶段监听 keydown,
|
||||
* 满足全部防误触条件时,点击卡片操作行里的按钮 —— 顺序由官方渲染
|
||||
* 固定为 [拒绝, 允许(单次), 始终允许?],回车点「允许(单次)」,
|
||||
* 永远不会误触「始终允许」;Esc 点「拒绝」。
|
||||
*
|
||||
* 防误触(与官方卡片内部规则对齐):
|
||||
* - 正在任何输入控件(input/textarea/select/contenteditable)里打字 → 不管
|
||||
* - 焦点已在卡片内 → 官方处理,绝不重复作答
|
||||
* - 带 Ctrl/Meta/Alt/Shift、长按连发、输入法组词中 → 不管
|
||||
* - 回车落在某个按钮/链接上 → 保留那个按钮自己的回车行为
|
||||
* - 卡片已作答(aria-busy=true)或按钮禁用 → 不管
|
||||
*/
|
||||
|
||||
const CARD_SELECTOR = '[data-approval-key]'
|
||||
const SCROLL_SELECTOR = '[data-approval-scroll]'
|
||||
const EDITABLE_SELECTOR = 'input, textarea, select, [contenteditable="true"], [contenteditable=""]'
|
||||
|
||||
/** 卡片操作行的按钮:详情滚动区之外的全部按钮,顺序 [拒绝, 允许, 始终允许?]。 */
|
||||
function actionButtons(card) {
|
||||
return [...card.querySelectorAll('button')].filter((b) => !b.closest(SCROLL_SELECTOR))
|
||||
}
|
||||
|
||||
/** 找当前可作答的审批卡(DOM 顺序第一张未作答、按钮齐全的卡)。 */
|
||||
function findPendingCard(doc) {
|
||||
for (const card of doc.querySelectorAll(CARD_SELECTOR)) {
|
||||
if (card.getAttribute('aria-busy') === 'true') continue
|
||||
const buttons = actionButtons(card)
|
||||
if (buttons.length >= 2 && !buttons[0].disabled && !buttons[1].disabled) return card
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯判定:这次 keydown 是否应该路由到审批卡。
|
||||
* @returns {'allow'|'reject'|null}
|
||||
*/
|
||||
function decideKeyAction(input) {
|
||||
const { key, ctrlKey, metaKey, altKey, shiftKey, repeat, isComposing, keyCode, defaultPrevented, target, activeElement, card } = input
|
||||
if (!card) return null
|
||||
if (defaultPrevented) return null
|
||||
if (key !== 'Enter' && key !== 'Escape') return null
|
||||
if (ctrlKey || metaKey || altKey || shiftKey) return null
|
||||
if (repeat || isComposing || keyCode === 229) return null
|
||||
if (activeElement && card.contains(activeElement)) return null // 焦点在卡内:官方处理
|
||||
if (target && typeof target.closest === 'function') {
|
||||
if (target.closest(EDITABLE_SELECTOR) !== null) return null // 正在别处输入
|
||||
if (key === 'Enter' && target.closest('button, a[href], [role="button"]') !== null) return null
|
||||
}
|
||||
return key === 'Enter' ? 'allow' : 'reject'
|
||||
}
|
||||
|
||||
/** 纯判定:审批卡出现时是否应该把焦点送进详情区。 */
|
||||
function shouldAutoFocus(activeElement, card) {
|
||||
if (!activeElement) return true
|
||||
if (activeElement === card.ownerDocument?.body) return true
|
||||
if (card.contains(activeElement)) return false // 已经在卡里
|
||||
if (typeof activeElement.closest === 'function' && activeElement.closest(EDITABLE_SELECTOR) !== null) return false // 正在别处输入
|
||||
return true
|
||||
}
|
||||
|
||||
function install(doc) {
|
||||
const focusedCards = new WeakSet()
|
||||
|
||||
const tryAutoFocus = () => {
|
||||
const card = findPendingCard(doc)
|
||||
if (!card || focusedCards.has(card)) return
|
||||
focusedCards.add(card)
|
||||
if (!shouldAutoFocus(doc.activeElement, card)) return
|
||||
const region = card.querySelector(SCROLL_SELECTOR)
|
||||
if (region && typeof region.focus === 'function') region.focus()
|
||||
}
|
||||
|
||||
const observer = new MutationObserver(tryAutoFocus)
|
||||
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
||||
tryAutoFocus()
|
||||
|
||||
const onKeyDown = (event) => {
|
||||
const card = findPendingCard(doc)
|
||||
const action = decideKeyAction({
|
||||
key: event.key,
|
||||
ctrlKey: event.ctrlKey, metaKey: event.metaKey, altKey: event.altKey, shiftKey: event.shiftKey,
|
||||
repeat: event.repeat, isComposing: event.isComposing, keyCode: event.keyCode,
|
||||
defaultPrevented: event.defaultPrevented,
|
||||
target: event.target, activeElement: doc.activeElement, card,
|
||||
})
|
||||
if (!action) return
|
||||
const buttons = actionButtons(card)
|
||||
const button = action === 'allow' ? buttons[1] : buttons[0]
|
||||
if (!button || button.disabled) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
button.click()
|
||||
}
|
||||
doc.addEventListener('keydown', onKeyDown, true)
|
||||
|
||||
return () => {
|
||||
observer.disconnect()
|
||||
doc.removeEventListener('keydown', onKeyDown, true)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 功能二:权限 UI —— 去掉「完全权限」选项,不改已有会话权限。
|
||||
*
|
||||
* 背景(DSH 0.2.2-rc.1 的权限预设,@deepseek-ai/dsh-client-ui-permission-presets):
|
||||
* 会话权限有四个预设值:read-only(仅可查看)、workspace-write(工作区内
|
||||
* 修改)、danger-full-access(完全权限)、auto(自动审查,EXP)。「自动
|
||||
* 审查」由实验层 @deepseek-ai/dsh-experimental-auto-review 提供:开启该层
|
||||
* 后才出现在当前会话的选择器里;通用设置不提供 auto,新会话默认值里
|
||||
* 也选不到它。宿主切换预设的通道是会话对象的 command(`/permission <值>`),
|
||||
* 带参命令直接生效、不弹风险确认。
|
||||
*
|
||||
* 本功能只做一件事:界面移除完全权限。它**不再**在页面加载、刷新或
|
||||
* 插件重载时遍历已有会话改权限:那会把用户明确选择的只读/工作区权限
|
||||
* 覆盖成 auto,而且 handled 只在内存里,刷新后会再次执行。默认权限
|
||||
* 属于宿主的新建会话流程;本插件没有可靠的新建扩展点,因此不拿轮询
|
||||
* 去补偿,用户仍可在宿主提供的权限选择器里自行选择自动审查。
|
||||
*/
|
||||
|
||||
/** 完全权限的预设机器值。 */
|
||||
const FULL_ACCESS_PRESET = 'danger-full-access'
|
||||
/** 自动审查的预设机器值。 */
|
||||
const AUTO_REVIEW_PRESET = 'auto'
|
||||
/** 完全权限在各语言界面里的选项标签(选项文字以标签开头)。 */
|
||||
const FULL_ACCESS_LABELS = ['完全权限', 'Full access']
|
||||
|
||||
/** 纯判定:一段选项文字是否就是「完全权限」选项(标签打头,或恰好相等)。 */
|
||||
function isFullAccessLabel(text) {
|
||||
if (typeof text !== 'string') return false
|
||||
const t = text.trim()
|
||||
return FULL_ACCESS_LABELS.some((label) => t === label || t.startsWith(label))
|
||||
}
|
||||
|
||||
/** 纯判定:这个会话现在是否应该被切到自动审查。 */
|
||||
function shouldAutoSwitch(preset, alreadyHandled) {
|
||||
return preset !== undefined && preset !== null && preset !== AUTO_REVIEW_PRESET && !alreadyHandled
|
||||
}
|
||||
|
||||
/**
|
||||
* 防御式枚举宿主的 live 会话:优先 keys()+binding(),退回 list()。
|
||||
* 服务形状对不上时安静返回空数组,绝不抛错。
|
||||
*/
|
||||
function liveSessions(sessions) {
|
||||
const out = []
|
||||
if (!sessions || typeof sessions !== 'object') return out
|
||||
try {
|
||||
if (typeof sessions.keys === 'function' && typeof sessions.binding === 'function') {
|
||||
for (const id of sessions.keys()) {
|
||||
const live = sessions.binding(id)?.session
|
||||
if (live) out.push({ id, live })
|
||||
}
|
||||
return out
|
||||
}
|
||||
if (typeof sessions.list === 'function') {
|
||||
for (const s of sessions.list() ?? []) {
|
||||
if (s && s.sessionId) out.push({ id: s.sessionId, live: s })
|
||||
}
|
||||
}
|
||||
} catch { /* 服务形状不同:放弃枚举 */ }
|
||||
return out
|
||||
}
|
||||
|
||||
/** 读会话当前的权限预设值(投影不可用时返回 undefined)。 */
|
||||
function currentPreset(live) {
|
||||
try {
|
||||
return live?.projections?.faceOf('permissions')?.getSnapshot?.()
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 把「完全权限」选项从当前文档里摘掉:原生 select 的 option、弹出
|
||||
* 选择器(role=listbox)与菜单(role=menu)里的 option/menuitem。
|
||||
* @returns 摘掉的个数
|
||||
*/
|
||||
function pruneFullAccess(doc) {
|
||||
let removed = 0
|
||||
for (const opt of doc.querySelectorAll('option')) {
|
||||
if (isFullAccessLabel(opt.textContent)) { opt.remove(); removed++ }
|
||||
}
|
||||
for (const item of doc.querySelectorAll('[role="listbox"] [role="option"], [role="menu"] [role="menuitem"]')) {
|
||||
if (isFullAccessLabel(item.textContent)) { item.remove(); removed++ }
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装权限 UI 策略:只观察 DOM、摘掉「完全权限」选项。
|
||||
*
|
||||
* 不接收 `getSessions`,也不启动任何会话轮询:页面加载、刷新和插件重载
|
||||
* 都不得改变已有会话的权限。新建会话的默认值由宿主自己的新建流程决定。
|
||||
* @returns 卸载函数
|
||||
*/
|
||||
function installPermissionPolicy(doc, _getSessions, timers = { setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: (id) => clearTimeout(id) }) {
|
||||
let disposed = false
|
||||
let scanTimer = 0
|
||||
const scheduleScan = () => {
|
||||
if (disposed || scanTimer) return
|
||||
scanTimer = timers.setTimeout(() => {
|
||||
scanTimer = 0
|
||||
if (!disposed) pruneFullAccess(doc)
|
||||
}, 120)
|
||||
}
|
||||
const observer = new MutationObserver(scheduleScan)
|
||||
if (doc.body) observer.observe(doc.body, { childList: true, subtree: true })
|
||||
pruneFullAccess(doc)
|
||||
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
if (scanTimer) timers.clearTimeout(scanTimer)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ *
|
||||
* 功能三:插件商店「更新」按钮。
|
||||
*
|
||||
* DSH 只给官方插件原地更新;从自定义索引装的插件在发现页只有
|
||||
* 「有新版本」标签、没有按钮,只能手动卸载重装。这里补一个真按钮:
|
||||
* 数据与动作都走宿主自己的远程服务——pluginMarket 查索引和安装
|
||||
* 状态,pluginManager.installBundle 按索引给出的精确 spec 覆盖
|
||||
* 安装——与官方安装流程同一套接口,不模拟点击、不动官方状态。
|
||||
* 覆盖安装在探针实测中可直接把已装旧版换成新版(changed/applied)。
|
||||
*
|
||||
* 服务经子插件声明 inject 取用:主插件保持 inject 为空,审批与
|
||||
* 权限功能不依赖这些服务;未启用实验性插件索引时子插件不生效,
|
||||
* 本功能静默关闭。
|
||||
* ------------------------------------------------------------------ */
|
||||
|
||||
const UPDATE_LABELS = ['有新版本', 'Update available']
|
||||
|
||||
/** 索引条目的本地化标题在当前语言下的文本(与发现页行内展示一致)。 */
|
||||
function localizedTitle(title, lang) {
|
||||
if (typeof title === 'string') return title
|
||||
if (!title || typeof title !== 'object') return ''
|
||||
const chain = [lang, lang && lang.split('-')[0], 'zh-CN', 'en']
|
||||
for (const key of chain) {
|
||||
if (key && typeof title[key] === 'string' && title[key]) return title[key]
|
||||
}
|
||||
const values = Object.values(title)
|
||||
return typeof values[0] === 'string' ? values[0] : ''
|
||||
}
|
||||
|
||||
/** 从各索引的搜索结果里挑出「有新版本」的条目,整理成可执行的更新计划。 */
|
||||
function pickUpdates(searchResults, lang) {
|
||||
const updates = []
|
||||
for (const result of searchResults ?? []) {
|
||||
const entries = result?.value?.entries ?? result?.entries ?? []
|
||||
for (const entry of entries) {
|
||||
if (entry?.installation?.status !== 'update-available') continue
|
||||
const versions = entry.versions ?? []
|
||||
const version = versions.find((v) => v.version === entry.defaultVersion) ?? versions[0]
|
||||
const spec = version?.install?.spec
|
||||
if (!entry.name || !version?.version || !spec) continue
|
||||
updates.push({
|
||||
name: entry.name,
|
||||
title: localizedTitle(entry.title, lang) || entry.name,
|
||||
installedVersion: entry.installation.installedVersion ?? '',
|
||||
version: version.version,
|
||||
spec,
|
||||
registry: version.install.registry,
|
||||
})
|
||||
}
|
||||
}
|
||||
return updates
|
||||
}
|
||||
|
||||
/** 执行一次更新:按索引 spec 覆盖安装,宿主结果信封原样返回。 */
|
||||
async function runUpdate(remote, update, makeRequestId) {
|
||||
const requestId = makeRequestId ? makeRequestId() : 'better-chat-update-' + Date.now()
|
||||
return remote.pluginManager.installBundle(update.spec, {
|
||||
enabled: true,
|
||||
requestId,
|
||||
...(update.registry ? { registry: update.registry } : {}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 发现页里某个插件的行:状态标签本身是个按钮,从它向上找第一个
|
||||
* 同时包含插件标题、且文本总量还像一行的祖先。
|
||||
*/
|
||||
function findUpdateRow(doc, title) {
|
||||
for (const el of doc.querySelectorAll('button')) {
|
||||
if (!UPDATE_LABELS.includes(el.textContent?.trim())) continue
|
||||
let node = el
|
||||
for (let depth = 0; depth < 6 && node; depth++) {
|
||||
node = node.parentElement
|
||||
if (node && node.textContent?.includes(title) && node.textContent.length < 600) return node
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
/** 更新按钮的点击处理:确认 → 调宿主覆盖安装 → 按结果改按钮文案。 */
|
||||
function makeUpdateClickHandler(doc, getRemote, update, button) {
|
||||
return async (event) => {
|
||||
event?.preventDefault?.()
|
||||
event?.stopPropagation?.()
|
||||
const view = doc.defaultView
|
||||
const ask = view?.confirm ?? globalThis.confirm
|
||||
const message = '更新「' + update.title + '」' + (update.installedVersion ? ' ' + update.installedVersion : '') + ' → ' + update.version + '?\n会直接覆盖安装新版,插件数据保留。'
|
||||
if (ask && !ask.call(view ?? globalThis, message)) return
|
||||
button.disabled = true
|
||||
button.textContent = '更新中…'
|
||||
try {
|
||||
const result = await runUpdate(getRemote(), update, () => globalThis.crypto?.randomUUID?.() ?? undefined)
|
||||
if (result?.value?.application === 'applied') {
|
||||
button.textContent = '已更新,重启 DSH 后生效'
|
||||
} else {
|
||||
console.error('[dsh-better-chat] update failed for', update.name, result?.value?.error ?? result)
|
||||
button.disabled = false
|
||||
button.textContent = '更新失败,点此重试'
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[dsh-better-chat] update failed for', update.name, error)
|
||||
button.disabled = false
|
||||
button.textContent = '更新失败,点此重试'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 发现页增强:轮询索引状态,把「更新」按钮挂到有新版本的行上。 */
|
||||
function installStoreUpdateButtons(doc, getRemote, timers = { setInterval: (fn, ms) => setInterval(fn, ms), clearInterval: (id) => clearInterval(id) }) {
|
||||
let disposed = false
|
||||
let updates = []
|
||||
const decorate = () => {
|
||||
for (const update of updates) {
|
||||
const row = findUpdateRow(doc, update.title)
|
||||
if (!row || row.querySelector('[data-better-chat-update]')) continue
|
||||
const button = doc.createElement('button')
|
||||
button.type = 'button'
|
||||
button.setAttribute('data-better-chat-update', update.name)
|
||||
button.textContent = '更新到 ' + update.version
|
||||
button.style.cssText = 'flex:none;margin-left:8px;padding:2px 10px;border:1px solid #7f7f7f55;border-radius:999px;background:transparent;color:inherit;font-size:12px;cursor:pointer'
|
||||
button.addEventListener('click', makeUpdateClickHandler(doc, getRemote, update, button))
|
||||
row.appendChild(button)
|
||||
}
|
||||
}
|
||||
const refresh = async () => {
|
||||
try {
|
||||
const remote = getRemote()
|
||||
if (!remote?.pluginMarket || !remote?.pluginManager) return
|
||||
const indexes = await remote.pluginMarket.listIndexes()
|
||||
const urls = (indexes?.value ?? indexes ?? []).map((entry) => entry?.url).filter(Boolean)
|
||||
const results = []
|
||||
for (const url of urls) {
|
||||
results.push(await remote.pluginMarket.search(url, { sort: { kind: 'index' }, offset: 0, limit: 100 }))
|
||||
}
|
||||
if (disposed) return
|
||||
updates = pickUpdates(results, doc.documentElement?.lang || 'zh-CN')
|
||||
decorate()
|
||||
} catch {
|
||||
// 索引服务不可用(未启用实验性插件索引等):静默关闭本功能。
|
||||
}
|
||||
}
|
||||
const observer = new MutationObserver(() => decorate())
|
||||
observer.observe(doc.documentElement, { childList: true, subtree: true })
|
||||
const timer = timers.setInterval(() => { void refresh() }, 30000)
|
||||
void refresh()
|
||||
return () => {
|
||||
disposed = true
|
||||
observer.disconnect()
|
||||
timers.clearInterval(timer)
|
||||
}
|
||||
}
|
||||
|
||||
/** 商店更新子插件:单独声明远程服务 inject,与主功能互相隔离。 */
|
||||
const storeUpdatePlugin = {
|
||||
name: 'dsh-better-chat-store-update',
|
||||
inject: ['remote', 'remote.pluginMarket', 'remote.pluginManager'],
|
||||
apply(childCtx) {
|
||||
childCtx.effect(
|
||||
() => installStoreUpdateButtons(document, () => childCtx.remote),
|
||||
'dsh-better-chat: store update buttons',
|
||||
)
|
||||
},
|
||||
}
|
||||
|
||||
/** 本插件不硬依赖任何客户端服务(sessions 服务是可选增强,缺了只是不自动切)。 */
|
||||
const inject = []
|
||||
|
||||
/** 插件主体:挂载两组增强,卸载时完整摘除。 */
|
||||
function apply(ctx) {
|
||||
ctx.effect(() => install(document), 'dsh-better-chat: approval enter/esc routing')
|
||||
ctx.effect(
|
||||
() => installPermissionPolicy(document),
|
||||
'dsh-better-chat: permission policy (no full access)',
|
||||
)
|
||||
try {
|
||||
ctx.plugin(storeUpdatePlugin)
|
||||
} catch {
|
||||
// 子插件挂不上(旧宿主等)不影响主功能。
|
||||
}
|
||||
}
|
||||
|
||||
var plugin = { name: "dsh-better-chat", inject: inject, apply: apply }
|
||||
if (typeof window !== "undefined" && window.__ModuleLoader__ && typeof window.__ModuleLoader__.load === "function") {
|
||||
window.__ModuleLoader__.load({ id: "dsh-better-chat", factory: function () { return plugin } })
|
||||
}
|
||||
})()
|
||||
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "dsh-better-chat",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.1",
|
||||
"description": "DSH 聊天增强插件:审批卡片全局回车批准 / Esc 拒绝",
|
||||
"type": "module",
|
||||
"main": "index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./client": "./client.js",
|
||||
"./client": "./lib/client.js",
|
||||
"./cordis.patch.yml": "./cordis.patch.yml",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
|
|
@ -20,7 +20,8 @@
|
|||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test tests/approval-keys.test.mjs"
|
||||
"test": "node --test tests/approval-keys.test.mjs tests/permission-policy.test.mjs tests/client-loader.test.mjs tests/store-update.test.mjs",
|
||||
"build": "node scripts/build-client.mjs"
|
||||
},
|
||||
"license": "MIT"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -138,6 +138,25 @@ export class SkillSync {
|
|||
statePath() {
|
||||
return skillsStatePath();
|
||||
}
|
||||
/**
|
||||
* Record a cloud-delivered skill. Upload provenance is cleared in the same
|
||||
* transition: a skill has exactly one source of truth. Keeping both marks
|
||||
* makes the DOWN pass skip the name (uploaded) while the UP pass skips its
|
||||
* local folder (delivery manifest), so neither side ever syncs again.
|
||||
*/
|
||||
markDelivered(state, name, manifest) {
|
||||
state.delivered[name] = { manifest };
|
||||
delete state.uploaded[name];
|
||||
}
|
||||
/**
|
||||
* Record a locally-originated upload. The delivery marker is cleared in the
|
||||
* same transition, so the next local edit is uploaded again instead of being
|
||||
* skipped as cloud-origin.
|
||||
*/
|
||||
markUploaded(state, name, record) {
|
||||
state.uploaded[name] = record;
|
||||
delete state.delivered[name];
|
||||
}
|
||||
async loadState() {
|
||||
const clean = { version: 1, uploaded: {}, delivered: {}, removed: {} };
|
||||
try {
|
||||
|
|
@ -287,6 +306,28 @@ export class SkillSync {
|
|||
const root = this.skillsRoot();
|
||||
const state = await this.loadState();
|
||||
let stateDirty = false;
|
||||
// Self-heal sidecars written before source provenance became exclusive:
|
||||
// a folder carrying a delivery manifest is cloud-delivered, even if an old
|
||||
// `uploaded` record survived. Clearing the stale upload marker lets the
|
||||
// DOWN pass judge local integrity (and surface a conflict) instead of
|
||||
// skipping both directions forever.
|
||||
for (const name of Object.keys(state.uploaded)) {
|
||||
let delivery = undefined;
|
||||
for (const area of [root, this.holdingRoot()]) {
|
||||
const dir = join(area, name);
|
||||
if (!(await isDirectory(dir)))
|
||||
continue;
|
||||
delivery = await this.readDelivery(dir);
|
||||
if (delivery !== undefined)
|
||||
break;
|
||||
}
|
||||
if (delivery !== undefined) {
|
||||
this.markDelivered(state, name, delivery.manifest_sha256 ?? '');
|
||||
stateDirty = true;
|
||||
}
|
||||
}
|
||||
if (stateDirty)
|
||||
await this.saveState(state);
|
||||
// ---- DOWN: cloud center -> local directory -------------------------
|
||||
for (const item of items) {
|
||||
if (item.enabled === false) {
|
||||
|
|
@ -330,7 +371,7 @@ export class SkillSync {
|
|||
}
|
||||
if (delivery.manifest_sha256 === item.manifest_sha256) {
|
||||
if (state.delivered[item.name]?.manifest !== item.manifest_sha256) {
|
||||
state.delivered[item.name] = { manifest: item.manifest_sha256 ?? '' };
|
||||
this.markDelivered(state, item.name, item.manifest_sha256 ?? '');
|
||||
stateDirty = true;
|
||||
}
|
||||
stats.skipped += 1;
|
||||
|
|
@ -361,7 +402,7 @@ export class SkillSync {
|
|||
continue;
|
||||
}
|
||||
await this.install(item, bundle.data, parked ? this.holdingRoot() : root);
|
||||
state.delivered[item.name] = { manifest: bundle.data.manifest_sha256 };
|
||||
this.markDelivered(state, item.name, bundle.data.manifest_sha256);
|
||||
stateDirty = true;
|
||||
(exists ? stats.updated : stats.downloaded).push(item.name);
|
||||
}
|
||||
|
|
@ -412,12 +453,12 @@ export class SkillSync {
|
|||
this.conflict(stats, skill.name, `upload_failed: ${describeError(created.error)}`);
|
||||
continue;
|
||||
}
|
||||
state.uploaded[skill.name] = {
|
||||
this.markUploaded(state, skill.name, {
|
||||
folder: entry.name,
|
||||
revision: created.data.skill?.revision ?? created.data.revision ?? 1,
|
||||
manifest: skill.manifest,
|
||||
syncedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
stateDirty = true;
|
||||
stats.uploaded.push(skill.name);
|
||||
}
|
||||
|
|
@ -437,12 +478,12 @@ export class SkillSync {
|
|||
this.conflict(stats, skill.name, reason);
|
||||
continue;
|
||||
}
|
||||
state.uploaded[skill.name] = {
|
||||
this.markUploaded(state, skill.name, {
|
||||
folder: entry.name,
|
||||
revision: updated.data.skill?.revision ?? updated.data.revision ?? record.revision + 1,
|
||||
manifest: skill.manifest,
|
||||
syncedAt: new Date().toISOString(),
|
||||
};
|
||||
});
|
||||
stateDirty = true;
|
||||
stats.updated.push(skill.name);
|
||||
}
|
||||
|
|
@ -658,7 +699,10 @@ export class SkillSync {
|
|||
if (!created.ok)
|
||||
throw new Error(`upload_failed: ${describeError(created.error)}`);
|
||||
const revision = created.data.skill?.revision ?? created.data.revision ?? 1;
|
||||
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
|
||||
// The local copy is now the upload source of truth: drop any stale
|
||||
// cloud-delivery marker before committing the success state.
|
||||
await rm(join(dir, '.manifest.json'), { force: true });
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
|
|
@ -676,7 +720,8 @@ export class SkillSync {
|
|||
throw new Error(`upload_failed: ${describeError(updated.error)}`);
|
||||
}
|
||||
const revision = updated.data.skill?.revision ?? updated.data.revision ?? (cloud.revision ?? 0) + 1;
|
||||
state.uploaded[name] = { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() };
|
||||
await rm(join(dir, '.manifest.json'), { force: true });
|
||||
this.markUploaded(state, name, { folder: name, revision, manifest: skill.manifest, syncedAt: new Date().toISOString() });
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
|
|
@ -698,7 +743,7 @@ export class SkillSync {
|
|||
await cp(dir, backup, { recursive: true, filter: (p) => !p.split(/[\\/]/).includes('.git') });
|
||||
}
|
||||
await this.install(cloud, bundle.data, parked ? this.holdingRoot() : root);
|
||||
state.delivered[name] = { manifest: bundle.data.manifest_sha256 };
|
||||
this.markDelivered(state, name, bundle.data.manifest_sha256);
|
||||
delete state.removed[name];
|
||||
await this.saveState(state);
|
||||
this.dropConflict(name);
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "dsh-brain",
|
||||
"version": "0.9.0",
|
||||
"version": "0.9.1",
|
||||
"description": "Cloud memory for DSH: report one activity turn per conversation round and expose memory_search / memory_read / memory_add tools against a LongMemory cloud endpoint.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
|
|
|||
|
|
@ -1,13 +1,13 @@
|
|||
{
|
||||
"name": "dsh-sansheng-liubu-mode",
|
||||
"version": "0.12.1",
|
||||
"private": true,
|
||||
"version": "0.14.0",
|
||||
"description": "三省六部工作台:十席独立会话、项目账本、派工与分层记忆",
|
||||
"type": "module",
|
||||
"main": "./index.js",
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./package.json": "./package.json"
|
||||
"./package.json": "./package.json",
|
||||
"./client": "./workbench/panel/lib/client.js"
|
||||
},
|
||||
"files": [
|
||||
"index.js",
|
||||
|
|
@ -23,11 +23,18 @@
|
|||
"manifestVersion": 1,
|
||||
"bundle": {
|
||||
"patch": "./cordis.patch.yml"
|
||||
},
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-api-session-controller",
|
||||
"@deepseek-ai/dsh-client-ui-workspace",
|
||||
"@deepseek-ai/dsh-client-ui-primitives"
|
||||
]
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"test": "node --test --test-isolation=none workbench/test/*.test.mjs workbench/panel/test/client.test.mjs",
|
||||
"workbench:install": "node scripts/workbench-install.mjs",
|
||||
"workbench:preflight": "node scripts/workbench-preflight.mjs",
|
||||
"preview:workbench": "node scripts/preview-workbench.mjs"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -58,7 +58,7 @@ export {
|
|||
* @param {() => number} [options.clock] 注入时钟。
|
||||
* @param {() => string} [options.random] 注入随机源(测试里固定 ID 用)。
|
||||
* @param {boolean} [options.load=true] 是否从磁盘加载既有账本。
|
||||
* @param {string} [options.presetId] 部门会话使用的 agentPreset,默认「上朝」。
|
||||
* @param {string} [options.presetId] 部门会话显式使用的 agentPreset;缺省不指定,走宿主默认创建流程。
|
||||
* @param {boolean} [options.startReconciler=true] 是否启动周期对账。
|
||||
* @param {number} [options.longPollMs] 事件长轮询上限(毫秒)。
|
||||
* @param {number} [options.pollIntervalMs] 长轮询内部检查间隔(毫秒)。
|
||||
|
|
|
|||
|
|
@ -1346,7 +1346,7 @@ export function createWorkbenchService(options = {}) {
|
|||
// ---------- 投影 ----------
|
||||
|
||||
/**
|
||||
* bootstrap:一次拿全。projectId 为空时取列表第一个;
|
||||
* bootstrap:一次拿全。projectId 为空时只返回项目清单,不默认选中第一个;
|
||||
* 传入的项目不可见按 NOT_FOUND 报错,不泄露其他项目是否存在。
|
||||
*/
|
||||
function bootstrap(projectId) {
|
||||
|
|
@ -1354,8 +1354,6 @@ export function createWorkbenchService(options = {}) {
|
|||
let selectedId = null
|
||||
if (projectId !== undefined && projectId !== null && projectId !== '') {
|
||||
selectedId = projectIdOf({ projectId }).id
|
||||
} else if (projects.length > 0) {
|
||||
selectedId = projects[0].id
|
||||
}
|
||||
if (selectedId === null) {
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -182,16 +182,24 @@ export function createSessionAdapter(options = {}) {
|
|||
/**
|
||||
* 订阅会话事件。alreadyAttached 时不重复起流:同一个会话只留一条 follow,
|
||||
* 避免双窗口/重启后重建出两条流导致事件重复。
|
||||
*
|
||||
* @param {string|object} target 普通会话 id,或宿主 `SessionAddress` 对象
|
||||
* (普通会话 `{kind:'session', sessionId}`;直接子代理会话
|
||||
* `{kind:'subagent', parentSessionId, childSessionId, mode}`)。
|
||||
* @param {object} [options]
|
||||
* @param {(frame: object) => void} [options.onFrame]
|
||||
* @param {(failure: {sessionId: string, code: string, message: string}) => void} [options.onError]
|
||||
*/
|
||||
function follow(sessionId, { onFrame } = {}) {
|
||||
function follow(target, { onFrame, onError } = {}) {
|
||||
ensureAlive()
|
||||
const address = normalizeAddress(target)
|
||||
const sessionId = address.kind === 'subagent' ? address.childSessionId : address.sessionId
|
||||
if (followers.has(sessionId)) return followers.get(sessionId).handle
|
||||
if (typeof controller.follow !== 'function') throw new SessionAdapterError('NO_FOLLOW', 'controller 无 follow')
|
||||
const abort = new AbortController()
|
||||
const handle = { sessionId, stop: () => abort.abort() }
|
||||
const handle = { sessionId, address, stop: () => abort.abort() }
|
||||
const done = (async () => {
|
||||
try {
|
||||
const address = { sessionId }
|
||||
const stream = controller.follow({ address }, abort.signal)
|
||||
for await (const frame of stream) {
|
||||
if (disposed || abort.signal.aborted) break
|
||||
|
|
@ -203,8 +211,23 @@ export function createSessionAdapter(options = {}) {
|
|||
log(`[sansheng-liubu] 处理会话帧失败:${messageOf(error)}`)
|
||||
}
|
||||
}
|
||||
if (!abort.signal.aborted && !disposed) log(`[sansheng-liubu] 会话订阅正常结束:${sessionId}`)
|
||||
} catch (error) {
|
||||
if (!abort.signal.aborted) log(`[sansheng-liubu] 会话流中断:${messageOf(error)}`)
|
||||
if (abort.signal.aborted) {
|
||||
log(`[sansheng-liubu] 会话订阅已取消:${sessionId}`)
|
||||
} else {
|
||||
const failure = {
|
||||
sessionId,
|
||||
code: error?.code ?? (error?.name === 'AbortError' ? 'ABORTED' : 'FOLLOW_FAILED'),
|
||||
message: messageOf(error),
|
||||
}
|
||||
log(`[sansheng-liubu] 会话流中断(${failure.code}):${failure.message}`)
|
||||
try {
|
||||
if (typeof onError === 'function') onError(failure)
|
||||
} catch (handlerError) {
|
||||
log(`[sansheng-liubu] 订阅失败回调异常:${messageOf(handlerError)}`)
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
followers.delete(sessionId)
|
||||
}
|
||||
|
|
@ -245,6 +268,26 @@ export function createSessionAdapter(options = {}) {
|
|||
})
|
||||
}
|
||||
|
||||
function normalizeAddress(target) {
|
||||
if (typeof target === 'string' && target.trim() !== '') return { kind: 'session', sessionId: target }
|
||||
if (target !== null && typeof target === 'object') {
|
||||
if (target.kind === 'subagent'
|
||||
&& typeof target.parentSessionId === 'string'
|
||||
&& typeof target.childSessionId === 'string') {
|
||||
return {
|
||||
kind: 'subagent',
|
||||
parentSessionId: target.parentSessionId,
|
||||
childSessionId: target.childSessionId,
|
||||
mode: ['one-shot', 'continuable', 'unknown'].includes(target.mode) ? target.mode : 'unknown',
|
||||
}
|
||||
}
|
||||
if (typeof target.sessionId === 'string' && target.sessionId !== '') {
|
||||
return { kind: 'session', sessionId: target.sessionId }
|
||||
}
|
||||
}
|
||||
throw new SessionAdapterError('BAD_ADDRESS', '会话订阅需要普通 sessionId 或宿主 SessionAddress')
|
||||
}
|
||||
|
||||
function messageOf(error) {
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ export const WORKBENCH_HOST_VERSION = 1
|
|||
* @param {object} [options.store] 已有 store(测试注入);缺省按环境建一个。
|
||||
* @param {object} [options.service] 已有 service;缺省按 store 新建。给了 service 就必须同时给 store,
|
||||
* 否则两边的账不是同一本。
|
||||
* @param {string} [options.presetId] 部门会话使用的 agentPreset,首版沿用「上朝」。
|
||||
* @param {string} [options.presetId] 部门会话显式使用的 agentPreset;缺省不指定,走宿主默认创建流程。
|
||||
* @param {boolean} [options.startReconciler] 是否启动周期对账,默认 true。
|
||||
*/
|
||||
export function createWorkbenchHost(ctx, options = {}) {
|
||||
|
|
@ -69,9 +69,82 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
reconciler = createReconciler({ store, service, sessions, log })
|
||||
hasSessions = true
|
||||
if (started && options.startReconciler !== false) reconciler.start()
|
||||
followBoundSessions()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* 订阅一个部门会话。subscribe 失败与正常结束分开处理:
|
||||
* - 正常结束/主动取消只记日志;
|
||||
* - 订阅失败把该绑定标成 unavailable,界面会显示“绑定失效,需重新接通”,
|
||||
* 而不是让用户对着一个永远不更新的会话猜。
|
||||
*/
|
||||
function followSession(sessionId) {
|
||||
if (sessions === null || typeof sessionId !== 'string' || sessionId === '') return
|
||||
try {
|
||||
sessions.follow(sessionId, {
|
||||
onFrame: (frame) => {
|
||||
if (reconciler !== null) {
|
||||
void Promise.resolve(reconciler.onSessionFrame({ sessionId })).catch((error) => {
|
||||
log(`[sansheng-liubo] 帧事件对账失败:${error?.message ?? error}`)
|
||||
})
|
||||
}
|
||||
void frame
|
||||
},
|
||||
onError: (failure) => {
|
||||
log(`[sansheng-liubo] 会话 ${failure.sessionId} 订阅失败(${failure.code}):${failure.message}`)
|
||||
markSessionUnavailable(failure.sessionId, failure.message)
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
const code = error?.code ?? 'UNKNOWN'
|
||||
log(`[sansheng-liubo] 无法订阅会话 ${sessionId}(${code}):${error?.message ?? error}`)
|
||||
// 宿主没有 follow 能力是“功能缺席”,不是绑定失效:不要因此标坏部门。
|
||||
if (code !== 'NO_FOLLOW') markSessionUnavailable(sessionId, error?.message ?? String(error))
|
||||
}
|
||||
}
|
||||
|
||||
/** 找到持有该会话的项目/席位,并把绑定状态标成 unavailable。 */
|
||||
function markSessionUnavailable(sessionId, reason) {
|
||||
if (typeof sessionId !== 'string' || sessionId === '') return
|
||||
for (const project of store.listProjects()) {
|
||||
let seats = []
|
||||
try {
|
||||
seats = service.listSeats(project.id)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
for (const seat of seats) {
|
||||
const binding = store.getBinding(project.id, seat.roleId)
|
||||
if (binding?.currentSessionId !== sessionId) continue
|
||||
try {
|
||||
service.setDepartmentStatus({ projectId: project.id, roleId: seat.roleId, status: 'unavailable' })
|
||||
} catch (error) {
|
||||
log(`[sansheng-liubo] 标记 ${seat.roleId} 订阅失败状态被拒:${error?.message ?? error}`)
|
||||
}
|
||||
log(`[sansheng-liubo] 部门 ${seat.roleId} 的会话订阅失败:${reason ?? 'unknown'}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 会话层晚挂或重挂后,把账本里已有的部门绑定重新接上事件流。 */
|
||||
function followBoundSessions() {
|
||||
if (sessions === null) return 0
|
||||
let count = 0
|
||||
for (const project of store.listProjects()) {
|
||||
for (const seat of service.listSeats(project.id)) {
|
||||
const binding = store.getBinding(project.id, seat.roleId)
|
||||
if (binding?.currentSessionId) {
|
||||
followSession(binding.currentSessionId)
|
||||
count += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
if (count > 0) log(`[sansheng-liubo] 已恢复 ${count} 个部门会话订阅`)
|
||||
return count
|
||||
}
|
||||
|
||||
/** 宿主稍后才提供 sessionController 时补挂(不重启也能用)。返回是否挂上。 */
|
||||
function attachSessions(controller) {
|
||||
const mounted = mountSessions(controller ?? null)
|
||||
|
|
@ -81,7 +154,35 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
|
||||
mountSessions(ctx?.sessionController ?? ctx?.remote?.session ?? null)
|
||||
|
||||
const presetId = typeof options.presetId === 'string' && options.presetId !== '' ? options.presetId : 'sansheng-liubu'
|
||||
const presetId = typeof options.presetId === 'string' && options.presetId !== '' ? options.presetId : null
|
||||
|
||||
/**
|
||||
* 显式预设先用宿主公开的 preset 名册校验;名册服务缺席时不假装能验,
|
||||
* 交给 `sessionController.create` 返回它自己的 agent-preset/not-found。
|
||||
*/
|
||||
async function assertAgentPreset(agentPreset) {
|
||||
if (typeof agentPreset !== 'string' || agentPreset.trim() === '') return
|
||||
let presets = null
|
||||
try {
|
||||
presets = typeof ctx?.get === 'function' ? ctx.get('agentPresets') : ctx?.agentPresets
|
||||
} catch {
|
||||
presets = null
|
||||
}
|
||||
if (presets === null || presets === undefined || typeof presets.list !== 'function') return
|
||||
let roster = null
|
||||
try {
|
||||
roster = await presets.list()
|
||||
} catch (error) {
|
||||
log(`[sansheng-liubo] 无法读取宿主预设名册:${error?.message ?? error}`)
|
||||
return
|
||||
}
|
||||
if (!Array.isArray(roster)) return
|
||||
if (!roster.some((row) => row?.id === agentPreset)) {
|
||||
const error = new Error(`指定的预设“${agentPreset}”不存在或未启用`)
|
||||
error.code = 'INVALID_INPUT'
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 接通某个部门的会话:已有绑定就直接用,没有就按 workspace 建一个并登记。
|
||||
|
|
@ -99,12 +200,17 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
const existing = binding?.currentSessionId ?? null
|
||||
if (existing !== null) {
|
||||
const known = await sessions.inspectSession(existing)
|
||||
if (known !== null) return { sessionId: existing, created: false, seat: seatOf(projectId, roleId) }
|
||||
if (known !== null) {
|
||||
followSession(existing)
|
||||
return { sessionId: existing, created: false, seat: seatOf(projectId, roleId) }
|
||||
}
|
||||
}
|
||||
const requestedPreset = input.agentPreset ?? presetId
|
||||
await assertAgentPreset(requestedPreset)
|
||||
const target = await sessions.ensureSession({
|
||||
workspaceId: project?.hostWorkspaceId,
|
||||
sessionId: input.sessionId ?? null,
|
||||
agentPreset: input.agentPreset ?? presetId,
|
||||
agentPreset: requestedPreset,
|
||||
})
|
||||
// 账上登记:同一会话被别的部门占用时 store 会拒绝,正是我们要的“会话独占”。
|
||||
const saved = service.bindDepartmentSession({
|
||||
|
|
@ -113,6 +219,7 @@ export function createWorkbenchHost(ctx, options = {}) {
|
|||
sessionId: target.sessionId,
|
||||
allowReplace: existing !== null,
|
||||
})
|
||||
followSession(target.sessionId)
|
||||
return { sessionId: target.sessionId, created: target.created === true, seat: saved.seat }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,9 @@
|
|||
# dsh-sansheng-liubu-workbench bundle patch
|
||||
#
|
||||
# One insert row loads the package: the host entry is a no-op stub, the
|
||||
# actual feature lives in the web client (./client export, see the `dsh`
|
||||
# manifest in package.json).
|
||||
- insert:
|
||||
- id: dsh-sansheng-liubu-workbench
|
||||
name: 'dsh-sansheng-liubu-workbench'
|
||||
config: {}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
/**
|
||||
* dsh-sansheng-liubu-workbench — 三省六部工作台面板(Web 客户端包)。
|
||||
*
|
||||
* 宿主侧入口只是占位:profile 组合要求 bundles 列表里的每个包都声明
|
||||
* dsh.bundle(补丁层),且补丁行加载的宿主插件就是本文件。面板的实际
|
||||
* 功能全在 Web 客户端(lib/client.js,见 package.json 的 dsh.client)。
|
||||
* 缺了这层声明时,宿主会在启动时以 "declares no dsh.bundle" 跳过本包,
|
||||
* 右侧栏的「朝堂」入口便不会出现。
|
||||
*/
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = 'dsh-sansheng-liubu-workbench'
|
||||
|
||||
/** Plugin body: nothing host-side; the client half does the work. */
|
||||
export function apply(ctx) {}
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
window.__ModuleLoader__.load({
|
||||
id: "dsh-sansheng-liubu-workbench",
|
||||
id: "dsh-sansheng-liubu-mode",
|
||||
factory: (require) => {
|
||||
var module = { exports: {} };
|
||||
var exports = module.exports;
|
||||
|
|
@ -15,7 +15,7 @@ window.__ModuleLoader__.load({
|
|||
const API_BASE = "/sansheng/workbench";
|
||||
const TAB_ID = "sansheng-liubu-workbench";
|
||||
const TAB_KIND = "sansheng-liubu-workbench";
|
||||
const CSS_ID = "dsh-sansheng-liubu-workbench/workbench.css";
|
||||
const CSS_ID = "dsh-sansheng-liubu-mode/workbench.css";
|
||||
const RAIL_WIDTH_KEY = "sansheng.workbench.railWidth";
|
||||
const MAIN_SWITCH_KEY = "sansheng.workbench.main";
|
||||
const RAIL_MIN = 340;
|
||||
|
|
@ -175,16 +175,12 @@ window.__ModuleLoader__.load({
|
|||
|
||||
function pickProjectId(data, hostWorkspaceId) {
|
||||
var projects = data && Array.isArray(data.projects) ? data.projects : [];
|
||||
if (hostWorkspaceId) {
|
||||
for (var i = 0; i < projects.length; i++) {
|
||||
var project = projects[i];
|
||||
if (project && project.hostWorkspaceId === hostWorkspaceId && project.id) return project.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (data && typeof data.projectId === "string" && data.projectId) return data.projectId;
|
||||
for (var j = 0; j < projects.length; j++) {
|
||||
if (projects[j] && projects[j].id) return projects[j].id;
|
||||
// 必须显式给出 hostWorkspaceId 才允许匹配;绝不在缺失时退回 bootstrap
|
||||
// 默认项目或列表第一项——那会把 A 项目的席位/任务显示到 B 工作区。
|
||||
if (typeof hostWorkspaceId !== "string" || hostWorkspaceId === "") return null;
|
||||
for (var i = 0; i < projects.length; i++) {
|
||||
var project = projects[i];
|
||||
if (project && project.hostWorkspaceId === hostWorkspaceId && project.id) return project.id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
|
@ -433,75 +429,102 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
}
|
||||
|
||||
function betterSidebarOf(ctx) {
|
||||
var candidates = [readService(ctx, "betterSidebar"), ctx && ctx.betterSidebar];
|
||||
for (var i = 0; i < candidates.length; i++) {
|
||||
var candidate = candidates[i];
|
||||
if (candidate && typeof candidate.registerTab === "function") return candidate;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function sidebarRightTabsOf(ctx) {
|
||||
var service = readService(ctx, "sidebarRightTabs");
|
||||
if (service && typeof service.register === "function") return service;
|
||||
return null;
|
||||
}
|
||||
|
||||
function effectOf(ctx, factory, label) {
|
||||
if (ctx && typeof ctx.effect === "function") return ctx.effect(factory, label);
|
||||
function workspacesSnapshotOf(ctx) {
|
||||
var service = readService(ctx, "workspaces");
|
||||
var source = service && service.list ? service.list : service;
|
||||
if (!source || typeof source.getSnapshot !== "function") return null;
|
||||
try {
|
||||
return factory();
|
||||
return source.getSnapshot();
|
||||
} catch (error) {
|
||||
console.warn("[sansheng-workbench] " + label + " 注册失败", error);
|
||||
return undefined;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 当前会话的公开来源:`sessions.list` 里保留在 `mainView` 引用源上的
|
||||
* 那一条。当前 DSH 不提供 `SessionListState.current`,也不提供
|
||||
* `uiWorkspace.currentWorkspaceId`/`selection`;这是宿主公开的等价事实。
|
||||
*/
|
||||
function currentSessionIdOf(ctx) {
|
||||
var sessions = readService(ctx, "sessions");
|
||||
var source = sessions && sessions.list ? sessions.list : sessions;
|
||||
if (!source || typeof source.getSnapshot !== "function") return null;
|
||||
try {
|
||||
var snapshot = source.getSnapshot();
|
||||
var byId = snapshot && snapshot.byId ? snapshot.byId : {};
|
||||
var ids = Object.keys(byId);
|
||||
for (var i = 0; i < ids.length; i++) {
|
||||
var row = byId[ids[i]];
|
||||
var retained = row && row.retainedBy ? row.retainedBy.mainView : 0;
|
||||
if (typeof retained === "number" && retained > 0) return ids[i];
|
||||
}
|
||||
} catch (error) {
|
||||
// 服务形状不认识时按“没有明确选择”处理。
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 由明确的会话-工作区关系取当前 workspaceId;空工作区的“新会话”
|
||||
* 在宿主里同样是一个选中的空白会话,因此这里不会回退到首个项目。
|
||||
*/
|
||||
function workspaceIdOf(ctx) {
|
||||
var workspace = ctx && ctx.uiWorkspace;
|
||||
if (!workspace) return null;
|
||||
var direct = workspace.currentWorkspaceId || workspace.workspaceId;
|
||||
if (direct) return String(direct);
|
||||
try {
|
||||
var selection = workspace.selection && typeof workspace.selection.getSnapshot === "function"
|
||||
? workspace.selection.getSnapshot()
|
||||
: null;
|
||||
if (selection && selection.workspaceId) return String(selection.workspaceId);
|
||||
} catch (error) {
|
||||
// 忽略:拿不到工作区就退回 bootstrap 自带 projectId。
|
||||
var snapshot = workspacesSnapshotOf(ctx);
|
||||
if (!snapshot || !Array.isArray(snapshot.items)) return null;
|
||||
var sessionId = currentSessionIdOf(ctx);
|
||||
if (typeof sessionId === "string" && sessionId !== "") {
|
||||
for (var i = 0; i < snapshot.items.length; i++) {
|
||||
var item = snapshot.items[i];
|
||||
if (!item || !Array.isArray(item.sessionIds)) continue;
|
||||
if (item.sessionIds.indexOf(sessionId) !== -1 && item.workspaceId) return String(item.workspaceId);
|
||||
}
|
||||
}
|
||||
// 可选的项目树状态服务(workspace-groups 等):只有它明确给出选择时才采用。
|
||||
var selection = readService(ctx, "workspaceGroupsSelection") || readService(ctx, "workspaceGroups");
|
||||
if (selection && typeof selection.selectedWorkspaceId === "string" && selection.selectedWorkspaceId) {
|
||||
return selection.selectedWorkspaceId;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function workspaceItemOf(ctx, workspaceId) {
|
||||
if (typeof workspaceId !== "string" || workspaceId === "") return null;
|
||||
var snapshot = workspacesSnapshotOf(ctx);
|
||||
if (!snapshot || !Array.isArray(snapshot.items)) return null;
|
||||
for (var i = 0; i < snapshot.items.length; i++) {
|
||||
var item = snapshot.items[i];
|
||||
if (item && String(item.workspaceId) === workspaceId) return item;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function displayNameOf(ctx, workspaceId) {
|
||||
var workspace = ctx && ctx.uiWorkspace;
|
||||
var name = workspace && (workspace.currentWorkspaceName || workspace.workspaceName || workspace.displayName);
|
||||
var workspace = workspaceItemOf(ctx, workspaceId);
|
||||
var name = workspace && workspace.title;
|
||||
if (typeof name === "string" && name) return name;
|
||||
return workspaceId ? "工作区 " + workspaceId : "";
|
||||
}
|
||||
|
||||
function canonicalRootOf(ctx) {
|
||||
var workspace = ctx && ctx.uiWorkspace;
|
||||
var root = workspace && (
|
||||
workspace.currentWorkspaceRoot ||
|
||||
workspace.workspaceRoot ||
|
||||
(workspace.currentWorkspace && workspace.currentWorkspace.root)
|
||||
);
|
||||
function canonicalRootOf(ctx, workspaceId) {
|
||||
var workspace = workspaceItemOf(ctx, workspaceId);
|
||||
var root = workspace && workspace.path;
|
||||
return typeof root === "string" && root ? root : null;
|
||||
}
|
||||
|
||||
async function resolveWorkbenchProject(ctx) {
|
||||
var hostWorkspaceId = workspaceIdOf(ctx);
|
||||
var value = await apiGet("bootstrap");
|
||||
var targetId = pickProjectId(value, hostWorkspaceId);
|
||||
// 没有明确的项目选择:只返回项目清单供界面提示,绝不拿 bootstrap
|
||||
// 默认的第一个项目冒充当前项目。
|
||||
if (!hostWorkspaceId) return { projectId: null, value: value };
|
||||
|
||||
if (hostWorkspaceId && !targetId) {
|
||||
var targetId = pickProjectId(value, hostWorkspaceId);
|
||||
if (!targetId) {
|
||||
var body = {
|
||||
hostWorkspaceId: hostWorkspaceId,
|
||||
displayNameCache: displayNameOf(ctx, hostWorkspaceId),
|
||||
};
|
||||
var root = canonicalRootOf(ctx);
|
||||
var root = canonicalRootOf(ctx, hostWorkspaceId);
|
||||
if (root) body.canonicalRoot = root;
|
||||
|
||||
var created = null;
|
||||
|
|
@ -518,15 +541,15 @@ window.__ModuleLoader__.load({
|
|||
targetId = (created.project && created.project.id) || created.id || targetId;
|
||||
}
|
||||
if (!targetId) {
|
||||
// 登记失败后重新读一次清单再精确匹配;仍无匹配就明确返回“未选择”。
|
||||
value = await apiGet("bootstrap");
|
||||
targetId = pickProjectId(value, hostWorkspaceId) || value.projectId || null;
|
||||
targetId = pickProjectId(value, hostWorkspaceId);
|
||||
}
|
||||
}
|
||||
|
||||
if (targetId && value.projectId !== targetId) {
|
||||
if (!targetId) return { projectId: null, value: value };
|
||||
if (value.projectId !== targetId) {
|
||||
value = await apiGet("bootstrap", { projectId: targetId });
|
||||
}
|
||||
if (!targetId) targetId = value.projectId || null;
|
||||
return { projectId: targetId, value: value };
|
||||
}
|
||||
|
||||
|
|
@ -688,7 +711,7 @@ window.__ModuleLoader__.load({
|
|||
var selector = "style[data-plugin-css=" + JSON.stringify(CSS_ID) + "]";
|
||||
if (typeof document.querySelector === "function" && document.querySelector(selector) !== null) return;
|
||||
var tag = document.createElement("style");
|
||||
tag.dataset.plugin = "dsh-sansheng-liubu-workbench";
|
||||
tag.dataset.plugin = "dsh-sansheng-liubu-mode";
|
||||
tag.dataset.pluginCss = CSS_ID;
|
||||
tag.textContent = CSS;
|
||||
if (document.head && typeof document.head.appendChild === "function") document.head.appendChild(tag);
|
||||
|
|
@ -1145,6 +1168,19 @@ window.__ModuleLoader__.load({
|
|||
projectIdRef.current = result.projectId;
|
||||
seqRef.current = Number(result.value && result.value.eventSeq) || 0;
|
||||
setProjectId(result.projectId);
|
||||
if (!result.projectId) {
|
||||
// 没有明确项目时只保留项目清单;bootstrap 的默认项目数据不能
|
||||
// 被渲染成“当前项目”,否则会误显示/误操作首项目。
|
||||
setData(assign({}, result.value, {
|
||||
projectId: null,
|
||||
project: null,
|
||||
seats: [],
|
||||
tasks: [],
|
||||
artifacts: [],
|
||||
results: [],
|
||||
}));
|
||||
return;
|
||||
}
|
||||
setData(result.value);
|
||||
}
|
||||
|
||||
|
|
@ -1192,14 +1228,17 @@ window.__ModuleLoader__.load({
|
|||
|
||||
function check() {
|
||||
var next = workspaceIdOf(ctx);
|
||||
if (!next || next === hostRef.current) return;
|
||||
if (next === hostRef.current) return;
|
||||
hostRef.current = next;
|
||||
var token = ++pendingToken;
|
||||
var loadToken = ++loadTokenRef.current;
|
||||
setData(null);
|
||||
setProjectId(null);
|
||||
setSelectedArtifactId(null);
|
||||
setNotice(null);
|
||||
setError(null);
|
||||
// No explicit project still re-reads the project list so the UI can
|
||||
// show “select a project”; it never falls back to the first project.
|
||||
resolveWorkbenchProject(ctx).then(function (result) {
|
||||
if (cancelled || token !== pendingToken) return;
|
||||
applyBootstrap(result, loadToken);
|
||||
|
|
@ -1209,16 +1248,25 @@ window.__ModuleLoader__.load({
|
|||
});
|
||||
}
|
||||
|
||||
var selection = workspace.selection;
|
||||
var sessionsService = readService(ctx, "sessions");
|
||||
var workspacesService = readService(ctx, "workspaces");
|
||||
if (sessionsService && sessionsService.list && typeof sessionsService.list.subscribe === "function") {
|
||||
disposers.push(sessionsService.list.subscribe(check));
|
||||
}
|
||||
if (workspacesService && workspacesService.list && typeof workspacesService.list.subscribe === "function") {
|
||||
disposers.push(workspacesService.list.subscribe(check));
|
||||
}
|
||||
// 兼容旧宿主:仍暴露 uiWorkspace 订阅时一并监听。
|
||||
var selection = workspace && workspace.selection;
|
||||
if (selection && typeof selection.subscribe === "function") {
|
||||
var off = selection.subscribe(check);
|
||||
if (typeof off === "function") disposers.push(off);
|
||||
}
|
||||
if (typeof workspace.subscribe === "function") {
|
||||
if (workspace && typeof workspace.subscribe === "function") {
|
||||
var offWorkspace = workspace.subscribe(check);
|
||||
if (typeof offWorkspace === "function") disposers.push(offWorkspace);
|
||||
}
|
||||
if (typeof workspace.on === "function") {
|
||||
if (workspace && typeof workspace.on === "function") {
|
||||
var offEvent = workspace.on("change", check);
|
||||
if (typeof offEvent === "function") disposers.push(offEvent);
|
||||
}
|
||||
|
|
@ -2012,7 +2060,15 @@ window.__ModuleLoader__.load({
|
|||
}
|
||||
|
||||
var content;
|
||||
if (view === "tasks") content = renderTasks();
|
||||
if (!projectId && data !== null) {
|
||||
content = h("div", { className: "wb-empty", role: "status", key: "no-project" }, [
|
||||
h("div", { key: "title" }, "尚未选择工作区项目"),
|
||||
h("div", { key: "detail", style: { marginTop: "6px", color: "var(--wb-ink-3)" } },
|
||||
"请在左侧工作区项目树中选择一个项目(空工作区也可以);未选择项目时不会读取或修改任何项目。"),
|
||||
]);
|
||||
} else if (!projectId) {
|
||||
content = renderCourt();
|
||||
} else if (view === "tasks") content = renderTasks();
|
||||
else if (view === "artifacts") content = renderArtifacts();
|
||||
else content = renderCourt();
|
||||
|
||||
|
|
@ -2059,7 +2115,14 @@ window.__ModuleLoader__.load({
|
|||
? renderFactorySlot(
|
||||
"conversation.content",
|
||||
{ variant: "main", phase: phaseValue, hero: heroValue },
|
||||
{ slots: { widthControls: input.widthControls || {} } },
|
||||
// widthControls 槽要的是组件本身(官方根组件传的是
|
||||
// ConversationWidthControls 函数);宿主没有给真组件时
|
||||
// 宁可不传 slots,让工厂用它自带的 NoConversationWidthControls
|
||||
// 兜底。旧版在这里塞了个空对象 {},工厂把它当组件渲染,
|
||||
// React 抛 #130(element type got: object),中央会话整片白屏。
|
||||
typeof input.widthControls === "function"
|
||||
? { slots: { widthControls: input.widthControls } }
|
||||
: {},
|
||||
)
|
||||
: null,
|
||||
]);
|
||||
|
|
@ -2149,41 +2212,166 @@ window.__ModuleLoader__.load({
|
|||
// 注册
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
function entryDiagnostic(level, message) {
|
||||
try {
|
||||
if (level === "error") console.error("[sansheng-workbench][entry] " + message);
|
||||
else if (level === "info") console.info("[sansheng-workbench][entry] " + message);
|
||||
else console.warn("[sansheng-workbench][entry] " + message);
|
||||
} catch (ignored) {
|
||||
// 日志失败不能影响入口。
|
||||
}
|
||||
}
|
||||
|
||||
/** 把一次注册托管给 ctx.effect;没有 effect 的宿主/测试直接返回 disposer。 */
|
||||
function ownRegistration(ctx, factory, label) {
|
||||
if (ctx && typeof ctx.effect === "function") {
|
||||
var dispose = ctx.effect(factory, label);
|
||||
return typeof dispose === "function" ? dispose : function () {};
|
||||
}
|
||||
try {
|
||||
var value = factory();
|
||||
return typeof value === "function" ? value : function () {};
|
||||
} catch (error) {
|
||||
entryDiagnostic("error", label + " 注册失败:" + (error && error.message ? error.message : error));
|
||||
return function () {};
|
||||
}
|
||||
}
|
||||
|
||||
function registerBetterEntry(ctx, better) {
|
||||
return ownRegistration(ctx, function () {
|
||||
return better.registerTab({
|
||||
id: TAB_ID,
|
||||
title: "朝堂",
|
||||
description: "三省六部 · 十席部门树",
|
||||
order: 5,
|
||||
single: true,
|
||||
component: function (props) {
|
||||
return h(WorkbenchPanel, { ctx: ctx, scope: props && props.scope });
|
||||
},
|
||||
});
|
||||
}, "三省六部工作台:better-sidebar 页签");
|
||||
}
|
||||
|
||||
function registerNativeEntry(ctx, tabs) {
|
||||
return ownRegistration(ctx, function () {
|
||||
return tabs.register({
|
||||
id: TAB_ID,
|
||||
kind: TAB_KIND,
|
||||
priority: "builtin",
|
||||
title: function () {
|
||||
return "朝堂";
|
||||
},
|
||||
// 原生右栏的 guide 是首次进入的唯一入口:没有它时页签类型虽注册,
|
||||
// 用户也找不到可点的“朝堂”胶囊。guide 与 title 保持同一文案。
|
||||
guide: [{
|
||||
id: TAB_ID,
|
||||
order: 5,
|
||||
title: function () {
|
||||
return "朝堂";
|
||||
},
|
||||
description: function () {
|
||||
return "三省六部 · 十席部门树";
|
||||
},
|
||||
}],
|
||||
});
|
||||
}, "三省六部工作台:原生右侧栏页签");
|
||||
}
|
||||
|
||||
/**
|
||||
* 入口注册控制器:betterSidebar 与原生 sidebarRightTabs 都按服务生命周期
|
||||
* 监听。任一时刻只保留一个活动入口;服务消失后自动清理,服务晚到/重挂
|
||||
* 时重新注册,绝不重复叠加。
|
||||
*/
|
||||
function createEntryController(ctx) {
|
||||
var better = null;
|
||||
var nativeTabs = null;
|
||||
var active = null;
|
||||
|
||||
function disposeActive() {
|
||||
if (active === null) return;
|
||||
var dispose = active.dispose;
|
||||
active = null;
|
||||
try {
|
||||
if (typeof dispose === "function") dispose();
|
||||
} catch (error) {
|
||||
entryDiagnostic("error", "清理旧入口失败:" + (error && error.message ? error.message : error));
|
||||
}
|
||||
}
|
||||
|
||||
function reconcile() {
|
||||
var wanted = better !== null
|
||||
? { kind: "better", service: better }
|
||||
: nativeTabs !== null
|
||||
? { kind: "native", service: nativeTabs }
|
||||
: null;
|
||||
if (wanted === null) {
|
||||
disposeActive();
|
||||
entryDiagnostic("warn", "betterSidebar / sidebarRightTabs 均未就绪,等待服务");
|
||||
return;
|
||||
}
|
||||
if (active !== null && active.kind === wanted.kind && active.service === wanted.service) return;
|
||||
disposeActive();
|
||||
try {
|
||||
var dispose = wanted.kind === "better"
|
||||
? registerBetterEntry(ctx, wanted.service)
|
||||
: registerNativeEntry(ctx, wanted.service);
|
||||
active = { kind: wanted.kind, service: wanted.service, dispose: typeof dispose === "function" ? dispose : function () {} };
|
||||
entryDiagnostic("info", "已注册朝堂入口(" + (wanted.kind === "better" ? "betterSidebar" : "原生 sidebarRightTabs") + ")");
|
||||
} catch (error) {
|
||||
active = null;
|
||||
entryDiagnostic("error", "朝堂入口注册失败:" + (error && error.message ? error.message : error));
|
||||
}
|
||||
}
|
||||
|
||||
function setBetter(service) {
|
||||
better = service !== null && service !== undefined && typeof service.registerTab === "function" ? service : null;
|
||||
reconcile();
|
||||
}
|
||||
|
||||
function setNativeTabs(service) {
|
||||
nativeTabs = service !== null && service !== undefined && typeof service.register === "function" ? service : null;
|
||||
reconcile();
|
||||
}
|
||||
|
||||
return {
|
||||
setBetter: setBetter,
|
||||
setNativeTabs: setNativeTabs,
|
||||
reconcile: reconcile,
|
||||
dispose: disposeActive,
|
||||
get activeKind() {
|
||||
return active === null ? null : active.kind;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function watchClientService(ctx, name, setter) {
|
||||
if (ctx && typeof ctx.inject === "function") {
|
||||
try {
|
||||
ctx.inject([name], function (scope) {
|
||||
setter(readService(scope, name));
|
||||
return function () {
|
||||
setter(null);
|
||||
};
|
||||
});
|
||||
return;
|
||||
} catch (error) {
|
||||
entryDiagnostic("error", "监听服务 " + name + " 失败:" + (error && error.message ? error.message : error));
|
||||
}
|
||||
}
|
||||
// 旧宿主或测试替身没有 ctx.inject:退化为一次同步探测。
|
||||
setter(readService(ctx, name));
|
||||
}
|
||||
|
||||
function apply(ctx) {
|
||||
if (!ctx) throw new Error("三省六部工作台需要宿主上下文");
|
||||
|
||||
// 1) 右侧栏页签「朝堂」:优先 better-sidebar 的 registerTab。
|
||||
var better = betterSidebarOf(ctx);
|
||||
if (better) {
|
||||
effectOf(ctx, function () {
|
||||
return better.registerTab({
|
||||
id: TAB_ID,
|
||||
title: "朝堂",
|
||||
description: "三省六部 · 十席部门树",
|
||||
order: 5,
|
||||
single: true,
|
||||
component: function (props) {
|
||||
return h(WorkbenchPanel, { ctx: ctx, scope: props && props.scope });
|
||||
},
|
||||
});
|
||||
}, "三省六部工作台:better-sidebar 页签");
|
||||
} else {
|
||||
var tabs = sidebarRightTabsOf(ctx);
|
||||
if (tabs) {
|
||||
effectOf(ctx, function () {
|
||||
return tabs.register({
|
||||
id: TAB_ID,
|
||||
kind: TAB_KIND,
|
||||
priority: "builtin",
|
||||
title: function () {
|
||||
return "朝堂";
|
||||
},
|
||||
});
|
||||
}, "三省六部工作台:右侧栏页签");
|
||||
} else {
|
||||
console.warn("[sansheng-workbench] 宿主没有 betterSidebar / sidebarRightTabs,页签可能无法停靠;pane 槽仍会注册。");
|
||||
}
|
||||
}
|
||||
// 1) 右侧栏页签「朝堂」:服务生命周期驱动注册。
|
||||
// 优先 better-sidebar;没有时用原生 sidebarRightTabs(含 guide 入口)。
|
||||
// 两条路径由同一个控制器互斥,服务重挂不会重复注册。
|
||||
var entry = createEntryController(ctx);
|
||||
watchClientService(ctx, "betterSidebar", entry.setBetter);
|
||||
watchClientService(ctx, "sidebarRightTabs", entry.setNativeTabs);
|
||||
entry.reconcile();
|
||||
|
||||
// 2) 页签内容 + 标题:即使上面没有服务也注册,宿主若按槽渲染仍可用。
|
||||
if (ctx.slots && typeof ctx.slots.inject === "function") {
|
||||
|
|
@ -2203,18 +2391,28 @@ window.__ModuleLoader__.load({
|
|||
// 逃生开关:localStorage["sansheng.workbench.main"] = "off" 时跳过本段。
|
||||
if (mainTakeoverEnabled() && ctx.slots && typeof ctx.slots.inject === "function") {
|
||||
ctx.slots.inject("main.conversation", function () {
|
||||
return ctx.slots.register({
|
||||
name: "main.conversation",
|
||||
priority: -1,
|
||||
children: {
|
||||
"conversation.header": { kind: "single", scope: "session-maybe" },
|
||||
},
|
||||
}, createConversationMain(ctx));
|
||||
try {
|
||||
return ctx.slots.register({
|
||||
name: "main.conversation",
|
||||
priority: -1,
|
||||
children: {
|
||||
"conversation.header": { kind: "single", scope: "session-maybe" },
|
||||
},
|
||||
}, createConversationMain(ctx));
|
||||
} catch (error) {
|
||||
// 官方会话入口已声明 conversation.header:重复声明会被宿主拒绝,
|
||||
// 退回不带 children 的注册——槽本身由官方入口声明、仍然存在,
|
||||
// 组件里的 renderSlot("conversation.header") 照常工作。
|
||||
return ctx.slots.register({
|
||||
name: "main.conversation",
|
||||
priority: -1,
|
||||
}, createConversationMain(ctx));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
exports.inject = ["slots", "sessions", "uiWorkspace", "uiConversation"];
|
||||
exports.inject = ["slots", "sessions", "workspaces", "uiWorkspace", "uiConversation"];
|
||||
exports.apply = apply;
|
||||
exports.WorkbenchRail = WorkbenchRail;
|
||||
exports.WorkbenchPanel = WorkbenchPanel;
|
||||
|
|
@ -2225,6 +2423,8 @@ window.__ModuleLoader__.load({
|
|||
mergeEvents: mergeEvents,
|
||||
apiPath: apiPath,
|
||||
pickProjectId: pickProjectId,
|
||||
workspaceIdOf: workspaceIdOf,
|
||||
currentSessionIdOf: currentSessionIdOf,
|
||||
formatModelLine: formatModelLine,
|
||||
seatDisplayName: seatDisplayName,
|
||||
modelTitle: modelTitle,
|
||||
|
|
|
|||
|
|
@ -1,26 +1,10 @@
|
|||
{
|
||||
"name": "dsh-sansheng-liubu-workbench",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "三省六部工作台:右侧朝堂部门树、任务与成果",
|
||||
"name": "dsh-sansheng-liubu-mode-panel-source",
|
||||
"version": "0.14.0",
|
||||
"description": "三省六部工作台面板源码(已并入 dsh-sansheng-liubu-mode,不是独立安装包)",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
"./client": "./lib/client.js"
|
||||
},
|
||||
"private": true,
|
||||
"files": [
|
||||
"lib/**"
|
||||
],
|
||||
"dsh": {
|
||||
"client": {
|
||||
"platform": "web",
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-api-session-controller",
|
||||
"@deepseek-ai/dsh-client-ui-workspace",
|
||||
"@deepseek-ai/dsh-client-ui-primitives"
|
||||
]
|
||||
}
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/cordis": "~4.0.5"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
File diff suppressed because one or more lines are too long
|
|
@ -1,7 +1,7 @@
|
|||
import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
// node_modules/js-yaml/dist/js-yaml.mjs
|
||||
// node_modules/.pnpm/js-yaml@4.3.2/node_modules/js-yaml/dist/js-yaml.mjs
|
||||
function getDefaultExportFromCjs(x) {
|
||||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,16 +14,32 @@
|
|||
* relies on the DSH-branch schemastery `.volatile()` marker, which a
|
||||
* bundled private copy would not share with the Loader.
|
||||
*
|
||||
* Row config nests per plugin: { remoteSsh: { ... } } reaches the
|
||||
* remote-ssh plugin; the groups half takes no row config. (Remote-ssh
|
||||
* connection profiles live in the DSH settings namespace `dsh-remote-ssh`
|
||||
* either way — merging changes nothing about stored data.)
|
||||
* The bundle row's config IS the remote-ssh prefs object: the composed
|
||||
* plugin exports remote-ssh's Config schema (below), so this row owns the
|
||||
* settings entry the remote-ssh settings face reads and writes (its entry
|
||||
* id resolves to this bundle's row — see the settings patch in
|
||||
* scripts/patch-remote-ssh.mjs). The groups half takes no row config.
|
||||
* (Pre-1.0.2 the row config nested under a `remoteSsh` key and the face
|
||||
* looked for a `dsh-remote-ssh` entry that a merged install does not
|
||||
* have, so saving any connection failed with "No configurable plugin
|
||||
* entry". No bundle-era data was ever stored in the nested shape —
|
||||
* saving was impossible — so flattening loses nothing.)
|
||||
*/
|
||||
import * as groups from './groups.js'
|
||||
import * as remoteSsh from './remote-ssh/index.js'
|
||||
|
||||
const groupsPlugin = { name: groups.name, inject: groups.inject, apply: groups.apply }
|
||||
const remoteSshPlugin = { name: remoteSsh.name, inject: remoteSsh.inject, Config: remoteSsh.Config, apply: remoteSsh.apply }
|
||||
// NOTE (1.0.3): the child plugin object must NOT carry its own Config.
|
||||
// When both this composed plugin (top-level `export const Config` below)
|
||||
// and the child declare the same schemastery Config, the child's fiber
|
||||
// silently never applies on DSH 0.2.2-rc.2 — the remote half stays dead
|
||||
// (no wrapper write, no /remote-ssh/api routes) while groups works.
|
||||
// Verified by A/B on a clean profile: 1.0.1 (no top-level Config) fine,
|
||||
// 1.0.2 (both Configs) remote dead, top-level-only Config fine — and the
|
||||
// settings face only needs the ENTRY, which the top-level export owns;
|
||||
// it resolves the entry id to this bundle's row (patch 11), never to the
|
||||
// child's own Cordis config.
|
||||
const remoteSshPlugin = { name: remoteSsh.name, inject: remoteSsh.inject, apply: remoteSsh.apply }
|
||||
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export const name = 'workspace-groups-remote'
|
||||
|
|
@ -31,12 +47,14 @@ export const name = 'workspace-groups-remote'
|
|||
/** Services required before mounting (union of both halves). */
|
||||
export const inject = ['webServer', 'subprocess', 'tools', 'workspaceRegistry']
|
||||
|
||||
/** The row's settings schema: remote-ssh's own Config (prefs object). */
|
||||
export const Config = remoteSsh.Config
|
||||
|
||||
/** Plugin body: mount both halves on this fiber. */
|
||||
export function apply(ctx, config = {}) {
|
||||
const remoteSshConfig = config?.remoteSsh ?? {}
|
||||
if (typeof remoteSshConfig !== 'object' || remoteSshConfig === null || Array.isArray(remoteSshConfig)) {
|
||||
throw new Error('workspace-groups-remote: the remoteSsh row config must be an object (it is passed through to @zhangfengshun/dsh-remote-ssh)')
|
||||
if (typeof config !== 'object' || config === null || Array.isArray(config)) {
|
||||
throw new Error('workspace-groups-remote: the row config must be an object (it is the @zhangfengshun/dsh-remote-ssh prefs object)')
|
||||
}
|
||||
ctx.plugin(groupsPlugin)
|
||||
ctx.plugin(remoteSshPlugin, remoteSshConfig)
|
||||
ctx.plugin(remoteSshPlugin, config)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1057,17 +1057,20 @@ function expandRemoteHome(path, home) {
|
|||
}
|
||||
|
||||
/**
|
||||
* Resolve a remote path to its canonical absolute form via one SSH round
|
||||
* trip (also learns the remote $HOME). Returns { canonical, home }; on any
|
||||
* failure canonical falls back to the home-expanded light form and the
|
||||
* caller proceeds exactly as upstream would (fail-open).
|
||||
* Resolve a remote path to its canonical absolute identity through one SSH
|
||||
* round trip (also learns the remote $HOME). Returns a discriminated result:
|
||||
* ok:false is NOT "not a duplicate" — the caller must refuse to create
|
||||
* because it cannot prove the path is distinct.
|
||||
*/
|
||||
async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
||||
const light = lightRemotePath(rawPath);
|
||||
if (!light) return { ok: false, error: "remotePath 为空", home: "" };
|
||||
try {
|
||||
const cmd = "printf '__DSH_HOME__%s\n' \"$HOME\"; cd " + shellQuotePath(light) + " 2>/dev/null && pwd -P";
|
||||
const r = await runRemote(subprocess, p, cmd, undefined, 64 * 1024, undefined, 15000);
|
||||
if (!r || !r.ok || !r.stdout) return { canonical: light, home: "" };
|
||||
if (!r || !r.ok) {
|
||||
return { ok: false, error: String((r && (r.error || r.stderr)) || "SSH 解析失败").trim() || "SSH 解析失败", home: "" };
|
||||
}
|
||||
let home = "";
|
||||
let resolved = "";
|
||||
const lines = String(r.stdout).split("\n");
|
||||
|
|
@ -1076,10 +1079,14 @@ async function resolveRemoteCanonical(subprocess, p, rawPath) {
|
|||
if (t.startsWith("__DSH_HOME__")) home = t.slice("__DSH_HOME__".length).trim();
|
||||
else if (t.startsWith("/")) resolved = t;
|
||||
}
|
||||
if (!resolved) return { canonical: expandRemoteHome(light, home), home: home };
|
||||
return { canonical: lightRemotePath(resolved), home: home };
|
||||
if (!resolved) {
|
||||
// cd failed (missing directory / permission / shell error): identity is
|
||||
// unknown, never silently treated as a new directory.
|
||||
return { ok: false, error: "无法解析远端目录(不存在或不可访问):" + light, home: home };
|
||||
}
|
||||
return { ok: true, canonical: lightRemotePath(resolved), home: home };
|
||||
} catch (e) {
|
||||
return { canonical: light, home: "" };
|
||||
return { ok: false, error: String(e && e.message ? e.message : e), home: "" };
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -4452,7 +4459,11 @@ function apply(ctx, config) {
|
|||
const rawConfig = config && typeof config === "object" ? config : {};
|
||||
|
||||
// ---- 先判断这一代 settings 用哪套 API(issue #34:0.1.5/0.1.6 两套都有)----
|
||||
const entryId = ownEntryId(ctx, name) || NS;
|
||||
// [workspace-groups-remote patch] Inside the merged bundle there is no
|
||||
// loader row named dsh-remote-ssh: the settings entry lives on the
|
||||
// bundle's own row, whose composed plugin exports this plugin's Config.
|
||||
// Resolve that row before falling back to the standalone namespace.
|
||||
const entryId = ownEntryId(ctx, name) || ownEntryId(ctx, "workspace-groups-remote") || NS;
|
||||
const settingsApi = settingsApiMode(svc, entryId);
|
||||
|
||||
// ---- 新版(0.1.7-rc.2+):数据在本插件 loader 行的 Config 里 ----
|
||||
|
|
@ -4925,25 +4936,47 @@ function apply(ctx, config) {
|
|||
// (或宿主重启丢了原生注册的那一条)必须在这里被"接管",而不是再造一条 ——
|
||||
// 否则设置面板里会出现两条一模一样的工作区,删其中一条还会连带删掉另一条的会话行。
|
||||
const prefsNow = settingsFace.read();
|
||||
// [workspace-groups-remote patch] Canonical-path reuse: compare
|
||||
// light-normalized spellings first; on a miss, resolve once over SSH
|
||||
// (fail-open) and compare canonical forms, so ~/x, x/ and the absolute
|
||||
// form of one directory all reuse the existing record instead of
|
||||
// registering a duplicate workspace + mirror. The stored spelling
|
||||
// converges to the matched/canonical form below.
|
||||
let existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && lightRemotePath(w.remotePath) === lightRemotePath(a.remotePath));
|
||||
if (existing) {
|
||||
a.remotePath = lightRemotePath(a.remotePath);
|
||||
} else {
|
||||
const resolvedCanonical = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
a.remotePath = resolvedCanonical.canonical;
|
||||
existing = prefsNow.workspaces.find((w) => w && w.profileId === a.profileId && expandRemoteHome(lightRemotePath(w.remotePath), resolvedCanonical.home) === resolvedCanonical.canonical);
|
||||
// [workspace-groups-remote patch] Canonical-path reuse: resolve the new
|
||||
// spelling once over SSH and resolve every existing record of the same
|
||||
// connection with the same rule (light form + remote $HOME + pwd -P),
|
||||
// so relative/~, trailing-slash and symlink spellings converge on one
|
||||
// directory identity. A resolution failure is NOT "not a duplicate":
|
||||
// creation is refused with an actionable error instead of silently
|
||||
// registering a second workspace.
|
||||
const targetResolved = await resolveRemoteCanonical(subprocess, p, a.remotePath);
|
||||
if (targetResolved.ok !== true) {
|
||||
return { ok: false, error: "无法确认远端路径是否重复:" + targetResolved.error + ";未创建新工作区" };
|
||||
}
|
||||
const sameProfile = prefsNow.workspaces.filter((w) => w && w.profileId === a.profileId && typeof w.remotePath === "string");
|
||||
let existing = undefined;
|
||||
for (const record of sameProfile) {
|
||||
const light = lightRemotePath(record.remotePath);
|
||||
// Fast path: the spelling expands to exactly the resolved target.
|
||||
if (expandRemoteHome(light, targetResolved.home) === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
// Slow path: resolve the old record with the SAME rules. This catches
|
||||
// relative paths, symlinks and historical spellings the old partial
|
||||
// expansion missed. A failure aborts instead of assuming uniqueness.
|
||||
const candidate = await resolveRemoteCanonical(subprocess, p, record.remotePath);
|
||||
if (candidate.ok !== true) {
|
||||
return { ok: false, error: "无法确认是否与已有远程工作区「" + String(record.title || record.id) + "」重复:" + candidate.error + ";未创建新工作区" };
|
||||
}
|
||||
if (candidate.canonical === targetResolved.canonical) {
|
||||
existing = record;
|
||||
break;
|
||||
}
|
||||
}
|
||||
a.remotePath = existing ? String(existing.remotePath) : targetResolved.canonical;
|
||||
const wsId = existing ? existing.id : ("w" + Date.now().toString(36) + Math.random().toString(36).slice(2, 6));
|
||||
// 默认标题取远程路径最后一段目录名(如 ~/proj/DSH_Test → DSH_Test);
|
||||
// 取不到有效段(如 ~/ 或 /)时回退为 连接名:远程路径。
|
||||
// [workspace-groups-remote patch] Reuse keeps the user's existing
|
||||
// title; only a new record (or an explicit a.title) derives one from
|
||||
// the path. Otherwise "reuse" could silently rename a custom workspace.
|
||||
const lastSeg = String(a.remotePath).replace(/\/+$/, "").split("/").pop();
|
||||
const title = a.title || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));
|
||||
const title = a.title || (existing && existing.title) || (lastSeg && lastSeg !== "~" ? lastSeg : (p.name + ":" + a.remotePath));
|
||||
// 本地镜像目录:作为原生工作区注册进 workspaceRegistry,会话 cwd 即指向它。
|
||||
// 根目录走 mirrorBaseDir()(与 fs 处理器的镜像判定同一处,避免两处各写一遍后漂移)。
|
||||
// 复用旧条目时沿用它原来的镜像目录 —— 里面可能有用户没推回去的本地改动。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* Attribute the tree puts on every row the branch should connect. */
|
||||
export declare const BRANCH_ROW_ATTRIBUTE = "data-wg-branch-row";
|
||||
/**
|
||||
* Attribute marking the row the stem should grow to.
|
||||
*
|
||||
* Only the DEEPEST row gets this (the session). Its ancestors — the project and
|
||||
* the category that contain it — deliberately do NOT, because a session belongs
|
||||
* to both and marking all three would make "which row is active?" ambiguous.
|
||||
* When several rows do carry it, the deepest (last in document order) wins.
|
||||
*/
|
||||
export declare const BRANCH_ACTIVE_ATTRIBUTE = "data-wg-branch-active";
|
||||
/** Row kind marker: a group boundary kinks the stem. */
|
||||
export declare const BRANCH_GROUP_ATTRIBUTE = "data-wg-branch-group";
|
||||
/**
|
||||
* The bloom at the branch's endpoint.
|
||||
*
|
||||
* Anchoring is done entirely by these transforms, in this order:
|
||||
*
|
||||
* 1. `translate(cx cy)` — put the origin on the stem's tip (the endpoint of
|
||||
* the grown stroke).
|
||||
* 2. `scale(FLOWER_SCALE)` — shrink the 1024-unit artwork about that origin.
|
||||
* 3. `translate(-512 -512)` — bring the glyph's own centre (512, 512) onto the
|
||||
* origin, so the flower is centred on the tip.
|
||||
*
|
||||
* The spin is applied by `wgFlowerArt` in CSS as a `rotate()` composed AFTER
|
||||
* that recentring (`translate(-512 -512) rotate(...)`), so the bloom turns about
|
||||
* its own centre and the recentring never drifts as it rotates.
|
||||
*
|
||||
* Note what is deliberately NOT used here: a percentage `translate(-50%, -50%)`
|
||||
* or `transform-box: fill-box` + percentage `transform-origin`. Measured on the
|
||||
* live page, the percentage form resolved against the SVG VIEWPORT rather than
|
||||
* the path's box, translating by (-24, -409.5) instead of (-373, -409.6) and
|
||||
* parking the bloom well right of the stem. Explicit user units remove the
|
||||
* question: 512 is the measured centre, not an inferred one.
|
||||
*
|
||||
* The flower rests while the session is idle and turns while it works: one
|
||||
* animation, paused rather than removed, so a state flip resumes the turn
|
||||
* instead of snapping the petals back to 0deg.
|
||||
*
|
||||
* @param props - endpoint coordinates and whether the session is working.
|
||||
* @returns the bloom group.
|
||||
*/
|
||||
/** In-flow session marker: its position follows the row, including disclosure animations. */
|
||||
export declare function SessionFlower({ spinning }: {
|
||||
spinning: boolean;
|
||||
}): import("react").JSX.Element;
|
||||
/**
|
||||
* Render the branch for the rows currently inside `scope`.
|
||||
* @param props - the element to measure, and whether the open session is working.
|
||||
* @returns the SVG overlay, or null until at least one row is measured.
|
||||
*/
|
||||
export declare function FlowerBranch({ scope, spinning }: {
|
||||
scope: HTMLElement | null;
|
||||
spinning: boolean;
|
||||
}): import("react").JSX.Element | null;
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import { type WorkspaceFolderEntry } from '../core/folders.ts';
|
||||
import type { GroupsBrowserProps } from './contract.ts';
|
||||
import { type RemoteProfileSummary } from './folder-directory.ts';
|
||||
export declare function FoldersDialog({ workspace, entry, t, busy, canOpen, remote, ownerRemotePath, profiles, profilesError, knownWorkspaceIds, onClose, onAddFolder, onAddRemote, onAddSubpath, onSetRoot, onRemove, onOpenFolder }: {
|
||||
workspace: WorkspaceView;
|
||||
entry: WorkspaceFolderEntry | undefined;
|
||||
t: GroupsBrowserProps['t'];
|
||||
busy: boolean;
|
||||
canOpen: boolean;
|
||||
/** Remote (mirror-backed) workspace: extra folders can also be typed subpaths. */
|
||||
remote: boolean;
|
||||
/** Remote root of a cloud owner, so a browsed subdirectory joins as a subfolder. */
|
||||
ownerRemotePath: string | null;
|
||||
/** SSH connections, `null` while loading or when the remote-ssh plugin is absent. */
|
||||
profiles: readonly RemoteProfileSummary[] | null;
|
||||
profilesError: string | null;
|
||||
/** Live workspace ids, so a member whose workspace is gone can say so. */
|
||||
knownWorkspaceIds: readonly string[];
|
||||
onClose: () => void;
|
||||
/** Pick any directory (local or an already-mirrored cloud folder). */
|
||||
onAddFolder: () => void;
|
||||
/** Register one cloud folder: returns true once it is stored. */
|
||||
onAddRemote: (profileId: string, remotePath: string) => Promise<boolean>;
|
||||
onAddSubpath: (relative: string) => Promise<boolean>;
|
||||
onSetRoot: (path: string) => void;
|
||||
onRemove: (path: string, deleteRecord: boolean) => void;
|
||||
onOpenFolder: (path: string) => void;
|
||||
}): import("react").JSX.Element;
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
import type { GroupsBrowserProps } from './contract.ts';
|
||||
/** Row reference used by drop targets: which kind of row, which key. */
|
||||
export type DropRowRef = {
|
||||
kind: 'category' | 'workspace' | 'topLevel';
|
||||
key: string;
|
||||
};
|
||||
/**
|
||||
* Which level's rows fold while a drag is in progress: dragging a project
|
||||
* folds every project row (grouped AND top-level), dragging a group folds
|
||||
* every group row. The other level keeps its expansion untouched.
|
||||
*/
|
||||
export type DragLevel = 'workspace' | 'category' | null;
|
||||
/**
|
||||
* Current drop indicator. A `line` renders a 2px insertion line above/below a
|
||||
* row (project reorder inside a group, or group reorder); an `into` renders
|
||||
* the whole-row highlight used when dropping a project into a group. Drop
|
||||
* handlers re-derive before/after from the drop event itself, so the
|
||||
* indicator is purely visual and can never go stale.
|
||||
*/
|
||||
export type DragIndicator = {
|
||||
mode: 'line';
|
||||
row: DropRowRef;
|
||||
before: boolean;
|
||||
} | {
|
||||
mode: 'into';
|
||||
categoryKey: string;
|
||||
} | null;
|
||||
/**
|
||||
* 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, useSessionStatus, useStore, actions, startSession, createSessionIn, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, pickDirectory, getDirectoryFlow, createDirectory, searchSessions, searchResultLimit, openTab, useTabs, tabActions, t, }: GroupsBrowserProps): import("react").JSX.Element;
|
||||
|
|
@ -0,0 +1,38 @@
|
|||
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { SessionListState } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
/** Which surface of the quick panel is active. */
|
||||
export type QuickTab = 'workspaces' | 'sessions';
|
||||
/** The locale seat's translate function (same shape GroupsBrowser receives). */
|
||||
type Translate = PropsLocale<'workspaceGroups'>['t'];
|
||||
/** Quick panel props: hooks snapshots + the two injected verbs + shared CSS context. */
|
||||
export type QuickPanelProps = {
|
||||
/** Close request (Escape, mask click, action completed, or parent Ctrl+R toggle). */
|
||||
onClose: () => void;
|
||||
/** Sessions list snapshot (drives running detection). */
|
||||
list: SessionListState;
|
||||
/** Real workspaces in stable Host order. */
|
||||
workspaces: readonly WorkspaceView[];
|
||||
/** Registry-global archive set. */
|
||||
archivedSessionIds: readonly SessionId[];
|
||||
/** Category label per grouped workspace id (badge column; top-level absent). */
|
||||
categoryByWorkspace: ReadonlyMap<string, string>;
|
||||
/** The Session the Conversation currently shows (mainView retention), if any. */
|
||||
current: SessionId | undefined;
|
||||
/** Start a New Session in a workspace (injected share verb). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/** Open a real Session (injected share verb). */
|
||||
openSession: (sessionId: SessionId) => void;
|
||||
/** Render clock for relative times (parent refreshes per render). */
|
||||
now: number;
|
||||
/** Dictionary accessor (workspaceGroups namespace). */
|
||||
t: Translate;
|
||||
};
|
||||
/**
|
||||
* Render the quick switch panel (portaled overlay).
|
||||
* @param props - hooks snapshots + injected verbs.
|
||||
* @returns the panel element tree.
|
||||
*/
|
||||
export declare function QuickPanel({ onClose, list, workspaces, archivedSessionIds, categoryByWorkspace, current: currentSessionId, startSession, openSession, now, t, }: QuickPanelProps): import("react").ReactPortal;
|
||||
export {};
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { SessionsTabsProps } from './contract.ts';
|
||||
/**
|
||||
* Render the session tab strip into the conversation column's head seat.
|
||||
* @param props - tab store, catalog/status hooks, navigation, locale.
|
||||
* @returns the portal (or null until the column has mounted).
|
||||
*/
|
||||
export declare function SessionTabs({ useTabs, actions, useSessions, useSessionStatus, useWorkspaces, activate, rename, t, }: SessionsTabsProps): import("react").ReactPortal | null;
|
||||
|
|
@ -0,0 +1,140 @@
|
|||
/**
|
||||
* The "flower branch" geometry for the sidebar tree.
|
||||
*
|
||||
* Reproduces the RewampUI *Flower Sidebar* mechanism: a single curly branch runs
|
||||
* down the left of the nav list, drawn as SVG so it can be *grown* — a faded
|
||||
* dashed ghost shows the whole route, and a solid stroke is drawn only as far as
|
||||
* the row you are on. Each row gets a dot sitting exactly on the curve, and the
|
||||
* active row's dot blooms.
|
||||
*
|
||||
* How it maps onto OUR tree (three levels: 分组 folder → 项目 folder → 会话 row):
|
||||
*
|
||||
* - The branch is **one continuous path** through every visible row, not one
|
||||
* rail per folder. That is what makes it read as a plant rather than as the
|
||||
* per-folder rail it replaces.
|
||||
* - The stem runs at `STEM_X`; at each **group boundary** it kinks outward to
|
||||
* `BULGE_X` and back — a half-pitch out plus a half-pitch back, which is
|
||||
* exactly the reference's 32px rhythm.
|
||||
* - Rows that are not group boundaries sit on a straight run, one row pitch
|
||||
* apart, each carrying a dot at its own y.
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `tabs.ts` / `store-core.ts`): the
|
||||
* component measures the DOM and hands plain numbers here, so the geometry is
|
||||
* unit-testable without a browser.
|
||||
*/
|
||||
/** Horizontal position of the stem's straight runs. */
|
||||
/**
|
||||
* Default x for a row's anchor, in SVG coordinates.
|
||||
*
|
||||
* A fallback only: rows carry their OWN measured `x`, because the tree indents
|
||||
* with per-row padding rather than one shared origin. A folder's chevron and a
|
||||
* session's text sit at different x, and no single constant lands on both.
|
||||
*/
|
||||
export declare const STEM_X = 30;
|
||||
/** Default vertical pitch between two rows. */
|
||||
export declare const ROW_PITCH = 32;
|
||||
/**
|
||||
* One row the branch must pass through.
|
||||
*
|
||||
* Both coordinates are MEASURED, not derived:
|
||||
* - `y` because the tree mixes row heights and inter-row gaps (deriving one
|
||||
* pitch from a single gap drifted the dots up to 15px off their rows);
|
||||
* - `x` because the tree indents per row via padding, so a folder's chevron and
|
||||
* a session's text are at different x.
|
||||
*/
|
||||
export interface BranchRow {
|
||||
/** Stable key, used to match a row to its dot. */
|
||||
readonly key: string;
|
||||
/** Row centre y, in the SVG's coordinate space. */
|
||||
readonly y: number;
|
||||
/**
|
||||
* Row anchor x, in the SVG's coordinate space.
|
||||
*
|
||||
* A folder row's anchor is its CHEVRON centre — the triangle the user already
|
||||
* reads as "this row opens" — so the stem visually hangs off the marker rather
|
||||
* than floating beside it. A session row's anchor is the indent its text sits
|
||||
* on.
|
||||
*/
|
||||
readonly x: number;
|
||||
/**
|
||||
* Row kind. A `'group'` row starts a new group and makes the stem kink;
|
||||
* an `'item'` row runs straight (or curves back in right after a group).
|
||||
*/
|
||||
readonly kind: 'group' | 'item';
|
||||
/** Whether this is the row the user is currently on (the bloomed dot). */
|
||||
readonly active: boolean;
|
||||
}
|
||||
/** A dot on the branch: one per row, positioned on the curve. */
|
||||
export interface BranchDot {
|
||||
/** The row this dot belongs to. */
|
||||
readonly key: string;
|
||||
readonly cx: number;
|
||||
readonly cy: number;
|
||||
readonly active: boolean;
|
||||
}
|
||||
/**
|
||||
* The bloom that flowers at the branch's endpoint.
|
||||
*
|
||||
* The endpoint is where the GROWN stroke stops — the row the user is on — not
|
||||
* the last visible row: the stem is drawn to the active row, so that is where
|
||||
* the plant has visibly reached, whether the tree is folded above it or not.
|
||||
*
|
||||
* This is deliberately the ONE row an active marker names, so the flower can
|
||||
* never disagree with the stem about where the branch ends.
|
||||
*/
|
||||
export interface BranchFlower {
|
||||
/** Row whose endpoint carries the bloom (the active row's key). */
|
||||
readonly key: string;
|
||||
/** Endpoint x: the last dot's centre, i.e. exactly where the grown path stops. */
|
||||
readonly cx: number;
|
||||
/** Endpoint y, on the measured row centre. */
|
||||
readonly cy: number;
|
||||
}
|
||||
/** The branch: one path for the ghost, its total length, and the dots. */
|
||||
export interface Branch {
|
||||
/** Full route, drawn as the faded dashed ghost. */
|
||||
readonly ghostPath: string;
|
||||
/** Path up to and including the active row (the "grown" part). */
|
||||
readonly grownPath: string;
|
||||
/** Drawn length of the full route. */
|
||||
readonly ghostLength: number;
|
||||
/** Drawn length of the grown part. */
|
||||
readonly grownLength: number;
|
||||
/** Dots, in row order. */
|
||||
readonly dots: readonly BranchDot[];
|
||||
/**
|
||||
* Bloom at the grown path's endpoint, or NULL when no row carries the active
|
||||
* marker.
|
||||
*
|
||||
* Deliberately stricter than `grownPath`: the stem has to be *some* path even
|
||||
* when nothing is active (it collapses to the bare origin, drawing nothing),
|
||||
* but a bloom with no active row has nothing to be the flower OF. Falling back
|
||||
* to the first dot — the earlier rule — put the blossom on a folder row at the
|
||||
* top of the tree as soon as the open session's folder was collapsed, because
|
||||
* folding removes the only row carrying the marker. No active row means no
|
||||
* flower.
|
||||
*/
|
||||
readonly flower: BranchFlower | null;
|
||||
/** Total vertical extent, so the SVG box can be sized. */
|
||||
readonly height: number;
|
||||
}
|
||||
/**
|
||||
* How far short of the flower's centre the stem stops, in SVG user units.
|
||||
*
|
||||
* The bloom is drawn ON the endpoint, so a stem that runs all the way to the
|
||||
* centre is visible through the petal notches and reads as a line crossing the
|
||||
* flower. Stopping the stroke at (a little over) the bloom's radius keeps the
|
||||
* stem ending cleanly at the flower's edge, where it reads as a stalk holding
|
||||
* the bloom.
|
||||
*
|
||||
* 7 units ≈ the 6.2-unit flower radius plus a hair, so the stroke's round cap
|
||||
* tucks just under the outer petals without a visible gap.
|
||||
*/
|
||||
export declare const STEM_END_CLEARANCE = 7;
|
||||
/**
|
||||
* Build the branch for a list of rows.
|
||||
*
|
||||
* @param rows - visible rows in render order, each carrying its MEASURED centre.
|
||||
* @returns the branch geometry; empty strings when there are no rows.
|
||||
*/
|
||||
export declare function buildBranch(rows: readonly BranchRow[]): Branch;
|
||||
|
|
@ -0,0 +1,138 @@
|
|||
/**
|
||||
* Registrant-private injected share for the workspace-groups browser entry.
|
||||
* Mirrors the official ui-workspace browser inject (same runtime calls), with
|
||||
* two differences: the directory-flow hole is kept occupied (`hooks.directoryFlow`)
|
||||
* because the official entry stays registered behind this one and gates its own
|
||||
* "Add workspace…" affordance on that hole — Add Workspace itself is
|
||||
* self-contained via `pickDirectory` — and no locale-keyed naming collision.
|
||||
*/
|
||||
import type { HostObservable, InjectFace, PropsLocale, PropsRuntime, PropsStore, SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { ComponentType } from 'react';
|
||||
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { SessionStatus, SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { WorkspaceId, WorkspaceSnapshot, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { createGroupsViewStore } from './stores.ts';
|
||||
import type { SessionTabsInstance, SessionTabsState } from './tab-store.ts';
|
||||
/** Services/slots this registrant's props depend on (documentation alias). */
|
||||
export type WorkspaceGroupsStoreHandle = ReturnType<typeof createGroupsViewStore>;
|
||||
/** Injected share (arrives via the register inject factory). */
|
||||
export type GroupsBrowserInjected = {
|
||||
/**
|
||||
* Reserved hooks compartment. `directoryFlow` reports the
|
||||
* `sidebar.workspaces.directoryFlow` hole as occupied: the official
|
||||
* ui-workspace entry stays registered behind this one and withdraws its
|
||||
* "Add workspace…" affordance when the hole is empty, so this browser keeps
|
||||
* it truthy (it drives the picker itself through `pickDirectory`).
|
||||
*/
|
||||
hooks: {
|
||||
/** True while the sidebar browsing region's directory-flow hole is occupied. */
|
||||
directoryFlow: HostObservable<boolean>;
|
||||
};
|
||||
/** Start a New Session in a Workspace (reuse-or-create its blank session and open it). */
|
||||
startSession: (workspaceId?: WorkspaceId) => void;
|
||||
/**
|
||||
* Create a real Session in one folder of a Workspace and open it. `cwd` is
|
||||
* omitted for the base folder (the Workspace's own canonical directory).
|
||||
*/
|
||||
createSessionIn: (workspaceId: WorkspaceId, cwd?: string) => Promise<SessionId>;
|
||||
/** 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>;
|
||||
/** Snapshot a self-contained standard picker without redeclaring its owned slot. */
|
||||
getDirectoryFlow: () => {
|
||||
component: ComponentType<DirectoryFlowOwnerProps>;
|
||||
injected: Record<string, unknown>;
|
||||
} | null;
|
||||
/** DSH native local directory creation (SSH routing is owned by our adapter). */
|
||||
createDirectory: (path: string, name: string) => Promise<string>;
|
||||
/**
|
||||
* Surface the session-tab strip for a session that is in play (called with the
|
||||
* session the browser itself just opened, and again whenever its status
|
||||
* changes). Tab visibility rules live in `shouldOpenTab`; the status is passed
|
||||
* in because "it started working" is a live-status fact the store layer cannot
|
||||
* read on its own.
|
||||
* @param sessionId - the session to consider.
|
||||
* @param status - its unified UI status, when one is published.
|
||||
*/
|
||||
openTab: (sessionId: SessionId, status: SessionStatus | undefined) => void;
|
||||
/**
|
||||
* Selector hook over the shared tab store, bound by this plugin (the strip is
|
||||
* not a slot occupant, so the framework does not bind it). Built from the one
|
||||
* live instance the browser writes through.
|
||||
*/
|
||||
useTabs: <S>(selector: (state: SessionTabsState) => S, eq?: (a: S, b: S) => boolean) => S;
|
||||
/** The tab store's baked write set (the same one `apply` writes through). */
|
||||
tabActions: SessionTabsInstance['actions'];
|
||||
};
|
||||
/** Full browser props: shell owner share + viewing store + injected actions + locale seat. */
|
||||
export type GroupsBrowserProps = PropsRuntime<'sidebar.workspaces'> & PropsStore<ReturnType<typeof createGroupsViewStore>> & InjectFace<GroupsBrowserInjected> & PropsLocale<'workspaceGroups'>;
|
||||
/**
|
||||
* The two framework global seats the strip reads, declared structurally because
|
||||
* `GlobalStandardProps`'s own members arrive from merge declarations this repo
|
||||
* cannot resolve (its packages ship no `src`, so the merged hook types are only
|
||||
* visible to the compiling package). Both are the shipped global selector hooks
|
||||
* with the same names and shapes, and both are seated on the
|
||||
* `sidebar.workspaces` occupant that renders this strip.
|
||||
*/
|
||||
export interface SessionsTabsStandardProps {
|
||||
/** Session list and current selection (framework global seat). */
|
||||
useSessions: SnapshotSelectorHook<SessionListState>;
|
||||
/** Unified per-session UI status (framework global seat). */
|
||||
useSessionStatus: SnapshotSelectorHook<SessionStatusSnapshot>;
|
||||
/**
|
||||
* Workspace registry (framework global seat). The strip reads it to label each
|
||||
* tab with the project that owns its session — the one fact a bare strip of
|
||||
* session titles cannot convey.
|
||||
*/
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
/**
|
||||
* Full tab-strip props.
|
||||
*
|
||||
* The strip is NOT a slot occupant: the conversation column declares no child
|
||||
* slot, so it renders through a DOM seat (`tab-seat.ts`) and receives plain
|
||||
* React props instead of framework shares. Only the two global selector hooks
|
||||
* below are framework-provided, and they arrive because the strip is rendered
|
||||
* as a CHILD of this plugin's own `sidebar.workspaces` occupant — which seats
|
||||
* both of them in the standard kit. Everything else is passed explicitly by
|
||||
* that parent, which is what removes the strip from the slot registry entirely
|
||||
* and with it the cross-scope store conflict the slot version hit.
|
||||
*/
|
||||
export type SessionsTabsProps = SessionsTabsStandardProps & {
|
||||
/** Selector hook over the shared tab store's snapshot. */
|
||||
useTabs: SnapshotSelectorHook<SessionTabsState>;
|
||||
/** The tab store's baked write set (the same set `apply` writes through). */
|
||||
actions: SessionTabsInstance['actions'];
|
||||
/** Make a tab's session the open one (`ctx.uiWorkspace.openSession`). */
|
||||
activate: (sessionId: SessionId) => void;
|
||||
/** Ask the browser to open its rename dialog for a tab session. */
|
||||
rename: (sessionId: SessionId, currentTitle: string) => void;
|
||||
} & PropsLocale<'workspaceGroups'>;
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { GroupsBrowserInjected } from './contract.ts';
|
||||
/** Adapt the elected self-contained picker, without stealing its original slot. */
|
||||
export declare function directoryFlowFromEntry(entry: StoredEntry | undefined): ReturnType<GroupsBrowserInjected['getDirectoryFlow']>;
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
export interface RemoteFolderWorkspace {
|
||||
mirrorPath: string;
|
||||
remotePath: string;
|
||||
profileId: string;
|
||||
/** Native DSH workspace registered for the mirror root ('' when unregistered). */
|
||||
workspaceId: string;
|
||||
/** remote-ssh's own record id ('' when it cannot be resolved). */
|
||||
recordId: string;
|
||||
}
|
||||
/** One SSH connection the remote plugin offers, as the picker needs it. */
|
||||
export interface RemoteProfileSummary {
|
||||
id: string;
|
||||
name: string;
|
||||
host: string;
|
||||
user: string;
|
||||
/** Directory the connection opens on (`~` when the plugin leaves it empty). */
|
||||
remoteRoot: string;
|
||||
}
|
||||
/** One row of a remote directory listing. */
|
||||
export interface RemoteDirEntry {
|
||||
name: string;
|
||||
type: 'directory' | 'file';
|
||||
size: number;
|
||||
}
|
||||
/** A remote directory and its children, as the cloud folder picker needs them. */
|
||||
export interface RemoteDirListing {
|
||||
/** Path as requested (`~`, a relative name or an absolute path). */
|
||||
requested: string;
|
||||
/** Absolute path the remote shell resolved it to (`requested` when unknown). */
|
||||
resolved: string;
|
||||
entries: readonly RemoteDirEntry[];
|
||||
}
|
||||
/** Parent of a directory path, or null where going up stops (`~`, `/`, root). */
|
||||
export declare function remoteDirParent(path: string): string | null;
|
||||
/** Join a child directory name onto a remote directory path. */
|
||||
export declare function remoteDirJoin(base: string, name: string): string;
|
||||
/**
|
||||
* List one remote directory through the SSH plugin's own pooled session, so
|
||||
* password auth, ProxyJump and host-key handling stay where they already work.
|
||||
* @param profileId - SSH connection to browse.
|
||||
* @param path - directory to list; empty means the connection's remote root.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function listRemoteDirectory(profileId: string, path: string, fetchImpl?: typeof fetch): Promise<RemoteDirListing>;
|
||||
/** A newly registered remote (mirror-backed) folder workspace. */
|
||||
export interface CreatedRemoteFolder {
|
||||
/** Absolute LOCAL mirror path — the member workspace's canonical directory. */
|
||||
path: string;
|
||||
/** Native DSH workspace id that now backs the folder row. */
|
||||
workspaceId: string;
|
||||
/** remote-ssh's own record id (used to delete the record again). */
|
||||
recordId: string;
|
||||
remotePath: string;
|
||||
profileId: string;
|
||||
title: string;
|
||||
/** True when an existing record for the same profile + remote path was taken over. */
|
||||
reused: boolean;
|
||||
}
|
||||
/**
|
||||
* The SSH connections available for a cloud folder, or null when the
|
||||
* `@zhangfengshun/dsh-remote-ssh` plugin does not answer at all.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function listRemoteProfiles(fetchImpl?: typeof fetch): Promise<RemoteProfileSummary[] | null>;
|
||||
/**
|
||||
* Register one cloud folder: the SSH plugin creates the local mirror, writes the
|
||||
* connection marker and registers a real DSH workspace for it — exactly what its
|
||||
* own "new remote workspace" flow does. The returned native workspace id backs
|
||||
* the folder row, and the workspace's own sidebar row is hidden once the entry
|
||||
* lists it (see `absorbedWorkspaceIds`).
|
||||
* @param profileId - SSH connection to use.
|
||||
* @param remotePath - remote directory (`~`, `~/proj`, `/srv/proj`).
|
||||
* @param title - optional display title; the plugin derives one from the path.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function createRemoteFolder(profileId: string, remotePath: string, title?: string, fetchImpl?: typeof fetch): Promise<CreatedRemoteFolder>;
|
||||
/**
|
||||
* Delete one remote workspace record through the SSH plugin: it removes the
|
||||
* record, unregisters the native workspace behind it (that workspace's
|
||||
* sessions go with it) and cleans up the mirror — the counterpart of
|
||||
* {@link createRemoteFolder}, for when a member folder is removed for good.
|
||||
* @param recordId - remote-ssh record id stored on the member.
|
||||
* @param fetchImpl - fetch implementation (tests inject one).
|
||||
*/
|
||||
export declare function deleteRemoteWorkspaceRecord(recordId: string, fetchImpl?: typeof fetch): Promise<void>;
|
||||
/** Resolve against the SSH plugin's registered mirrors, not copied marker files. */
|
||||
export declare function remoteFolderWorkspace(path: string, remoteBase: string | null, fetchImpl?: typeof fetch): Promise<RemoteFolderWorkspace | null>;
|
||||
/** Single-segment names match DSH createDirectory(path, name). */
|
||||
export declare function validateFolderName(raw: string): string;
|
||||
export declare function createWorkspaceDirectory(parent: string, rawName: string, remoteBase: string | null, createLocal: (path: string, name: string) => Promise<string>, fetchImpl?: typeof fetch): Promise<{
|
||||
path: string;
|
||||
remote: boolean;
|
||||
}>;
|
||||
|
|
@ -0,0 +1,75 @@
|
|||
/**
|
||||
* Client side of the per-workspace folder list, talking to
|
||||
* `GET|PUT /workspace-groups/folders` on the host.
|
||||
*
|
||||
* The document is the host's JSON sidecar verbatim (`version` + `workspaces`),
|
||||
* so the client and the host agree on one shape: `folders` holds EXTRA folders
|
||||
* only — the workspace's canonical directory is implicit folder #0 — and
|
||||
* `root` names one of those extras (absent means "the workspace itself").
|
||||
*
|
||||
* Reads are best-effort, like the manual overlay and the tab strip: a failed
|
||||
* read means "no extra folders". A failed write, however, rejects so the caller
|
||||
* can say so — a folder row that silently forgot its edit would be worse than
|
||||
* the toast.
|
||||
*/
|
||||
import { type FoldersDocument } from '../core/folders.ts';
|
||||
/** Host route holding the folder overlay. */
|
||||
export declare const FOLDERS_ROUTE = "/workspace-groups/folders";
|
||||
/** One successful read: the overlay plus the mirror base the host reported. */
|
||||
export interface FoldersSnapshot {
|
||||
readonly document: FoldersDocument;
|
||||
/**
|
||||
* Local mirror root of the remote-ssh plugin, when the host named one.
|
||||
* Workspaces whose directory lives below it are remote mirrors, so their extra
|
||||
* folders must be subdirectories of that same mirror.
|
||||
*/
|
||||
readonly remoteBase?: string;
|
||||
}
|
||||
/**
|
||||
* One folder-overlay read result. A failed read must never masquerade as the
|
||||
* empty document: the browser uses `ok` to keep the last confirmed rows and
|
||||
* show a retryable error instead of rendering every member as a duplicate.
|
||||
*/
|
||||
export interface FoldersLoadResult extends FoldersSnapshot {
|
||||
readonly ok: boolean;
|
||||
/** Human-readable failure reason; absent on success. */
|
||||
readonly error?: string;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored folder overlay.
|
||||
*
|
||||
* A non-2xx response, a malformed body or a transport error is returned as
|
||||
* `ok:false` with the reason. The empty document is still present for callers
|
||||
* that only need a safe value, but `ok` is the authority: the browser must not
|
||||
* treat a failed read as "no folders".
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @param signal - optional cancellation for a superseded read/retry.
|
||||
*/
|
||||
export declare function loadFolders(fetchImpl?: typeof fetch, signal?: AbortSignal): Promise<FoldersLoadResult>;
|
||||
/**
|
||||
* Read a whole folder document off the wire (GET response, PUT echo or the
|
||||
* 409 conflict body), or null when it is not a version-1 document.
|
||||
* @param source - parsed JSON body.
|
||||
*/
|
||||
export declare function parseWireDocument(source: Record<string, unknown>): FoldersDocument | null;
|
||||
/**
|
||||
* A save rejected because another window wrote first (HTTP 409). Carries the
|
||||
* host's current document so the caller can adopt it and resync its state
|
||||
* instead of leaving the user looking at a phantom edit.
|
||||
*/
|
||||
export declare class FoldersConflictError extends Error {
|
||||
readonly current: FoldersDocument;
|
||||
/** The unsaved document the failed PUT attempted to write. */
|
||||
readonly attempted: FoldersDocument;
|
||||
constructor(current: FoldersDocument, attempted?: FoldersDocument);
|
||||
}
|
||||
/**
|
||||
* Store the whole folder overlay.
|
||||
*
|
||||
* Unlike the tab strip this does NOT swallow failures: folder edits are explicit
|
||||
* row/dialog actions, so the caller turns a rejection into a toast instead of
|
||||
* leaving the user with a row that silently forgot its folder.
|
||||
* @param document - the client's current document.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveFolders(document: FoldersDocument, fetchImpl?: typeof fetch): Promise<FoldersDocument>;
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
import type { GroupIconId } from '../core/types.ts';
|
||||
/** Bilingual accessible names also make native browser tooltips recognizable in either locale. */
|
||||
export declare const GROUP_ICON_LABELS: Record<GroupIconId, string>;
|
||||
/** All presets satisfy the existing host's 1–4 Unicode-code-point custom-glyph rule. */
|
||||
export declare const GROUP_EMOJI_ICONS: readonly [{
|
||||
readonly icon: "🚀";
|
||||
readonly label: "启动 / Launch";
|
||||
}, {
|
||||
readonly icon: "📚";
|
||||
readonly label: "学习 / Learning";
|
||||
}, {
|
||||
readonly icon: "🔬";
|
||||
readonly label: "科研 / Research";
|
||||
}, {
|
||||
readonly icon: "🧪";
|
||||
readonly label: "实验 / Experiment";
|
||||
}, {
|
||||
readonly icon: "🎨";
|
||||
readonly label: "创作 / Art";
|
||||
}, {
|
||||
readonly icon: "🎯";
|
||||
readonly label: "目标 / Target";
|
||||
}, {
|
||||
readonly icon: "💡";
|
||||
readonly label: "想法 / Idea";
|
||||
}, {
|
||||
readonly icon: "🛠️";
|
||||
readonly label: "工具 / Tools";
|
||||
}, {
|
||||
readonly icon: "🌱";
|
||||
readonly label: "成长 / Growth";
|
||||
}, {
|
||||
readonly icon: "🏠";
|
||||
readonly label: "生活 / Home";
|
||||
}, {
|
||||
readonly icon: "💼";
|
||||
readonly label: "工作 / Work";
|
||||
}, {
|
||||
readonly icon: "🎮";
|
||||
readonly label: "游戏 / Games";
|
||||
}, {
|
||||
readonly icon: "🎵";
|
||||
readonly label: "音乐 / Music";
|
||||
}, {
|
||||
readonly icon: "❤️";
|
||||
readonly label: "收藏 / Favorites";
|
||||
}, {
|
||||
readonly icon: "⭐";
|
||||
readonly label: "星标 / Star";
|
||||
}, {
|
||||
readonly icon: "🔥";
|
||||
readonly label: "热门 / Hot";
|
||||
}];
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
/**
|
||||
* Self-drawn monochrome artwork for the "Materials & Lab" icon family.
|
||||
*
|
||||
* The Host primitive package only ships product/generic glyphs, so the 28
|
||||
* research icons are drawn here in the exact same visual language as the Host
|
||||
* ones: a 16x16 viewBox, `currentColor` stroke, 1.3 stroke width (Host
|
||||
* `ICON_MEDIUM_STROKE`), round caps/joins and no fill. Keeping the artwork as
|
||||
* primitive data (instead of one opaque `<path>` per icon) lets the icon test
|
||||
* assert every coordinate stays inside the viewBox and that each id has
|
||||
* artwork — a hand-tuned path string could silently drift out of frame.
|
||||
*/
|
||||
import type { ReactElement } from 'react';
|
||||
/** One drawable primitive of a 16x16 icon; coordinates are in viewBox units. */
|
||||
export type SciencePrimitive = {
|
||||
readonly kind: 'line';
|
||||
readonly x1: number;
|
||||
readonly y1: number;
|
||||
readonly x2: number;
|
||||
readonly y2: number;
|
||||
} | {
|
||||
readonly kind: 'rect';
|
||||
readonly x: number;
|
||||
readonly y: number;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
readonly radius?: number;
|
||||
} | {
|
||||
readonly kind: 'circle';
|
||||
readonly cx: number;
|
||||
readonly cy: number;
|
||||
readonly radius: number;
|
||||
readonly filled?: boolean;
|
||||
} | {
|
||||
readonly kind: 'ellipse';
|
||||
readonly cx: number;
|
||||
readonly cy: number;
|
||||
readonly rx: number;
|
||||
readonly ry: number;
|
||||
/** Rotation around the icon centre (8,8), in degrees. */
|
||||
readonly rotate?: number;
|
||||
} | {
|
||||
readonly kind: 'path';
|
||||
readonly d: string;
|
||||
};
|
||||
/** Ids appended to the shared registry; order is the picker's section order. */
|
||||
export declare const SCIENCE_ICON_IDS: readonly ["test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance", "atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel", "microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve", "illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
|
||||
/** Union of the research icon ids (a subset of the shared `GroupIconId`). */
|
||||
export type ScienceIconId = (typeof SCIENCE_ICON_IDS)[number];
|
||||
/** The picker's section split of the research family. */
|
||||
export declare const SCIENCE_ICON_SECTIONS: readonly [{
|
||||
readonly key: "lab";
|
||||
readonly ids: readonly ["test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance"];
|
||||
}, {
|
||||
readonly key: "materials";
|
||||
readonly ids: readonly ["atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel"];
|
||||
}, {
|
||||
readonly key: "characterization";
|
||||
readonly ids: readonly ["microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve"];
|
||||
}, {
|
||||
readonly key: "devices";
|
||||
readonly ids: readonly ["illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
|
||||
}];
|
||||
/** Primitive artwork per research icon. */
|
||||
export declare const SCIENCE_ICON_ART: Record<ScienceIconId, readonly SciencePrimitive[]>;
|
||||
/** Research icon id → picker section key. */
|
||||
export declare const SCIENCE_ICON_SECTION_OF: Record<ScienceIconId, (typeof SCIENCE_ICON_SECTIONS)[number]['key']>;
|
||||
/**
|
||||
* Render one research icon in the Host glyph's visual language: 16x16,
|
||||
* `currentColor` stroke, 1.3px, round joins, decorative for screen readers (the
|
||||
* row/picker button already carries the bilingual name).
|
||||
* @param props.icon - research icon id.
|
||||
* @param props.size - rendered square size in CSS pixels (default 16, like Host glyphs).
|
||||
*/
|
||||
export declare function ScienceGlyph({ icon, size }: {
|
||||
icon: ScienceIconId;
|
||||
size?: number;
|
||||
}): ReactElement;
|
||||
/** Research icon id → rendered node, merged into the row icon registry. */
|
||||
export declare function scienceIconNodes(): Record<ScienceIconId, ReactElement>;
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
/**
|
||||
* @dsh-xhl/workspace-groups client half. ONE registration, plus a DOM-seated
|
||||
* view that hangs off it:
|
||||
*
|
||||
* The three-level grouped workspace browser into `sidebar.workspaces`,
|
||||
* 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 — the shared navigation service + `workspaces.create()`, no
|
||||
* hole.
|
||||
*
|
||||
* The session tab strip is NOT a second registration. It renders into a DOM
|
||||
* seat at the head of the conversation column (`pI_x6G_centerCol`) because that
|
||||
* column declares no child slot — its only child is the `main` slot's occupant
|
||||
* — so there is nowhere to register. See `tab-seat.ts` for the injection and
|
||||
* `SessionTabs.tsx` for the portal.
|
||||
*
|
||||
* Two consequences of that choice, both deliberate:
|
||||
* - The strip is a CHILD of this entry's component, so it inherits this
|
||||
* fiber's frame; it needs no injected seam, no cross-entry callback set,
|
||||
* and the rename dialog stays owned by one place.
|
||||
* - The tab store is seated by exactly ONE entry. Registering one handle
|
||||
* under a second, differently-scoped slot throws inside the registry
|
||||
* ("one handle, one scope") and would abort this whole `apply()` — which
|
||||
* is precisely why the strip does not occupy a slot.
|
||||
*
|
||||
* 0.1.6 适配:导航(选中会话 / New Session / fork / archive / 目录选择)从
|
||||
* `ctx.sessions` 抽到 ui-workspace 提供的 `ctx.uiWorkspace` 服务
|
||||
* (`ISessions` 现在只有目录 / retain / search 能力,选中由 `mainView` 保留位
|
||||
* 表达)。本插件不再自建 connectWorkspace/recentWorkspace 语义,全部委托给该
|
||||
* 服务,只保留改名、删除、排序、搜索等数据动作。
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
import type { SnapshotSelectorHook } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { WorkspaceSnapshot } from '@deepseek-ai/dsh-api-workspace-controller/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;
|
||||
}
|
||||
interface GlobalStandardProps {
|
||||
/** Selector hook over the pure Workspace Controller snapshot. */
|
||||
useWorkspaces: SnapshotSelectorHook<WorkspaceSnapshot>;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Required services (cordis fiber inject; 0.1.6 service roster). `uiWorkspace`
|
||||
* is the shipped navigation face this entry delegates selection to.
|
||||
*/
|
||||
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: Context): void;
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
/**
|
||||
* workspace-groups-remote — merged client entry.
|
||||
*
|
||||
* One package gets exactly one client row in the DSH web shell (the module
|
||||
* loader keys graph rows by package name), so this entry composes the two
|
||||
* client halves on one fiber:
|
||||
*
|
||||
* - groupsClient: the workspace-groups browser + session tab strip
|
||||
* (groups-client.ts, formerly this file).
|
||||
* - remoteSshClient: the dsh-remote-ssh client, vendored from
|
||||
* vendor/dsh-remote-ssh/lib/client.js. Upstream ships it as a
|
||||
* self-registering module-loader bundle; scripts/build-remote-ssh-client.mjs
|
||||
* strips that registration wrapper and re-exports the bare factory, which
|
||||
* is invoked here with this bundle's own require (its only requires are
|
||||
* `react` and `@deepseek-ai/dsh-client-ui-primitives`, both platform
|
||||
* modules) and applied alongside the groups client.
|
||||
*
|
||||
* The inject list is the union of both halves (remote-ssh's `slots`/`locale`
|
||||
* are a subset of the groups list).
|
||||
*/
|
||||
import type { Context } from '@deepseek-ai/cordis';
|
||||
/** Services required before mounting (union of both client halves). */
|
||||
export declare const inject: string[];
|
||||
/** Plugin body: apply both client halves on this bundle's fiber. */
|
||||
export declare function apply(ctx: Context): 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' | 'workspace.moveOutOfGroup' | 'workspace.openInFolder' | 'workspace.openInFolderError' | 'folder.title' | 'folder.manage' | 'folder.listAria' | 'folder.sectionList' | 'folder.sectionAdd' | 'folder.emptyHint' | 'folder.base' | 'folder.setRoot' | 'folder.rootBadge' | 'folder.remove' | 'folder.add' | 'folder.done' | 'folder.duplicate' | 'folder.conflict' | 'folder.removeError' | 'folder.removeRemotePrompt' | 'folder.removeRemoteDelete' | 'folder.removeRemoteOnly' | 'folder.addError' | 'folder.sessionError' | 'folder.saveError' | 'folder.notReady' | 'folder.remoteSessionUnsupported' | 'folder.remoteHint' | 'folder.remoteNeedsSubpath' | 'folder.subpathLabel' | 'folder.subpathPlaceholder' | 'folder.addSubpath' | 'folder.subpathInvalid' | 'folder.cloudSection' | 'folder.profileLabel' | 'folder.remotePathLabel' | 'folder.remotePathPlaceholder' | 'folder.remotePathOrName' | 'folder.createAndAdd' | 'folder.cloudNoteBoth' | 'folder.addRemote' | 'folder.noProfiles' | 'folder.profilesError' | 'folder.cloudTag' | 'folder.localTag' | 'folder.memberMissing' | 'folder.memberNested' | 'folder.alreadyRoot' | 'folder.addAria' | 'folder.tabLocal' | 'folder.tabCloud' | 'folder.pickLocal' | 'folder.localNote' | 'folder.localIntoRemote' | 'folder.cloudNote' | 'folder.browse' | 'folder.browseTitle' | 'folder.browseListAria' | 'folder.browseNote' | 'folder.browseFailed' | 'folder.chooseHere' | 'folder.up' | 'folder.home' | 'folder.refresh' | 'folder.loading' | 'folder.loadingState' | 'folder.loadError' | 'folder.refreshError' | 'folder.retry' | 'folder.retryDraft' | 'folder.discardDraft' | 'folder.conflictDetail' | 'folder.emptyDir' | 'group.create' | 'group.createTitle' | 'group.createPlaceholder' | 'group.createConfirm' | 'group.createCancel' | 'group.rename' | 'group.renameTitle' | 'group.renameConfirm' | 'group.delete' | 'group.deleteTitle' | 'group.deleteConfirm' | 'group.deleteCancel' | 'group.nameDuplicate' | 'group.nameReserved' | 'group.pin' | 'group.unpin' | 'group.pinned' | 'group.appearance' | 'group.appearanceTitle' | 'group.appearanceDone' | 'group.color' | 'group.colorDefault' | 'group.icon' | 'group.iconDefault' | 'group.iconCustom' | 'group.iconInvalid' | 'group.icon.section.common' | 'group.icon.section.lab' | 'group.icon.section.materials' | 'group.icon.section.characterization' | 'group.icon.section.devices' | 'group.icon.section.emoji' | 'color.red' | 'color.orange' | 'color.amber' | 'color.green' | 'color.teal' | 'color.blue' | 'color.indigo' | 'color.purple' | 'color.pink' | 'color.gray' | 'section.topLevel' | 'section.defaultWorkspace' | 'manual.saveError' | 'manual.conflict' | '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' | 'quick.title' | 'quick.tab.workspaces' | 'quick.tab.sessions' | 'quick.search.placeholder' | 'quick.search.sessions' | 'quick.empty.workspaces' | 'quick.action.newSession' | 'quick.action.running' | 'quick.action.noneRunning' | 'quick.empty.sessions' | 'quick.select.hint' | 'quick.hint' | 'tabs.aria' | 'tabs.close' | 'tabs.archive' | 'tabs.pin' | 'tabs.unpin' | 'tabs.pinned' | 'tabs.rename' | 'tabs.renameSession' | 'tabs.renamePlaceholder' | 'tabs.closeOthers' | 'tabs.closeRight' | 'tabs.dragHint';
|
||||
export type WorkspaceGroupsDict = LocaleDictOf<'workspaceGroups'>;
|
||||
/** Simplified Chinese dictionary. */
|
||||
export declare const zh: WorkspaceGroupsDict;
|
||||
/** English dictionary. */
|
||||
export declare const en: WorkspaceGroupsDict;
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
/**
|
||||
* Transport for the official open-in-app host routes served by
|
||||
* `@deepseek-ai/dsh-host-open-in-app`. The project row offers "open this
|
||||
* project's folder" by asking that host half for the applications it verified
|
||||
* as installed, then POSTing the launcher it already resolved — this plugin
|
||||
* never probes or spawns a launcher itself, and a host without the capability
|
||||
* (no resolved application, e.g. an SSH launch) simply yields no menu entry.
|
||||
*/
|
||||
/** GET route serving the probed application ids (host-owned constant). */
|
||||
export declare const OPEN_IN_APP_APPS_ROUTE = "/open-in-app/apps";
|
||||
/** POST route launching one resolved application on one absolute directory. */
|
||||
export declare const OPEN_IN_APP_OPEN_ROUTE = "/open-in-app/open";
|
||||
/**
|
||||
* The installed file-manager id for this host, or undefined when the host
|
||||
* resolved none (the row then offers no "open in folder" entry).
|
||||
* @param apps - installed catalog ids from the apps route.
|
||||
* @returns the preferred available id.
|
||||
*/
|
||||
export declare function folderAppId(apps: readonly string[]): string | undefined;
|
||||
/**
|
||||
* Read the host's installed-application ids. A host without the capability
|
||||
* (or one that refuses) reads as an empty list rather than an error, so the
|
||||
* caller can treat "no apps" and "no route" identically.
|
||||
* @param signal - aborts the read when the browser half unmounts.
|
||||
* @returns installed catalog ids, in host menu order.
|
||||
*/
|
||||
export declare function fetchOpenInApps(signal?: AbortSignal): Promise<readonly string[]>;
|
||||
/**
|
||||
* Launch one installed application on one absolute directory.
|
||||
* @param appId - catalog id from the apps route.
|
||||
* @param path - the project's absolute directory.
|
||||
* @returns after the host acknowledged the launch; rejects on any refusal.
|
||||
*/
|
||||
export declare function openPathInApp(appId: string, path: string): Promise<void>;
|
||||
|
|
@ -0,0 +1,74 @@
|
|||
/**
|
||||
* Pure data shaping for the Ctrl+R quick switch panel. Runtime-free (same
|
||||
* discipline as store-core.ts): unit tests exercise the real semantics
|
||||
* without a browser module loader; the panel only binds them to the
|
||||
* framework's global hooks.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionListState, SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
/**
|
||||
* Running quick-switchable sessions across the whole list, newest first.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @returns running summaries in recency order (id as deterministic tiebreak).
|
||||
*/
|
||||
export declare function runningSessions(list: SessionListState, archived: ReadonlySet<SessionId>): SessionSummary[];
|
||||
/**
|
||||
* Every quick-switchable session across the whole list — the sessions tab's
|
||||
* data: running rows pinned on top, everything else under them, both groups
|
||||
* newest first. Visibility mirrors the tree (subagent rows never; archived
|
||||
* never; a blank row only while it is the open session).
|
||||
* @param list - sessions list snapshot.
|
||||
* @param archived - registry-global archive set (archived rows never surface).
|
||||
* @param current - the selected session (`mainView` retention; keeps its blank row visible).
|
||||
* @returns summaries with running first, then recency (id as deterministic tiebreak).
|
||||
*/
|
||||
export declare function allSessions(list: SessionListState, archived: ReadonlySet<SessionId>, current: SessionId | undefined): SessionSummary[];
|
||||
/**
|
||||
* Session search for the quick panel: display-title or owning-workspace-title
|
||||
* substring match (trimmed, case-insensitive). Filters only — the incoming
|
||||
* running-first/recency order is preserved verbatim, so "running on top"
|
||||
* survives any query.
|
||||
* @param sessions - allSessions() output (running pinned on top, then recency).
|
||||
* @param query - raw query.
|
||||
* @param workspaceTitleOf - owning workspace title resolver (sub-line source).
|
||||
* @param limit - hard render cap.
|
||||
* @returns matching sessions in the given order.
|
||||
*/
|
||||
export declare function filterSessions(sessions: readonly SessionSummary[], query: string, workspaceTitleOf: (session: SessionSummary) => string | undefined, limit?: number): SessionSummary[];
|
||||
/**
|
||||
* Most recently updated running session inside one workspace.
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspace - target workspace (its session account order is irrelevant;
|
||||
* recency picks the row).
|
||||
* @returns the session id, or undefined when nothing in the workspace runs.
|
||||
*/
|
||||
export declare function latestRunningInWorkspace(list: SessionListState, workspace: WorkspaceView): SessionId | undefined;
|
||||
/**
|
||||
* Running-session count per workspace id (badge on the workspace tab rows).
|
||||
* @param running - runningSessions() output.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @returns counts keyed by workspace id; absent key = none running.
|
||||
*/
|
||||
export declare function runningCountByWorkspace(running: readonly SessionSummary[], workspaces: readonly WorkspaceView[]): Map<string, number>;
|
||||
/**
|
||||
* The workspace that owns the currently open session.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param currentSessionId - the selected session (`mainView` retention); may be undefined
|
||||
* (no session open, cleared selection) or an id no listed workspace holds
|
||||
* (e.g. an addressed subagent session).
|
||||
* @returns the workspace id, or undefined when there is no active workspace.
|
||||
*/
|
||||
export declare function activeWorkspaceId(workspaces: readonly WorkspaceView[], currentSessionId: SessionId | undefined): string | undefined;
|
||||
/**
|
||||
* Workspace search for the quick panel: title prefix → title substring →
|
||||
* category label substring → path substring; ties keep host order via a
|
||||
* stable title compare inside one rank.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param query - raw query (trimmed, case-insensitive).
|
||||
* @param categoryLabelOf - category label resolver (grouped workspaces only).
|
||||
* @param limit - hard render cap.
|
||||
* @returns ranked matches; an empty query returns host order.
|
||||
*/
|
||||
export declare function filterWorkspaces(workspaces: readonly WorkspaceView[], query: string, categoryLabelOf?: (workspace: WorkspaceView) => string | undefined, limit?: number): WorkspaceView[];
|
||||
|
|
@ -0,0 +1,161 @@
|
|||
/**
|
||||
* 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.
|
||||
*
|
||||
* Drag & drop: workspace rows are draggable sources; category rows (and
|
||||
* workspace rows, standing for their containing category) are drop targets.
|
||||
* The payload is a custom dataTransfer type so only in-plugin drags land.
|
||||
*/
|
||||
import { type DragEvent, type ReactNode } from 'react';
|
||||
import { type StateDotState } from '@deepseek-ai/dsh-client-ui-primitives';
|
||||
import type { TranslateNS } from '@deepseek-ai/dsh-client-ui-slots';
|
||||
import type { CategoryNode, FolderNode, SessionNode, WorkspaceGroupNode } from './tree.ts';
|
||||
type T = TranslateNS<'workspaceGroups'>;
|
||||
/** dataTransfer type carrying the dragged workspace id (in-plugin drags only). */
|
||||
export declare const DND_WORKSPACE_TYPE = "application/x-dsh-workspace-groups";
|
||||
/** dataTransfer type carrying the dragged category key (group reorder). */
|
||||
export declare const DND_CATEGORY_TYPE = "application/x-dsh-workspace-groups-category";
|
||||
/** Whether a drag carries any of the plugin's payloads (drop targets accept both). */
|
||||
export declare function hasPluginDragType(types: DOMStringList | readonly string[]): boolean;
|
||||
/** 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;
|
||||
/** Drop-target props shared by category and workspace rows (all optional). */
|
||||
export interface RowDropProps {
|
||||
/** Row is under the dragged workspace — show the drop highlight. */
|
||||
dropActive?: boolean;
|
||||
/** Insertion indicator: a line above (before) or below (after) this row. */
|
||||
insertLine?: 'before' | 'after';
|
||||
/** Accept a drag over this row (must preventDefault to allow the drop). */
|
||||
onRowDragOver?: (event: DragEvent) => void;
|
||||
/** Clear the highlight when the pointer leaves the row. */
|
||||
onRowDragLeave?: (event: DragEvent) => void;
|
||||
/** Drop a workspace onto this row. */
|
||||
onRowDrop?: (event: DragEvent) => void;
|
||||
}
|
||||
/**
|
||||
* Render one stored icon value (preset artwork or a short glyph). Shared by the
|
||||
* category row's icon slot and the appearance picker grid, so both show exactly
|
||||
* the same artwork. `fallback` renders when the value is empty or unknown.
|
||||
*/
|
||||
export declare function CategoryGlyph({ icon, fallback }: {
|
||||
icon: string | undefined;
|
||||
fallback?: ReactNode;
|
||||
}): JSX.Element;
|
||||
/**
|
||||
* One category folder row: toggle, rename/delete menu (every group — rule
|
||||
* groups via overlay renames/hides), draggable source for group reorder and
|
||||
* drop target for both workspace moves and group reorders.
|
||||
*/
|
||||
export declare function CategoryRow({ node, t, onToggle, onAddWorkspace, addingWorkspace, onRename, onDelete, onTogglePin, onEditAppearance, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartCategory }: {
|
||||
node: CategoryNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
/** Create and assign a workspace directly to this category. */
|
||||
onAddWorkspace?: () => void;
|
||||
addingWorkspace?: boolean;
|
||||
/** Rename/delete actions; the hover menu renders only when both provided. */
|
||||
onRename?: () => void;
|
||||
onDelete?: () => void;
|
||||
/** Pin/unpin this group (menu row). */
|
||||
onTogglePin?: () => void;
|
||||
/** Open the appearance dialog (menu row). */
|
||||
onEditAppearance?: () => void;
|
||||
/** Group reorder source; the row becomes draggable only when provided. */
|
||||
onDragStartCategory?: (event: DragEvent) => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/** One workspace folder row inside a category: draggable source + drop target. */
|
||||
export declare function WorkspaceRow({ node, t, onToggle, onNewSession, onRename, onDelete, canMoveOut, onMoveOut, onManageFolders, onOpenInFolder, flat, dropActive, insertLine, onRowDragOver, onRowDragLeave, onRowDrop, onDragStartExtra }: {
|
||||
node: WorkspaceGroupNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
onNewSession: () => void;
|
||||
onRename: () => void;
|
||||
onDelete: () => void;
|
||||
/** Project currently sits inside a group — offer "move out of group". */
|
||||
canMoveOut?: boolean;
|
||||
onMoveOut?: () => void;
|
||||
/** Open the folder-management dialog (extra folders + root). */
|
||||
onManageFolders?: () => void;
|
||||
/**
|
||||
* Open the project directory in the host's file manager. Omitted when the
|
||||
* host resolved no folder application (no capability, or a remote launch),
|
||||
* which keeps the entry out of the menu entirely.
|
||||
*/
|
||||
onOpenInFolder?: () => void;
|
||||
/** Render as a top-level row (no folder indentation). */
|
||||
flat?: boolean;
|
||||
/** Extra dragstart hook (e.g. collapse all expanded projects while dragging). */
|
||||
onDragStartExtra?: () => void;
|
||||
} & RowDropProps): import("react").JSX.Element;
|
||||
/**
|
||||
* One folder row under a project: the base directory (folder #0) plus every
|
||||
* extra folder of that workspace. Sits at the session indent level so the
|
||||
* 42/58/74 ladder is preserved, and its own session rows indent one step
|
||||
* deeper (see `.wgSessionNested`).
|
||||
*
|
||||
* Deliberately NOT a drag source or drop target: folders are a fixed,
|
||||
* host-ordered list; reordering them would need a write path this feature does
|
||||
* not have.
|
||||
*/
|
||||
export declare function FolderRow({ node, t, onToggle, onNewSession, onSetRoot, onRemove, onOpenInFolder, creating }: {
|
||||
node: FolderNode;
|
||||
t: T;
|
||||
onToggle: () => void;
|
||||
onNewSession: () => void;
|
||||
onSetRoot: () => void;
|
||||
onRemove: () => void;
|
||||
/** Absent when the host resolved no folder application. */
|
||||
onOpenInFolder?: () => void;
|
||||
/** A session is being created here: the hover + stays disabled. */
|
||||
creating?: boolean;
|
||||
}): import("react").JSX.Element;
|
||||
/**
|
||||
* Children container for one folder's rows.
|
||||
*
|
||||
* Keeps the tree's `role="group"` semantics and gives the rows a single
|
||||
* positioned ancestor. It used to draw a per-folder guide rail; that is now the
|
||||
* flower branch's job (one continuous stem for the whole tree, see
|
||||
* `FlowerBranch.tsx`), so this is structure only.
|
||||
*/
|
||||
export declare function TreeChildren({ children }: {
|
||||
children: ReactNode;
|
||||
}): import("react").JSX.Element;
|
||||
/**
|
||||
* Animated disclosure body shared by the category and project levels.
|
||||
*
|
||||
* Collapsed state renders nothing at all (same DOM as the old
|
||||
* `{expanded && …}`), so hidden subtrees cost no layout. Expanding plays a
|
||||
* 0fr→1fr grid animation; collapsing keeps the rows mounted for one closing
|
||||
* animation and unmounts on its `animationend`. `prefers-reduced-motion`
|
||||
* unmounts synchronously instead — waiting for an `animationend` that CSS
|
||||
* disabled would leave the group stuck half-closed.
|
||||
*
|
||||
* The flower-branch overlay cannot follow a moving row box, so the animation
|
||||
* phase exposes `data-wg-animating` (styles.css fades the vine while it is
|
||||
* present).
|
||||
*/
|
||||
export declare function RowGroup({ expanded, className, animate, children }: {
|
||||
expanded: boolean;
|
||||
className?: string;
|
||||
/** Disable the animation for huge subtrees or during drag folding. */
|
||||
animate?: boolean;
|
||||
children: ReactNode;
|
||||
}): JSX.Element | null;
|
||||
/** One session leaf row. */
|
||||
export declare function SessionRow({ node, currentId, now, t, onOpen, onRename, onFork, onArchive, nested }: {
|
||||
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;
|
||||
/** Rendered under a folder row: one indent step deeper than a plain session. */
|
||||
nested?: boolean;
|
||||
}): 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,7 @@
|
|||
import type { ActionsDecl, StoreInstance } from '@deepseek-ai/dsh-client-store';
|
||||
/**
|
||||
* Build a selector hook bound to one store instance.
|
||||
* @param instance - the live store instance (snapshot source).
|
||||
* @returns a `SnapshotSelectorHook`-compatible hook over that instance.
|
||||
*/
|
||||
export declare function createStoreHook<T, A extends ActionsDecl<T>>(instance: StoreInstance<T, A>): <S>(selector: (state: T) => S, eq?: (a: S, b: S) => boolean) => S;
|
||||
|
|
@ -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-store';
|
||||
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,27 @@
|
|||
/**
|
||||
* Plugin-owned projection of descendant counts from Session summaries.
|
||||
*
|
||||
* 0.1.2 移除了 `@deepseek-ai/dsh-client-runtime/client`(平台模块表不再提供
|
||||
* `indexSubagentDescendants`),官方 ui-workspace 改为各自持有本地副本
|
||||
* (packages/client/ui-workspace/src/client/subagent-lineage.ts,MIT)。这里
|
||||
* 保持同一实现,使运行中的子代理会话数在树行上继续可见。
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
interface LineageEntry {
|
||||
readonly id: SessionId;
|
||||
readonly parentId?: SessionId;
|
||||
readonly origin?: 'subagent';
|
||||
readonly running: boolean;
|
||||
}
|
||||
/** Descendant counts for one possible parent Session. */
|
||||
export interface SubagentDescendantSummary {
|
||||
readonly count: number;
|
||||
readonly runningCount: number;
|
||||
}
|
||||
/**
|
||||
* Index uninterrupted subagent descendants under each ancestor.
|
||||
* @param summaries - Session summaries keyed by id.
|
||||
* @returns descendant totals keyed by possible parent id.
|
||||
*/
|
||||
export declare function indexSubagentDescendants(summaries: Readonly<Record<SessionId, LineageEntry>>): ReadonlyMap<SessionId, SubagentDescendantSummary>;
|
||||
export {};
|
||||
|
|
@ -0,0 +1,45 @@
|
|||
/**
|
||||
* Client side of the session-tab persistence, talking to
|
||||
* `GET|PUT /workspace-groups/tabs` on the host.
|
||||
*
|
||||
* Why not browser storage: **the origin includes the PORT**, and every `dsh web`
|
||||
* / `dsh test` / desktop launch picks a different one. `localStorage` and
|
||||
* `sessionStorage` are both scoped to the origin, so they start empty on the
|
||||
* next launch — a tab list kept there survives a reload only when the port
|
||||
* happens to match. The host's JSON sidecar has no such problem, which is why
|
||||
* the strip is stored there and read back verbatim.
|
||||
*
|
||||
* There is deliberately no per-browser-session marker. A marker has to live in
|
||||
* browser storage, which the port invalidates, so every restart looked like a
|
||||
* fresh session and silently discarded the user's tabs — the exact failure this
|
||||
* module exists to prevent.
|
||||
*
|
||||
* Every call is best-effort: a failed read means "no tabs" and a failed write is
|
||||
* swallowed, because the strip is a convenience and must never break the app.
|
||||
*/
|
||||
/** Host route holding the strip. */
|
||||
export declare const TABS_ROUTE = "/workspace-groups/tabs";
|
||||
/** One tab as it crosses the wire. */
|
||||
export interface WireTab {
|
||||
readonly sessionId: string;
|
||||
readonly order: number;
|
||||
/** Pinned tabs are restored at the front of the strip. */
|
||||
readonly pinned?: boolean;
|
||||
/** A label the user typed for the tab itself (absent = follow the session). */
|
||||
readonly title?: string;
|
||||
}
|
||||
/**
|
||||
* Fetch the stored strip.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
* @returns the tabs, oldest first; empty on any failure.
|
||||
*/
|
||||
export declare function loadTabs(fetchImpl?: typeof fetch): Promise<WireTab[]>;
|
||||
/**
|
||||
* Store the strip. Failures are swallowed.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @param fetchImpl - fetch implementation (injectable for tests).
|
||||
*/
|
||||
export declare function saveTabs(state: {
|
||||
order: number;
|
||||
tabs: readonly WireTab[];
|
||||
}, fetchImpl?: typeof fetch): Promise<void>;
|
||||
|
|
@ -0,0 +1,56 @@
|
|||
/**
|
||||
* DOM seat for the session tab strip.
|
||||
*
|
||||
* Why this exists instead of a slot: the strip belongs at the very top of the
|
||||
* conversation column — `pI_x6G_centerCol` (ui-layout's AppFrame `.centerCol`,
|
||||
* a hashed CSS-Modules class). That column declares NO child slots: its only
|
||||
* child is the `main` slot's occupant (`renderSlot('main', …)`, the
|
||||
* Conversation or a global panel), so there is nowhere to register. The
|
||||
* shipped slot in that neighbourhood — `conversation.composer.dock` — is the
|
||||
* band UNDER the composer card, a different place entirely.
|
||||
*
|
||||
* So the strip gets a real DOM seat: this module finds the column, prepends a
|
||||
* `<div>` to it, and hands that element to a React portal. The element is
|
||||
* OURS, never React's: it is inserted outside the column's child list that
|
||||
* React reconciles, and it is re-inserted if React (or a theme/titlebar
|
||||
* re-render) ever drops it.
|
||||
*
|
||||
* Two hazards this module is built around:
|
||||
*
|
||||
* 1. `centerCol` is a hashed class name (`pI_x6G_centerCol`) that changes when
|
||||
* the package is rebuilt. Matching is therefore done on the *structural*
|
||||
* contract — a grid-item column that holds the `main` panel — plus a
|
||||
* `[class*="_centerCol"]` probe, never on the exact hash.
|
||||
* 2. The column mounts after the client plugin's `apply()` runs. Discovery is
|
||||
* therefore a MutationObserver on `document.body` plus a `requestAnimationFrame`
|
||||
* retry, and both are torn down when the owning effect disposes.
|
||||
*/
|
||||
/** A mounted seat: the host element plus the disposer that removes it. */
|
||||
export interface TabSeat {
|
||||
/**
|
||||
* The element the React portal renders into — null until the conversation
|
||||
* column mounts. The portal is simply not rendered while this is null.
|
||||
*/
|
||||
readonly host: HTMLElement | null;
|
||||
/** Remove the seat and stop watching for the column. */
|
||||
dispose: () => void;
|
||||
}
|
||||
/**
|
||||
* Ensure a seat exists as the FIRST child of the conversation column, creating
|
||||
* it if needed, and keep it there for as long as the returned handle is live.
|
||||
*
|
||||
* The seat element is created once and reused: a portal that re-mounts into a
|
||||
* fresh node on every shell re-render would drop the tab strip's React state
|
||||
* and visible focus. If React removes the node (it owns the column's child
|
||||
* list, and our node is not part of it), the observer re-inserts the SAME
|
||||
* element, so the portal's subtree moves with it.
|
||||
*
|
||||
* @param onReady - called with the host element each time it becomes attached
|
||||
* (once immediately when the column already exists). Used to seed React
|
||||
* state; may fire more than once if the column is remounted.
|
||||
* @returns the seat handle. `host` is null until the column appears, so the
|
||||
* caller renders nothing meanwhile and starts rendering when `onReady`
|
||||
* fires. Never null: a missing column must degrade to "no strip", not to a
|
||||
* thrown error that would take the whole client plugin down.
|
||||
*/
|
||||
export declare function mountTabSeat(onReady: (host: HTMLElement) => void): TabSeat;
|
||||
|
|
@ -0,0 +1,94 @@
|
|||
/**
|
||||
* The session-tab store: the `defineStore` binding and nothing else.
|
||||
*
|
||||
* The action TRANSFORMS live in `tabs.ts` (pure, runtime-free), so unit tests
|
||||
* exercise the real semantics without pulling in the store engine — this module
|
||||
* is the only place that needs `@deepseek-ai/dsh-client-store`, and importing it
|
||||
* from a test would drag `zustand` into the test process.
|
||||
*
|
||||
* One handle, one scope: the tab store is seated by the `sidebar.workspaces`
|
||||
* entry alone. The tab strip is a CHILD of that entry (rendered through a DOM
|
||||
* portal into the conversation column), not a second slot registration, so the
|
||||
* handle is never mounted under a second, differently-scoped slot — which the
|
||||
* registry rejects outright ("one handle, one scope").
|
||||
*
|
||||
* Placement is navigation, not data: the strip derives its active chip from the
|
||||
* open session, and arrival order is the strip's only order, so nothing here
|
||||
* mirrors selection.
|
||||
*/
|
||||
import { type EngineStoreHandle, type StoreHandle } from '@deepseek-ai/dsh-client-store';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import { closeAfterImpl, closeOthersImpl, closeTabImpl, moveTabImpl, pinTabImpl, renameTabImpl, restoreTabsImpl, touchTabImpl, type SessionTab, type SessionTabsState } from './tabs.ts';
|
||||
export type { SessionTabsState };
|
||||
/**
|
||||
* Session-tab strip actions (bound by the framework, handed to the browser).
|
||||
*
|
||||
* There is deliberately NO "drop tabs whose session vanished" action. An open
|
||||
* tab is closed by the USER and by nothing else — a program that trims the strip
|
||||
* on its own eventually eats tabs the user wanted, and the whole point of the
|
||||
* strip is that it holds what you opened.
|
||||
*
|
||||
* This is also why the store needs no catalog at all: it never consults one.
|
||||
*/
|
||||
export interface SessionTabsActions {
|
||||
/** Add the open session, or leave its existing tab untouched in place. */
|
||||
touch: (sessionId: SessionId) => void;
|
||||
/** Close one tab; navigation is untouchable from here (the caller decides). */
|
||||
close: (sessionId: SessionId) => void;
|
||||
/**
|
||||
* Replace the strip with tabs loaded from the host.
|
||||
*
|
||||
* The host read is a `fetch`, so it cannot happen inside `init()`. This action
|
||||
* is how the async result lands, and it is a no-op once the user has already
|
||||
* opened a tab — a slow response must never discard what they just did.
|
||||
*/
|
||||
restore: (tabs: readonly SessionTab[]) => void;
|
||||
/** Pin or unpin one tab (re-inserts it at the block boundary). */
|
||||
pin: (sessionId: SessionId) => void;
|
||||
/** Move one tab to an index in the resulting strip (drag and drop). */
|
||||
move: (sessionId: SessionId, targetIndex: number) => void;
|
||||
/** Set (or clear, with a blank value) one tab's own label. */
|
||||
rename: (sessionId: SessionId, title: string | undefined) => void;
|
||||
/** Close everything except one tab; pinned tabs are kept. */
|
||||
closeOthers: (sessionId: SessionId) => void;
|
||||
/** Close every tab after one in display order. */
|
||||
closeAfter: (sessionId: SessionId) => void;
|
||||
}
|
||||
/** Annotation twin of the actions literal below (structural `ActionsDecl`). */
|
||||
type SessionTabsActionsDecl = {
|
||||
touch: typeof touchTabImpl;
|
||||
close: typeof closeTabImpl;
|
||||
restore: typeof restoreTabsImpl;
|
||||
pin: typeof pinTabImpl;
|
||||
move: typeof moveTabImpl;
|
||||
rename: typeof renameTabImpl;
|
||||
closeOthers: typeof closeOthersImpl;
|
||||
closeAfter: typeof closeAfterImpl;
|
||||
};
|
||||
/**
|
||||
* The tab store's registered handle: identity + spec + the instance factory the
|
||||
* framework resolves per entry x scope. It deliberately does NOT claim the live
|
||||
* instance's faces (`getSnapshot` / `actions`) — `defineStore`'s concrete return
|
||||
* is structurally narrower, and this alias has to stay a type that value can be
|
||||
* assigned to.
|
||||
*/
|
||||
export type SessionTabsStoreHandle = StoreHandle<SessionTabsState, SessionTabsActionsDecl>;
|
||||
/**
|
||||
* The live tab store value: the handle's `create()` product, which carries the
|
||||
* baked write set and the snapshot source. Named here so the registrations and
|
||||
* the strip's props can share one type without importing the store engine.
|
||||
*/
|
||||
export type SessionTabsInstance = ReturnType<EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl>['create']>;
|
||||
/**
|
||||
* Create the session-tab store handle.
|
||||
*
|
||||
* The strip starts EMPTY and is hydrated by the caller through the `restore`
|
||||
* action: persistence lives on the host behind a `fetch`, which cannot run
|
||||
* during `init()`. Browser storage is deliberately not used — the origin
|
||||
* includes the port, and every launch picks a new one, so `localStorage` and
|
||||
* `sessionStorage` both start empty on the next start.
|
||||
*
|
||||
* @returns the store handle (spec + type + identity + factory in one).
|
||||
*/
|
||||
export declare function createSessionTabsStore(): EngineStoreHandle<SessionTabsState, SessionTabsActionsDecl>;
|
||||
export type { SessionTab };
|
||||
|
|
@ -0,0 +1,366 @@
|
|||
/**
|
||||
* Pure session-tab state: the ordered strip of sessions the user has opened,
|
||||
* the active one, and each tab's derived presentation.
|
||||
*
|
||||
* Position model: a tab's place in the strip is decided when it is first opened
|
||||
* and otherwise only moves when the USER moves it. Switching to a tab, or
|
||||
* re-opening a session that already has one, leaves the strip exactly as it was
|
||||
* — so clicking a chip never moves the chip out from under the pointer. The
|
||||
* order changes on: a session opening for the FIRST time (append), a tab closing
|
||||
* (remove), a drag (move), and a pin toggle (which carries the chip across the
|
||||
* pinned boundary).
|
||||
*
|
||||
* The array IS the display order, with one invariant the transforms maintain:
|
||||
* every pinned tab sits before every unpinned one. New tabs therefore append at
|
||||
* the end (the unpinned block) and pinning/unpinning re-inserts at the boundary
|
||||
* between the two blocks. A stored strip from an older build has no `pinned`
|
||||
* flag, which reads as "unpinned" and satisfies the invariant as-is.
|
||||
*
|
||||
* Runtime-free on purpose (same discipline as `store-core.ts` / `quick.ts`):
|
||||
* the component owns the ref + React state, this module owns every rule, and
|
||||
* unit tests exercise the real semantics without a browser module loader.
|
||||
*
|
||||
* Retention note: a tab outlives whatever it points at. The strip is a list of
|
||||
* things the USER opened, so nothing here consults the session catalog — a tab
|
||||
* whose session is gone stays visible until the user closes it, and no
|
||||
* background sweep ever trims the strip.
|
||||
*/
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import type { SessionSummary } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { SessionStatus } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
/** One open tab: a session id plus its arrival key (React list identity). */
|
||||
export interface SessionTab {
|
||||
/** The session the tab shows. */
|
||||
readonly sessionId: SessionId;
|
||||
/**
|
||||
* Monotonic arrival key. It doubles as the React `key`, so it must stay
|
||||
* attached to the session for the tab's whole life — a reused key would make
|
||||
* React move an existing chip's DOM node instead of reconciling it in place.
|
||||
*/
|
||||
readonly order: number;
|
||||
/**
|
||||
* Pinned tabs stay at the front of the strip and survive `close others`.
|
||||
*
|
||||
* Absent means unpinned: that is both the `false` case and the shape an older
|
||||
* build's stored strip has, so no migration step is needed to read one back.
|
||||
*/
|
||||
readonly pinned?: boolean;
|
||||
/**
|
||||
* A label the user typed for THIS tab, overriding the session's title.
|
||||
*
|
||||
* Kept separate from the session title on purpose: renaming a tab here must
|
||||
* not rewrite the conversation's own name (which the sidebar and the search
|
||||
* results show). Absent/empty means "follow the session".
|
||||
*/
|
||||
readonly title?: string;
|
||||
}
|
||||
/** Feature switch: whether opening a session also surfaces a tab. */
|
||||
export type TabOpenMode = 'auto' | 'manual';
|
||||
/** Per-tab indicator derived from the catalog summary and the live UI status. */
|
||||
export interface SessionTabIndicator {
|
||||
/** A domain request is waiting for the user (approval / plan review / question). */
|
||||
readonly attention: boolean;
|
||||
/** The agent is producing output, or a descendant subagent is. */
|
||||
readonly running: boolean;
|
||||
/** The turn finished while the tab was in the background and was never looked at. */
|
||||
readonly unread: boolean;
|
||||
/** Idle tab whose session already has a title (a settled conversation). */
|
||||
readonly settled: boolean;
|
||||
}
|
||||
/**
|
||||
* Add a session to the strip, or leave an existing entry exactly where it is.
|
||||
*
|
||||
* Arrival order is the strip's only order, so re-opening a session that already
|
||||
* has a tab is a NO-OP: the tab keeps its position and its arrival key. Moving
|
||||
* it to the front here would fight the whole point of stable positions — a user
|
||||
* clicking through sessions would watch the strip reshuffle on every click.
|
||||
*
|
||||
* @param tabs - current strip (oldest first).
|
||||
* @param sessionId - arriving session.
|
||||
* @param nextOrder - monotonic arrival counter to spend when appending.
|
||||
* @returns the strip, unchanged (same array) when the session already has a tab.
|
||||
*/
|
||||
export declare function appendTab(tabs: readonly SessionTab[], sessionId: SessionId, nextOrder: number): SessionTab[];
|
||||
/**
|
||||
* Remove one session's tab. An absent session leaves the strip untouched.
|
||||
* @param tabs - current strip.
|
||||
* @param sessionId - session whose tab closes.
|
||||
* @returns a new strip.
|
||||
*/
|
||||
export declare function removeTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
|
||||
/**
|
||||
* Count the leading pinned block.
|
||||
*
|
||||
* The transforms keep every pinned tab before every unpinned one, so the pinned
|
||||
* block is always a prefix and its length is the single index that separates
|
||||
* the two blocks — which is exactly where a chip lands when it changes sides.
|
||||
*
|
||||
* @param tabs - strip in display order.
|
||||
* @returns how many leading tabs are pinned.
|
||||
*/
|
||||
export declare function pinnedCount(tabs: readonly SessionTab[]): number;
|
||||
/**
|
||||
* Stable-partition a strip so every pinned tab precedes every unpinned one.
|
||||
*
|
||||
* Needed by the restore path: stored tabs are merged onto whatever the startup
|
||||
* flow already opened, and an append would otherwise park a pinned tab at the
|
||||
* end of the strip. Already-normalized strips come back as a copy.
|
||||
*
|
||||
* @param tabs - any strip.
|
||||
* @returns a strip satisfying the pinned-first invariant.
|
||||
*/
|
||||
export declare function normalizeTabs(tabs: readonly SessionTab[]): SessionTab[];
|
||||
/**
|
||||
* Move one tab to a new place in the strip (drag and drop).
|
||||
*
|
||||
* `targetIndex` is an index in the RESULTING strip. The move is clamped to the
|
||||
* tab's own block — a dragged chip can be reordered within the pinned block or
|
||||
* within the unpinned one, but never carried across that boundary. Crossing it
|
||||
* is `togglePinTab`'s job, because it changes the tab's meaning rather than
|
||||
* just its position: pinning is what makes a tab survive `close others`.
|
||||
*
|
||||
* @param tabs - strip in display order.
|
||||
* @param sessionId - the tab being moved.
|
||||
* @param targetIndex - desired index in the resulting strip.
|
||||
* @returns a new strip, or the same array when nothing moved.
|
||||
*/
|
||||
export declare function moveTab(tabs: readonly SessionTab[], sessionId: SessionId, targetIndex: number): SessionTab[];
|
||||
/**
|
||||
* Pin or unpin one tab, re-inserting it at the boundary between the blocks.
|
||||
*
|
||||
* Pinning puts the chip at the END of the pinned block (next to the other
|
||||
* kept tabs) and unpinning at the START of the unpinned one, so a toggle never
|
||||
* throws a chip to the far end of the strip.
|
||||
*
|
||||
* @param tabs - strip in display order.
|
||||
* @param sessionId - the tab to toggle.
|
||||
* @returns a new strip, or the same array when the tab is absent.
|
||||
*/
|
||||
export declare function togglePinTab(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
|
||||
/**
|
||||
* Set or clear one tab's own label.
|
||||
*
|
||||
* A blank value CLEARS the override (the chip falls back to the session title)
|
||||
* rather than storing an empty label, so "rename to nothing" and "rename back to
|
||||
* the session title" are the same gesture.
|
||||
*
|
||||
* @param tabs - strip.
|
||||
* @param sessionId - the tab to relabel.
|
||||
* @param title - the new label; blank clears it.
|
||||
* @returns a new strip, or the same array when the tab is absent.
|
||||
*/
|
||||
export declare function renameTab(tabs: readonly SessionTab[], sessionId: SessionId, title: string | undefined): SessionTab[];
|
||||
/**
|
||||
* Close every tab except one — pinned tabs stay.
|
||||
*
|
||||
* Pinning is exactly how a user says "keep this no matter what"; letting
|
||||
* `close others` eat the pinned block would make the flag pointless.
|
||||
*
|
||||
* @param tabs - strip.
|
||||
* @param keepSessionId - the tab to keep (plus every pinned one).
|
||||
* @returns a new strip.
|
||||
*/
|
||||
export declare function closeOtherTabs(tabs: readonly SessionTab[], keepSessionId: SessionId): SessionTab[];
|
||||
/**
|
||||
* Close every tab after one in display order.
|
||||
*
|
||||
* "After" is display order (pinned block first), which is the order the user
|
||||
* sees; a pinned tab is never after an unpinned one, so this cannot silently
|
||||
* drop the kept block.
|
||||
*
|
||||
* @param tabs - strip in display order.
|
||||
* @param sessionId - the last tab that stays.
|
||||
* @returns a new strip, or the same array when the tab is absent.
|
||||
*/
|
||||
export declare function closeTabsAfter(tabs: readonly SessionTab[], sessionId: SessionId): SessionTab[];
|
||||
/**
|
||||
* Order the strip for display: strictly by arrival, regardless of which tab is
|
||||
* active.
|
||||
*
|
||||
* Position is a property of the TAB, not of the selection. Switching to a tab
|
||||
* must not move it — an earlier version pulled the active tab to the front,
|
||||
* which made every click reshuffle the strip and slid the chip out from under
|
||||
* the pointer that had just clicked it.
|
||||
*
|
||||
* `activeId` is therefore accepted only to document that "active" deliberately
|
||||
* does NOT participate in ordering; it is unused. The returned array is a copy
|
||||
* so callers cannot mutate the store's state through it.
|
||||
*
|
||||
* @param tabs - strip in arrival order.
|
||||
* @param activeId - the open session, if it has a tab (intentionally unused).
|
||||
* @returns a new array in arrival order.
|
||||
*/
|
||||
export declare function orderedTabs(tabs: readonly SessionTab[], activeId: SessionId | undefined): SessionTab[];
|
||||
/**
|
||||
* Whether the open session must surface a tab.
|
||||
*
|
||||
* A tab means "this conversation is in play right now", not "I once opened
|
||||
* this". Browsing history is what the sidebar is for; opening an old
|
||||
* conversation to read it should not litter the strip, which is the whole point
|
||||
* of the strip being a working set rather than a second session list.
|
||||
*
|
||||
* A session therefore earns a tab only once a conversation has actually STARTED
|
||||
* in it and is still engaged, which is any of:
|
||||
* - **running** — the agent is producing output (including subagents);
|
||||
* - **waiting on you** — an approval / plan review / question is pending;
|
||||
* - **unseen completion** — it finished while you were elsewhere, so the tab is
|
||||
* the thing that tells you to come back.
|
||||
*
|
||||
* A still-blank draft gets NO tab: the tab appears the moment the first message
|
||||
* is sent (which is when the controller flips `blank` on `turn/start`). Once the
|
||||
* turn ends and you have read the result, the session is settled history and
|
||||
* does not earn a tab — so clicking through finished conversations leaves the
|
||||
* strip alone. Tabs already opened stay open: this gate only decides whether a
|
||||
* NEW tab appears, never whether an existing one closes.
|
||||
*
|
||||
* `blank` (from `sessionListMetadata`) is exactly "no turn has started": the
|
||||
* controller flips it to false on `turn/start`. It is the right signal for
|
||||
* "has this conversation begun", and the wrong one ALONE — a conversation
|
||||
* finished a week ago is also non-blank, which is why the earlier `!blank` rule
|
||||
* surfaced every old conversation the user clicked.
|
||||
*
|
||||
* @param mode - feature switch ('auto' applies the engagement rule).
|
||||
* @param summary - the session's catalog row (absent while the catalog has not
|
||||
* caught up with a just-created session).
|
||||
* @param status - the session's unified UI status (absent → no live signal).
|
||||
* @returns true when a tab belongs in the strip.
|
||||
*/
|
||||
export declare function shouldOpenTab(mode: TabOpenMode, summary: SessionSummary | undefined, status: SessionStatus | undefined): boolean;
|
||||
/**
|
||||
* Derive one tab's indicators from the catalog row and the unified UI status.
|
||||
* @param summary - the tab session's catalog row (absent → inert indicators).
|
||||
* @param status - the tab session's unified UI status (absent → idle).
|
||||
* @returns the indicator quadruple.
|
||||
*/
|
||||
export declare function tabIndicator(summary: SessionSummary | undefined, status: SessionStatus | undefined): SessionTabIndicator;
|
||||
/**
|
||||
* Where one session lives: the project (workspace) that accounts for it.
|
||||
*
|
||||
* Tabs carry this because a strip of bare session titles is ambiguous once
|
||||
* several projects are open — two checkouts both named "api", or a session
|
||||
* titled after a file, give no hint which project it belongs to.
|
||||
*/
|
||||
export interface TabProject {
|
||||
/** Stable workspace id. */
|
||||
readonly workspaceId: string;
|
||||
/** Display label: the workspace title, falling back to its directory name. */
|
||||
readonly label: string;
|
||||
/** Canonical directory path, for the tooltip. */
|
||||
readonly path: string;
|
||||
}
|
||||
/**
|
||||
* Index sessions by the project that owns them.
|
||||
*
|
||||
* Membership comes from the workspace registry (`sessionIds`), which is the same
|
||||
* authority the sidebar tree uses — a tab and its sidebar row therefore agree on
|
||||
* the project without a second derivation.
|
||||
*
|
||||
* Built once per render pass rather than scanned per tab: a strip of N tabs over
|
||||
* M projects is O(N×M) with a naive `find` per tab.
|
||||
*
|
||||
* @param workspaces - workspace views from the controller snapshot.
|
||||
* @returns a session id → project map; sessions in no workspace are absent.
|
||||
*/
|
||||
export declare function projectIndex(workspaces: readonly WorkspaceViewLike[]): ReadonlyMap<SessionId, TabProject>;
|
||||
/** Minimal workspace shape this module needs (keeps it importable in tests). */
|
||||
export interface WorkspaceViewLike {
|
||||
readonly workspaceId: string;
|
||||
readonly path: string;
|
||||
readonly title: string;
|
||||
readonly sessionIds: readonly SessionId[];
|
||||
}
|
||||
/**
|
||||
* Display label for a project: its title, else the directory basename.
|
||||
* @param workspace - workspace view.
|
||||
* @returns a non-empty label, falling back to the raw path.
|
||||
*/
|
||||
export declare function projectLabel(workspace: Pick<WorkspaceViewLike, 'title' | 'path'>): string;
|
||||
/**
|
||||
* Whether two strips are the same sequence of sessions (arrival keys ignored).
|
||||
* @param left - previous strip.
|
||||
* @param right - next strip.
|
||||
* @returns true when no entry was added, removed, or reordered.
|
||||
*/
|
||||
export declare function sameTabs(left: readonly SessionTab[], right: readonly SessionTab[]): boolean;
|
||||
/** Session-tab strip state (the shape the store persists). */
|
||||
export interface SessionTabsState {
|
||||
/** Open tabs in arrival order — the strip's one and only order. */
|
||||
tabs: SessionTab[];
|
||||
/** Monotonic arrival counter; each FIRST-time session spends one. */
|
||||
order: number;
|
||||
}
|
||||
/**
|
||||
* Store transform: add the open session, or leave its existing tab in place.
|
||||
*
|
||||
* Live here rather than in `tab-store.ts` so unit tests can exercise the real
|
||||
* semantics without importing `@deepseek-ai/dsh-client-store` (which pulls
|
||||
* `zustand` into the test process). The store module binds these into its
|
||||
* actions table.
|
||||
*
|
||||
* The no-op guard matters: this runs on EVERY catalog change for the open
|
||||
* session, so an unguarded write would wake the strip and spend arrival keys on
|
||||
* every projection tick.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the session that just became open.
|
||||
*/
|
||||
export declare function touchTabImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: close one tab. Closing a session that has no tab is not a
|
||||
* state change, so it writes nothing.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab to close.
|
||||
*/
|
||||
export declare function closeTabImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: adopt tabs loaded from the host, MERGING with whatever is
|
||||
* already in the strip.
|
||||
*
|
||||
* Async by nature (the host read is a `fetch`), so it can land after the browser
|
||||
* has already opened a tab for the current session. Merging — rather than
|
||||
* "ignore the read if the strip is non-empty" — is what makes a restart safe:
|
||||
* the tab opened during startup survives AND the stored tabs still come back.
|
||||
* (Bailing on a non-empty strip would silently drop every stored tab whenever
|
||||
* the startup tab won the race, which is the common case for a session that is
|
||||
* running or unread.)
|
||||
*
|
||||
* The arrival counter is lifted above every restored key so a tab opened later
|
||||
* cannot reuse one; a reused key makes React move a chip's DOM node instead of
|
||||
* reconciling it.
|
||||
*
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param tabs - tabs read from the host, oldest first.
|
||||
*/
|
||||
export declare function restoreTabsImpl(state: SessionTabsState, tabs: readonly SessionTab[]): void;
|
||||
/**
|
||||
* Store transform: pin or unpin one tab.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab to toggle.
|
||||
*/
|
||||
export declare function pinTabImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: move one tab to a new index (drag and drop).
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab being moved.
|
||||
* @param targetIndex - desired index in the resulting strip.
|
||||
*/
|
||||
export declare function moveTabImpl(state: SessionTabsState, sessionId: SessionId, targetIndex: number): void;
|
||||
/**
|
||||
* Store transform: set or clear one tab's own label.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the tab to relabel.
|
||||
* @param title - the new label; blank clears it.
|
||||
*/
|
||||
export declare function renameTabImpl(state: SessionTabsState, sessionId: SessionId, title: string | undefined): void;
|
||||
/**
|
||||
* Store transform: close every unlisted tab, keeping the pinned ones.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param keepSessionId - the tab to keep.
|
||||
*/
|
||||
export declare function closeOthersImpl(state: SessionTabsState, keepSessionId: SessionId): void;
|
||||
/**
|
||||
* Store transform: close every tab after one in display order.
|
||||
* @param state - store draft, mutated in place.
|
||||
* @param sessionId - the last tab that stays.
|
||||
*/
|
||||
export declare function closeAfterImpl(state: SessionTabsState, sessionId: SessionId): void;
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
/**
|
||||
* 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 { SessionListState, SessionSearchResultItem } from '@deepseek-ai/dsh-api-session-controller/client';
|
||||
import type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-api-workspace-controller/client';
|
||||
import type { SessionStatusSnapshot } from '@deepseek-ai/dsh-client-ui-session/client';
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session/types';
|
||||
import { type FoldersDocument } from '../core/folders.ts';
|
||||
import { type CategoryAppearance, type GroupsConfig, type ManualGroups } from '../core/types.ts';
|
||||
/** Pending interaction kinds with dedicated Workspace-row presentation. */
|
||||
export type SessionPendingInteractionStatus = 'approval' | 'plan-review' | 'question';
|
||||
/** Current unified UI status by Session (ui-session snapshot). */
|
||||
type SessionStatuses = SessionStatusSnapshot;
|
||||
/**
|
||||
* The Session the Conversation is currently showing.
|
||||
*
|
||||
* 0.1.6 removed `SessionListState.current`: selection is expressed as the
|
||||
* Session retained through the `mainView` reference source (the ui-workspace
|
||||
* navigation holds exactly one). Same read the official browser performs.
|
||||
* @param list - sessions list snapshot.
|
||||
* @returns the retained Session id, or undefined while no Session is selected.
|
||||
*/
|
||||
export declare function currentSessionId(list: SessionListState): SessionId | undefined;
|
||||
/** 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?: SessionPendingInteractionStatus;
|
||||
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 folder row inside a workspace folder (base or extra). */
|
||||
export interface FolderNode {
|
||||
/** Absolute folder path. */
|
||||
path: string;
|
||||
/** Display label: last path segment, or the whole path for drive roots. */
|
||||
label: string;
|
||||
/** The workspace's default target for new sessions (★). */
|
||||
isRoot: boolean;
|
||||
expanded: boolean;
|
||||
/** The workspace's own canonical directory (folder #0); cannot be removed. */
|
||||
isBase: boolean;
|
||||
/** Visible sessions whose recorded cwd lives inside this folder. */
|
||||
sessions: readonly SessionNode[];
|
||||
}
|
||||
/** 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 (every folder included). */
|
||||
sessionCount: number;
|
||||
expanded: boolean;
|
||||
/** The folder contains the selected session (active folder tint). */
|
||||
containsCurrent: boolean;
|
||||
/** Base-owned visible session rows (empty while the folder is folded). */
|
||||
sessions: readonly SessionNode[];
|
||||
/**
|
||||
* Folder rows, present only when the workspace carries at least one extra
|
||||
* folder: root first, then stored order, base included. Absent means "this
|
||||
* workspace has exactly one directory", the plain pre-folders node shape.
|
||||
*/
|
||||
folders?: readonly FolderNode[];
|
||||
}
|
||||
/** 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[];
|
||||
/** Presentation (color / icon / pin) for this category, when configured. */
|
||||
appearance?: CategoryAppearance;
|
||||
}
|
||||
/** Viewing state consumed by the derivation. */
|
||||
export interface GroupsTreeView {
|
||||
expandedCategories: readonly string[];
|
||||
expandedWorkspaces: readonly string[];
|
||||
/**
|
||||
* Collapsed folder rows, keyed by `folderKey(workspaceId, path)`. Folders are
|
||||
* expanded by default: adding a folder must never hide the sessions that used
|
||||
* to show flat under the project.
|
||||
*/
|
||||
collapsedFolders?: readonly string[];
|
||||
}
|
||||
/** Key of the uncategorized bucket (matches the config fallback label). */
|
||||
export declare const UNCATEGORIZED_KEY = "\u672A\u5206\u7C7B";
|
||||
/** Whether this category key names the "not yet classified" bucket. */
|
||||
export declare function isDockedCategoryKey(key: string): boolean;
|
||||
/** Directory display label: basename of the path (both separators accepted). */
|
||||
export declare function workspaceLabel(cwd: string | undefined): string;
|
||||
/** A workspace-backed ("member") folder resolved against the workspace list. */
|
||||
export interface MemberWorkspaces {
|
||||
/** Member workspace id → owning workspace id (the rows to hide). */
|
||||
absorbed: ReadonlyMap<string, string>;
|
||||
/** Owning workspace id → member workspaces in stored folder order. */
|
||||
byOwner: ReadonlyMap<string, readonly WorkspaceView[]>;
|
||||
}
|
||||
/**
|
||||
* Resolve the workspace-backed folders of every project.
|
||||
*
|
||||
* A member folder is a real DSH workspace whose OWN row must disappear: its
|
||||
* sessions are rendered under its owner's folder row instead, so one project can
|
||||
* carry local and cloud (SSH-mirrored) folders at once. Members the Host no
|
||||
* longer knows are dropped from the index — the folder row survives (its path is
|
||||
* still stored) but shows no sessions.
|
||||
* @param workspaces - real workspaces in Host order.
|
||||
* @param folders - per-workspace extra folders + members + root.
|
||||
*/
|
||||
export declare function memberWorkspaces(workspaces: readonly WorkspaceView[], folders?: FoldersDocument): MemberWorkspaces;
|
||||
/**
|
||||
* Display label of one folder: the last path segment. A drive root (`C:\`) or
|
||||
* the POSIX root has no segment, so the whole path is the honest label.
|
||||
* @param path - absolute folder path.
|
||||
*/ export declare function folderLabel(path: string): string;
|
||||
/** Stable identity of one folder row (same path may live under two workspaces). */
|
||||
export declare function folderKey(workspaceId: WorkspaceId, path: string): 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 (rule categories).
|
||||
* @param view - local expansion arrays.
|
||||
* @param manual - runtime overlay (manual groups + overrides). A workspace's
|
||||
* manual override wins over rule classification; removing it reverts to rules.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root. A workspace with extras
|
||||
* gains folder rows and its extra-folder sessions move under them; a workspace
|
||||
* without extras keeps exactly the pre-folders node shape.
|
||||
* @returns category sections in render order (rule categories first, then
|
||||
* manual-only ones, uncategorized last). Manual groups render even while
|
||||
* empty; empty rule buckets stay hidden.
|
||||
*/
|
||||
export declare function deriveGroups(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): CategoryNode[];
|
||||
/**
|
||||
* Top-level (ungrouped) workspace rows: workspaces resolving to no category
|
||||
* (no manual override and no matching rule, or a forced `null` override).
|
||||
* Rendered after the group folders as plain project rows (not inside any
|
||||
* folder), in manual top-level order (`workspaceOrder[TOP_LEVEL_ORDER_KEY]`),
|
||||
* falling back to host registration order.
|
||||
*/
|
||||
export declare function deriveTopLevel(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], config: GroupsConfig, view: GroupsTreeView, manual: ManualGroups, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode[];
|
||||
/**
|
||||
* The Host's default workspace as a standalone node for the pinned bottom bar.
|
||||
*
|
||||
* The default workspace is not part of the grouping tree (it is excluded from
|
||||
* `deriveGroups`, `deriveTopLevel` and the search results), yet it keeps the
|
||||
* full workspace-row behaviour: expansion, session count, its sessions and its
|
||||
* extra folders. This derives exactly that node, reusing the same visibility,
|
||||
* folder partitioning and current-session marking as the tree.
|
||||
*
|
||||
* @param list - sessions list snapshot.
|
||||
* @param workspaces - real workspaces in stable Host order.
|
||||
* @param archivedSessionIds - registry-global archive set.
|
||||
* @param view - local expansion arrays.
|
||||
* @param statuses - unified UI status by Session.
|
||||
* @param folders - per-workspace extra folders + root.
|
||||
* @returns the default workspace node, or undefined when the Host has none.
|
||||
*/
|
||||
export declare function deriveDefaultWorkspace(list: SessionListState, workspaces: readonly WorkspaceView[], archivedSessionIds: readonly SessionId[], view: GroupsTreeView, statuses?: SessionStatuses, folders?: FoldersDocument): WorkspaceGroupNode | undefined;
|
||||
/** 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, folders?: FoldersDocument): SearchMatchSet;
|
||||
/** Search tree: group folders plus top-level (ungrouped) matched workspaces. */
|
||||
export interface SearchTree {
|
||||
/** Group folders containing matched sessions, in display order. */
|
||||
categories: CategoryNode[];
|
||||
/** Top-level (ungrouped) workspaces holding matched sessions. */
|
||||
topLevel: WorkspaceGroupNode[];
|
||||
/**
|
||||
* The Host default workspace's matched branch, when it has a hit. It is
|
||||
* rendered in the pinned bottom bar instead of the results list, so a hit
|
||||
* never makes the default workspace appear twice.
|
||||
*/
|
||||
defaultWorkspace?: WorkspaceGroupNode;
|
||||
}
|
||||
/**
|
||||
* 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.
|
||||
* Classification uses the same precedence as the idle tree (manual override →
|
||||
* rules), so search shows the same grouping the user sees. Matched top-level
|
||||
* workspaces are returned separately (rendered as plain rows).
|
||||
*
|
||||
* @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 manual - runtime overlay (manual groups + overrides).
|
||||
* @param snippetsBySession - optional content-match snippets keyed by session id.
|
||||
* @param statuses - unified UI status by Session (drives the running / warning
|
||||
* / unread-completion row indicators); defaults to none (tests).
|
||||
* @param folders - per-workspace extra folders + root, so a hit inside an extra
|
||||
* folder surfaces under that folder instead of flat under the project.
|
||||
* @returns group folders in render order plus top-level matched workspaces,
|
||||
* pruned to matched branches only.
|
||||
*/
|
||||
export declare function deriveSearchGroups(list: SessionListState, workspaces: readonly WorkspaceView[], config: GroupsConfig, matchedIds: ReadonlySet<SessionId>, archivedSessionIds: readonly SessionId[], manual: ManualGroups, snippetsBySession?: ReadonlyMap<SessionId, string>, statuses?: SessionStatuses, folders?: FoldersDocument): SearchTree;
|
||||
export {};
|
||||
|
|
@ -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,32 @@
|
|||
/**
|
||||
* Recognising the Host's own default workspace ("默认工作区").
|
||||
*
|
||||
* The workspace snapshot carries no `isDefault` flag, so the only Host-owned
|
||||
* signal is the one the Host itself uses: the registry title. Its
|
||||
* `workspaceDisplayTitle()` treats a title equal to `DEFAULT_WORKSPACE_DIRECTORY`
|
||||
* as "the default workspace" and swaps in a localized label. That constant lives
|
||||
* in the workspace-controller package, which this plugin must not import at
|
||||
* runtime (it is a client bundle), so the string is mirrored here.
|
||||
*
|
||||
* Two Host signals are combined:
|
||||
* - the registry title (primary: exactly what the Host substitutes for);
|
||||
* - the Host's own directory layout (`<Documents>/deepseek-harness/default-workspace`),
|
||||
* which still identifies the workspace after the user renames it.
|
||||
* A user-created directory that merely happens to be called "default-workspace"
|
||||
* somewhere else on disk is NOT treated as the default workspace, and no single
|
||||
* directory name is used as the sole test.
|
||||
*/
|
||||
/** Directory name the Host uses for its default workspace (host mirror). */
|
||||
export declare const DEFAULT_WORKSPACE_TITLE = "default-workspace";
|
||||
/** The fields the identification needs from a workspace snapshot. */
|
||||
export interface DefaultWorkspaceIdentity {
|
||||
/** Registry title (`WorkspaceView.title`). */
|
||||
title?: string | undefined;
|
||||
/** Absolute workspace directory (`WorkspaceView.path`). */
|
||||
path?: string | undefined;
|
||||
}
|
||||
/**
|
||||
* Whether a workspace snapshot is the Host's default workspace.
|
||||
* @param workspace - workspace snapshot (title is the primary signal, path the fallback).
|
||||
*/
|
||||
export declare function isDefaultWorkspace(workspace: DefaultWorkspaceIdentity): boolean;
|
||||
|
|
@ -0,0 +1,219 @@
|
|||
/**
|
||||
* Pure folder-list logic for per-workspace multi-root folders.
|
||||
*
|
||||
* DSH core gives a workspace exactly ONE canonical directory
|
||||
* (`WorkspaceView.path`). This module layers a plugin-owned list of EXTRA
|
||||
* folders on top of it, plus one designated root folder per workspace:
|
||||
*
|
||||
* - the canonical directory is always folder #0 (the "base"); it cannot be
|
||||
* removed and may be the root;
|
||||
* - `root` is stored only when it names an EXTRA folder — "base is the root"
|
||||
* is expressed by omitting the key, so the base path is never duplicated
|
||||
* into the sidecar;
|
||||
* - a session whose recorded `cwd` lives inside an extra folder belongs to
|
||||
* that folder, not to the project row.
|
||||
*
|
||||
* Everything here is pure and platform-agnostic: it imports no React, no DOM
|
||||
* and no cordis so plain Node (the verifier, the host route) can load it.
|
||||
*/
|
||||
/** Kind of a member folder: a plain local directory, or an SSH-mirrored one. */
|
||||
export type FolderMemberKind = 'local' | 'remote';
|
||||
/**
|
||||
* A folder row that is backed by its OWN DSH workspace ("member").
|
||||
*
|
||||
* Plain extra folders ( {@link WorkspaceFolderEntry.folders} ) live inside the
|
||||
* owner's canonical directory tree and their sessions run with the OWNER's
|
||||
* workspace id. A member has a directory the owner cannot reach that way — a
|
||||
* remote (mirror-backed) folder, or a local directory added to a remote project
|
||||
* — so the platform registers a real workspace for it and the row delegates
|
||||
* session creation to that workspace id. The member's own workspace row is
|
||||
* hidden from the sidebar while some entry lists it (see
|
||||
* {@link absorbedWorkspaceIds}), so the project reads as one project with both
|
||||
* kinds of folders.
|
||||
*/
|
||||
export interface FolderMember {
|
||||
/** Absolute LOCAL path of the member workspace (its canonical directory). */
|
||||
readonly path: string;
|
||||
/** Native DSH workspace id backing this folder row. */
|
||||
readonly workspaceId: string;
|
||||
readonly kind: FolderMemberKind;
|
||||
/** Remote root, when `kind` is 'remote' (`~`, `~/proj`, `/srv/proj`). */
|
||||
readonly remotePath?: string;
|
||||
/** SSH connection profile id, when `kind` is 'remote'. */
|
||||
readonly profileId?: string;
|
||||
/** remote-ssh's own record id, when `kind` is 'remote'. */
|
||||
readonly recordId?: string;
|
||||
/** Display title the platform gave the member workspace. */
|
||||
readonly title?: string;
|
||||
}
|
||||
/** Folders attached to one workspace: EXTRA folders only (the base is implicit). */
|
||||
export interface WorkspaceFolderEntry {
|
||||
/**
|
||||
* Plain local extra folders: directories the owner workspace can address
|
||||
* directly, so their sessions keep the owner's workspace id.
|
||||
*/
|
||||
readonly folders: readonly string[];
|
||||
/** Workspace-backed extra folders (remote mirrors, or local on a remote owner). */
|
||||
readonly members?: readonly FolderMember[];
|
||||
readonly root?: string;
|
||||
}
|
||||
/** The whole `workspace-groups.folders.json` document. */
|
||||
export interface FoldersDocument {
|
||||
readonly version: 1;
|
||||
/**
|
||||
* Monotonic write counter, owned by the host: every accepted PUT bumps it
|
||||
* and a PUT whose revision does not match the stored one is rejected
|
||||
* (409), so two windows can no longer silently overwrite each other's
|
||||
* edits. Absent in documents written before revisions existed — read as 0.
|
||||
*/
|
||||
readonly revision?: number;
|
||||
readonly workspaces: Readonly<Record<string, WorkspaceFolderEntry>>;
|
||||
}
|
||||
/** Canonical empty document, shared so callers need not allocate one each time. */
|
||||
export declare const EMPTY_FOLDERS_DOCUMENT: FoldersDocument;
|
||||
/**
|
||||
* Path equality: case-insensitive for Windows-style paths, tolerant of
|
||||
* trailing separators, exact for POSIX paths.
|
||||
* @param a - first path.
|
||||
* @param b - second path.
|
||||
*/
|
||||
export declare function samePath(a: string, b: string): boolean;
|
||||
/**
|
||||
* Look up the folder entry saved for one workspace.
|
||||
* @param doc - folders document.
|
||||
* @param workspaceId - host workspace id.
|
||||
* @returns the entry, or undefined when the workspace has none.
|
||||
*/
|
||||
export declare function entryFor(doc: FoldersDocument, workspaceId: string): WorkspaceFolderEntry | undefined;
|
||||
/**
|
||||
* The workspace's effective folder list, base first. The base cannot be
|
||||
* duplicated and blank extra entries are dropped.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
*/
|
||||
export declare function effectiveFolders(workspacePath: string, entry: WorkspaceFolderEntry | undefined): readonly string[];
|
||||
/**
|
||||
* The member record behind one folder path, when that folder is workspace-backed.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param path - folder path as stored.
|
||||
*/
|
||||
export declare function memberOf(entry: WorkspaceFolderEntry | undefined, path: string): FolderMember | undefined;
|
||||
/**
|
||||
* Light canonical form of a REMOTE path (POSIX — the server's filesystem):
|
||||
* trimmed, trailing slashes removed. Deliberately string-only: the client
|
||||
* cannot resolve `~` or symlinks; the remote-ssh host canonicalizes fully
|
||||
* at registration time. This is the second line of defense, catching the
|
||||
* spelling variants a user can type into the add-cloud-folder dialog.
|
||||
* @param raw - remote path as typed or as stored.
|
||||
*/
|
||||
export declare function lightRemotePath(raw: string): string;
|
||||
/**
|
||||
* Whether two remote paths name the same directory under {@link lightRemotePath}.
|
||||
* @param a - first remote path.
|
||||
* @param b - second remote path.
|
||||
*/
|
||||
export declare function sameRemotePath(a: string, b: string): boolean;
|
||||
/**
|
||||
* The member backed by one native workspace id, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param workspaceId - native workspace id backing the member.
|
||||
*/
|
||||
export declare function memberByWorkspaceId(entry: WorkspaceFolderEntry | undefined, workspaceId: string): FolderMember | undefined;
|
||||
/**
|
||||
* The remote member for one connection + remote directory, when one exists.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @param profileId - remote-ssh connection id.
|
||||
* @param remotePath - remote directory to look up.
|
||||
*/
|
||||
export declare function findRemoteMember(entry: WorkspaceFolderEntry | undefined, profileId: string, remotePath: string): FolderMember | undefined;
|
||||
/**
|
||||
* Every member folder of one owner workspace, in stored order.
|
||||
* @param doc - folders document.
|
||||
* @param ownerWorkspaceId - workspace the members hang off.
|
||||
*/
|
||||
export declare function membersOf(doc: FoldersDocument, ownerWorkspaceId: string): readonly FolderMember[];
|
||||
/**
|
||||
* Member workspace id → owning workspace id.
|
||||
*
|
||||
* These are the workspaces whose own row disappears from the sidebar: their
|
||||
* sessions render under the owning project's folder row instead. A workspace
|
||||
* that is itself an owner (it carries an entry) is never absorbed — absorbing
|
||||
* it would hide a project together with the folders nested below it.
|
||||
* @param doc - folders document.
|
||||
*/
|
||||
export declare function absorbedWorkspaceIds(doc: FoldersDocument): ReadonlyMap<string, string>;
|
||||
/**
|
||||
* True when the entry carries neither a plain folder nor a member, i.e. it can
|
||||
* be dropped from the sidecar instead of being written empty.
|
||||
* @param entry - folder entry.
|
||||
*/
|
||||
export declare function isEmptyEntry(entry: WorkspaceFolderEntry | undefined): boolean;
|
||||
/**
|
||||
* The folder new sessions start in by default.
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the stored root when it names an effective extra folder, else the
|
||||
* workspace's own directory.
|
||||
*/
|
||||
export declare function rootOf(workspacePath: string, entry: WorkspaceFolderEntry | undefined): string;
|
||||
/**
|
||||
* Owning folder of a session cwd: the most specific (longest) effective folder
|
||||
* that equals the cwd or is a proper path ancestor of it.
|
||||
* @param cwd - recorded session cwd; undefined means "the workspace itself".
|
||||
* @param workspacePath - canonical directory of the workspace.
|
||||
* @param entry - saved folder entry, if any.
|
||||
* @returns the owning folder, or the workspace path when nothing matches.
|
||||
*/
|
||||
export declare function folderOfCwd(cwd: string | undefined, workspacePath: string, entry: WorkspaceFolderEntry | undefined): string;
|
||||
/**
|
||||
* Append an extra folder. Idempotent under `samePath`, and the stored root (if
|
||||
* any) survives untouched.
|
||||
* @param entry - current entry, or undefined for a workspace with no extras.
|
||||
* @param path - folder path to append.
|
||||
*/
|
||||
export declare function addFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
/**
|
||||
* Append a workspace-backed folder. Idempotent under `samePath`: a later call
|
||||
* for the same path replaces the stored member (so a re-registered workspace id
|
||||
* wins) instead of stacking a duplicate row.
|
||||
* @param entry - current entry, or undefined for a workspace with no extras.
|
||||
* @param member - member record to store.
|
||||
*/
|
||||
export declare function addMember(entry: WorkspaceFolderEntry | undefined, member: FolderMember): WorkspaceFolderEntry;
|
||||
/**
|
||||
* Drop an extra folder, plain or workspace-backed. A root that pointed at it is
|
||||
* cleared, so the workspace falls back to its own directory instead of
|
||||
* referencing a folder it no longer has.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder path to drop.
|
||||
*/
|
||||
export declare function removeFolder(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
/**
|
||||
* Designate the root folder. Only an extra folder can be stored: naming the
|
||||
* base directory means "no explicit root", which is represented by clearing
|
||||
* the key.
|
||||
* @param entry - current entry, or undefined.
|
||||
* @param path - folder to make the root.
|
||||
*/
|
||||
export declare function setRoot(entry: WorkspaceFolderEntry | undefined, path: string): WorkspaceFolderEntry;
|
||||
/**
|
||||
* True when `path` is `base` itself or lives somewhere below it, with the same
|
||||
* separator and case rules as {@link samePath}.
|
||||
* @param path - candidate path.
|
||||
* @param base - containing directory.
|
||||
*/
|
||||
export declare function isUnderBase(path: string, base: string): boolean;
|
||||
/**
|
||||
* Resolve a user-typed SUBPATH against a base directory.
|
||||
*
|
||||
* This is what remote (mirror-backed) workspaces need: their canonical
|
||||
* directory is a local mirror of a remote root, so an extra folder must be a
|
||||
* directory INSIDE the mirror — that is the only spelling that also exists on
|
||||
* the remote side. Absolute input and `..` escapes are rejected outright so a
|
||||
* typo cannot smuggle in an unrelated local directory.
|
||||
* @param base - the workspace's canonical directory.
|
||||
* @param relative - typed subpath, either separator style.
|
||||
* @returns the joined path, or null when the input is empty, absolute, or
|
||||
* escapes the base.
|
||||
*/
|
||||
export declare function joinSubpath(base: string, relative: string): string | null;
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
/**
|
||||
* Pure classification + ordering logic: decides which category a workspace
|
||||
* belongs to and how categories/workspaces are ordered. Shared by the host
|
||||
* half (validation) and the client half (tree derivation), so the semantics
|
||||
* can never drift between the config surface and the rendered tree.
|
||||
*
|
||||
* Category identity: a category's STABLE origin is its YAML rule category
|
||||
* name (or a manual-group name). Its DISPLAY key is what the tree renders and
|
||||
* what assignments reference — for rule categories that is the rename
|
||||
* override when present. Hidden rule categories are inert: workspaces that
|
||||
* would match them become top-level (ungrouped).
|
||||
*/
|
||||
import { type CategoryAppearance, type GroupCategory, type GroupsConfig, type ManualGroups } from './types.ts';
|
||||
/** Classify a workspace by rules only; hidden categories are inert. */
|
||||
export declare function classify(categories: readonly GroupCategory[], path: string, title: string): GroupCategory | undefined;
|
||||
/** Display name of a rule category: the rename override when present. */
|
||||
export declare function ruleDisplayName(manual: ManualGroups | undefined, originalName: string): string;
|
||||
/** Whether a rule category has been hidden by a UI delete. */
|
||||
export declare function isHiddenRule(manual: ManualGroups | undefined, originalName: string): boolean;
|
||||
/** Presentation for a category display key, or undefined when unset. */
|
||||
export declare function categoryAppearance(manual: ManualGroups | undefined, key: string): CategoryAppearance | undefined;
|
||||
/** Whether a category display key is pinned. */
|
||||
export declare function isCategoryPinned(manual: ManualGroups | undefined, key: string): boolean;
|
||||
/**
|
||||
* Drop empty presentation fields: `undefined` values, `pinned: false`, `icon: ''`.
|
||||
* Returns undefined when nothing is left, so callers can delete the whole entry.
|
||||
*/
|
||||
export declare function pruneAppearance(value: CategoryAppearance): CategoryAppearance | undefined;
|
||||
/** Rule category display names, in YAML render order (hidden ones excluded). */
|
||||
export declare function ruleDisplayNames(categories: readonly GroupCategory[], manual: ManualGroups | undefined): string[];
|
||||
/** Original YAML rule name whose display name equals `key` (undefined when none). */
|
||||
export declare function originalRuleNameForDisplay(categories: readonly GroupCategory[], manual: ManualGroups | undefined, key: string): string | undefined;
|
||||
/**
|
||||
* Effective category entries in display order: rule categories (YAML order,
|
||||
* hidden skipped, renamed applied) first, then manual-only groups in
|
||||
* creation order — unless `manual.categoryOrder` overrides the sequence.
|
||||
* Top-level (ungrouped) workspaces are never included; they render as
|
||||
* separate top-level rows after the group folders.
|
||||
*
|
||||
* The pin partition is part of DISPLAY ORDER, not a render-time concern:
|
||||
* pinned groups sort before unpinned ones *within* the manual order, and both
|
||||
* the tree and the drag-drop landing neighbours read this list, so they can
|
||||
* never disagree about what sits next to what.
|
||||
*/
|
||||
export interface EffectiveCategory {
|
||||
/** Display key (what the tree renders and assignments reference). */
|
||||
key: string;
|
||||
/** Origin: a YAML rule category or a manual group. */
|
||||
source: 'rule' | 'manual';
|
||||
}
|
||||
export declare function effectiveCategories(config: GroupsConfig, manual: ManualGroups | undefined): EffectiveCategory[];
|
||||
/** Display keys of all effective categories (top-level workspaces excluded). */
|
||||
export declare function displayCategoryKeys(config: GroupsConfig, manual: ManualGroups | undefined): string[];
|
||||
/**
|
||||
* Resolve the category key a workspace renders under, or `undefined` when it
|
||||
* is top-level (ungrouped). Precedence: manual override (`null` = forced
|
||||
* top-level) → rule classification (hidden rules inert) → top-level.
|
||||
*/
|
||||
export declare function resolveCategory(config: GroupsConfig, manual: ManualGroups | undefined, workspaceId: string, path: string, title: string): string | undefined;
|
||||
/** Whether a category key is a manual-only group (manageable via list). */
|
||||
export declare function isManualOnlyCategory(config: GroupsConfig, manual: ManualGroups | undefined, key: string): boolean;
|
||||
/**
|
||||
* Names that may not be used for a new/renamed group: the legacy reserved
|
||||
* label plus every current display key.
|
||||
*/
|
||||
export declare function takenCategoryNames(config: GroupsConfig, manual: ManualGroups | undefined): Set<string>;
|
||||
/**
|
||||
* Order a bucket of workspace ids: the stored per-category order first
|
||||
* (filtered to actual members), then any remaining members in `fallback`
|
||||
* (host) order. Deterministic; the renderer never re-sorts on its own.
|
||||
*/
|
||||
export declare function orderedWorkspaceIds(manual: ManualGroups | undefined, categoryKey: string, members: readonly string[]): string[];
|
||||
/** Move `id` before `beforeId` (undefined = append) within an ordered list. */
|
||||
export declare function moveBefore(list: readonly string[], id: string, beforeId: string | undefined): string[];
|
||||
/** Move `id` after `afterId` (undefined = append) within an ordered list. */
|
||||
export declare function moveAfter(list: readonly string[], id: string, afterId: string | undefined): string[];
|
||||
|
|
@ -0,0 +1,139 @@
|
|||
/**
|
||||
* Shared config types for @dsh-xhl/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[];
|
||||
}
|
||||
/** Theme-safe palette id for a group's accent. */
|
||||
export type GroupColor = 'red' | 'orange' | 'amber' | 'green' | 'teal' | 'blue' | 'indigo' | 'purple' | 'pink' | 'gray';
|
||||
/** Whitelist shared by the host write-validation and the client picker. */
|
||||
export declare const GROUP_COLORS: readonly GroupColor[];
|
||||
/** Curated icon ids (rendered from @deepseek-ai/dsh-client-ui-primitives). */
|
||||
export declare const GROUP_ICON_IDS: readonly ["folder", "workspace", "code", "plugin", "skill", "data", "database", "api", "plan", "goal", "light", "globe", "archive", "branch", "users", "clock", "shield", "checklist", "sparkle", "tree", "chat", "search", "settings", "document", "edit", "think", "agent", "browse", "context", "link", "share", "user", "send", "attachment", "download", "play", "design", "moon", "monitor", "gauge", "queue", "notes", "inspect", "help", "info", "alarm", "compare", "done", "pin", "microphone", "test-tube", "flask", "pipette", "dropper", "stirrer", "hotplate", "centrifuge", "balance", "atom", "molecule", "lattice", "layered", "framework", "thin-film", "fiber", "hydrogel", "microscope", "xrd", "spectrum", "tensile", "electrode", "iv-curve", "illumination", "temperature", "humidity", "actuator", "flex-sensor", "battery"];
|
||||
/** Derived from the shared registry so host validation and UI cannot drift. */
|
||||
export type GroupIconId = (typeof GROUP_ICON_IDS)[number];
|
||||
/**
|
||||
* Presentation metadata for one group. Every field optional.
|
||||
*
|
||||
* The explicit `| undefined` on each field is what lets a UI patch clear a
|
||||
* value (`pruneAppearance` then drops it): under `exactOptionalPropertyTypes`
|
||||
* a bare `color?: GroupColor` would reject `{ color: undefined }`.
|
||||
*/
|
||||
export interface CategoryAppearance {
|
||||
/** Palette id; the CSS palette lives in styles.css `[data-wg-color]`. */
|
||||
color?: GroupColor | undefined;
|
||||
/** `GroupIconId` preset id, or a short glyph (1–4 Unicode code points, emoji/latin). */
|
||||
icon?: string | undefined;
|
||||
/** Pinned groups sort before unpinned ones (within the manual order). */
|
||||
pinned?: boolean | undefined;
|
||||
}
|
||||
/** The full sidecar configuration (mirrors workspace-groups.yaml). */
|
||||
export interface GroupsConfig {
|
||||
/** Category folders, in render order. First match wins. */
|
||||
categories: GroupCategory[];
|
||||
/**
|
||||
* Runtime grouping overlay (manual groups + per-workspace overrides).
|
||||
* Optional: the YAML file itself never carries it — the host GET route
|
||||
* merges it from `workspace-groups.manual.json`, and the browser PUT route
|
||||
* replaces it whole.
|
||||
*/
|
||||
manual?: ManualGroups;
|
||||
}
|
||||
/**
|
||||
* Runtime-managed grouping overlay: groups created in the sidebar UI plus
|
||||
* per-workspace category overrides and user-controlled ordering. Owned by the
|
||||
* plugin (JSON sidecar, `$DSH_HOME/workspace-groups.manual.json`), never
|
||||
* written back into the operator YAML.
|
||||
*
|
||||
* All new fields are optional for backward compatibility (files written by
|
||||
* older plugin versions keep working); rendering falls back to sensible
|
||||
* defaults when they are absent. Note that an older plugin version writes the
|
||||
* whole file back, which silently drops fields it does not know about — e.g.
|
||||
* `appearance` (group color / icon / pin) is lost after a downgrade.
|
||||
*/
|
||||
export interface ManualGroups {
|
||||
/**
|
||||
* Monotonic write counter, owned by the host (same contract as the folder
|
||||
* overlay): a PUT whose revision does not match the stored one is
|
||||
* rejected with 409 instead of silently overwriting another window's
|
||||
* edits. Absent in files written before revisions existed — read as 0.
|
||||
*/
|
||||
revision?: number;
|
||||
/**
|
||||
* Manually created category folder names. These have no rules — they render
|
||||
* even while empty (a new group appears before anything is dragged into
|
||||
* it) and hold only workspaces assigned to them.
|
||||
*/
|
||||
categories: string[];
|
||||
/**
|
||||
* Per-workspace category override, keyed by workspace id. Value is a
|
||||
* category display name (rule or manual), or `null` to force the workspace
|
||||
* into the uncategorized bucket even when a rule would match. An absent
|
||||
* key means "classify by rules".
|
||||
*/
|
||||
assignments: Record<string, string | null>;
|
||||
/**
|
||||
* Display order of all category keys (rule display names + manual names).
|
||||
* The uncategorized bucket is never listed — it always renders last.
|
||||
* Absent = rule categories first (YAML order), manual groups appended in
|
||||
* creation order.
|
||||
*/
|
||||
categoryOrder?: string[];
|
||||
/**
|
||||
* Per-category ordered workspace ids (user drag-reorder within a group).
|
||||
* Keyed by category display name; absent key = host registration order.
|
||||
*/
|
||||
workspaceOrder?: Record<string, string[]>;
|
||||
/**
|
||||
* Rule category rename overrides: original YAML rule category name →
|
||||
* display name (UI rename of a rule group). Rules still classify by the
|
||||
* original name; only the rendered label/keys change.
|
||||
*/
|
||||
renamed?: Record<string, string>;
|
||||
/**
|
||||
* Rule category original names hidden by a UI delete. Hidden rules are
|
||||
* inert: workspaces matching them become top-level (ungrouped).
|
||||
*/
|
||||
hidden?: string[];
|
||||
/**
|
||||
* Per-group presentation, keyed by category DISPLAY name (same key space as
|
||||
* `categoryOrder`). Optional per field; an absent group has no presentation.
|
||||
* Dangling keys (a YAML category that no longer exists) are tolerated on read
|
||||
* and on write — see validateManualGroups.
|
||||
*/
|
||||
appearance?: Record<string, CategoryAppearance>;
|
||||
}
|
||||
/**
|
||||
* Legacy label of the fallback bucket. The top-level (ungrouped) concept
|
||||
* replaced the rendered "未分类" bucket: workspaces in no group render as
|
||||
* top-level rows beside the group folders. The constant survives for data
|
||||
* compatibility (reserved name, assignment null marker).
|
||||
*/
|
||||
export declare const UNCATEGORIZED_LABEL = "\u672A\u5206\u7C7B";
|
||||
/**
|
||||
* Reserved key under `workspaceOrder` holding the manual order of TOP-LEVEL
|
||||
* (ungrouped) project rows. Distinct from any real group display name (a group
|
||||
* may not be named this), so it can never collide; the top-level list's order
|
||||
* is preserved exactly like a group's, and top-level rows can be reordered by
|
||||
* dragging.
|
||||
*/
|
||||
export declare const TOP_LEVEL_ORDER_KEY = "__topLevel__";
|
||||
/** 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,88 @@
|
|||
import { type FoldersDocument } from './core/folders.ts';
|
||||
/** File name of the folder sidecar (also the stable error-text prefix). */
|
||||
export declare const FOLDERS_FILE_NAME = "workspace-groups.folders.json";
|
||||
/** Hard limits enforced at the write boundary. */
|
||||
export declare const FOLDERS_PER_WORKSPACE_LIMIT = 32;
|
||||
export declare const MEMBERS_PER_WORKSPACE_LIMIT = 16;
|
||||
export declare const WORKSPACE_ID_LIMIT = 200;
|
||||
export declare const FOLDER_PATH_LIMIT = 1024;
|
||||
export declare const REMOTE_PATH_LIMIT = 1024;
|
||||
/** Default overlay location: `$DSH_HOME/workspace-groups.folders.json`. */
|
||||
export declare function defaultFoldersPath(): string;
|
||||
/**
|
||||
* Local mirror root of `@zhangfengshun/dsh-remote-ssh`.
|
||||
*
|
||||
* That plugin registers every remote workspace as an ordinary DSH workspace
|
||||
* whose canonical directory is a LOCAL mirror (`<homedir>/.dsh/remote-workspaces/
|
||||
* <workspaceId>`) and keeps the real remote path in its own records. Telling the
|
||||
* browser this base lets it treat such workspaces differently: their extra
|
||||
* folders must be subdirectories of the mirror, because only those also exist on
|
||||
* the remote side.
|
||||
*
|
||||
* The path is hardcoded there (not read from `DSH_HOME`), so it is hardcoded
|
||||
* here too — a mismatch would silently disable the distinction.
|
||||
*/
|
||||
export declare function defaultRemoteMirrorBase(): string;
|
||||
/**
|
||||
* True when `path` is absolute in the host platform's spelling: a drive
|
||||
* letter or UNC prefix on Windows, a leading slash elsewhere.
|
||||
* @param path - candidate path.
|
||||
*/
|
||||
export declare function isAbsoluteFolderPath(path: string): boolean;
|
||||
/** Validate a local path for the read-only remote hint endpoint. */
|
||||
export declare function validateRemoteHintPath(path: unknown): string;
|
||||
/**
|
||||
* Presence-only safety hint, never a trusted SSH connection or registration.
|
||||
* lstat also treats dangling symlinks as hints without reading their targets.
|
||||
* Only ENOENT is ignored: permissions and all other inspection failures must
|
||||
* prevent callers from silently falling back to local operations.
|
||||
*/
|
||||
export declare function hasRemoteMarkerHint(path: string): Promise<boolean>;
|
||||
/**
|
||||
* Tolerant reader: shape-normalizes whatever was on disk and drops unusable
|
||||
* workspaces, folders and roots instead of throwing. A missing, non-mapping or
|
||||
* unknown-version document yields the empty document.
|
||||
* @param raw - parsed JSON value.
|
||||
*/
|
||||
export declare function parseFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* The document's write counter: a non-negative safe integer, else 0. Tolerant
|
||||
* on purpose — reads must survive hand-edited sidecars; the strict writer
|
||||
* below rejects bad values instead of letting them through.
|
||||
* @param value - the raw `revision` field.
|
||||
*/
|
||||
export declare function readRevision(value: unknown): number;
|
||||
/**
|
||||
* Strict writer-side validation. Every rule is enforced and the first problem
|
||||
* throws, so the PUT route rejects instead of persisting a half-valid file.
|
||||
* @param raw - parsed JSON value from the request body.
|
||||
* @returns the normalized document to save.
|
||||
* @throws when version, workspace ids, folder paths, duplicates or the root
|
||||
* membership are wrong.
|
||||
*/
|
||||
export declare function validateFoldersDocument(raw: unknown): FoldersDocument;
|
||||
/**
|
||||
* Read + tolerate the overlay file. A missing or unreadable file yields the
|
||||
* empty document: folders are a convenience, and a broken sidecar must not take
|
||||
* the tree down with it.
|
||||
* @param path - overlay file path.
|
||||
*/
|
||||
export declare function readFoldersDocument(path: string): Promise<FoldersDocument>;
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param document - validated document to persist.
|
||||
*/
|
||||
export declare function writeFoldersDocument(path: string, document: FoldersDocument): Promise<void>;
|
||||
/**
|
||||
* Join a remote path with a mirror-relative subpath.
|
||||
*
|
||||
* The remote path is POSIX (the server's), so this never uses `node:path`:
|
||||
* a Windows host would otherwise hand `/home/me/proj\data` to the remote shell.
|
||||
* @param remotePath - the workspace's remote root (`~`, `~/proj`, `/srv/proj`).
|
||||
* @param relativePath - subpath inside the mirror, either separator style.
|
||||
* @returns the remote counterpart, or null for an empty or escaping subpath.
|
||||
*/
|
||||
export declare function remoteSubpath(remotePath: string, relativePath: string): string | null;
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import { type ManualGroups } from './core/types.ts';
|
||||
/** Default overlay location: `$DSH_HOME/workspace-groups.manual.json`. */
|
||||
export declare function defaultManualPath(): string;
|
||||
/**
|
||||
* Parse + shape-validate a raw overlay document into a ManualGroups.
|
||||
* Validates types only — category references are checked against the rule set
|
||||
* at the write boundary (validateManualGroups), because reads must tolerate
|
||||
* files written while the rule set was different.
|
||||
* @param raw - parsed JSON value.
|
||||
* @returns the normalized overlay.
|
||||
* @throws when the shape is malformed (non-mapping, bad names, duplicates,
|
||||
* the reserved uncategorized label, bad assignment/order values).
|
||||
*/
|
||||
export declare function parseManualGroups(raw: unknown): ManualGroups;
|
||||
/**
|
||||
* Cross-validate a parsed overlay against the current rule categories
|
||||
* (write boundary only). Every assignment value must be `null`, a rule
|
||||
* display name, a manual category name, or the uncategorized label; order
|
||||
* keys must reference existing categories; renames/hides must reference
|
||||
* actual rule categories.
|
||||
* @param manual - parsed overlay.
|
||||
* @param ruleCategoryNames - current YAML rule category original names.
|
||||
* @throws when the overlay references categories that do not exist.
|
||||
*/
|
||||
export declare function validateManualGroups(manual: ManualGroups, ruleCategoryNames: readonly string[]): void;
|
||||
/** Read + parse the overlay file. A missing file yields an empty overlay. */
|
||||
export declare function readManualGroups(path: string): Promise<ManualGroups>;
|
||||
/**
|
||||
* Atomically replace the overlay file: write a same-directory temp file,
|
||||
* fsync it, then rename over the target. A crash never leaves a torn JSON at
|
||||
* the real path (readers see either the old or the new file).
|
||||
* @param path - target file path.
|
||||
* @param manual - overlay to persist.
|
||||
*/
|
||||
export declare function writeManualGroups(path: string, manual: ManualGroups): Promise<void>;
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
/** One persisted tab. */
|
||||
export interface PersistedTab {
|
||||
/** Session id the tab points at. */
|
||||
readonly sessionId: string;
|
||||
/** Arrival key (React list identity). */
|
||||
readonly order: number;
|
||||
/** Pinned tabs are restored at the front of the strip. */
|
||||
readonly pinned?: boolean;
|
||||
/** A label the user typed for the tab itself (absent = follow the session). */
|
||||
readonly title?: string;
|
||||
}
|
||||
/** The persisted document. */
|
||||
export interface TabsDocument {
|
||||
/**
|
||||
* Shape version.
|
||||
*
|
||||
* 1 = `{sessionId, order}` only (what the shipped build writes); 2 adds the
|
||||
* optional `pinned` / `title` per tab. A version-1 file is READ as version 2
|
||||
* with every tab unpinned and untitled — that is exactly what it meant — and
|
||||
* the next write upgrades it. The two shapes are field-compatible, so no
|
||||
* conversion step exists: an older build reading a version-2 file would drop
|
||||
* the extra flags and keep working, which is why this stayed a tolerance
|
||||
* instead of a hard rejection.
|
||||
*/
|
||||
readonly version: 2;
|
||||
/** Arrival counter, kept ahead of every tab's own order. */
|
||||
readonly order: number;
|
||||
readonly tabs: readonly PersistedTab[];
|
||||
}
|
||||
/** Default location: `$DSH_HOME/workspace-groups.tabs.json`. */
|
||||
export declare function defaultTabsPath(): string;
|
||||
/**
|
||||
* Normalize one tab row (used by both the file reader and the PUT body check, so
|
||||
* the two can never drift).
|
||||
*
|
||||
* @param entry - one element of a stored/`posted` `tabs` array.
|
||||
* @returns the tab, or null when the row is unusable.
|
||||
*/
|
||||
export declare function parsePersistedTab(entry: unknown): PersistedTab | null;
|
||||
/**
|
||||
* Parse + shape-validate a tabs document.
|
||||
*
|
||||
* Tolerant on purpose: this file is a display cache, so a malformed one must
|
||||
* read as "no tabs" rather than break the strip. Individual bad rows are dropped
|
||||
* and the rest kept. Unknown fields (such as the `sessionKey` an older build
|
||||
* wrote) are ignored, so an existing file keeps working across the change.
|
||||
*
|
||||
* @param raw - parsed JSON value.
|
||||
* @returns the normalized document, or null when it is unusable.
|
||||
*/
|
||||
export declare function parseTabsDocument(raw: unknown): TabsDocument | null;
|
||||
/**
|
||||
* Read the tabs document.
|
||||
*
|
||||
* A missing file is not an error (first run). A corrupt one is reported as null
|
||||
* so the caller starts empty, and the next write repairs the file.
|
||||
*
|
||||
* @param path - sidecar path.
|
||||
* @returns the document, or null when absent/unusable.
|
||||
*/
|
||||
export declare function readTabsDocument(path: string): Promise<TabsDocument | null>;
|
||||
/**
|
||||
* Write the tabs document atomically.
|
||||
* @param path - sidecar path.
|
||||
* @param document - document to store.
|
||||
*/
|
||||
export declare function writeTabsDocument(path: string, document: TabsDocument): Promise<void>;
|
||||
/**
|
||||
* Build the document to persist.
|
||||
* @param state - the client's current strip and its arrival counter.
|
||||
* @returns the document to write.
|
||||
*/
|
||||
export declare function documentForTabs(state: {
|
||||
order: number;
|
||||
tabs: readonly PersistedTab[];
|
||||
}): TabsDocument;
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import type { GroupsContext } from './context-types.ts';
|
||||
/** Plugin identity for cordis.yml rows. */
|
||||
export declare const name = "workspace-groups-local";
|
||||
/** Services required before mounting: the webserver route. */
|
||||
export declare const inject: string[];
|
||||
/** Plugin body: mount the config snapshot route and the overlay write route. */
|
||||
export declare function apply(ctx: GroupsContext): void;
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "workspace-groups-remote",
|
||||
"version": "1.0.0",
|
||||
"version": "1.1.0",
|
||||
"description": "Merged DSH bundle: the workspace-groups sidebar manager (category -> project -> session grouped tree, session tab strip) plus dsh-remote-ssh (VSCode Remote-SSH-like remote development: remote workspaces, file access, integrated terminal) in one installable package.",
|
||||
"keywords": [
|
||||
"dsh",
|
||||
|
|
@ -141,4 +141,4 @@
|
|||
"vitest": "4.1.8",
|
||||
"zustand": "^5.0.15"
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue