跪拜 Guibai
← Back to the summary

Replicating WorkBuddy's User Entry in DeepSeek Harness: A Slot Takeover Plugin

One article to cover: how to replicate the user info entry at WorkBuddy's bottom-left corner in DSH (DeepSeek Harness). From environment setup, plugin structure, slot selection, data interface, complete client code, to real account API and pitfalls, reproduction checklist – all with copyable code.

Table of Contents


1. Goal, effect, and prerequisites

1.1 What we are building

WorkBuddy's client has a user info area at the bottom-left: avatar + nickname + "Trial" badge. Clicking it opens a profile popover with membership tier, points balance, Buddy Station, growth plan, settings, appearance switching, and sign out.

The goal is to create an entry in DSH that is highly consistent in position and interaction.

The final effect: only one row at the bottom-left (real avatar + real nickname). Clicking opens a blended menu:

Warning: DSH does not have WorkBuddy's membership/points account system; its account service only provides DeepSeek nickname, avatar, and wallet balance. So this is a "UI faithful replication + local demo data". Buttons like upgrade/station claim/points detail that require WorkBuddy backend only show a "demo entry" hint and do not fake success.

1.2 Prerequisites

Requirement Description
A DSH project This guide assumes root directory D:/zhonglin/zhonglin-dsh, commands use ./dsh.cmd
A web profile ~/.dsh/profiles/web/, plugins are installed here
Node.js For syntax validation; client half does not need a build tool

2. Plugin structure and loading mechanism

2.1 Dual-half design

The same npm package contains code for two runtime environments:

┌─────────────────────────┐         ┌─────────────────────────┐
│   host half (Node process)    │         │   client half (browser)   │
│  host/index.js          │         │  client/index.js        │
│  host/api.js            │         │                         │
│  · Provides HTTP API    │         │  · Renders UI / responds to clicks │
│  · Reads server files   │         │  · Can only do same-origin fetch │
└────────────┬────────────┘         └────────────┬────────────┘
             └──── GET /workbuddy-user/api/profile ┘

Host only "provides data"; client only "displays and interacts". They communicate via a URL + JSON structure. This way, future changes to real account services only touch host, client stays unchanged.

2.2 Complete directory tree

plugins/dsh-workbuddy-user/
├── package.json          # Package manifest: entries for both halves, client dependencies
├── cordis.patch.yml      # Mount declaration: tells profile to load plugin
├── profile.json          # Demo data (edit to change person)
├── host/
│   ├── index.js          # Host entry: registers routes
│   └── api.js            # Route implementation: GET /profile
├── client/
│   └── index.js          # All client code (541 lines)
├── locale/
│   ├── zh.json
│   └── en.json
└── learning-vue3/        # Companion Vue3 learning version (read-only, not loaded)

2.3 package.json

// File path: plugins/dsh-workbuddy-user/package.json
{
  "name": "@local/dsh-workbuddy-user",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "description": "Take over DSH Web's bottom-left official account entry, pop up a blended menu: real avatar/nickname/settings/sign out + WorkBuddy-style tier/points/station demo info.",
  "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"
}

Key points:

2.4 cordis.patch.yml

# File path: plugins/dsh-workbuddy-user/cordis.patch.yml
# This plugin's mount layer: profile reads this file when merging plugin tree.
# id is the identity in the tree; name is the package name the loader imports.
- insert:
    - id: dsh-workbuddy-user
      name: '@local/dsh-workbuddy-user'

id is a unique identity in the plugin tree; name must match the name in package.json.

2.5 profile.json (demo data)

// File path: 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": ""
}

Edit this file to change demo data (tier, points, stationDays/stationTotal). Real avatar and nickname come from the logged-in account, not here.

2.6 locale dictionaries

// File path: 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": "加载中…"
}
// File path: 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…"
}

This locale is a leftover from an earlier version; the current client inlines the dictionary in code. Keeping them does not affect running.

2.7 Installation and verification

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"

Seeing id: dsh-workbuddy-user means mount succeeded. Start with ./dsh.cmd web.

Warning: after changing client/index.js you must close and reopen dsh web – the frontend bundle's rev is content-hash based, so cache exists.


