@luosuqwq/dsh-ui-appearance 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,183 @@
1
+ import fs from 'node:fs/promises'
2
+ import { readFileSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import crypto from 'node:crypto'
5
+ import { spawn } from 'node:child_process'
6
+ import { fileURLToPath } from 'node:url'
7
+
8
+ const NS = 'dsh-ui-appearance'
9
+ const userRoot = path.join(process.env.USERPROFILE || process.env.HOME || process.cwd(), '.dsh', 'plugins', NS)
10
+ const configuredWorkspace = process.env.DSH_WORKSPACE
11
+ const bundledAssets = process.env.DSH_APPEARANCE_ASSETS
12
+ const configFile = path.join(userRoot, 'config.json')
13
+ const types = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif' }
14
+ /** 随包附带的默认壁纸;没有配置过的用户直接用它。 */
15
+ const DEFAULT_WALLPAPER = '/bg/' + encodeURIComponent('花与大肥鱼 version2.png')
16
+ /** 包内的只读壁纸目录:npm 安装(没有检出目录)时默认壁纸也从这里提供。 */
17
+ const packageAssets = fileURLToPath(new URL('../../assets/backgrounds', import.meta.url))
18
+ const defaults = {
19
+ bgImage: DEFAULT_WALLPAPER, bgSize: 'cover', bgOpacity: 1, bgBlur: 0,
20
+ bgMask: '#f8f7f7', bgMaskOpacity: 0,
21
+ parallaxEnabled: true, parallaxAmplitude: 12, parallaxEasing: 'ease-out',
22
+ conversationEnabled: true, conversationOpacity: 0.2, conversationBlur: 2, conversationColor: '#ffffff', conversationWidth: 870,
23
+ chatBoxColor: '#ffffff', chatBoxOpacity: 0.59, chatBoxBlur: 0, chatBoxBorder: 'none', chatBoxRadius: 24,
24
+ newChatBoxColor: '#ffffff', newChatBoxOpacity: 0.9, newChatBoxBlur: 8, newChatBoxBorder: 'thin', newChatBoxRadius: 16,
25
+ existingChatBoxColor: '#ffffff', existingChatBoxOpacity: 0.82, existingChatBoxBlur: 10, existingChatBoxBorder: 'thin', existingChatBoxRadius: 16,
26
+ settingsOpacity: 0.4, settingsBlur: 16, settingsColor: '#ffffff',
27
+ sidebarOpacity: 0.4, sidebarAutoHide: false, prewarmFirstSlide: true,
28
+ previewPopupShared: true, previewPopupInset: 8,
29
+ pageCard: true,
30
+ }
31
+ const clamp = (n, min, max) => { n = Number(n); return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : min }
32
+ const safeConfig = (value) => {
33
+ const out = { ...defaults, ...(value && typeof value === 'object' ? value : {}) }
34
+ out.bgOpacity = clamp(out.bgOpacity, 0, 1); out.bgBlur = clamp(out.bgBlur, 0, 60)
35
+ out.bgMaskOpacity = clamp(out.bgMaskOpacity, 0, 1); out.parallaxAmplitude = clamp(out.parallaxAmplitude, 0, 50)
36
+ out.conversationOpacity = clamp(out.conversationOpacity, 0, 1); out.conversationBlur = clamp(out.conversationBlur, 0, 60)
37
+ out.settingsOpacity = clamp(out.settingsOpacity, 0, 1); out.settingsBlur = clamp(out.settingsBlur, 0, 60)
38
+ for (const key of ['newChatBoxOpacity', 'existingChatBoxOpacity']) out[key] = clamp(out[key], 0, 1)
39
+ for (const key of ['newChatBoxBlur', 'existingChatBoxBlur', 'newChatBoxRadius', 'existingChatBoxRadius']) out[key] = clamp(out[key], 0, 60)
40
+ out.previewPopupInset = clamp(out.previewPopupInset, 0, 48)
41
+ return out
42
+ }
43
+ const send = (res, status, data, type = 'application/json') => { res.statusCode = status; if (res.setHeader) res.setHeader('content-type', type); if (type === 'application/json') data = JSON.stringify(data); res.end(data) }
44
+
45
+ export const name = NS
46
+ export const inject = ['webServer', 'workspaceRegistry']
47
+ const resolveWorkspaceRoot = (ctx) => {
48
+ if (configuredWorkspace) return path.resolve(configuredWorkspace)
49
+ try {
50
+ const workspace = ctx.workspaceRegistry.list()[0]
51
+ if (workspace?.path) return path.resolve(workspace.path)
52
+ } catch {}
53
+ return path.resolve(process.cwd())
54
+ }
55
+ export function apply(ctx) {
56
+ const root = path.join(resolveWorkspaceRoot(ctx), 'plugins', NS)
57
+ const dir = path.join(root, 'assets', 'backgrounds')
58
+ // 顺序即优先级:用户自己的目录优先,其次是 DSH_APPEARANCE_ASSETS,最后是包内默认壁纸。
59
+ const assetDirs = [...new Set([dir, bundledAssets ? path.resolve(bundledAssets) : null, packageAssets].filter(Boolean).map((item) => path.resolve(item)))]
60
+ const legacyDir = path.join(userRoot, 'assets', 'backgrounds')
61
+ const migrateLegacy = async () => {
62
+ if (path.resolve(legacyDir).toLowerCase() === path.resolve(dir).toLowerCase()) return
63
+ const files = await fs.readdir(legacyDir, { withFileTypes: true }).catch(() => [])
64
+ const images = files.filter((entry) => entry.isFile() && /\.(jpe?g|png|webp|gif)$/i.test(entry.name))
65
+ if (!images.length) return
66
+ await fs.mkdir(dir, { recursive: true })
67
+ for (const entry of images) {
68
+ const source = path.join(legacyDir, entry.name)
69
+ const target = path.join(dir, entry.name)
70
+ try {
71
+ await fs.access(target)
72
+ } catch {
73
+ try {
74
+ await fs.rename(source, target)
75
+ } catch (error) {
76
+ if (error.code !== 'EXDEV') throw error
77
+ await fs.copyFile(source, target)
78
+ await fs.unlink(source)
79
+ }
80
+ }
81
+ }
82
+ await fs.rm(legacyDir, { recursive: false, force: true }).catch(() => {})
83
+ }
84
+ const ready = migrateLegacy().catch(() => {})
85
+ const load = async () => { try { return safeConfig(JSON.parse(await fs.readFile(configFile, 'utf8'))) } catch { return null } }
86
+ const save = async (value) => { await fs.mkdir(userRoot, { recursive: true }); await fs.writeFile(configFile, JSON.stringify(safeConfig(value), null, 2), 'utf8') }
87
+ const route = async (req, res) => {
88
+ await ready
89
+ const url = new URL(req.url || '/', 'http://localhost')
90
+ if (url.pathname === '/bg/list') {
91
+ // 返回 { url, name }:name 是解码后的原文件名。只给 URL 的话,中文文件名会被
92
+ // encodeURIComponent 成 %E5%B0%91%E5%A5%B3,设置页的壁纸下拉框就只能显示乱码。
93
+ const entries = new Map()
94
+ for (const assetDir of assetDirs) {
95
+ for (const file of await fs.readdir(assetDir).catch(() => [])) {
96
+ if (!/\.(jpe?g|png|webp|gif)$/i.test(file) || entries.has(file)) continue
97
+ entries.set(file, { url: '/bg/' + encodeURIComponent(file), name: file })
98
+ }
99
+ }
100
+ return send(res, 200, [...entries.values()])
101
+ }
102
+ if (url.pathname === '/bg/path') return send(res, 200, { path: dir })
103
+ // 设置页的「壁纸文件夹」按钮:在系统文件管理器里打开壁纸目录。
104
+ // 只接受这个固定目录,不接受调用方传入路径。
105
+ if (url.pathname === '/bg/reveal' && req.method === 'POST') {
106
+ await fs.mkdir(dir, { recursive: true }).catch(() => {})
107
+ try {
108
+ const [command, args] = process.platform === 'win32'
109
+ ? ['explorer.exe', [dir]]
110
+ : process.platform === 'darwin'
111
+ ? ['open', [dir]]
112
+ : ['xdg-open', [dir]]
113
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: false })
114
+ child.on('error', () => {})
115
+ child.unref()
116
+ return send(res, 200, { opened: true, path: dir })
117
+ } catch (error) {
118
+ return send(res, 500, { error: String(error?.message ?? error) })
119
+ }
120
+ }
121
+ if (url.pathname === '/bg/upload' && req.method === 'POST') {
122
+ let body = Buffer.alloc(0)
123
+ for await (const chunk of req) { body = Buffer.concat([body, chunk]); if (body.length > 12 * 1024 * 1024) break }
124
+ const ext = types[(req.headers['content-type'] || '').split(';')[0]]
125
+ if (!ext || body.length > 12 * 1024 * 1024) return send(res, 415, { error: 'only JPEG/PNG/WebP/GIF up to 12MB' })
126
+ await fs.mkdir(dir, { recursive: true })
127
+ const file = crypto.randomUUID() + '.' + ext
128
+ await fs.writeFile(path.join(dir, file), body)
129
+ return send(res, 201, { url: '/bg/' + encodeURIComponent(file), name: file })
130
+ }
131
+ if (url.pathname === '/bg/config') {
132
+ if (req.method === 'GET') {
133
+ const value = await load()
134
+ return value ? send(res, 200, value) : send(res, 404, { error: 'appearance config not found' })
135
+ }
136
+ if (req.method === 'POST') { const data = JSON.parse((await collect(req)) || '{}'); await save(data); await refreshCfg(); return send(res, 200, activeCfg || safeConfig(data)) }
137
+ }
138
+ if (url.pathname.startsWith('/bg/')) {
139
+ const file = path.basename(decodeURIComponent(url.pathname.slice(4)))
140
+ const clean = file === decodeURIComponent(url.pathname.slice(4))
141
+ if (!clean) return send(res, 400, { error: 'bad filename' })
142
+ const ext = path.extname(file).toLowerCase()
143
+ const mime = { '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.webp': 'image/webp', '.gif': 'image/gif' }[ext]
144
+ if (!mime) return send(res, 404, { error: 'not found' })
145
+ try {
146
+ for (const assetDir of assetDirs) {
147
+ try {
148
+ const data = await fs.readFile(path.join(assetDir, file))
149
+ return send(res, 200, data, mime)
150
+ } catch {}
151
+ }
152
+ return send(res, 404, { error: 'not found' })
153
+ } catch { return send(res, 404, { error: 'not found' }) }
154
+ }
155
+ res.statusCode = 404; res.end()
156
+ }
157
+ const collect = async (req) => { let body = Buffer.alloc(0); for await (const chunk of req) { body = Buffer.concat([body, chunk]); if (body.length > 1e6) break } return body.toString('utf8') }
158
+
159
+ // —— 首帧预加载:把壁纸作为一段极早的 <style> 注入每个被服务页面的 <head>。
160
+ // 这发生在任何外观 JS 之前、HTML 一解析到 <head> 就画出来,所以即使某个首屏页面
161
+ // 因为插件尚未注册而没加载外观 client,也能直接看到壁纸(只要本 host 已 apply,
162
+ // 即 /bg 图片本身也可用)。
163
+ let activeCfg = defaults
164
+ // 同步读好配置:首屏一被服务就立刻有壁纸样式注入,不等异步迁移/读盘。
165
+ try { activeCfg = safeConfig(JSON.parse(readFileSync(configFile, 'utf8'))) } catch { /* config absent yet */ }
166
+ const refreshCfg = async () => { activeCfg = (await load()) || defaults }
167
+ ready.then(() => { void refreshCfg() })
168
+ const backgroundCss = () => {
169
+ const c = activeCfg
170
+ if (!c || !c.bgImage) return null
171
+ const url = String(c.bgImage).replace(/"/g, '\\"')
172
+ const size = c.bgSize === 'contain' ? 'contain' : c.bgSize === 'tile' ? 'auto' : 'cover'
173
+ const repeat = c.bgSize === 'tile' ? 'repeat' : 'no-repeat'
174
+ return `/*dsh-ui-appearance-head*/html{background-color:#ffffff!important;background-image:url("${url}")!important;background-size:${size}!important;background-repeat:${repeat}!important;background-position:center!important}#root{background:transparent!important}`
175
+ }
176
+ ctx.on('webserver/index-inject', (table) => {
177
+ const css = backgroundCss()
178
+ if (css !== null && Array.isArray(table)) table.push({ kind: 'style', placement: 'head', text: css })
179
+ })
180
+
181
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: '/bg', handler: route }), 'dsh-ui-appearance: bg routes')
182
+ }
183
+ export { defaults, safeConfig }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Appearance",
4
+ "description": "Paints a wallpaper behind the conversation with a parallax offset, turns panels into frosted glass, and lets the sidebar fade or auto-hide. Everything is adjustable in Settings → Appearance; drop images into the wallpaper folder to use your own."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "外观",
4
+ "description": "在会话后面铺壁纸并做视差偏移,把面板做成毛玻璃,侧边栏可以淡化或自动隐藏。全部在「设置 → 外观」里调整;把图片放进壁纸文件夹即可用上自己的壁纸。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,62 @@
1
1
  {
2
2
  "name": "@luosuqwq/dsh-ui-appearance",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.2",
4
+ "description": "Wallpapers with parallax, frosted-glass panels, sidebar auto-hide and chat styling, all adjustable from a Settings section.",
5
+ "author": "LuoSu <2681153600@qq.com>",
6
+ "keywords": [
7
+ "deepseek-harness",
8
+ "dsh",
9
+ "dsh-plugin",
10
+ "dsh-bundle",
11
+ "theme",
12
+ "appearance",
13
+ "wallpaper",
14
+ "glassmorphism"
15
+ ],
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "main": "lib/host/index.js",
19
+ "exports": {
20
+ ".": "./lib/host/index.js",
21
+ "./client": "./lib/client/index.js",
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./icon": "./icon.svg",
24
+ "./cordis.patch.yml": "./cordis.patch.yml",
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "lib",
29
+ "assets/backgrounds/花与大肥鱼 version1.png",
30
+ "assets/backgrounds/花与大肥鱼 version2.png",
31
+ "test",
32
+ "locale/*.json",
33
+ "icon.svg",
34
+ "cordis.patch.yml",
35
+ "README.md",
36
+ "README.zh-CN.md",
37
+ "LICENSE",
38
+ "package.json",
39
+ "AGENTS.md"
40
+ ],
41
+ "dsh": {
42
+ "manifestVersion": 1,
43
+ "bundle": {
44
+ "patch": "./cordis.patch.yml"
45
+ },
46
+ "client": {
47
+ "platform": "web",
48
+ "inject": []
49
+ }
50
+ },
51
+ "scripts": {
52
+ "test": "node test/appearance-motion.cjs"
53
+ },
54
+ "repository": {
55
+ "type": "git",
56
+ "url": "git+https://github.com/LuosuQWQ/dsh-ui-appearance.git"
57
+ },
58
+ "homepage": "https://github.com/LuosuQWQ/dsh-ui-appearance#readme",
59
+ "bugs": {
60
+ "url": "https://github.com/LuosuQWQ/dsh-ui-appearance/issues"
61
+ }
62
+ }
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * dsh-ui-appearance「动效预算」静态回归测试(无第三方依赖)。
4
+ *
5
+ * 为什么要静态断言而不是跑 DOM:jsdom 不实现 transition/合成层,测不出"滑入是否卡",
6
+ * 但能测出"代码里还有没有逐帧重活"这类结构性错误——那才是首次滑入掉帧的成因。
7
+ *
8
+ * 运行:node test/appearance-motion.cjs
9
+ */
10
+ const fs = require('node:fs')
11
+ const path = require('node:path')
12
+
13
+ const FILE = path.join(__dirname, '..', 'lib', 'client', 'index.js')
14
+ const source = fs.readFileSync(FILE, 'utf8')
15
+
16
+ let failed = 0
17
+ const check = (name, ok, detail) => {
18
+ if (ok) {
19
+ console.log(` ok ${name}`)
20
+ return
21
+ }
22
+ failed += 1
23
+ console.log(` FAIL ${name}${detail ? `\n ${detail}` : ''}`)
24
+ }
25
+ const slice = (start, end) => {
26
+ const from = source.indexOf(start)
27
+ if (from < 0) return ''
28
+ const to = end ? source.indexOf(end, from) : source.length
29
+ return source.slice(from, to < 0 ? source.length : to)
30
+ }
31
+ const count = (needle) => source.split(needle).length - 1
32
+ // 去掉行注释再匹配:注释里会提到 applyBackground 之类的名字,不能算数。
33
+ const stripComments = (text) => text.replace(/\/\*[\s\S]*?\*\//g, '').split(/\r?\n/).map((line) => line.replace(/\/\/.*$/, '')).join('\n')
34
+ // 取出一个反引号模板字面量的内容(CSS 里不含反引号)。
35
+ const templateOf = (marker) => {
36
+ const at = source.indexOf(marker)
37
+ if (at < 0) return ''
38
+ const start = source.indexOf('`', at)
39
+ if (start < 0) return ''
40
+ const end = source.indexOf('`', start + 1)
41
+ return end < 0 ? '' : source.slice(start + 1, end)
42
+ }
43
+
44
+ console.log('appearance-motion')
45
+
46
+ // —— 1. 结构:动画期间不得直接跑全量 applyBackground ——
47
+ const runSync = slice('const runSync = () => {', 'const scheduleSync')
48
+ check('合并同步存在于 runSync', runSync.includes('applyBackground(current, theme)'))
49
+ check('runSync 先判断动效窗口', runSync.includes('motionActive()') && runSync.indexOf('motionActive()') < runSync.indexOf('applyBackground'))
50
+
51
+ const observer = slice('const mo = new MutationObserver((records) => {', 'mo.observe(document.body')
52
+ check('MutationObserver 回调里不再直接 applyBackground', observer.length > 0 && !observer.includes('applyBackground'))
53
+ check('MutationObserver 回调走合并同步', observer.includes('scheduleSync()'))
54
+ check('右栏展开被登记为动效窗口', observer.includes("attributeName === 'data-sidebar-right-open'") && observer.includes('enterMotion(420)'))
55
+
56
+ const columns = stripComments(slice('const scheduleColumns = () => {', 'const watchColumns'))
57
+ check('centerCol 的 ResizeObserver 只同步几何', columns.includes('syncFrameNow()') && !columns.includes('applyBackground'))
58
+ // 回归:syncFrameNow 以前用缓存宽度写左轨 → 拖左分界线时把宽度按回去(拖不动)。
59
+ check('左轨宽度以官方 inline 第一轨为准', source.includes('frameSidebarTrackPx(raw)'))
60
+ check('读到的左轨宽度会回写缓存(但不会被 56px 窄栏覆盖)', /if \(nativeSidebarPx > 200\) sidebarWideWidth = nativeSidebarPx/.test(source))
61
+ check('拖拽结束补一次同步', source.includes('onPointerRelease') && source.includes("addEventListener('pointerup', onPointerRelease, true)"))
62
+
63
+ const hover = slice('const applySidebarHover = (e) => {', 'const sidebarHover = (e)')
64
+ check('Hover 只在展开状态变化时写样式', hover.includes("=== String(revealed)) return"))
65
+ check('Hover 不逐次量 rect 之后再写样式(侧栏宽度走缓存)', !hover.includes('root.getBoundingClientRect().width'))
66
+
67
+ const syncRoot = slice('const syncSidebarRoot = (sidebar, autoHide, instant) => {', '// applyBackground 的"几何半"')
68
+ // 回归:收起偏移曾只用缓存宽度。缓存会被窄栏(56px)/过渡中间值写小,也会在自动隐藏
69
+ // 期间不再刷新,于是收起只推出去缓存那么多 → 左边残留一条缝或半截侧栏。
70
+ check('收起偏移按真实宽度计算', syncRoot.includes('root.getBoundingClientRect().width') && syncRoot.includes('measuredWidth'))
71
+ check('收起偏移取"实测宽度 / 缓存"较大值', /Math\.max\(\s*measuredWidth > 50 \? measuredWidth : 0/.test(syncRoot))
72
+ check('syncSidebarRoot 回写缓存也不被窄栏覆盖', /if \(measuredWidth > 200\) sidebarWideWidth = measuredWidth/.test(syncRoot))
73
+ check('点击开关回写缓存同样只认展开宽度', /measuredWidth > 200.*sidebarWideWidth = measuredWidth/.test(source))
74
+ check('首次展开瞬时定位', syncRoot.includes('firstReveal') && syncRoot.includes("transition', 'none'"))
75
+ check('瞬时定位后会还回过渡(带令牌,避免旧回调覆盖)', syncRoot.includes('sidebarInstantToken'))
76
+ check('同步路径会清掉预热用的临时 opacity', syncRoot.includes("removeProperty('opacity')"))
77
+
78
+ const prewarm = slice('const prewarmSidebar = () => {', 'const sidebarStyleState')
79
+ check('存在静默预热', prewarm.length > 0)
80
+ check('预热用的是不可见透明度而不是 visibility', prewarm.includes("opacity', '0.002'"))
81
+ check('预热期间不吃指针事件', prewarm.includes("pointer-events', 'none'"))
82
+ check('预热有兜底回收(后台标签页 rAF 不跑)', prewarm.includes('setTimeout(finish, 400)'))
83
+ check('预热结束会清掉临时样式', prewarm.includes("removeProperty('opacity')") && prewarm.includes("removeProperty('pointer-events')"))
84
+
85
+ const click = slice('const sidebarToggleClick = (e) => {', "window.addEventListener('pointerdown'")
86
+ check('点击开关不再同步跑 applyBackground', !click.includes('applyBackground('))
87
+ check('点击开关会开启动效窗口', click.includes('enterMotion(340)'))
88
+
89
+ // —— 2. 样式:右栏毛玻璃在滑动期间摘掉 + 内容延迟入场 ——
90
+ const popup = slice('const POPUP_STYLE = `', 'const appearanceRootStyles')
91
+ check('滑动期间摘掉 backdrop-filter', popup.includes('data-dsh-popup-motion="true"') && popup.includes('backdrop-filter:none!important'))
92
+ check('毛玻璃有淡回过渡', popup.includes('transition:backdrop-filter .16s linear'))
93
+ // 右栏"容器闪出来"的根因:插件把面板推到屏外却没有给 transform 过渡 → 打开时容器瞬移到位。
94
+ check('右栏容器自己有 transform 过渡', popup.includes('transition:transform .22s'))
95
+ check('内容跟随容器、不再二次位移', popup.includes('[data-dockkit-host="dock"]') && popup.includes('transform:none!important'))
96
+ check('右栏容器过渡有首帧闸门', popup.includes('[data-dsh-popup-anim="false"]') && popup.includes('transition:none!important'))
97
+ check('instant 切换(fullscreen→push)不播容器过渡', popup.includes('[data-rightbar-instant]'))
98
+ check('闸门会被首次展开放行', source.includes('openPopupAnimGate') && observer.includes('openPopupAnimGate()'))
99
+ check('右栏内容延迟入场(容器先动、内容后入)', popup.includes('dsh-appearance-popup-in') && /animation:dsh-appearance-popup-in \.16s linear \.\d+s/.test(popup))
100
+ check('尊重 reduced-motion', popup.includes('prefers-reduced-motion:reduce') && popup.includes('animation:none'))
101
+ check('弹窗样式仍在独立样式表', source.includes('popupTag.textContent = POPUP_STYLE') && source.includes("NS + ':popup'"))
102
+
103
+ // —— 3. 主面板卡片(插件页 / 自动化任务页)——
104
+ const page = templateOf('const PAGE_STYLE =')
105
+ check('主面板卡片复用会话区玻璃变量', page.includes('background:var(--dsh-conv-bg)!important') && page.includes('backdrop-filter:blur(var(--dsh-conv-blur))!important'))
106
+ check('主面板卡片几何与会话卡片一致(宽度/圆角/外边距)', page.includes('--dsh-conversation-width,760px') && page.includes('border-radius:20px!important') && page.includes('margin:24px auto!important'))
107
+ check('插件页自身滚动 → 卡片保留 auto', page.includes('overflow:auto!important'))
108
+ check('任务页滚动在内层 → 卡片用 hidden', page.includes('[data-testid="task-manager-page"]{overflow:hidden!important}'))
109
+ check('打标走 main 槽锚点的子元素', source.includes('[data-slot="main"]') && source.includes('anchor.children'))
110
+ check('会话页不会被误打标', source.includes("el.querySelector('[data-phase]') !== null") && source.includes("el.querySelector('[data-conversation-scroll]') !== null"))
111
+ check('主面板卡片有开关且默认开', source.includes('pageCard: true') && source.includes("'pageCard'"))
112
+ check('卸载会清掉打标与样式表', source.includes("querySelectorAll('[data-dsh-appearance-page]')") && source.includes("NS + ':page'"))
113
+
114
+ // —— 4. 既有硬约定不回归 ——
115
+ const mainStyle = templateOf('const STYLE =')
116
+ check('主样式表长度合理(没有整块回流/死 CSS 复活)', mainStyle.length > 4000 && mainStyle.length < 16000, `实际 ${mainStyle.length} 字节`)
117
+ check('弹窗不写 width(避免面板内容逐帧重排)', !popup.includes('width:calc('))
118
+ check('拖拽期间不写行内 !important 的列宽', source.includes('dragging ? \'\' : \'important\''))
119
+
120
+ // —— 4. 括号平衡(曾经被未闭合 @media 吞掉整批规则) ——
121
+ check('主样式表大括号平衡', mainStyle.length > 0 && (mainStyle.split('{').length === mainStyle.split('}').length), `{=${mainStyle.split('{').length - 1} }=${mainStyle.split('}').length - 1}`)
122
+
123
+
124
+ // —— 5. 串流热路径("越用越卡"):不得每帧做全文档扫描 / 强制布局 ——
125
+ const moNew = slice('const mo = new MutationObserver((records) => {', 'mo.observe(document.body')
126
+ check('mutation 流不再无条件全量同步', moNew.includes('scheduleFullSync()') && !/^\s*scheduleSync\(\)\s*$/m.test(moNew))
127
+ check('结构变化才立刻全量同步', moNew.includes('hasStructuralAddition(records)'))
128
+ check('全量同步去抖', /const FULL_SYNC_DEBOUNCE_MS = \d+/.test(source) && source.includes('setTimeout(() => { fullSyncTimer = null'))
129
+
130
+ const light = slice('const scheduleLightSync = () => {', '// 右栏(文档预览)')
131
+ check('轻活只跟随最新,不跑 applyBackground/tagDom', light.includes('scheduleConversationScroll()') && !light.includes('applyBackground') && !light.includes('tagDom'))
132
+
133
+ const scroller = slice('const scrollConversationToLatest = (force = false) => {', 'const scheduleConversationScroll')
134
+ check('跟随最新不再每帧量容器尺寸', !scroller.includes('scroll.offsetWidth') && !scroller.includes('scroll.clientWidth'))
135
+ check('滚动容器样式只在切换滚动容器时写', (scroller.match(/setProperty\('overflow-y'/g) || []).length === 1)
136
+
137
+ const measure = slice('const measureLatestButton = (scroll) => {', 'const scrollConversationToLatest')
138
+ check('气泡按钮位置缓存后才写', measure.includes('latestMetrics.right') && measure.includes('measureLatestButton'))
139
+ check('窗口 resize 触发一次全量同步', source.includes("addEventListener('resize', onWindowResize)"))
140
+
141
+ const tooltipSync = slice('const involvesTooltip = (records) => {', 'observer.observe(document.body')
142
+ check('tooltip 观察者按批次过滤(不再每次全文档扫描)', tooltipSync.includes("getAttribute('role') === 'tooltip'") && !tooltipSync.includes('new MutationObserver(schedule)'))
143
+
144
+ const parallax = slice('let lastParallax =', "document.addEventListener('mousemove', move)")
145
+ check('视差走合成器 transform 且值不变不写', parallax.includes('translate3d(') && parallax.includes('if (next === lastParallax) return'))
146
+ check('壁纸层常驻合成层', mainStyle.includes('will-change:transform'))
147
+
148
+ check('新增定时器/rAF 在卸载时清理', source.includes('if (fullSyncTimer !== null) { clearTimeout(fullSyncTimer); fullSyncTimer = null }') && source.includes('if (lightSyncFrame !== 0) { cancelAnimationFrame(lightSyncFrame); lightSyncFrame = 0 }'))
149
+
150
+
151
+ // —— 6. 设置页:壁纸文件夹按钮 + 中文名 + 控件美化 ——
152
+ const panel = slice('function Panel() {', 'function apply(ctx) {')
153
+ check('设置页不再有文件选择框', !panel.includes("type: 'file'"))
154
+ check('设置页不再显示存储路径', !panel.includes('wallpaperDir') && !panel.includes('存储位置'))
155
+ check('壁纸文件夹按钮调用宿主路由', panel.includes("fetch('/bg/reveal', { method: 'POST' })"))
156
+ check('按钮有禁用态与提示文案', panel.includes('正在打开…') && panel.includes('dsh-appearance-notice'))
157
+ check('壁纸名字解码后再显示', panel.includes('decodeURIComponent') && panel.includes('item?.name') && panel.includes('name }'))
158
+ check('选中但已不在文件夹里的壁纸仍可显示', panel.includes('已不在文件夹中'))
159
+ check('壁纸下拉框用解码名作 option 文本', /files\.map\(\(f\) => h\('option', \{ key: f\.url, value: f\.url \}, f\.name\)\)/.test(panel))
160
+ for (const cls of ['dsh-appearance-switch', 'dsh-appearance-select', 'dsh-appearance-range', 'dsh-appearance-color', 'dsh-appearance-btn']) {
161
+ check('美化的控件有样式:' + cls, mainStyle.includes('.' + cls) && panel.includes(cls))
162
+ }
163
+ check('按钮有 hover / focus-visible / disabled 态', mainStyle.includes('.dsh-appearance-btn:hover') && mainStyle.includes('.dsh-appearance-btn:focus-visible') && mainStyle.includes('.dsh-appearance-btn:disabled'))
164
+ check('下拉框自绘箭头(不依赖原生外观)', mainStyle.includes('.dsh-appearance-select::after') && mainStyle.includes('-webkit-appearance:none'))
165
+ check('开关用 input+label 结构保持可访问性', /h\('label', \{ className: 'dsh-appearance-switch' \}, h\('input', \{ type: 'checkbox'/.test(panel))
166
+
167
+
168
+ // —— 7. 随包默认壁纸 ——
169
+ const pkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "package.json"), "utf8"))
170
+ const hostSrc = fs.readFileSync(path.join(__dirname, "..", "lib", "host", "index.js"), "utf8")
171
+ check("包内清单带两张默认壁纸", pkg.files.filter((f) => f.includes("花与大肥鱼")).length === 2)
172
+ check("默认壁纸是 version2", hostSrc.includes("DEFAULT_WALLPAPER") && hostSrc.includes("version2.png"))
173
+ check("客户端默认值与宿主一致", source.includes("DEFAULT_WALLPAPER") && source.includes("bgImage: DEFAULT_WALLPAPER"))
174
+ check("宿主把包内目录作为只读壁纸源", hostSrc.includes("packageAssets") && hostSrc.includes("import.meta.url"))
175
+ check("用户目录优先于包内默认", /assetDirs = \[\.\.\.new Set\(\[dir,/.test(hostSrc))
176
+
177
+
178
+ // —— 8. 宿主与客户端的 defaults 必须逐键一致(默认外观由真机配置固化而来) ——
179
+ const defaultsOf = (text, marker) => {
180
+ const at = text.indexOf(marker)
181
+ if (at < 0) return null
182
+ const start = text.indexOf("{", at)
183
+ let depth = 0
184
+ let end = -1
185
+ for (let i = start; i < text.length; i++) {
186
+ if (text[i] === "{") depth++
187
+ else if (text[i] === "}") { depth--; if (depth === 0) { end = i; break } }
188
+ }
189
+ if (end < 0) return null
190
+ const body = text.slice(start + 1, end)
191
+ const out = {}
192
+ // 一个 default 对象里可能一行放多个键,所以按逗号切分(值都是简单字面量,不含逗号)。
193
+ for (const entry of body.split(",")) {
194
+ const m = /^\s*([A-Za-z]+)\s*:\s*(.+?)\s*$/.exec(entry)
195
+ if (!m) continue
196
+ out[m[1]] = m[2]
197
+ }
198
+ return out
199
+ }
200
+ const hostDefaults = defaultsOf(hostSrc, "const defaults = {")
201
+ const clientDefaults = defaultsOf(source, "const defaults = {")
202
+ check("能解析出两份 defaults", hostDefaults !== null && clientDefaults !== null)
203
+ if (hostDefaults && clientDefaults) {
204
+ const hostKeys = Object.keys(hostDefaults).sort()
205
+ const clientKeys = Object.keys(clientDefaults).sort()
206
+ check("键集合一致", JSON.stringify(hostKeys) === JSON.stringify(clientKeys), "host=" + hostKeys.length + " client=" + clientKeys.length)
207
+ const diffs = hostKeys.filter((k) => hostDefaults[k] !== clientDefaults[k])
208
+ check("每个键的默认值一致", diffs.length === 0, diffs.join(", "))
209
+ const expected = {
210
+ bgOpacity: "1", bgMask: "'#f8f7f7'", bgMaskOpacity: "0",
211
+ conversationOpacity: "0.2", conversationBlur: "2", conversationWidth: "870",
212
+ chatBoxOpacity: "0.59", chatBoxRadius: "24",
213
+ settingsOpacity: "0.4", sidebarOpacity: "0.4", previewPopupInset: "8",
214
+ }
215
+ const wrong = Object.entries(expected).filter(([k, v]) => hostDefaults[k] !== v)
216
+ check("固化的默认外观是当前调好的那套", wrong.length === 0, wrong.map(([k]) => k + "=" + hostDefaults[k]).join(", "))
217
+ check("默认壁纸在两份 defaults 里都是 version2", hostDefaults.bgImage.includes("DEFAULT_WALLPAPER") && clientDefaults.bgImage.includes("DEFAULT_WALLPAPER"))
218
+ }
219
+
220
+ if (failed > 0) {
221
+ console.log(`\n${failed} check(s) failed`)
222
+ process.exit(1)
223
+ }
224
+ console.log('\nall checks passed')