Files
dsh-worktable/01_content/src/index.ts
T
wangheng 1b053e5577 fix(update): 更新检查改走宿主中转,修复 Gitea 无 CORS 导致请求被拦 (v0.5.3-local.8)
0.5.3-local.6 把更新检查从上游 GitHub 改到自建 Gitea API,但仍不通:
页面来源是 http://127.0.0.1:<随机端口>,请求 https://gitea.ququclean.com/api/...
属跨源,而 Gitea 不返回 Access-Control-Allow-Origin,浏览器直接拦截 fetch。
表现为「立即检查」无反应、长期显示「上次检查未成功」。

改为宿主中转:
- src/index.ts 新增 /api/worktable/update-check 路由,服务端(Node 无 CORS
  约束)代取 Gitea releases/latest,客户端只请求同源路径
- updateCheck.ts / index.tsx 的 fetch 改指向该同源路由
- 该路由沿既有约定需要鉴权(request-auth.test.mjs 要求除 health/preview-static
  外所有路由都必须拒绝未鉴权请求),未传 publicAsset

测试:sidebar-popup.test.mjs 的 releaseUrl 改为 /api/worktable/update-check。

验证:npm run pack 全绿,双资产同源 sha256 225e8568…。
2026-12-02 17:30:41 +08:00