3. Slot mechanism and mount point selection

3.1 What is a slot

DSH's UI is composed of a set of slots; plugins inject components into slots:

// File path: plugins/dsh-workbuddy-user/client/index.js (inside 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',
)

Slots are of two types:

Type How many Rendering rule Example
list Many All render, sorted by order sidebar.footer.action
single One Only the one with the lowest priority number renders settings.launcher

3.2 First attempt: sidebar.footer.action (failed)

The example plugin dsh-slot-explorer/topology.json shows only sidebar.footer.action (list type, root scope, owner props { wide }). The first version registered the entry here:

// Early version code (deprecated, only for explanation)
ctx.slots.inject('sidebar.footer.action', () => ctx.slots.register({
  name: 'sidebar.footer.action',
  order: 90,
  locale: NS,
}, FooterUser))

Result: two rows at bottom-left:

实验室
吴小祥 体验版     ← our plugin
钟~lin            ← official account entry, originally in another slot

Reason: official account entry lives in settings.launcher; we just added a new row, didn't replace the old one.

3.3 Correct approach: take over settings.launcher

After digging into the source, the official account entry is in settings.launcher (single, root), owner props are { wide, settingsOpen, settingsShortcut, openSettings, openOnboarding }. The menu's settings goes through openSettings(), sign out through ctx.remote.account.signOut().

So we switch to taking over this single slot: replace the official AccountMenu UI with our component, while the underlying account service continues to run. Now there's only one row at bottom-left, but settings/sign out still use official native APIs.

3.4 priority shadowing

For single slots, the smallest number wins. Official uses default 0; we must explicitly give a negative number:

ctx.slots.register({
  name: 'settings.launcher',
  priority: -100,   // Critical: negative numbers allow shadowing official's 0
  locale: NS,
}, AccountLauncher)

Not specifying priority (default also 0) will throw: already has a registration at priority 0 ... to shadow it (lowest renders).

3.5 Comparison of the two slots

Dimension sidebar.footer.action settings.launcher
Type list (multiple) single (one)
Official occupancy No Yes
Adding effect Adds a row → two entries Must shadow to display
Can access account API No Yes
Final choice ❌ Abandoned ✅ Take over

4. Host half and data interface

4.1 host/index.js

// File path: plugins/dsh-workbuddy-user/host/index.js
/**
 * host half (Node process): only responsible for turning "user profile" into a same-origin JSON API.
 *
 * Why doesn't the client hardcode the profile? – So you can change one profile.json to switch people,
 * and it leaves a place for plugging in a real account service later.
 *
 * Endpoint: GET /workbuddy-user/api/profile
 *   → { ok, from:'host', profile:{ name, contact, tier, points, avatarUrl, ... }, at }
 *
 * All registrations go into ctx.effect(), which tears down routes on unload, leaving no ghosts.
 */

import { registerUserApi } from './api.js'

export const name = 'dsh-workbuddy-user'
export const inject = ['webServer', 'connection']

export function apply(ctx) {
  // Host admission gate: blocks DNS rebinding and cross-site calls; returns undefined to allow.
  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 mounted, route prefix /workbuddy-user/api')
}

4.2 host/api.js

// File path: plugins/dsh-workbuddy-user/host/api.js
/**
 * Host route implementation: one prefix, one GET endpoint.
 * Uses the same skeleton as dsh-sidebar-lab's host/api.js (register → fence → dispatch → sendJson).
 */

import { readFile } from 'node:fs/promises'

/** Route prefix, must match API_BASE in client/index.js. */
const PREFIX = '/workbuddy-user/api'

/** User profile file: edit to change avatar/nickname/tier/points without touching code. */
const PROFILE_FILE = new URL('../profile.json', import.meta.url)

/**
 * Mount routes.
 * @param {any} ctx
 * @param {(req: import('node:http').IncomingMessage) => 401 | 403 | undefined} fence
 * @returns {() => void} unregister function
 */
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] failed to read 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} handling failed: ${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)
}

Four-step skeleton: register (register prefix route, return unregister function) → fence (admission check) → dispatch (parse pathname) → sendJson (uniform output, no-store to prevent caching). new URL('../profile.json', import.meta.url) guarantees locating the profile file from any working directory.

