一篇讲完:如何在 DSH(DeepSeek Harness)里复刻 WorkBuddy 左下角的用户信息入口。 从环境准备、插件结构、插槽选择、数据接口、client 完整代码,到真实账号 API 与踩坑、复现清单,全部带可复制代码。
目录
- 一、目标、效果与前提
- 二、插件结构与加载机制
- 三、插槽机制与挂载点选择
- 四、host 半身与数据接口
- 五、client 半身完整实现(541 行全文)
- 六、真实账号 API 与三个隐藏的坑
- 七、从零复现清单
- 八、常见问题 FAQ
一、目标、效果与前提
1.1 我们要做什么
WorkBuddy 客户端左下角有一块用户信息区:头像 + 昵称 + 「体验版」徽章,点开是个人中心浮层,里面有会员等级、积分余额、Buddy 加油站、成长计划、设置、外观切换、退出登录。
目标是:在 DSH 里做一个位置和交互都高度一致的入口。
最终效果:左下角只有一行(真实头像 + 真实昵称),点开是融合菜单:
- 上半段演示数据:体验版等级、加油站、积分 1,628.3、成长计划、去邀约;
- 下半段真实功能:设置(真打开官方面板)、外观(真切换主题)、意见反馈、检查更新、退出登录(真退出,带二次确认)。
⚠️ 前提:DSH 没有 WorkBuddy 的会员/积分账号体系,它的账号服务只有 DeepSeek 的昵称、头像和钱包余额。所以这是「UI 忠实复刻 + 本地演示资料」,升级/加油站领取/积分明细这类需要 WorkBuddy 后端的按钮,点击只提示「演示入口」,不假装成功。
1.2 前置条件
| 需要 | 说明 |
|---|---|
| 一个 DSH 工程 | 本文假设根目录 D:/zhonglin/zhonglin-dsh,命令用 ./dsh.cmd |
| 一个 web profile | ~/.dsh/profiles/web/,插件安装到这里 |
| Node.js | 用于语法校验,client 半身无需构建工具 |
二、插件结构与加载机制
2.1 双半身设计
同一个 npm 包包含两个运行环境的代码:
bash
┌─────────────────────────┐ ┌─────────────────────────┐
│ host 半身(Node 进程) │ │ client 半身(浏览器) │
│ host/index.js │ │ client/index.js │
│ host/api.js │ │ │
│ · 提供 HTTP 接口 │ │ · 渲染 UI / 响应点击 │
│ · 读服务端文件 │ │ · 只能同源 fetch │
└────────────┬────────────┘ └────────────┬────────────┘
└──── GET /workbuddy-user/api/profile ┘
host 只管「给数据」,client 只管「显示和交互」,两者靠一个 URL + JSON 结构通信。这样将来换真实账号服务,只改 host,client 不动。
2.2 完整目录树
bash
plugins/dsh-workbuddy-user/
├── package.json # 包清单:两半入口、客户端依赖
├── cordis.patch.yml # 挂载声明:告诉 profile 加载插件
├── profile.json # 演示资料(改这里换人)
├── host/
│ ├── index.js # host 入口:注册路由
│ └── api.js # 路由实现:GET /profile
├── client/
│ └── index.js # client 全部代码(541 行)
├── locale/
│ ├── zh.json
│ └── en.json
└── learning-vue3/ # 配套 Vue3 学习版(只读,不参与加载)
2.3 package.json
json
// 文件路径:plugins/dsh-workbuddy-user/package.json
{
"name": "@local/dsh-workbuddy-user",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "接管 DSH Web 左下角官方账号入口,弹出融合菜单:真实头像/昵称/设置/退出登录 + WorkBuddy 风格的等级/积分/加油站演示信息。",
"main": "./host/index.js",
"exports": {
".": "./host/index.js",
"./client": "./client/index.js",
"./locale/*.json": "./locale/*.json"
},
"files": [
"host",
"client",
"locale",
"profile.json",
"cordis.patch.yml"
],
"dsh": {
"bundle": {
"patch": "./cordis.patch.yml"
},
"client": {
"platform": "web",
"immediately": true,
"inject": [
"@deepseek-ai/dsh-client-locale",
"@deepseek-ai/dsh-client-ui-layout",
"@deepseek-ai/dsh-client-ui-sidebar",
"@deepseek-ai/dsh-client-ui-theme"
]
}
},
"license": "MIT"
}
要点:
main:host 入口;exports["./client"]:client 入口,浏览器加载器通过它找到client/index.js。dsh.bundle.patch:挂载声明文件。dsh.client.immediately: true:前端启动即加载。dsh.client.inject:客户端依赖的服务包 名;client 代码内inject数组列的是服务名,两者不同(第六章有一个因漏写服务名导致插件不激活的坑)。
2.4 cordis.patch.yml
yaml
# 文件路径:plugins/dsh-workbuddy-user/cordis.patch.yml
# 本插件的挂载层:profile 合并插件树时读这个文件。
# id 是这一行在树里的身份;name 是加载器要 import 的包名。
- insert:
- id: dsh-workbuddy-user
name: '@local/dsh-workbuddy-user'
id 是插件树里的唯一身份,name 必须和 package.json 的 name 一致。
2.5 profile.json(演示数据)
json
// 文件路径:plugins/dsh-workbuddy-user/profile.json
{
"name": "吴小祥",
"contact": "186****7809",
"avatarUrl": "",
"initials": "吴",
"tier": "体验版",
"points": "1,628.3",
"stationDays": 4,
"stationTotal": 400,
"growth": "连登抽 Buddy 周边",
"invite": "最高得 650 积分/人",
"version": "v0.1.0",
"upgradeUrl": "",
"growthUrl": "",
"inviteUrl": ""
}
改这个文件就能换演示数据(等级 tier、积分 points、加油站 stationDays/stationTotal)。真实头像昵称来自登录账号,不在这里。
2.6 locale 词典
json
// 文件路径:plugins/dsh-workbuddy-user/locale/zh.json
{
"footer": "个人中心",
"upgrade": "升级",
"station": "Buddy 加油站",
"stationDaily": "每日可领 100 通用积分",
"claimToday": "今日已领",
"verifyClaim": "认证领积分",
"balance": "积分余额",
"growth": "成长计划",
"invite": "去邀约",
"settings": "设置",
"appearance": "外观",
"light": "浅色",
"dark": "深色",
"help": "帮助与反馈",
"update": "检查更新",
"logout": "退出登录",
"demoHint": "演示入口:DSH 不提供 WorkBuddy 账号能力",
"loading": "加载中..."
}
json
// 文件路径:plugins/dsh-workbuddy-user/locale/en.json
{
"footer": "Profile",
"upgrade": "Upgrade",
"station": "Buddy Station",
"stationDaily": "Claim 100 bonus points daily",
"claimToday": "Claimed today",
"verifyClaim": "Verify & claim",
"balance": "Points balance",
"growth": "Growth plan",
"invite": "Invite friends",
"settings": "Settings",
"appearance": "Appearance",
"light": "Light",
"dark": "Dark",
"help": "Help & feedback",
"update": "Check for updates",
"logout": "Sign out",
"demoHint": "Demo entry: WorkBuddy account features are unavailable in DSH",
"loading": "Loading..."
}
这份 locale 是早期版本遗留,当前 client 把词典内联在代码里了。保留它们不影响运行。
2.7 安装与验证
bash
cd D:/zhonglin/zhonglin-dsh
./dsh.cmd plugin --profile web add "link:D:/zhonglin/zhonglin-dsh/plugins/dsh-workbuddy-user"
./dsh.cmd --profile web --dump-config 2>&1 | grep -A3 -B1 "workbuddy-user"
看到 id: dsh-workbuddy-user 即挂载成功。启动用 ./dsh.cmd web。
⚠️ 改完
client/index.js必须关掉 dsh web 重新打开------前端 bundle 的 rev 是内容哈希,有缓存。
三、插槽机制与挂载点选择
3.1 什么是插槽
DSH 界面由一堆插槽(slot)拼成,插件往插槽里塞组件:
js
// 文件路径:plugins/dsh-workbuddy-user/client/index.js(apply 内)
ctx.effect(
() => ctx.slots.inject('settings.launcher', () => ctx.slots.register({
name: 'settings.launcher',
priority: -100,
locale: NS,
}, AccountLauncher)),
'dsh-workbuddy-user: account launcher takeover',
)
插槽分两种:
| 类型 | 能放几个 | 渲染规则 | 例子 |
|---|---|---|---|
list |
多个 | 全部渲染,按 order 排序 |
sidebar.footer.action |
single |
一个 | 只渲染优先级数字最低的那个 | settings.launcher |
3.2 第一次尝试:sidebar.footer.action(失败)
示例插件 dsh-slot-explorer/topology.json 显示侧栏底部只有 sidebar.footer.action(list 类型,root 作用域,owner props { wide })。第一版把入口注册到这里:
js
// 早期版本代码(已废弃,仅作讲解)
ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
name: 'sidebar.footer.action',
order: 90,
locale: NS,
}, FooterUser))
结果左下角出现两行:
实验室
吴小祥 体验版 ← 我们的插件
钟~lin ← 官方账号入口,原本就在另一个插槽里
原因:官方账号入口在 settings.launcher,我们只是「新增一行」,没有替换旧的。
3.3 正确做法:接管 settings.launcher
摸清源码后发现官方账号入口在 settings.launcher(single、root),owner props 是 { wide, settingsOpen, settingsShortcut, openSettings, openOnboarding },菜单的设置走 openSettings()、退出走 ctx.remote.account.signOut()。
所以改成接管这个 single 插槽:用我们的组件替换官方 AccountMenu 的 UI,底层账号服务照常运行。左下角只剩一行,但设置/退出仍是官方原生 API。
3.4 priority shadowing
single 插槽数字最小者胜出。官方用默认 0,我们必须显式给负数:
js
ctx.slots.register({
name: 'settings.launcher',
priority: -100, // 关键:负数才能 shadow 官方的 0
locale: NS,
}, AccountLauncher)
不写 priority(默认也是 0)会报:already has a registration at priority 0 ... to shadow it (lowest renders)。
3.5 两个插槽对照
| 维度 | sidebar.footer.action |
settings.launcher |
|---|---|---|
| 类型 | list(多个) | single(一个) |
| 官方是否占用 | 否 | 是 |
| 新增效果 | 多一行 → 两个入口 | 必须遮蔽才能显示 |
| 能拿到账号 API | 否 | 是 |
| 最终选择 | ❌ 放弃 | ✅ 接管 |
四、host 半身与数据接口
4.1 host/index.js
js
// 文件路径:plugins/dsh-workbuddy-user/host/index.js
/**
* host 半身(Node 进程):只负责把「用户资料」做成一个同源 JSON 接口。
*
* client 为什么不直接写死资料?------ 方便你改一处 profile.json 就换人,
* 也让这个插件保留了「真实账号服务将来能接进来」的位置。
*
* 端点:GET /workbuddy-user/api/profile
* → { ok, from:'host', profile:{ name, contact, tier, points, avatarUrl, ... }, at }
*
* 所有注册都放进 ctx.effect(),卸载时自动摘掉路由,不留幽灵。
*/
import { registerUserApi } from './api.js'
export const name = 'dsh-workbuddy-user'
export const inject = ['webServer', 'connection']
export function apply(ctx) {
// 宿主的准入闸门:挡 DNS 重绑定与跨站调用,返回 undefined 才放行。
const fence = (req) => ctx.connection.requestRejection({ headers: req.headers })
ctx.effect(
() => registerUserApi(ctx, fence),
'dsh-workbuddy-user: /workbuddy-user/api routes',
)
ctx.logger?.info?.('[dsh-workbuddy-user] host 已挂载,路由前缀 /workbuddy-user/api')
}
inject:依赖宿主 Web 服务与连接安全服务,服务就绪后才apply。fence:挡 DNS 重绑定与跨站请求,返回undefined才放行。ctx.effect:把注册包成副作用,卸载时自动摘掉路由。
4.2 host/api.js
js
// 文件路径:plugins/dsh-workbuddy-user/host/api.js
/**
* host 路由实现:一个前缀,一个 GET 端点。
* 和 dsh-sidebar-lab 的 host/api.js 是同一套骨架(register → fence → 分发 → sendJson)。
*/
import { readFile } from 'node:fs/promises'
/** 路由前缀,必须与 client/index.js 的 API_BASE 一致。 */
const PREFIX = '/workbuddy-user/api'
/** 用户资料文件:改这个文件就能换头像/昵称/等级/积分,无需改代码。 */
const PROFILE_FILE = new URL('../profile.json', import.meta.url)
/**
* 挂路由。
* @param {any} ctx
* @param {(req: import('node:http').IncomingMessage) => 401 | 403 | undefined} fence
* @returns {() => void} 注销函数
*/
export function registerUserApi(ctx, fence) {
return ctx.webServer.register({
kind: 'prefix',
path: PREFIX,
handler: (req, res) => {
void handle(ctx, fence, req, res)
},
})
}
async function handle(ctx, fence, req, res) {
const rejection = fence(req)
if (rejection !== undefined) {
sendJson(res, rejection, { ok: false, code: 'rejected' })
return
}
const url = new URL(req.url ?? '/', 'http://localhost')
const endpoint = url.pathname.slice(PREFIX.length) || '/'
try {
if (req.method === 'GET' && endpoint === '/profile') {
let profile = {}
try {
profile = JSON.parse(await readFile(PROFILE_FILE, 'utf8'))
} catch (error) {
ctx.logger?.warn?.(`[dsh-workbuddy-user] 读 profile.json 失败: ${String(error)}`)
}
sendJson(res, 200, {
ok: true,
from: 'host',
profile,
at: new Date().toISOString(),
})
return
}
sendJson(res, 404, { ok: false, code: 'not-found', path: endpoint })
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
ctx.logger?.warn?.(`[dsh-workbuddy-user] ${endpoint} 处理失败: ${message}`)
sendJson(res, 500, { ok: false, code: 'internal', message })
}
}
function sendJson(res, status, payload) {
const body = JSON.stringify(payload)
res.writeHead(status, {
'content-type': 'application/json; charset=utf-8',
'cache-control': 'no-store',
'content-length': Buffer.byteLength(body),
})
res.end(body)
}
四步骨架:register (注册前缀路由,返回注销函数)→ fence (准入检查)→ 分发 (解析 pathname)→ sendJson (统一输出,no-store 防缓存)。new URL('../profile.json', import.meta.url) 保证任意工作目录下都能定位到资料文件。
4.3 接口契约与验证
成功响应:
json
{ "ok": true, "from": "host", "profile": { "tier": "体验版", "points": "1,628.3" }, "at": "..." }
验证命令:
bash
./dsh.cmd web --no-open --port 5199
# 从日志拿 token
curl -s -c /tmp/cookie.txt -o /dev/null "http://127.0.0.1:5199/?token=<token>"
curl -s -b /tmp/cookie.txt "http://127.0.0.1:5199/workbuddy-user/api/profile" # 200
curl -s -w "\n%{http_code}\n" "http://127.0.0.1:5199/workbuddy-user/api/profile" # 401
五、client 半身完整实现(541 行全文)
5.1 为什么是单文件
浏览器加载器只认 window.__ModuleLoader__.load({ id, factory }),factory 里的 require 只能解析宿主共享模块表(如 react、react-dom),不认识相对路径。所以所有代码必须塞进一个文件。
5.2 完整代码
js
// 文件路径:plugins/dsh-workbuddy-user/client/index.js(完整 541 行)
/**
* ============================================================================
* client 半身(浏览器):接管 DSH 左下角的「账号入口」,弹出融合菜单。
* ============================================================================
*
* 复刻对象:WorkBuddy 侧边栏最底部的头像/用户名/会员等级入口 + 个人中心浮层。
*
* 与上一版的关键区别:
* 上一版把入口注册到 sidebar.footer.action → 和官方账号行并列,出现两个入口。
* 本版改为接管官方账号所在的 settings.launcher(single 插槽)。
* 动态插件注册会拿到更低的 shadowing priority,从而成为这个插槽的赢家,
* 官方 AccountMenu 的 UI 被替换,但账号服务(ctx.remote.account.*)照常运行。
*
* 因此菜单里的真实功能一律走宿主 API,不做摆设:
* 设置 → owner props.openSettings() 打开官方设置面板
* 意见反馈 → 官方飞书表单 URL(window.open)
* 外观 → ctx.theme.setTheme('light'|'dark') 真实切换主题
* 退出登录 → ctx.remote.account.signOut(client()) 真实退出
* 头像/昵称 → ctx.remote.account.getProfile(client()) 真实账号资料
* WorkBuddy 特有信息(等级/积分/加油站/成长计划)DSH 没有账号体系,
* 来自 host 的 profile.json(演示数据)。
*
* 单文件原因:浏览器加载器只认 window.__ModuleLoader__.load({ id, factory }),
* factory 的 require 只能解析宿主共享模块表,不认识相对路径。
*/
window.__ModuleLoader__.load({
id: '@local/dsh-workbuddy-user',
factory(require) {
const React = require('react')
const h = React.createElement
const { useState, useEffect, useRef, useCallback } = React
// react-dom 把浮层挂到 document.body,避免被侧栏 overflow 裁掉。
let createPortal = null
try {
createPortal = require('react-dom')?.createPortal ?? null
} catch (_) {
createPortal = null
}
// ────────────────────────────────────────────────────────────────────────
// 1. 常量与词典
// ────────────────────────────────────────────────────────────────────────
const NS = 'workbuddyUser'
const API_BASE = '/workbuddy-user/api'
const LS_KEY = 'dsh-workbuddy-user.profile'
// 与官方账号插件的 client metadata 版本保持一致,否则 Platform 请求可能被拒。
const CLIENT_VERSION = '0.2.1-rc.5'
const CONTACT_URL = 'https://trtgsjkv6r.feishu.cn/share/base/form/shrcnlCoGElW7MQznGy9r3YYXcg?hide_uid=1&hide_device_info=1&hide_harness_version=1'
/** 默认值:host 还没响应 / 接口不可用时的兜底。 */
const DEFAULT_PROFILE = {
tier: '体验版',
points: '0',
stationDays: 0,
stationTotal: 0,
growth: '',
invite: '',
version: '',
}
const zh = {
menu: '账号菜单',
signedIn: '已登录',
upgrade: '升级',
station: 'Buddy 加油站',
stationDaily: '每日可领 100 通用积分',
stationProgress: (d, total) => `本期已领 ${d} 天 · 累计 ${total} 分`,
claimToday: '今日已领',
verifyClaim: '认证领积分',
balance: '积分余额',
growth: '成长计划',
invite: '去邀约',
settings: '设置',
contact: '意见反馈',
appearance: '外观',
light: '浅色',
dark: '深色',
update: '检查更新',
logout: '退出登录',
logoutBusy: '正在退出...',
logoutConfirm: '确认退出登录?',
logoutDesc: '退出不会丢失任何数据,你仍可以重新登录此账号。',
logoutCancel: '取消',
logoutConfirmBtn: '确认退出',
signIn: '登录账号',
demoHint: '等级/积分为演示数据 · DSH 无 WorkBuddy 账号体系',
}
const en = {
menu: 'Account menu',
signedIn: 'Signed in',
upgrade: 'Upgrade',
station: 'Buddy Station',
stationDaily: 'Claim 100 bonus points daily',
stationProgress: (d, total) => `Claimed ${d} days · ${total} pts total`,
claimToday: 'Claimed today',
verifyClaim: 'Verify & claim',
balance: 'Points balance',
growth: 'Growth plan',
invite: 'Invite friends',
settings: 'Settings',
contact: 'Feedback',
appearance: 'Appearance',
light: 'Light',
dark: 'Dark',
update: 'Check for updates',
logout: 'Sign out',
logoutBusy: 'Signing out...',
logoutConfirm: 'Sign out?',
logoutDesc: 'Signing out keeps your data. You can sign in again anytime.',
logoutCancel: 'Cancel',
logoutConfirmBtn: 'Sign out',
signIn: 'Sign in',
demoHint: 'Tier/points are demo data · DSH has no WorkBuddy account',
}
/** 模块级服务引用,apply 时替换成宿主真身。 */
let t = (key) => key
let setTheme = (_id) => {}
let getPreference = () => 'system'
let clientMeta = () => ({ version: CLIENT_VERSION, locale: 'zh', timezoneOffsetSeconds: 0 })
let accountApi = null // { getProfile, signOut, hasRunningAccountTasks, watch, start }
// ────────────────────────────────────────────────────────────────────────
// 2. 样式(宿主主题令牌,浅色/深色自动跟随)
// ────────────────────────────────────────────────────────────────────────
const CSS = [
'.dsh-wbu-trigger { appearance: none; border: 0; background: transparent; cursor: pointer;',
' display: flex; align-items: center; gap: 8px; min-width: 0;',
' width: 100%; height: 40px; padding: 0 8px; border-radius: 8px;',
' color: var(--dsw-alias-label-primary); text-align: left; font: inherit; }',
'.dsh-wbu-trigger:hover { background: var(--dsw-alias-bg-layer-2); }',
'.dsh-wbu-trigger:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }',
'.dsh-wbu-trigger-name { flex: 1 1 auto; min-width: 0; overflow: hidden;',
' text-overflow: ellipsis; white-space: nowrap; font-size: 12px; font-weight: 500; }',
'.dsh-wbu-avatar { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center;',
' overflow: hidden; border-radius: 50%; background: var(--dsw-alias-brand-primary);',
' color: var(--dsw-alias-label-on-brand, #fff); font-weight: 600;',
' border: 1px solid var(--dsw-alias-border-l1); }',
'.dsh-wbu-avatar img { width: 100%; height: 100%; object-fit: cover; }',
'.dsh-wbu-layer { position: fixed; inset: 0; z-index: 10000; }',
'.dsh-wbu-pop {',
' position: absolute; width: 296px; max-height: calc(100vh - 96px);',
' overflow-y: auto; box-sizing: border-box;',
' padding: 14px; border-radius: 14px;',
' border: 1px solid var(--dsw-alias-border-l1);',
' background: var(--dsw-alias-bg-layer-1); color: var(--dsw-alias-label-primary);',
' box-shadow: 0 12px 32px rgba(0,0,0,.18); font: inherit; }',
'.dsh-wbu-head { display: flex; align-items: center; gap: 10px; }',
'.dsh-wbu-head-name { font-size: 14px; font-weight: 600; line-height: 1.3; }',
'.dsh-wbu-head-meta { margin-top: 3px; font-size: 11px; color: var(--dsw-alias-label-secondary); }',
'.dsh-wbu-head-tier { display: inline-flex; align-items: center; gap: 4px; margin-top: 6px;',
' padding: 3px 8px; border-radius: 999px; font-size: 11px; cursor: pointer;',
' border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-2);',
' color: var(--dsw-alias-label-secondary); }',
'.dsh-wbu-card { margin-top: 12px; padding: 12px; border-radius: 10px;',
' border: 1px solid var(--dsw-alias-border-l1); background: var(--dsw-alias-bg-layer-2);',
' display: flex; flex-direction: column; gap: 8px; }',
'.dsh-wbu-card-title { margin: 0; font-size: 12px; font-weight: 600; }',
'.dsh-wbu-card-sub { margin: 0; font-size: 11px; line-height: 1.5; color: var(--dsw-alias-label-secondary); }',
'.dsh-wbu-buttons { display: flex; gap: 8px; }',
'.dsh-wbu-btn { flex: 1 1 0; min-width: 0; height: 28px; padding: 0 8px;',
' border-radius: 7px; border: 1px solid var(--dsw-alias-border-l2);',
' background: var(--dsw-alias-bg-base); color: var(--dsw-alias-label-primary);',
' font: inherit; font-size: 11px; cursor: pointer; white-space: nowrap; }',
'.dsh-wbu-btn:hover:not(:disabled) { border-color: var(--dsw-alias-brand-primary); }',
'.dsh-wbu-btn:disabled { opacity: .55; cursor: default; }',
'.dsh-wbu-btn-primary { background: var(--dsw-alias-brand-primary);',
' color: var(--dsw-alias-label-on-brand, #fff); border-color: transparent; }',
'.dsh-wbu-row { appearance: none; border: 0; background: transparent; cursor: pointer;',
' display: flex; align-items: center; justify-content: space-between; gap: 8px;',
' width: 100%; padding: 9px 4px; border-radius: 8px; text-align: left;',
' color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; }',
'.dsh-wbu-row:hover { background: var(--dsw-alias-bg-layer-2); }',
'.dsh-wbu-row:focus-visible { outline: 2px solid var(--dsw-alias-brand-primary); outline-offset: 1px; }',
'.dsh-wbu-row-value { font-size: 12px; font-variant-numeric: tabular-nums;',
' color: var(--dsw-alias-label-secondary); }',
'.dsh-wbu-row-sub { margin-top: 2px; font-size: 11px; color: var(--dsw-alias-label-secondary); }',
'.dsh-wbu-seg { display: inline-flex; padding: 2px; gap: 2px; border-radius: 8px;',
' background: var(--dsw-alias-bg-layer-2); border: 1px solid var(--dsw-alias-border-l1); }',
'.dsh-wbu-seg button { appearance: none; border: 0; cursor: pointer; padding: 3px 9px;',
' border-radius: 6px; background: transparent; color: var(--dsw-alias-label-secondary);',
' font: inherit; font-size: 11px; }',
'.dsh-wbu-seg button[aria-pressed="true"] { background: var(--dsw-alias-bg-base);',
' color: var(--dsw-alias-label-primary); box-shadow: 0 1px 2px rgba(0,0,0,.08); }',
'.dsh-wbu-divider { height: 1px; margin: 10px 0; background: var(--dsw-alias-border-l1); }',
'.dsh-wbu-foot { margin: 8px 0 0; font-size: 10px; line-height: 1.5;',
' color: var(--dsw-alias-label-tertiary, var(--dsw-alias-label-secondary)); }',
'.dsh-wbu-danger { color: var(--dsw-alias-label-danger, #c0392b); }',
'.dsh-wbu-confirm { margin-top: 10px; padding: 12px; border-radius: 10px;',
' border: 1px solid var(--dsw-alias-border-l2); background: var(--dsw-alias-bg-layer-2); }',
'.dsh-wbu-confirm-title { margin: 0 0 4px; font-size: 13px; font-weight: 600; }',
'.dsh-wbu-confirm-desc { margin: 0 0 10px; font-size: 11px; line-height: 1.5;',
' color: var(--dsw-alias-label-secondary); }',
].join('\n')
// ────────────────────────────────────────────────────────────────────────
// 3. 数据层
// ────────────────────────────────────────────────────────────────────────
function readLocalOverride() {
try {
const raw = window.localStorage?.getItem(LS_KEY)
return raw ? JSON.parse(raw) : {}
} catch (_) {
return {}
}
}
/** WorkBuddy 演示资料:默认值 ← host profile.json ← localStorage。 */
function useDemoProfile() {
const [profile, setProfile] = useState(() => ({ ...DEFAULT_PROFILE, ...readLocalOverride() }))
useEffect(() => {
let alive = true
fetch(API_BASE + '/profile', { credentials: 'same-origin' })
.then((res) => res.json().catch(() => ({ ok: false })))
.then((payload) => {
if (alive && payload?.ok) {
setProfile({ ...DEFAULT_PROFILE, ...payload.profile, ...readLocalOverride() })
}
})
.catch(() => {})
return () => { alive = false }
}, [])
return profile
}
/** 真实账号资料:从 DSH 账号服务读取,失败则退回 null。 */
function useRealAccount() {
const [account, setAccount] = useState({ name: '', contact: '', avatarUrl: '', signedIn: false })
useEffect(() => {
let alive = true
const load = async () => {
if (!accountApi) return
try {
const view = await accountApi.getView()
const signedIn = view?.status === 'credential-stored'
if (!alive) return
if (!signedIn) {
setAccount({ name: '', contact: '', avatarUrl: '', signedIn: false })
return
}
const result = await accountApi.getProfile(clientMeta())
if (!alive) return
const p = result?.ok && result.value?.status === 'ready' ? result.value.value : null
setAccount({
name: p?.name ?? '',
contact: p?.contact ?? '',
avatarUrl: p?.avatarUrl ?? '',
signedIn: true,
})
} catch (e) {
// 账号服务不可用时保留空资料,界面不崩。
}
}
void load()
// 账号状态变化时(登录/退出)重新读取。
let off = () => {}
try { off = accountApi?.subscribe?.(load) ?? (() => {}) } catch (_) {}
return () => { alive = false; off() }
}, [])
return account
}
// ────────────────────────────────────────────────────────────────────────
// 4. 组件
// ────────────────────────────────────────────────────────────────────────
function Avatar({ name, url, size = 28 }) {
const [failed, setFailed] = useState(false)
const box = { width: size, height: size, fontSize: Math.max(10, Math.round(size * 0.42)) }
return h('span', { className: 'dsh-wbu-avatar', style: box, 'aria-hidden': 'true' },
url && !failed
? h('img', { src: url, alt: '', onError: () => setFailed(true) })
: String(name || '账').slice(0, 1))
}
function Menu({ anchor, account, demo, settingsShortcut, openSettings, onClose }) {
const rootRef = useRef(null)
const [pref, setPref] = useState(getPreference())
const [busy, setBusy] = useState(false)
const [confirming, setConfirming] = useState(false)
useEffect(() => {
const onDown = (e) => {
if (rootRef.current && !rootRef.current.contains(e.target)) onClose()
}
const onKey = (e) => { if (e.key === 'Escape') onClose() }
document.addEventListener('mousedown', onDown)
document.addEventListener('keydown', onKey)
return () => {
document.removeEventListener('mousedown', onDown)
document.removeEventListener('keydown', onKey)
}
}, [onClose])
// 外观:真实主题服务。
const applyTheme = (id) => {
try { setTheme(id); setPref(id) } catch (_) {}
}
// 退出登录:走真实 signOut,先询问一次(与官方一致,避免误触中断任务)。
const requestLogout = async () => {
if (!account.signedIn) return
setConfirming(true)
}
const confirmLogout = async () => {
setBusy(true)
try {
await accountApi.signOut(clientMeta())
onClose()
} catch (_) {
setBusy(false)
}
}
const openFeedback = () => {
try {
window.open(CONTACT_URL, '_blank', 'noopener,noreferrer')
} catch (_) {}
}
const position = {
left: Math.max(8, Math.min(anchor?.left ?? 8, (window.innerWidth || 1024) - 312)),
bottom: Math.max(8, (window.innerHeight || 768) - (anchor?.top ?? 600) + 6),
}
const displayName = account.name || (account.signedIn ? t('signedIn') : 'DeepSeek Harness')
// keys 里的元素本身可能已带 '+'(如 ['Ctrl','+','Alt']),规整后再拼,避免重复加号。
const shortcutText = Array.isArray(settingsShortcut?.keys)
? settingsShortcut.keys.filter((k) => k !== '+').join(' + ')
: ''
const body = h('div', {
className: 'dsh-wbu-pop',
ref: rootRef,
role: 'menu',
'aria-label': t('menu'),
style: position,
},
// 头部:真实头像 + 昵称 + 等级
h('div', { className: 'dsh-wbu-head' },
h(Avatar, { name: displayName, url: account.avatarUrl, size: 44 }),
h('div', { style: { minWidth: 0, flex: '1 1 auto' } },
h('div', { className: 'dsh-wbu-head-name' }, displayName),
account.contact
? h('div', { className: 'dsh-wbu-head-meta' }, account.contact)
: null,
h('span', { className: 'dsh-wbu-head-tier', style: { cursor: 'default' } },
demo.tier, h('span', {}, ' · '), t('signedIn')))),
// Buddy 加油站(演示)
h('section', { className: 'dsh-wbu-card' },
h('h3', { className: 'dsh-wbu-card-title' }, t('station')),
h('p', { className: 'dsh-wbu-card-sub' }, t('stationDaily')),
h('p', { className: 'dsh-wbu-card-sub' },
t('stationProgress')(demo.stationDays ?? 0, demo.stationTotal ?? 0)),
h('div', { className: 'dsh-wbu-buttons' },
h('button', { type: 'button', className: 'dsh-wbu-btn', disabled: true }, t('claimToday')),
h('button', { type: 'button', className: 'dsh-wbu-btn dsh-wbu-btn-primary', disabled: true }, t('verifyClaim')))),
// 积分余额 / 成长计划 / 去邀约(演示)
h('button', { type: 'button', className: 'dsh-wbu-row', disabled: true, style: { cursor: 'default' } },
h('span', {}, t('balance')),
h('span', { className: 'dsh-wbu-row-value' }, demo.points)),
h('button', { type: 'button', className: 'dsh-wbu-row', disabled: true, style: { cursor: 'default' } },
h('span', {},
h('div', {}, t('growth')),
demo.growth ? h('div', { className: 'dsh-wbu-row-sub' }, demo.growth) : null),
h('span', { className: 'dsh-wbu-row-value' }, '›')),
h('button', { type: 'button', className: 'dsh-wbu-row', disabled: true, style: { cursor: 'default' } },
h('span', {},
h('div', {}, t('invite')),
demo.invite ? h('div', { className: 'dsh-wbu-row-sub' }, demo.invite) : null),
h('span', { className: 'dsh-wbu-row-value' }, '›')),
h('div', { className: 'dsh-wbu-divider' }),
// ── 以下为真实功能 ──
// 设置:打开官方设置面板
h('button', { type: 'button', className: 'dsh-wbu-row', onClick: () => { onClose(); openSettings() } },
h('span', {}, t('settings')),
h('span', { className: 'dsh-wbu-row-value' }, shortcutText ? `${shortcutText} ›` : '›')),
// 外观:真实主题
h('div', { className: 'dsh-wbu-row' },
h('span', {}, t('appearance')),
h('span', { className: 'dsh-wbu-seg', role: 'group', 'aria-label': t('appearance') },
h('button', { type: 'button', 'aria-pressed': pref === 'light', onClick: () => applyTheme('light') }, t('light')),
h('button', { type: 'button', 'aria-pressed': pref === 'dark', onClick: () => applyTheme('dark') }, t('dark')))),
// 意见反馈:官方表单
h('button', { type: 'button', className: 'dsh-wbu-row', onClick: openFeedback },
h('span', {}, t('contact')), h('span', { className: 'dsh-wbu-row-value' }, '›')),
// 检查更新:跳到设置面板的通用页(官方没有独立入口,借道设置)
h('button', { type: 'button', className: 'dsh-wbu-row', onClick: () => { onClose(); openSettings() } },
h('span', {}, t('update')), h('span', { className: 'dsh-wbu-row-value' }, '›')),
h('div', { className: 'dsh-wbu-divider' }),
// 退出登录 / 登录:真实账号操作
confirming
? h('div', { className: 'dsh-wbu-confirm' },
h('p', { className: 'dsh-wbu-confirm-title' }, t('logoutConfirm')),
h('p', { className: 'dsh-wbu-confirm-desc' }, t('logoutDesc')),
h('div', { className: 'dsh-wbu-buttons' },
h('button', { type: 'button', className: 'dsh-wbu-btn', onClick: () => setConfirming(false) }, t('logoutCancel')),
h('button', { type: 'button', className: 'dsh-wbu-btn dsh-wbu-btn-primary', disabled: busy, onClick: () => void confirmLogout() },
busy ? t('logoutBusy') : t('logoutConfirmBtn'))))
: h('button', {
type: 'button',
className: 'dsh-wbu-row dsh-wbu-danger',
onClick: () => void requestLogout(),
}, account.signedIn ? t('logout') : t('signIn')),
h('p', { className: 'dsh-wbu-foot' }, t('demoHint'))
)
if (createPortal) {
return createPortal(h('div', { className: 'dsh-wbu-layer', onClick: onClose }, body), document.body)
}
return h('div', { className: 'dsh-wbu-layer', onClick: onClose }, body)
}
/**
* 接管官方账号入口:注册进 settings.launcher(single、root)。
* owner props: { wide, settingsOpen, settingsShortcut, openSettings, openOnboarding }
*/
function AccountLauncher({ wide = true, settingsShortcut, openSettings }) {
const account = useRealAccount()
const demo = useDemoProfile()
const btnRef = useRef(null)
const [anchor, setAnchor] = useState(null)
const toggle = useCallback(() => {
if (anchor) { setAnchor(null); return }
const rect = btnRef.current?.getBoundingClientRect()
setAnchor(rect ? { left: rect.left, top: rect.top } : { left: 8, top: 600 })
}, [anchor])
const close = useCallback(() => setAnchor(null), [])
const displayName = account.name || (account.signedIn ? t('signedIn') : t('menu'))
return h(React.Fragment, null,
h('style', {}, CSS),
h('button', {
ref: btnRef,
type: 'button',
className: 'dsh-wbu-trigger',
title: displayName,
'aria-label': t('menu'),
'aria-haspopup': 'menu',
'aria-expanded': anchor !== null,
onClick: toggle,
},
h(Avatar, { name: displayName, url: account.avatarUrl, size: 26 }),
wide ? h('span', { className: 'dsh-wbu-trigger-name' }, displayName) : null),
anchor
? h(Menu, {
anchor, account, demo, settingsShortcut,
openSettings: openSettings || (() => {}),
onClose: close,
})
: null)
}
// ────────────────────────────────────────────────────────────────────────
// 5. apply:接管官方账号插槽
// ────────────────────────────────────────────────────────────────────────
return {
inject: ['slots', 'locale', 'theme', 'remote', 'remote.account'],
apply(ctx) {
t = ctx.locale.bind(NS)
setTheme = (id) => ctx.theme.setTheme(id)
getPreference = () => {
try { return ctx.theme.getTheme()?.preference ?? 'system' } catch (_) { return 'system' }
}
clientMeta = () => ({
version: CLIENT_VERSION,
locale: ctx.locale.getSnapshot().active,
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
})
// 封装真实账号 API。watch/getView 都是宿主远调用,签名与官方一致。
accountApi = {
getView: async () => {
const r = await ctx.remote.account.getState?.()
// getState 可能直接返回 AccountView,也可能包一层 RemoteResult。
return r?.ok === false ? null : (r?.value ?? r ?? null)
},
getProfile: (client) => ctx.remote.account.getProfile(client),
signOut: async (client) => {
const r = await ctx.remote.account.signOut(client)
if (!r?.ok) throw (r?.error ?? new Error('signOut failed'))
return r.value
},
subscribe: (listener) => {
try {
return ctx.remote.$on('deepseek-account/signed-out', listener) ?? (() => {})
} catch (_) {
return () => {}
}
},
}
ctx.effect(
() => ctx.locale.register(NS, { zh, en }),
'dsh-workbuddy-user: dictionaries',
)
// 动态插件注册会拿到更低的 shadowing priority → 成为 single 插槽赢家,
// 官方 AccountMenu 的 UI 被替换,账号服务本身照常运行。
// 显式负 priority 才能 shadow 官方注册:single 插槽冲突检测按 priority 去重,
// 官方用默认 0,动态加载的插件也拿到 0 会直接报错。规则是 priority 最低者渲染。
ctx.effect(
() => ctx.slots.inject('settings.launcher', () => ctx.slots.register({
name: 'settings.launcher',
priority: -100,
locale: NS,
}, AccountLauncher)),
'dsh-workbuddy-user: account launcher takeover',
)
},
}
},
})
5.3 五段拆解
第 1 段:常量与词典(47--126 行) window.__ModuleLoader__.load 是所有代码的容器;CLIENT_VERSION = '0.2.1-rc.5' 必须和官方一致否则 Platform 拒请求。t / setTheme / clientMeta / accountApi 先给空实现,apply() 时替换成宿主真身------这是单文件里的依赖注入土办法。
第 2 段:样式(132--200 行) 用宿主 --dsw-alias-* 主题令牌,浅色/深色自动跟随。坑点 :定义了 CSS 字符串不等于生效,必须在组件里 h('style', {}, CSS) 注入(见 AccountLauncher 第一行)。
第 3 段:数据层(206--272 行) useDemoProfile() 拉 host /profile,合并顺序 默认值 ← host ← localStorage;useRealAccount() 先 getView() 判断登录态(credential-stored)再 getProfile() 拿真实资料,并订阅账号变化。
第 4 段:组件(278--476 行) Avatar 有图显示图、无图显示首字、加载失败回退;Menu 用 createPortal 挂到 body 避免裁切,位置由 getBoundingClientRect() 算出,点外部/Esc 关闭,菜单分「演示(disabled)」和「真实」两段;AccountLauncher 是左下角入口,第一行就是样式注入。
第 5 段:apply(482--538 行) inject 必须含 remote.account;包装 theme/locale/remote 服务;clientMeta() 动态取语言时区;两处 ctx.effect 注册词典和接管插槽(priority: -100)。
六、真实账号 API 与三个隐藏的坑
6.1 真实调用链
| 菜单项 | 真实调用 |
|---|---|
| 头像/昵称 | ctx.remote.account.getProfile(client()) |
| 登录态 | ctx.remote.account.getState() |
| 设置 | owner props openSettings() |
| 外观 | `ctx.theme.setTheme('light' |
| 退出登录 | ctx.remote.account.signOut(client()) |
client metadata 必须和官方一致:
js
const CLIENT_VERSION = '0.2.1-rc.5'
clientMeta = () => ({
version: CLIENT_VERSION,
locale: ctx.locale.getSnapshot().active,
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
})
实测返回结构:
js
// getState()
{ ok: true, value: { status: 'credential-stored', ... } }
// getProfile()
{ ok: true, value: { status: 'ready', value: { name, contact, avatarUrl } } }
两个易错点:真实 API 是 getState() 不是 getView();getProfile() 结果套两层,资料在 result.value.value。
6.2 坑 1:样式定义了但没注入
现象 :左下角显示「吴吴小祥体验版」裸文字,看起来插件没生效。 根因 :定义了 CSS 字符串但组件里没渲染 <style>。DOM、接口、控制台都正常,所以 curl 和启动包检查发现不了。 修复 :组件第一行加 h('style', {}, CSS)。顺带把浮层 max-height 从 560px 改成 calc(100vh - 96px)。
6.3 坑 2:single 插槽 priority 冲突
现象 :already has a registration at priority 0 ... to shadow it (lowest renders)。 根因 :官方用默认 priority 0,我们静态加载也是 0,同优先级冲突。single 插槽数字最低者渲染,必须显式给负数 priority: -100。
6.4 坑 3:漏写 remote.account,插件不激活
现象 :菜单能显示但读不到真实账号,web boot: 1 entry did not activate。 根因 :官方 inject 是 ['slots','locale','remote','remote.account','remote.session','theme','configForms'],我们只写了 'remote'。Cordis 的 inject 是硬依赖,服务缺失会阻止激活。 修复 :inject: ['slots','locale','theme','remote','remote.account']。
6.5 浏览器验证方法
三个坑都藏在「加载成功」之下,必须真跑浏览器:
bash
npm install puppeteer-core --no-save
./dsh.cmd web --no-open --port 5199 # 从日志拿 token
js
// 临时探针 probe.cjs(验证完可删)
const puppeteer = require('puppeteer-core')
;(async () => {
const browser = await puppeteer.launch({
executablePath: 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe',
headless: 'new', args: ['--no-sandbox', '--disable-gpu'],
defaultViewport: { width: 1600, height: 900 },
})
const page = await browser.newPage()
page.on('console', m => {
if (m.type() === 'error' || m.text().includes('did not activate')) console.log('CONSOLE:', m.text())
})
page.on('pageerror', e => console.log('PAGEERROR:', e.message))
await page.goto('http://127.0.0.1:5199/?token=<你的token>', { waitUntil: 'networkidle2', timeout: 60000 })
await new Promise(r => setTimeout(r, 5000))
console.log('counts:', await page.evaluate(() => ({
ourTrigger: document.querySelectorAll('.dsh-wbu-trigger').length,
popovers: document.querySelectorAll('.dsh-wbu-pop').length,
})))
await page.click('.dsh-wbu-trigger')
await new Promise(r => setTimeout(r, 500))
console.log('menu:', await page.evaluate(() => document.querySelector('.dsh-wbu-pop')?.innerText))
await page.screenshot({ path: './probe-menu.png' })
await browser.close()
})().catch(e => { console.error(e); process.exit(1) })
验收清单:入口 1 个(旧入口和官方旧按钮 0 个)、头像真实、菜单含积分/设置/退出/外观、设置真弹面板、主题切换生效、控制台零报错。改代码后必须重启 dsh web(内容哈希缓存)。
七、从零复现清单
阶段 1 · 建文件 :按第二章目录树建目录,把 2.3--2.6 的 package.json / cordis.patch.yml / profile.json / locale 存好,第三章的 host 两个文件存到 host/,第五章的 541 行存到 client/index.js。
阶段 2 · 语法自检:
bash
cd D:/zhonglin/zhonglin-dsh/plugins/dsh-workbuddy-user
node --check host/index.js
node --check host/api.js
node -e "const fs=require('fs');new Function(fs.readFileSync('client/index.js','utf8'));JSON.parse(fs.readFileSync('package.json','utf8'));console.log('syntax OK')"
阶段 3 · 安装:
bash
cd D:/zhonglin/zhonglin-dsh
./dsh.cmd plugin --profile web add "link:D:/zhonglin/zhonglin-dsh/plugins/dsh-workbuddy-user"
./dsh.cmd --profile web --dump-config 2>&1 | grep -A3 -B1 "workbuddy-user"
阶段 4 · 验证接口:见 4.3 的三条 curl。
阶段 5 · 验证界面 :用 6.5 的探针或直接打开 ./dsh.cmd web 肉眼确认。
八、常见问题 FAQ
Q:改头像/昵称/积分在哪改? 真实头像昵称来自登录账号,改不了。积分/等级/加油站改 profile.json 后重启。临时试改可在控制台执行 localStorage.setItem('dsh-workbuddy-user.profile', JSON.stringify({points:'999'})),刷新即可(本地值优先级最高),还原用 removeItem。
Q:左下角有两个入口? 插件注册到了 sidebar.footer.action,而官方在 settings.launcher。改成接管 settings.launcher 并给 priority: -100。见第三章。
Q:左下角是裸文字/看不到? 九成是样式没注入,检查 AccountLauncher 里有没有 h('style', {}, CSS)。见 6.2。
Q:头像昵称是空的/提示未登录? 无头浏览器的 ?token= 只是 harness 会话令牌,不是 DeepSeek 账号凭证,读到未登录是正常的;真实登录浏览器能读到。另一个可能是 inject 漏了 remote.account,见 6.4。
Q:报 priority 0 冲突? 见 6.3。
Q:设置/退出登录没反应? 确认插件完全激活(无 did not activate)、owner props 的 openSettings 传入、client metadata 的 version 与官方一致。
Q:升级/加油站领取为什么只提示演示入口? DSH 没有 WorkBuddy 账号体系,这些是需要后端的演示入口。真接后端时把 host 的 /profile 换真实接口,client 不用改。
Q:改了代码没生效? 关掉 dsh web 重新打开(前端内容哈希缓存)。
Q:能用于生产吗? 这是 UI 复刻 + 演示数据的学习项目。接真实账号需替换 host 数据源并把演示字段映射到真实体系,架构已留好替换点。
总结
核心经验两条:
- 插槽位置决定能力 :选
sidebar.footer.action只能新增一行,选settings.launcher才能整合真实账号功能; - 验证必须到浏览器层:接口 200、脚本加载成功、DOM 存在都不等于界面正确------样式注入、插槽冲突、依赖缺失只有真实运行才暴露。
想用更易懂的 Vue3 + Element Plus 写法读懂同样的逻辑,请看配套的 2-Vue3学习版逐文件讲解.md。