723 lines
34 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { Context } from '@deepseek-ai/cordis'
import { execFile } from 'node:child_process'
import { readdirSync, realpathSync } from 'node:fs'
import { readdir, readFile } from 'node:fs/promises'
import { dirname, resolve as pathResolve, sep } from 'node:path'
import { createRequire } from 'node:module'
import { homedir } from 'node:os'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { requestRejection, rejectionText } from './requestAuth'
import { createPreviewFiles, PREVIEW_PREFIX, PREVIEW_CSP } from './previewFiles'
import { injectThemeBridge, THEME_BRIDGE_JS } from './theme'
/**
* 基础数据目录解析:不加载任何官方包(loadPkg 的兜底只能用它,禁止反向调用包加载函数——否则成环)。
* 规则与官方 @deepseek-ai/dsh-home-paths 的 resolveDshHome 一致:
* DSH_HOME 环境变量优先(空/纯空白视为未设置),否则 ~/.dsh;
* 支持 ~、~/、~\ 前缀展开;相对路径按进程 cwd 解析;结果归一为绝对路径。
* 禁止任何业务代码直接拼 homedir()/.dsh —— 自定义 DSH_HOME(Desktop/隔离测试)会读错数据。
*/
function baseDshHome(): string {
const env = process.env.DSH_HOME
// 与官方一致:trim 只用于判断是否全空白,实际路径保留原字符串(两端空格有含义)
const value = env !== undefined && env.trim().length > 0 ? env : pathResolve(homedir(), '.dsh')
if (value === '~') return homedir()
if (value.startsWith('~/') || value.startsWith('~\\')) return pathResolve(homedir(), value.slice(2))
return pathResolve(value)
}
/** 解析 DSH 数据根目录:优先官方 @deepseek-ai/dsh-home-paths(显式配置/DSH_HOME/默认),
* 不可用或返回非法值时回退 baseDshHome()(同官方规则)。带缓存。 */
let cachedDshHome: string | null = null
/** 本次解析实际走了哪条路径(供测试断言官方包是否真的被使用) */
let dshHomeSource: 'official' | 'fallback' = 'fallback'
function resolveDshHomeSafe(): string {
if (cachedDshHome) return cachedDshHome
try {
const pkg = loadPkg('@deepseek-ai/dsh-home-paths') as any
if (pkg && typeof pkg.resolveDshHome === 'function') {
const home = pkg.resolveDshHome(undefined, process.env)
if (typeof home === 'string' && home.trim() !== '') {
dshHomeSource = 'official'
cachedDshHome = home
return cachedDshHome
}
}
} catch {}
dshHomeSource = 'fallback'
cachedDshHome = baseDshHome()
return cachedDshHome
}
/**
* dsh-worktable 服务端:健康路由 + 工作区内容窗的数据路由。
* 参考 dsh-better-sidebar 的架构——内容窗能力由本插件自己的服务端路由提供:
* - POST /api/worktable/fs 目录列表(资源管理器窗)
* - POST /api/worktable/git git 状态(源代码管理窗)
* - WS /api/worktable/term node-pty 终端流(终端窗;依赖宿主 node_modules 中的
* node-pty 与 ws,缺失时该路由不注册、终端窗降级提示)
*/
declare const __WT_VERSION__: string
const PLUGIN_VERSION = typeof __WT_VERSION__ === 'undefined' ? 'dev' : __WT_VERSION__
export const name = 'dsh-worktable'
export const inject = ['webServer', 'sessions']
export const HEALTH_PATH = '/api/worktable/health'
const MAX_ENTRIES = 500
/** 本地文件/站点静态资源的 MIME 映射(file 与 site 两条路由共用) */
const FILE_TYPES: Record<string, string> = {
html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8',
css: 'text/css; charset=utf-8', js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8',
json: 'application/json; charset=utf-8', map: 'application/json; charset=utf-8',
md: 'text/markdown; charset=utf-8', markdown: 'text/markdown; charset=utf-8',
txt: 'text/plain; charset=utf-8', log: 'text/plain; charset=utf-8',
pdf: 'application/pdf', svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp', ico: 'image/x-icon', avif: 'image/avif',
woff: 'font/woff', woff2: 'font/woff2', ttf: 'font/ttf', otf: 'font/otf',
wasm: 'application/wasm', mp3: 'audio/mpeg', mp4: 'video/mp4', webm: 'video/webm',
}
const SITE_PREFIX = '/api/worktable/site'
// 原生皮肤模板(esbuild text loader 嵌入;/api/worktable/template 路由直接下发)
// @ts-ignore
import dshellCss from '../template/dshell.css'
// @ts-ignore
import dshellHtml from '../template/dshell.html'
const TEMPLATE_PREFIX = '/api/worktable/template'
/**
* 从本插件模块位置向祖先方向查找并加载 node_modules 包(如 ws / node-pty)。
* 本包经 junction 链接进 profile,普通 import 可能解析不到 profile 级依赖;
* 同时尝试 junction 路径与 realpath 两条祖先链。
*/
/** 依赖探测尝试计数(供测试断言「有界探测、无循环重入」) */
let loadProbeAttempts = 0
function loadPkg(pkg: string): any | null {
const starts = new Set<string>()
try { starts.add(dirname(fileURLToPath(import.meta.url))) } catch {}
try { starts.add(realpathSync(dirname(fileURLToPath(import.meta.url)))) } catch {}
for (const start of starts) {
let dir: string | null = start
while (dir && dir !== pathResolve(dir, '..')) {
loadProbeAttempts++
try {
const req = createRequire(pathToFileURL(pathResolve(dir, '__wt_probe__.js')).href)
return req(pkg)
} catch {}
dir = pathResolve(dir, '..')
}
}
// 兜底:DSH profiles/*/node_modules(按 baseDshHome 解析根目录——不能用 resolveDshHomeSafe,否则与本函数成环)
try {
const profilesDir = pathResolve(baseDshHome(), 'profiles')
for (const profile of readdirSync(profilesDir, { withFileTypes: true })) {
if (!profile.isDirectory() && !profile.isSymbolicLink()) continue
const nm = pathResolve(profilesDir, profile.name, 'node_modules')
loadProbeAttempts++
try {
const req = createRequire(pathToFileURL(pathResolve(nm, '__wt_probe__.js')).href)
return req(pkg)
} catch {}
}
} catch {}
return null
}
/** 测试钩子:依赖探测尝试次数 + 数据目录解析路径(循环回归与官方路径断言用) */
export function __wtLoadProbeStats(): { attempts: number; homeSource: 'official' | 'fallback' } {
return { attempts: loadProbeAttempts, homeSource: dshHomeSource }
}
/** 解析会话工作目录:服务端 header.cwd 优先,其次客户端传入 cwd,最后进程 cwd */
function serverCwd(ctx: any, sessionId?: string, clientCwd?: string): string {
if (sessionId) {
try {
const headerCwd = ctx.sessions?.get?.(sessionId)?.header?.cwd
if (typeof headerCwd === 'string' && headerCwd) return headerCwd
} catch {}
}
if (typeof clientCwd === 'string' && clientCwd) return clientCwd
return process.cwd()
}
function json(res: any, status: number, body: unknown) {
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
res.end(JSON.stringify(body))
}
async function readJsonBody(req: any): Promise<any> {
const chunks: Buffer[] = []
let bytes = 0
for await (const chunk of req) {
const data = typeof chunk === 'string' ? Buffer.from(chunk) : chunk
bytes += data.length
if (bytes > 22 * 1024 * 1024) throw Object.assign(new Error('request too large'), { status: 413 })
chunks.push(data)
}
const text = Buffer.concat(chunks).toString('utf8')
if (!text) return {}
try { return JSON.parse(text) } catch { return {} }
}
/** 列出一个目录层级(目录在前、大小写不敏感排序、上限 500、隐藏项标注) */
async function listDirectory(path: string) {
const abs = pathResolve(path)
const dirents = await readdir(abs, { withFileTypes: true })
const entries = dirents
.map((d) => ({ name: d.name, path: abs + sep + d.name, isDir: d.isDirectory(), hidden: d.name.startsWith('.') }))
.sort((a, b) => {
if (a.isDir !== b.isDir) return a.isDir ? -1 : 1
return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
})
const truncated = entries.length > MAX_ENTRIES
return { path: abs, entries: truncated ? entries.slice(0, MAX_ENTRIES) : entries, truncated }
}
function gitExec(args: string[], cwd: string): Promise<string> {
return new Promise((resolvePromise, reject) => {
execFile('git', args, { cwd, windowsHide: true, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
if (err) reject(err)
else resolvePromise(stdout)
})
})
}
/** git 状态快照(porcelain v1 -z;非仓库返回 isRepo:false) */
async function gitStatus(cwd: string) {
try {
const branchRaw = await gitExec(['rev-parse', '--abbrev-ref', 'HEAD'], cwd)
const porcelain = await gitExec(['status', '--porcelain=v1', '-z'], cwd)
const entries = porcelain
.split('\0')
.filter((s) => s.length > 2)
.map((s) => ({ xy: s.slice(0, 2), path: s.slice(3) }))
return { isRepo: true, branch: branchRaw.trim() || 'HEAD', entries }
} catch {
return { isRepo: false, branch: undefined, entries: [] }
}
}
/** 终端 WebSocket 升级路由(同步注册 + ctx.effect,同 better-sidebar;node-pty 缺失时不注册) */
function setupTerminal(webServer: any, ctx: any) {
if (typeof webServer.registerUpgrade !== 'function') return
const wsMod = loadPkg('ws')
const ptyMod = loadPkg('node-pty')
ctx.logger?.info?.('[dsh-worktable] term deps: ws=' + (wsMod ? 'ok' : 'MISSING') + ' node-pty=' + (ptyMod ? 'ok' : 'MISSING'))
if (!wsMod || !ptyMod) {
ctx.logger?.warn('[dsh-worktable] 终端路由未注册:ws/node-pty 不可用')
return
}
const WebSocketServer = wsMod.WebSocketServer ?? wsMod.default?.WebSocketServer
if (!WebSocketServer) return
const pty = ptyMod.default ?? ptyMod
const wss = new WebSocketServer({ noServer: true })
let disposed = false
const terminals = new Set<any>()
ctx.effect(() => () => {
disposed = true
for (const ws of wss.clients ?? []) { try { ws.terminate() } catch {} }
for (const term of terminals) { try { term.kill() } catch {} }
terminals.clear()
try { wss.close() } catch {}
}, 'dsh-worktable: terminal sessions')
const spawnShell = (): { cmd: string; args: string[] } =>
process.platform === 'win32'
? { cmd: 'powershell.exe', args: ['-NoLogo', '-NoProfile'] } // -NoProfile:跳过用户配置(oh-my-posh 花哨提示符在 xterm 里是乱码,PSReadLine 长输入行不换行被截断)
: { cmd: process.env.SHELL || '/bin/bash', args: [] }
const clampDim = (v: number, fallback: number) => Math.min(1024, Math.max(2, Number.isFinite(v) ? v : fallback))
ctx.effect(() => webServer.registerUpgrade({
path: '/api/worktable/term',
handler: async (req: any, socket: any, head: any) => {
let rejected = await requestRejection(ctx, req)
if (disposed) rejected = 503
if (rejected !== undefined) {
socket.end(`HTTP/1.1 ${rejected} ${rejectionText(rejected)}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
return
}
wss.handleUpgrade(req, socket, head, (ws: any) => {
const u = new URL(req.url ?? '/', 'http://dsh.internal')
const cwd = serverCwd(ctx, u.searchParams.get('sessionId') || undefined, u.searchParams.get('cwd') || undefined)
const cols = clampDim(Number(u.searchParams.get('cols')), 80)
const rows = clampDim(Number(u.searchParams.get('rows')), 24)
let term: any = null
try {
const shell = spawnShell()
term = pty.spawn(shell.cmd, shell.args, { name: 'xterm-256color', cols, rows, cwd, env: process.env })
terminals.add(term)
} catch (err) {
try { ws.send('\r\n[worktable] 终端启动失败:' + String(err)) } catch {}
try { ws.close() } catch {}
return
}
term.onData((d: string) => { try { ws.send(d) } catch {} })
term.onExit(() => { terminals.delete(term); try { ws.close() } catch {} })
ws.on('message', (raw: any) => {
const text = String(raw)
try {
const msg = JSON.parse(text)
if (msg && msg.type === 'resize' && Number.isFinite(msg.cols) && Number.isFinite(msg.rows)) {
term.resize(clampDim(msg.cols, cols), clampDim(msg.rows, rows))
return
}
} catch {}
try { term.write(text) } catch {}
})
ws.on('close', () => { terminals.delete(term); try { term.kill() } catch {} })
})
},
}), 'dsh-worktable: terminal upgrade')
}
export function apply(ctx: Context) {
const webServer = (ctx as any).webServer
if (!webServer) {
ctx.logger?.warn('[dsh-worktable] ctx.webServer 不可用(headless profile?),跳过服务端路由')
return
}
const previews = createPreviewFiles()
ctx.effect(() => () => previews.clear(), 'dsh-worktable: preview capabilities')
/** 诊断日志:状态路由到底有没有被调用、被什么挡住(排查重启丢数据用,稳定后可删) */
const stateLog = (line: string) => {
void (async () => {
try {
const fsx = await import('node:fs/promises')
const dir = pathResolve(resolveDshHomeSafe(), 'logs')
await fsx.mkdir(dir, { recursive: true })
await fsx.appendFile(pathResolve(dir, 'worktable-state.log'), new Date().toISOString() + ' ' + line + '\n', 'utf8')
} catch {}
})()
}
// Direct WebServer routes do NOT inherit the host's /api authentication route.
// REQ: 容忍热重载期重复路由 —— 旧 fiber 尚未释放时再次注册会抛 duplicate,
// 若直接抛出会让新 fiber 激活失败、客户端贡献(侧边栏抽屉)整体消失。
// 此时跳过注册即可:路由仍由存活 fiber 服务,下次重启自然收敛回单 fiber。
const register = (route: any, publicAsset = false) => {
let dispose: (() => void) | undefined
try {
dispose = webServer.register({
...route,
handler: async (req: any, res: any) => {
if (!publicAsset && route.path !== HEALTH_PATH) {
const rejected = await requestRejection(ctx, req)
if (rejected !== undefined) {
if (route.path === '/api/worktable/state') stateLog('REJECT ' + req.method + ' -> ' + rejected)
json(res, rejected, { error: rejectionText(rejected) }); return
}
}
return route.handler(req, res)
},
})
} catch (err) {
if (String(err).includes('duplicate')) {
ctx.logger?.warn('[dsh-worktable] 路由已被占用(热重载泄漏自保),跳过: ' + route?.path)
return
}
throw err
}
try { ctx.effect(() => dispose, 'dsh-worktable: ' + route.path) } catch {}
}
register({
kind: 'exact', path: '/api/worktable/preview',
handler: async (req: any, res: any) => {
if (req.method !== 'POST') { json(res, 405, { error: 'method not allowed' }); return }
try {
const body = await readJsonBody(req)
if (typeof body.revoke === 'string') { previews.revoke(body.revoke); json(res, 200, { ok: true }); return }
if (typeof body.root !== 'string') { json(res, 400, { error: 'missing root' }); return }
const token = await previews.mount(body.root)
json(res, 200, { token, base: PREVIEW_PREFIX + '/' + token + '/' })
} catch (err: any) { json(res, err.status ?? 400, { error: String(err) }) }
},
})
register({
kind: 'prefix', path: PREVIEW_PREFIX,
handler: async (req: any, res: any) => {
// A sandboxed document has an opaque origin. It can read only this capability's
// static directory, without credentials; it cannot pass the host API admission.
if (req.method !== 'GET' && req.method !== 'HEAD') { json(res, 405, { error: 'method not allowed' }); return }
try {
const parts = new URL(req.url ?? '/', 'http://dsh.internal').pathname.slice(PREVIEW_PREFIX.length + 1).split('/').map(decodeURIComponent)
const file = await previews.file(parts.shift() ?? '', parts.filter(Boolean), req.method === 'HEAD')
if (!file) { json(res, 404, { error: 'preview unavailable; refresh to reopen' }); return }
const ext = (file.path.split('.').pop() || '').toLowerCase()
res.writeHead(200, {
'content-type': FILE_TYPES[ext] ?? 'application/octet-stream',
'cache-control': 'no-store', 'referrer-policy': 'no-referrer',
'content-security-policy': PREVIEW_CSP, 'x-content-type-options': 'nosniff',
'access-control-allow-origin': '*',
})
res.end(file.data)
} catch (err: any) { json(res, err?.status === 413 ? 413 : 404, { error: err?.status === 413 ? 'file too large' : 'preview unavailable' }) }
},
}, true)
register({
kind: 'exact',
path: HEALTH_PATH,
handler: (_req: any, res: any) => {
json(res, 200, { plugin: 'dsh-worktable', version: PLUGIN_VERSION, ok: true })
},
})
// 更新检查中转:客户端页面来源是 http://127.0.0.1:<随机端口>,直接 fetch
// 自建 Gitea 属跨源请求;Gitea 不返回 Access-Control-Allow-Origin,浏览器会拦截
// (表现为「立即检查」无反应 / 「上次检查未成功」)。改由宿主服务端代取,同源无 CORS。
register({
kind: 'exact',
path: '/api/worktable/update-check',
handler: async (_req: any, res: any) => {
const upstream = 'https://gitea.ququclean.com/api/v1/repos/xiaoqu/dsh-worktable/releases/latest'
const ctrl = new AbortController()
const timer = setTimeout(() => ctrl.abort(), 8000)
try {
const r = await fetch(upstream, {
headers: { Accept: 'application/json', 'user-agent': 'dsh-worktable/' + PLUGIN_VERSION },
signal: ctrl.signal,
})
if (!r.ok) { json(res, 502, { error: 'upstream status ' + r.status }); return }
const d: any = await r.json()
json(res, 200, {
tag_name: typeof d?.tag_name === 'string' ? d.tag_name : '',
body: typeof d?.body === 'string' ? d.body : '',
html_url: typeof d?.html_url === 'string' ? d.html_url : '',
})
} catch (err: any) {
json(res, 502, { error: 'upstream unreachable: ' + String(err?.message ?? err) })
} finally {
clearTimeout(timer)
}
},
})
// 本地文件读取(资源管理器点击 .html 后浏览器标签内打开)
register({
kind: 'exact',
path: '/api/worktable/file',
handler: async (req: any, res: any) => {
try {
const u = new URL(req.url ?? '/', 'http://dsh.internal')
const p = u.searchParams.get('path') || ''
if (!p) { json(res, 400, { error: 'missing path' }); return }
const abs = pathResolve(p)
const stat = await import('node:fs/promises').then((m) => m.stat(abs))
if (stat.size > 20 * 1024 * 1024) { json(res, 413, { error: 'file too large' }); return }
const data = await readFile(abs)
const ext = (abs.split('.').pop() || '').toLowerCase()
const types: Record<string, string> = {
html: 'text/html; charset=utf-8', htm: 'text/html; charset=utf-8',
css: 'text/css; charset=utf-8', js: 'text/javascript; charset=utf-8', mjs: 'text/javascript; charset=utf-8',
json: 'application/json; charset=utf-8', md: 'text/markdown; charset=utf-8', markdown: 'text/markdown; charset=utf-8', txt: 'text/plain; charset=utf-8', log: 'text/plain; charset=utf-8',
pdf: 'application/pdf', svg: 'image/svg+xml', png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp', bmp: 'image/bmp', ico: 'image/x-icon',
}
res.writeHead(200, { 'content-type': FILE_TYPES[ext] ?? 'application/octet-stream', 'cache-control': 'no-store',
'x-content-type-options': 'nosniff',
...(/^(html?|svg)$/.test(ext) ? { 'content-security-policy': PREVIEW_CSP, 'referrer-policy': 'no-referrer' } : {}),
})
res.end(data)
} catch (err) {
json(res, 404, { error: String(err) })
}
},
})
// 本地站点(目录级静态托管):点开 index.html 时挂载整个所在目录,
// 让 ./assets/... 等相对引用正常解析(前缀路由,余下路径 = <rootToken>/<相对路径>)。
// 原生皮肤模板:HTML 骨架 + 设计系统样式表(随插件分发,主题自动适配)
register({
kind: 'prefix',
path: TEMPLATE_PREFIX,
handler: (req: any, res: any) => {
try {
if (req.method !== 'GET') { res.writeHead(405); res.end(); return }
const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
const rel = pathname.slice(TEMPLATE_PREFIX.length)
if (rel === '/dshell.css') {
res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' })
res.end(dshellCss)
} else if (rel === '/theme.js') {
// REQ-20261117-0013:主题桥显式引用入口(站点路由已自动注入内联版;
// 独立打开 / 嵌套 iframe 时手动引这一份)。移植自 qiudl 0.4.x 分支。
res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
res.end(THEME_BRIDGE_JS)
} else {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
res.end(dshellHtml)
}
} catch (err) {
res.writeHead(404); res.end(String(err))
}
},
})
register({
kind: 'prefix',
path: SITE_PREFIX,
handler: async (req: any, res: any) => {
try {
if (req.method !== 'GET') { res.writeHead(405); res.end(); return }
const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
const segs = pathname.slice(SITE_PREFIX.length).split('/').filter(Boolean)
const rootToken = decodeURIComponent(segs.shift() ?? '')
const rel = segs.map((s) => { try { return decodeURIComponent(s) } catch { return s } }).join('/')
if (!rootToken) { json(res, 400, { error: 'missing root' }); return }
const root = pathResolve(rootToken)
let abs = pathResolve(root, rel)
if (abs !== root && !abs.startsWith(root + sep)) { json(res, 403, { error: 'outside root' }); return }
const statMod = await import('node:fs/promises')
let info = await statMod.stat(abs).catch(() => null)
if (info && info.isDirectory()) {
abs = pathResolve(abs, 'index.html')
info = await statMod.stat(abs).catch(() => null)
}
if (!info || !info.isFile()) { json(res, 404, { error: 'not found' }); return }
if (info.size > 40 * 1024 * 1024) { json(res, 413, { error: 'file too large' }); return }
const data = await readFile(abs)
const ext = (abs.split('.').pop() || '').toLowerCase()
res.writeHead(200, { 'content-type': FILE_TYPES[ext] ?? 'application/octet-stream', 'cache-control': 'no-store',
'content-security-policy': PREVIEW_CSP, 'referrer-policy': 'no-referrer', 'x-content-type-options': 'nosniff' })
// REQ-20261117-0013:产物 HTML 自动挂主题桥,让所有工作台页跟随 DSH 主题
// (浅色/深色/跟随系统)。幂等:已含 data-wt-theme-bridge 标记则原样返回;
// 非 HTML 不受影响。移植自 qiudl 0.4.x 分支(0.5.x 线缺失该能力)。
res.end(ext === 'html' || ext === 'htm'
? Buffer.from(injectThemeBridge(data.toString('utf8')), 'utf8')
: data)
} catch (err) {
json(res, 404, { error: String(err) })
}
},
})
register({
kind: 'exact',
path: '/api/worktable/fs',
handler: async (req: any, res: any) => {
try {
const body = await readJsonBody(req)
const path = typeof body.path === 'string' && body.path
? body.path
: serverCwd(ctx, body.sessionId, body.cwd)
json(res, 200, await listDirectory(path))
} catch (err) {
json(res, (err as any).status ?? 500, { path: '', entries: [], truncated: false, error: String(err) })
}
},
})
// 工作区列表(自定义窗口会话分组用):
// 优先走宿主正式服务 ctx.workspaceRegistry(0.1.1/0.1.2 均有,正确感知 DSH_HOME 与存储后端);
// 不可用时回退按 resolveDshHomeSafe() 读 storages/workspace.json(只读)。
// 返回结构是客户端契约,两种来源都映射成同一 shape。
register({
kind: 'exact',
path: '/api/worktable/workspaces',
handler: async (_req: any, res: any) => {
try {
// cordis 对未 inject 服务的属性访问会直接 throw(不返回 undefined),必须 try-catch 探测
let registry: any = null
try { registry = (ctx as any).workspaceRegistry ?? null } catch {}
if (!registry) {
try { registry = ctx.get?.('workspaceRegistry') ?? null } catch {}
}
if (registry && typeof registry.list === 'function') {
const list = registry.list() ?? []
const workspaceIds: string[] = []
const tables: Record<string, { title?: string; sessionIds?: string[] }> = {}
for (const ws of list) {
const id = String(ws?.id ?? '')
if (!id) continue
workspaceIds.push(id)
tables[id] = {
title: typeof ws?.title === 'string' ? ws.title : undefined,
sessionIds: Array.isArray(ws?.sessionIds) ? ws.sessionIds.map(String) : [],
}
}
let archived: string[] = []
try { archived = (registry.archivedSessionIds ?? []).map(String) } catch {}
json(res, 200, {
unit: { name: 'workspace', version: 2 },
global: { initialized: true, workspaceIds, archivedSessionIds: archived },
tables: { workspaces: tables },
})
return
}
const file = pathResolve(resolveDshHomeSafe(), 'storages', 'workspace.json')
const raw = await readFile(file, 'utf8')
// 容忍 BOM(外部工具改写可能带 EF BB BF,JSON.parse 会抛错)
json(res, 200, JSON.parse(raw.charCodeAt(0) === 0xFEFF ? raw.slice(1) : raw))
} catch (err) {
json(res, 404, { error: String(err) })
}
},
})
// 本地文件写入(MD 编辑模式保存回磁盘)
register({
kind: 'exact',
path: '/api/worktable/write',
handler: async (req: any, res: any) => {
try {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
const body = await readJsonBody(req)
const p = typeof body.path === 'string' ? body.path : ''
const content = typeof body.content === 'string' ? body.content : ''
if (!p) { json(res, 400, { error: 'missing path' }); return }
if (content.length > 20 * 1024 * 1024) { json(res, 413, { error: 'content too large' }); return }
const abs = pathResolve(p)
await import('node:fs/promises').then((m) => m.writeFile(abs, content, 'utf8'))
json(res, 200, { ok: true })
} catch (err) {
json(res, (err as any).status ?? 500, { error: String(err) })
}
},
})
// 新建分组:创建目录(仅当父目录已存在,避免递归误建深层垃圾目录)
register({
kind: 'exact',
path: '/api/worktable/mkdir',
handler: async (req: any, res: any) => {
try {
if (req.method !== 'POST') { res.writeHead(405); res.end(); return }
const body = await readJsonBody(req)
const p = typeof body.path === 'string' ? body.path.trim() : ''
if (!p) { json(res, 400, { error: 'missing path' }); return }
const abs = pathResolve(p)
const fsx = await import('node:fs/promises')
const parent = dirname(abs)
try { await fsx.access(parent) } catch { json(res, 400, { error: 'parent not found' }); return }
await fsx.mkdir(abs)
json(res, 200, { ok: true, path: abs })
} catch (err: any) {
json(res, err?.code === 'EEXIST' ? 200 : err.status ?? 500, err?.code === 'EEXIST' ? { ok: true, exists: true } : { error: String(err) })
}
},
})
register({
kind: 'exact',
path: '/api/worktable/git',
handler: async (req: any, res: any) => {
try {
const body = await readJsonBody(req)
const cwd = serverCwd(ctx, body.sessionId, body.cwd)
json(res, 200, await gitStatus(cwd))
} catch (err: any) { json(res, err.status ?? 500, { error: String(err) }) }
},
})
/**
* 本机配置候选路径(REQ-20261117-0013:把 qiudl 分支的云状态能力并入本线)。
*
* 查找顺序:环境变量 DSH_WORKTABLE_LOCAL_DIR → <插件根>/03_local → 上两层/上三层 03_local
* → <DSH_HOME>/03_local。个人绝对路径只存在于这些配置文件里,源码与打包产物零出现。
*/
const localConfigPaths = (fileName: string): string[] => {
const out: string[] = []
const envDir = process.env.DSH_WORKTABLE_LOCAL_DIR
if (typeof envDir === 'string' && envDir.trim()) out.push(pathResolve(envDir.trim(), fileName))
try {
const libDir = dirname(fileURLToPath(import.meta.url))
out.push(pathResolve(libDir, '..', '03_local', fileName))
out.push(pathResolve(libDir, '..', '..', '03_local', fileName))
out.push(pathResolve(libDir, '..', '..', '..', '03_local', fileName))
} catch { /* 解析不到就去试 DSH_HOME 兜底 */ }
try {
const home = resolveDshHomeSafe()
if (typeof home === 'string' && home) out.push(pathResolve(home, '03_local', fileName))
} catch { /* DSH_HOME 解析失败就只保留相对链候选 */ }
return out
}
/** 按候选路径读本机配置的一个字符串字段;文件缺失 / 坏 JSON / 字段空 → 试下一个,全落空为 null。 */
const readLocalConfigField = async (fileName: string, field: string): Promise<string | null> => {
for (const file of localConfigPaths(fileName)) {
try {
const raw = await readFile(file, 'utf8')
const parsed = JSON.parse(raw.charCodeAt(0) === 0xFEFF ? raw.slice(1) : raw)
const value = parsed && typeof parsed === 'object' ? (parsed as Record<string, unknown>)[field] : undefined
const text = typeof value === 'string' ? value.trim() : ''
if (text) return text
} catch { /* 继续下一个候选 */ }
}
return null
}
/**
* 工作台状态宿主侧镜像(本地补丁)。
*
* 桌面端宿主以 `--port 0` 启动,端口每次随机,页面来源跟着变;而 localStorage 按来源隔离,
* 于是「新建的项目重启就没了」。这里把项目/视图这份 JSON 落到一个固定文件:
* 跨重启、跨端口稳定。客户端启动时比对时间戳决定是否回填(见 client/hostState.ts)。
*
* REQ-20261117-0013:路径优先取本机配置 03_local/local.json 的 cloudStatePath
* —— 该文件指向一个独立 git 仓(由外部定时 commit+push),于是「云状态 + git 历史」
* 这份能力随本线一起保留:换机器、清缓存、跨重启都能恢复,且每次写入进版本历史。
* 未配置时回落到 DSH_HOME 下的 worktable-state.json(与旧行为一致)。
*/
const statePath = async (): Promise<string> =>
(await readLocalConfigField('local.json', 'cloudStatePath'))
?? pathResolve(resolveDshHomeSafe(), 'worktable-state.json')
register({
kind: 'exact',
path: '/api/worktable/state',
handler: async (req: any, res: any) => {
const file = await statePath()
if (req.method === 'GET' || req.method === 'HEAD') {
try {
const raw = await readFile(file, 'utf8')
const text = raw.charCodeAt(0) === 0xFEFF ? raw.slice(1) : raw
const parsed: any = JSON.parse(text)
json(res, 200, { ok: true, path: file, state: parsed })
} catch (err: any) {
if (err?.code === 'ENOENT') { stateLog('GET empty (no file)'); json(res, 200, { ok: true, path: file, state: null }); return }
stateLog('GET error ' + String(err))
json(res, 500, { error: String(err) })
}
return
}
if (req.method !== 'POST') { json(res, 405, { error: 'method not allowed' }); return }
try {
const body = await readJsonBody(req)
const incoming = body && typeof body.state === 'object' && body.state !== null ? body.state : null
if (!incoming) { stateLog('POST 400 missing state'); json(res, 400, { error: 'missing state' }); return }
// 按 key 合并:客户端只带 view 的半截写入不能把 projects 抹掉
let previous: any = null
try {
const raw = await readFile(file, 'utf8')
previous = JSON.parse(raw.charCodeAt(0) === 0xFEFF ? raw.slice(1) : raw)
} catch {}
const state = previous && typeof previous === 'object' && !Array.isArray(previous)
? { ...previous, ...incoming }
: incoming
const text = JSON.stringify(state)
// 只在「项目变少」时记一行:正常保存不写日志,避免文件无限增长
const inN = incoming?.projects?.layouts?.length ?? 0
const prevN = previous?.projects?.layouts?.length ?? 0
if (inN < prevN) {
stateLog('WARN projects shrink ' + prevN + ' -> ' + inN + ' (keys=' + Object.keys(incoming).join('+') + ')')
}
if (text.length > 20 * 1024 * 1024) { json(res, 413, { error: 'state too large' }); return }
const fsx = await import('node:fs/promises')
await fsx.mkdir(dirname(file), { recursive: true })
const tmp = file + '.tmp-' + process.pid + '-' + Date.now()
await fsx.writeFile(tmp, text, 'utf8')
await fsx.rename(tmp, file)
json(res, 200, { ok: true, path: file })
} catch (err: any) {
json(res, err?.status ?? 500, { error: String(err) })
}
},
})
setupTerminal(webServer, ctx)
}