4.3 Interface contract and verification

Success response:

{ "ok": true, "from": "host", "profile": { "tier": "体验版", "points": "1,628.3" }, "at": "..." }

Verification commands:

./dsh.cmd web --no-open --port 5199
# Get token from log
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

5. Complete client implementation (541 lines full text)

5.1 Why a single file

The browser loader only recognizes window.__ModuleLoader__.load({ id, factory }); the require inside factory can only resolve host-shared module table (like react, react-dom), and does not understand relative paths. So all code must be in one file.

5.2 Complete code

// File path: plugins/dsh-workbuddy-user/client/index.js (full 541 lines)
/**
 * ============================================================================
 * client half (browser): take over DSH's bottom-left "account entry", pop up a blended menu.
 * ============================================================================
 *
 * Replication target: WorkBuddy's bottom-most avatar/username/membership tier entry + profile popover.
 *
 * Key difference from previous version:
 *   Previous version registered entry to sidebar.footer.action → appeared alongside official account row, resulting in two entries.
 *   This version takes over the official account's settings.launcher (single slot).
 *   Dynamic plugin registration gets a lower shadowing priority, thus becomes the winner of this slot,
 *   official AccountMenu UI is replaced, but account service (ctx.remote.account.*) continues to run.
 *
 * Therefore real functionality in the menu always goes through host APIs, not decorative:
 *   Settings    → owner props.openSettings()          opens official settings panel
 *   Feedback    → official Feishu form URL (window.open)
 *   Appearance  → ctx.theme.setTheme('light'|'dark')  actually switches theme
 *   Sign out    → ctx.remote.account.signOut(client()) actually signs out
 *   Avatar/nickname → ctx.remote.account.getProfile(client()) real account profile
 * WorkBuddy-specific info (tier/points/station/growth) DSH has no account system,
 * comes from host's profile.json (demo data).
 *
 * Single-file reason: browser loader only recognizes window.__ModuleLoader__.load({ id, factory }),
 * factory's require can only resolve host-shared module table, doesn't understand relative paths.
 */

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 mounts the popover to document.body to avoid clipping by sidebar overflow.
    let createPortal = null
    try {
      createPortal = require('react-dom')?.createPortal ?? null
    } catch (_) {
      createPortal = null
    }

    // ────────────────────────────────────────────────────────────────────────
    // 1. Constants and dictionaries
    // ────────────────────────────────────────────────────────────────────────

    const NS = 'workbuddyUser'
    const API_BASE = '/workbuddy-user/api'
    const LS_KEY = 'dsh-workbuddy-user.profile'
    // Keep in sync with official account plugin's client metadata version, otherwise Platform may reject requests.
    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'

    /** Default values: fallback when host hasn't responded / API unavailable. */
    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',
    }

    /** Module-level service references, replaced with host real ones during 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. Styles (host theme tokens, auto follow light/dark)
    // ────────────────────────────────────────────────────────────────────────

    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. Data layer
    // ────────────────────────────────────────────────────────────────────────

    function readLocalOverride() {
      try {
        const raw = window.localStorage?.getItem(LS_KEY)
        return raw ? JSON.parse(raw) : {}
      } catch (_) {
        return {}
      }
    }

    /** WorkBuddy demo data: default ← 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
    }

    /** Real account data: read from DSH account service, fallback to null on failure. */
    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) {
            // Account service unavailable, keep empty profile, UI won't crash.
          }
        }

        void load()
        // Re-read on account status changes (sign in/out).
        let off = () => {}
        try { off = accountApi?.subscribe?.(load) ?? (() => {}) } catch (_) {}
        return () => { alive = false; off() }
      }, [])

      return account
    }

    // ────────────────────────────────────────────────────────────────────────
    // 4. Components
    // ────────────────────────────────────────────────────────────────────────

    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])

      // Appearance: real theme service.
      const applyTheme = (id) => {
        try { setTheme(id); setPref(id) } catch (_) {}
      }

      // Sign out: use real signOut, ask once (consistent with official, avoid accidental interruption of tasks).
      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 in the array may already have '+' (like ['Ctrl','+','Alt']), normalize before joining to avoid duplicate pluses.
      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,
      },
        // Header: real avatar + nickname + tier
        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 Station (demo)
        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')))),

        // Points balance / Growth plan / Invite (demo)
        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' }),

        // ── Real functionality below ──
        // Settings: opens official settings panel
        h('button', { type: 'button', className: 'dsh-wbu-row', onClick: () => { onClose(); openSettings() } },
          h('span', {}, t('settings')),
          h('span', { className: 'dsh-wbu-row-value' }, shortcutText ? `${shortcutText} ›` : '›')),

        // Appearance: real theme
        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')))),

        // Feedback: official form
        h('button', { type: 'button', className: 'dsh-wbu-row', onClick: openFeedback },
          h('span', {}, t('contact')), h('span', { className: 'dsh-wbu-row-value' }, '›')),

        // Check for updates: jumps to settings panel's general page (official has no separate entry, borrow settings)
        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' }),

        // Sign out / Sign in: real account operations
        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)
    }

    /**
     * Take over official account entry: register into 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: take over official account slot
    // ────────────────────────────────────────────────────────────────────────

    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,
        })

        // Wrap real account API. watch/getView are host remote calls, signatures identical to official.
        accountApi = {
          getView: async () => {
            const r = await ctx.remote.account.getState?.()
            // getState may directly return AccountView or wrap in 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',
        )

        // Dynamic plugin registration gets a lower shadowing priority → becomes the single slot winner,
        // official AccountMenu UI is replaced, but account service itself continues to run.
        // Explicit negative priority is required to shadow official registration: single slot conflict detection deduplicates by priority,
        // official uses default 0, dynamic plugins also get 0 and will error. Rule is lowest priority renders.
        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 Five-part breakdown

Part 1: Constants and dictionaries (lines 47–126) window.__ModuleLoader__.load is the container for all code; CLIENT_VERSION = '0.2.1-rc.5' must match official or Platform rejects requests. t / setTheme / clientMeta / accountApi are stubbed first, then replaced with host real instances in apply() – this is a crude dependency-injection technique in a single file.

Part 2: Styles (lines 132–200) Use host --dsw-alias-* theme tokens; light/dark follows automatically. Pitfall: defining a CSS string doesn't mean it's applied; you must inject via h('style', {}, CSS) in the component (see first line of AccountLauncher).

Part 3: Data layer (lines 206–272) useDemoProfile() fetches host /profile, merge order default ← host ← localStorage; useRealAccount() first calls getView() to check sign-in state (credential-stored) then getProfile() for real data, and subscribes to account changes.

Part 4: Components (lines 278–476) Avatar shows image if available, falls back to first character, and falls back on load failure; Menu uses createPortal to mount to body to avoid clipping, position calculated from getBoundingClientRect(), closes on outside click/Esc, menu is split into demo (disabled) and real sections; AccountLauncher is the bottom-left entry, first line injects styles.

Part 5: apply (lines 482–538) inject must include remote.account; wraps theme/locale/remote services; clientMeta() dynamically gets locale and timezone; two ctx.effect calls register dictionaries and take over the slot (priority: -100).


6. Real account API and three hidden pitfalls

6.1 Real call chain

Menu item Real call
Avatar/nickname ctx.remote.account.getProfile(client())
Sign-in state ctx.remote.account.getState()
Settings owner props openSettings()
Appearance ctx.theme.setTheme('light'|'dark')
Sign out ctx.remote.account.signOut(client())

Client metadata must match official:

const CLIENT_VERSION = '0.2.1-rc.5'
clientMeta = () => ({
  version: CLIENT_VERSION,
  locale: ctx.locale.getSnapshot().active,
  timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
})

Measured response structures:

// getState()
{ ok: true, value: { status: 'credential-stored', ... } }
// getProfile()
{ ok: true, value: { status: 'ready', value: { name, contact, avatarUrl } } }

Two easy-to-miss points: the real API is getState() not getView(); getProfile() returns two nested layers, profile is at result.value.value.

6.2 Pitfall 1: Styles defined but not injected

Symptom: bottom-left shows raw text like "吴吴小祥体验版", looks like plugin didn't work. Root cause: defined CSS string but didn't render <style> in component. DOM, API, console all fine, so curl and startup bundle checks don't catch it. Fix: add h('style', {}, CSS) as first line in component. Also changed popover max-height from 560px to calc(100vh - 96px).

6.3 Pitfall 2: Single slot priority conflict

Symptom: already has a registration at priority 0 ... to shadow it (lowest renders). Root cause: official uses default priority 0, our static load also 0, same priority conflicts. Single slot renders lowest number, must explicitly give negative priority: -100.

6.4 Pitfall 3: Missing remote.account, plugin doesn't activate

Symptom: menu shows but can't read real account, web boot: 1 entry did not activate. Root cause: official inject is ['slots','locale','remote','remote.account','remote.session','theme','configForms'], we only wrote 'remote'. Cordis inject is a hard dependency; missing service blocks activation. Fix: inject: ['slots','locale','theme','remote','remote.account'].

6.5 Browser verification method

All three pitfalls hide under "loaded successfully", so you must actually run a browser:

npm install puppeteer-core --no-save
./dsh.cmd web --no-open --port 5199   # get token from log
// Temporary probe probe.cjs (can delete after verification)
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=<your 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) })

Acceptance checklist: entry count 1 (old entry and official button count 0), real avatar, menu includes points/settings/sign out/appearance, settings actually opens panel, theme switching works, zero console errors. After code changes, restart dsh web (content-hash caching).


7. From-scratch reproduction checklist

Phase 1 · Create files: follow directory tree in Chapter 2, save package.json / cordis.patch.yml / profile.json / locale from 2.3–2.6, place host files in host/, and 541-line client in client/index.js from Chapter 5.

Phase 2 · Syntax self-check:

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')"

Phase 3 · Install:

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"

Phase 4 · Verify interface: see 4.3 for three curl commands.

Phase 5 · Verify UI: use probe from 6.5 or open ./dsh.cmd web and check visually.


8. FAQ

Q: Where to change avatar/nickname/points? Real avatar and nickname come from the logged-in account, cannot be changed. Points/tier/station can be changed in profile.json then restart. For temporary testing, run localStorage.setItem('dsh-workbuddy-user.profile', JSON.stringify({points:'999'})) in console, refresh (local value has highest priority), use removeItem to revert.

Q: Two entries at bottom-left? Plugin registered to sidebar.footer.action, while official is in settings.launcher. Change to take over settings.launcher with priority: -100. See Chapter 3.

Q: Bottom-left shows raw text / not visible? Most likely styles not injected; check if AccountLauncher has h('style', {}, CSS). See 6.2.

Q: Avatar/nickname empty or shows not signed in? Headless browser's ?token= is just a harness session token, not DeepSeek account credentials; reading as not signed in is normal; real login browser can read it. Another possibility is inject missing remote.account, see 6.4.

Q: Priority 0 conflict? See 6.3.

Q: Settings/sign out no response? Ensure plugin fully activated (no did not activate), owner props openSettings is passed, client metadata version matches official.

Q: Why do upgrade/station claim only show demo entry? DSH has no WorkBuddy account system; these are demo entries requiring backend. When connecting a real backend, replace host's /profile with real interface, client unchanged.

Q: Code changes not taking effect? Close dsh web and reopen (frontend content-hash caching).

Q: Can this be used in production? This is a UI replication + demo data learning project. To connect real account, replace host data source and map demo fields to real system; architecture has a replacement point ready.


Summary

Two core lessons:

  1. Slot position determines capability: choosing sidebar.footer.action only adds a row; choosing settings.launcher allows integrating real account functionality;
  2. Verification must go to browser layer: interface 200, script loaded, DOM exists does not mean UI is correct – style injection, slot conflicts, and missing dependencies only surface in real running.

For a more accessible Vue3 + Element Plus explanation of the same logic, see companion 2-Vue3学习版逐文件讲解.md.

Comments

Top 1 from juejin.cn, machine-translated. The original thread is authoritative.

组合搭配函数

Using the slot as a mount point is a clean design. The plugin only handles mounting, while the host handles the entire lifecycle. An independent repository can be reused across projects, which is quite forward-thinking.