modelstage 0.6.1 → 0.10.1

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/config/models/live2d.assetbundls.json +1 -1
  3. package/config/models/live2d.azurlane_bundle.json +1 -1
  4. package/config/models/live2d.bd2_mod.json +1 -0
  5. package/config/models/live2d.bluearchive.json +1 -1
  6. package/config/models/live2d.sample_haru.json +1 -0
  7. package/config/models/spine.assetbundls.json +1 -1
  8. package/config/models/spine.azurlane_bundle.json +1 -1
  9. package/config/models/spine.bd2_mod.json +1 -0
  10. package/config/models/spine.bluearchive.json +1 -1
  11. package/config/models/spine.sample_haru.json +1 -0
  12. package/package.json +2 -2
  13. package/plugins/unity-live2d-bundle/index.js +43 -1
  14. package/plugins/unity-live2d-bundle/lib/bundle-probe.js +79 -0
  15. package/plugins/unity-live2d-bundle/plugin.json +2 -1
  16. package/plugins/unity-spine-bundle/index.js +38 -1
  17. package/plugins/unity-spine-bundle/lib/bundle-probe.js +323 -0
  18. package/plugins/unity-spine-bundle/plugin.json +3 -1
  19. package/src/server/analyze/index.mjs +470 -0
  20. package/src/server/data/catalog.mjs +30 -2
  21. package/src/server/data/display-name-cache.mjs +142 -0
  22. package/src/server/data/entry-states.mjs +21 -0
  23. package/src/server/http/write.mjs +7 -6
  24. package/src/server/index.mjs +1 -1
  25. package/src/server/plugins/registry.mjs +2 -2
  26. package/src/server/routes/display-name.mjs +157 -0
  27. package/src/server/serve.mjs +8 -0
  28. package/src/web/infra/plugin-host-unpack.mjs +13 -3
  29. package/src/web/infra/plugin-host.js +3 -0
  30. package/src/web/render/surface.js +49 -2
  31. package/src/web/roster/display-name.js +79 -0
  32. package/src/web/roster/events.js +40 -1
  33. package/src/web/roster/list.js +8 -2
  34. package/src/web/roster/store.js +48 -0
  35. package/tool/lib/bundle-probe-node.mjs +146 -32
@@ -279,10 +279,31 @@ export function createEntryStates(opts = {}) {
279
279
  }
280
280
  }
281
281
 
282
+ /**
283
+ * 列表显示名(工厂第四字段)。
284
+ *
285
+ * 只从调用方注入的 `ctx.displayNameFor` 取,本函数**不解析、不猜语义**:
286
+ * 名字是内容语义,归插件;这里是"把缓存里的值原样带出"。
287
+ * 拿不到 / 抛错 / 空串 / 全空白 一律 null ⇒ 前端回落既有规则(costume > 目录名 > 文件名),
288
+ * 即"插件未声明"与"缓存没命中"对上层是同一个表现,旧行为不变。
289
+ */
290
+ let displayName = null;
291
+ if (typeof ctx.displayNameFor === 'function') {
292
+ try {
293
+ const got = ctx.displayNameFor(state);
294
+ displayName = typeof got === 'string' && got.trim() ? got.trim() : null;
295
+ } catch {
296
+ displayName = null; // 显示名是展示态,不能因为取它失败而让整条状态算不出来
297
+ }
298
+ }
299
+
282
300
  return {
283
301
  display: { accent, provider, candidates },
284
302
  support,
285
303
  loadResult,
304
+ // 第四字段:列表显示名。由调用方经 ctx.displayNameFor 注入(缓存里查出来的),
305
+ // 本函数不认识任何格式知识,只把值原样带出;null 表示"没取到",前端据此回落旧规则。
306
+ displayName,
286
307
  // 结论已作废 / 从没结论 ⇒ 需要 §八 后台探测(调用方据此排队,不在同步路径解析包体)
287
308
  pendingProbe,
288
309
  };
@@ -244,14 +244,15 @@ function selfCheckImportedFiles(configDir, written, files) {
244
244
  * 为什么两件事分开 try:它们互相独立,一个失败不该连累另一个;
245
245
  * 失败信息汇总到 `error` 回给调用方(缓存没清只是"下次更慢",不该让导入失败)。
246
246
  *
247
+ * @param {string} configFile 资源配置文件路径(失效清单要它推清单目录)
247
248
  * @param {object} spine data/spine.mjs 实例
248
249
  * @param {object} names data/names.mjs 实例
249
250
  * @returns {{models:boolean, names:boolean, error:string|null}}
250
251
  */
251
- function invalidateImportCaches(models, names) {
252
+ function invalidateImportCaches(configFile, spine, names) {
252
253
  const out = { models: false, names: false, error: null };
253
254
  try {
254
- spine.invalidateCaches();
255
+ spine.invalidateCaches(configFile);
255
256
  out.models = true;
256
257
  } catch (e) {
257
258
  out.error = String((e && e.message) || e);
@@ -272,11 +273,11 @@ function invalidateImportCaches(models, names) {
272
273
  * @param {{paths: object, config: object, models: object, names: object}} deps
273
274
  * paths = core/paths.mjs 的路径表(configDir / configFile / root)
274
275
  * config = core/config.mjs(readConfigRaw / writeConfig / readConfig / buildGroups)
275
- * spine = data/spine.mjs(invalidateCaches:不传参 = 失效全部)
276
+ * spine = data/spine.mjs(invalidateCaches(configFile, rootId):不传 rootId = 失效全部)
276
277
  * names = data/names.mjs(clearNameCache:导入替换名表后必须清缓存)
277
278
  * @returns {{writeRoots: Function, writeConfigImport: Function}}
278
279
  */
279
- export function createWriteApi({ paths, config, models, names }) {
280
+ export function createWriteApi({ paths, config, spine, names }) {
280
281
  // 串行队列:两个写请求并发时会各自读旧配置再写回,后写的覆盖先写的(丢一次改动)。
281
282
  // 排队保证「读-改-写」这一串不交错;前一个失败不影响后一个继续排队。
282
283
  let queue = Promise.resolve();
@@ -543,7 +544,7 @@ export function createWriteApi({ paths, config, models, names }) {
543
544
  : plan.changed.id;
544
545
  const invalidated = { models: false, rootId: affectedId, error: null };
545
546
  try {
546
- spine.invalidateCaches(affectedId);
547
+ spine.invalidateCaches(paths.configFile, affectedId);
547
548
  invalidated.models = true;
548
549
  } catch (e) {
549
550
  // 清理失败不影响本次写入结果:配置已生效,下次请求会重新生成清单
@@ -625,7 +626,7 @@ export function createWriteApi({ paths, config, models, names }) {
625
626
  { backup, written: w.written });
626
627
  }
627
628
 
628
- const invalidated = invalidateImportCaches(models, names);
629
+ const invalidated = invalidateImportCaches(paths.configFile, spine, names);
629
630
  const { readback, selfCheckFailed } = selfCheckImportedFiles(paths.configDir, w.written, files);
630
631
  if (selfCheckFailed) {
631
632
  return fail(500, `导入后自检未通过(备份可回滚): ${selfCheckFailed}`,
@@ -68,7 +68,7 @@ export function createServerData({ root, dataRoot, avatarRoot, log, activity })
68
68
  if (typeof fn === 'function') { try { fn.call(log, msg, detail); } catch { /* 同上 */ } }
69
69
  };
70
70
  const entryStates = getSharedEntryStates({ root, log: logFn });
71
- const catalog = createCatalog({ config, spine, live2d, tree, plugins, entryStates });
71
+ const catalog = createCatalog({ config, spine, live2d, tree, plugins, entryStates, configFile: paths.configFile });
72
72
  // 后台形态探测(契约 §八):**事件驱动**,由 catalog 在"这一根清单重建完"时喊一声。
73
73
  // · 没有待探测项时内部立刻返回(指纹没变 ⇒ 零读包、零计数,S10)
74
74
  // · 单轮串行 + 包间限速 + 跑完即停,不留常驻定时器(INV-D7)
@@ -12,10 +12,10 @@ import { parseJsonc } from '../../../tool/parse-jsonc.mjs';
12
12
  import { validateDeclaredSlots, validateDeclaredSettings } from './slot-catalog.mjs';
13
13
 
14
14
  /**
15
- * 插件角色集合(契约 插件契约 §一):五类角色,**别处不得自创角色名**。
15
+ * 插件角色集合(契约 插件契约 §一):六类角色,**别处不得自创角色名**。
16
16
  * 一个插件可以同时担任多个角色(provides 是数组)。
17
17
  */
18
- export const PLUGIN_ROLES = ['asset-provider', 'renderer', 'editor', 'exporter', 'panel'];
18
+ export const PLUGIN_ROLES = ['asset-provider', 'bundle-analyzer', 'renderer', 'editor', 'exporter', 'panel'];
19
19
 
20
20
  // ---------------- 契约 §九(受限扩展点 effects / controls)的共用校验 ----------------
21
21
  // 这份实现同时被「运行期注册」(本文件 readPluginManifest)与「离线门禁」(tool/check-plugin.mjs)
@@ -0,0 +1,157 @@
1
+ // server/routes/display-name.mjs —— 取列表显示名(POST /api/entries/display-name)
2
+ //
3
+ // 为什么单独一条路由而不是塞进 /api/analyze:
4
+ // /api/analyze 的语义是"只读分析、不写任何东西";而这里**要写展示态缓存**。
5
+ // 混在一起会让"只读接口"变成有副作用的接口,调用方再也不能假设它只读。
6
+ //
7
+ // 名字从哪来:插件 analyze() 的 displayName(契约 §1.3)。核心不推导、不认识格式,
8
+ // 插件没给就返回 null,调用方回落文件名。
9
+ //
10
+ // 什么时候调:条目被选中/装载时,前端按需发一次(不批量、不后台预扫)。
11
+
12
+ import { analyzeFile } from '../analyze/index.mjs';
13
+ import { findAnalyzerProvider, libDirFor, libOrderFor } from '../../../tool/lib/bundle-probe-node.mjs';
14
+ import fs from 'node:fs';
15
+ import {
16
+ readDisplayNameCache,
17
+ writeDisplayNameCache,
18
+ setDisplayNameEntry,
19
+ lookupDisplayName,
20
+ hasDisplayNameRecord,
21
+ } from '../data/display-name-cache.mjs';
22
+
23
+ /**
24
+ * 分析器指纹:当前提供者 `lib/bundle-probe.js` 的 size+mtime。
25
+ *
26
+ * 为什么需要:缓存里会写"这个包取不到名字"(null)。插件后来支持了 displayName 后,
27
+ * 那条旧记录仍会命中 ⇒ 列表永远显示文件名,且没有任何迹象说明原因。
28
+ * 判据取**实现文件**而不是 plugin.json 的 version:版本号未必随 lib 变化更新,
29
+ * 而 size/mtime 一定跟着实现走。
30
+ * @returns {string|null} 没有提供者时 null(此时不参与失效判定)
31
+ */
32
+ function analyzerFingerprint() {
33
+ try {
34
+ const provider = findAnalyzerProvider();
35
+ if (!provider) return null;
36
+ const dir = libDirFor(provider);
37
+ const parts = [];
38
+ for (const rel of libOrderFor(provider)) {
39
+ if (!/bundle-probe/i.test(rel)) continue;
40
+ const st = fs.statSync(`${dir}/${rel}`);
41
+ parts.push(`${rel}:${st.size}:${Math.round(st.mtimeMs)}`);
42
+ }
43
+ return parts.length ? `${provider.pluginId}|${parts.join(',')}` : provider.pluginId;
44
+ } catch {
45
+ return null; // 算不出指纹就不参与失效判定(宁可用旧结论,也不因此报错)
46
+ }
47
+ }
48
+
49
+ /**
50
+ * POST /api/entries/display-name body: { rootId, rel }
51
+ *
52
+ * 返回 { ok, displayName, cached, reason? }
53
+ * · 命中缓存:cached=true,不跑分析
54
+ * · 分析拿到名字:写缓存后返回
55
+ * · 插件没给名字 / 分析失败:displayName=null(调用方回落文件名),不报错
56
+ *
57
+ * @param {object} req
58
+ * @param {object} res
59
+ * @param {string} p
60
+ * @param {object} ctx 含 data / resolveSafe / readBody / sendJson / log
61
+ * @returns {Promise<boolean>}
62
+ */
63
+ export async function handleDisplayName(req, res, p, ctx) {
64
+ const { sendJson, readBody } = ctx;
65
+ if (p !== '/api/entries/display-name') return false;
66
+ if (req.method !== 'POST') {
67
+ sendJson(res, 405, { ok: false, error: '只支持 POST' });
68
+ return true;
69
+ }
70
+
71
+ // readBody 是**回调式**的(返回 undefined),所以这里必须显式 return true 表示"已认领",
72
+ // 否则 dispatch 会继续往下走到 /api/ 兜底,表现成"未知接口"。
73
+ readBody(req, res, async (raw) => {
74
+ // readBody 只 catch 同步抛错;本回调是 async,reject 会逃逸成 unhandledRejection ⇒ 自己兜住
75
+ try {
76
+ let body = {};
77
+ try {
78
+ body = raw ? JSON.parse(raw) : {};
79
+ } catch {
80
+ sendJson(res, 400, { ok: false, error: '请求体不是合法 JSON' });
81
+ return;
82
+ }
83
+ const rootId = String(body.rootId || '');
84
+ const rel = String(body.rel || '');
85
+ if (!rootId || !rel) {
86
+ sendJson(res, 400, { ok: false, error: '需要 rootId 与 rel' });
87
+ return;
88
+ }
89
+
90
+ const configFile = ctx.data && ctx.data.paths ? ctx.data.paths.configFile : null;
91
+ const cfg = (ctx.data && ctx.data.config ? ctx.data.config.readConfig() : []).find((r) => r.id === rootId);
92
+ if (!cfg) {
93
+ sendJson(res, 404, { ok: false, error: `未找到资源根: ${rootId}` });
94
+ return;
95
+ }
96
+ const absPath = ctx.resolveSafe(cfg.path, rel);
97
+ if (!absPath) {
98
+ sendJson(res, 403, { ok: false, error: '路径越界' });
99
+ return;
100
+ }
101
+
102
+ // ① 先查缓存:**有记录就不跑分析**(含"记录为 null"的情况 —— 那表示上次确认过这个包取不到名字)
103
+ const table = readDisplayNameCache(configFile);
104
+ let size = null;
105
+ try {
106
+ size = Number(ctx.fs.statSync(absPath).size);
107
+ } catch {
108
+ sendJson(res, 404, { ok: false, error: `文件不存在:${rel}` });
109
+ return;
110
+ }
111
+ if (hasDisplayNameRecord(table, rootId, rel, { size }, analyzerFingerprint())) {
112
+ const cachedName = lookupDisplayName(table, rootId, rel, { size });
113
+ sendJson(res, 200, { ok: true, displayName: cachedName, cached: true });
114
+ return;
115
+ }
116
+
117
+ // ② 跑分析取名字(复用 /api/analyze 的实现,不新写解析)
118
+ const { status, body: analyzed } = await analyzeFile(absPath);
119
+ if (status !== 200 || !analyzed || !analyzed.ok) {
120
+ // 分析失败不是错误:名字拿不到就回落文件名,但把原因带回去便于排查
121
+ sendJson(res, 200, {
122
+ ok: true,
123
+ displayName: null,
124
+ cached: false,
125
+ reason: (analyzed && (analyzed.code || analyzed.error)) || `analyze-status-${status}`,
126
+ });
127
+ return;
128
+ }
129
+
130
+ const displayName = typeof analyzed.displayName === 'string' && analyzed.displayName.trim()
131
+ ? analyzed.displayName.trim()
132
+ : null;
133
+
134
+ // ③ 无论有没有拿到都写一条(写 null 也是有效结论:下次不再为它重跑一遍分析)
135
+ setDisplayNameEntry(table, rootId, rel, { displayName, mtimeMs: 0, size, analyzerFingerprint: analyzerFingerprint() });
136
+ try {
137
+ writeDisplayNameCache(configFile, table);
138
+ } catch (e) {
139
+ // 缓存写失败不影响本次返回(名字已经拿到了),但要留下可查的痕迹
140
+ if (ctx.log && ctx.log.warn) ctx.log.warn('显示名缓存写入失败', { rootId, rel, err: e.message });
141
+ }
142
+
143
+ sendJson(res, 200, {
144
+ ok: true,
145
+ displayName,
146
+ cached: false,
147
+ warnings: Array.isArray(analyzed.warnings) ? analyzed.warnings.slice(0, 3) : [],
148
+ });
149
+ } catch (e) {
150
+ // 这里已经是响应的最后一道:分析/缓存任何一步炸了都要给可读结果,而不是让连接悬着
151
+ try {
152
+ sendJson(res, 200, { ok: true, displayName: null, cached: false, reason: String((e && e.message) || e) });
153
+ } catch { /* 响应已发出,忽略 */ }
154
+ }
155
+ });
156
+ return true; // 已认领(响应由上面的回调发出)
157
+ }
@@ -39,6 +39,10 @@ import { handleReady } from './routes/ready.mjs';
39
39
  import { handleBackgrounds } from './routes/backgrounds.mjs';
40
40
  import { handleBackgroundSolids } from './routes/background-solids.mjs';
41
41
  import { handleEntries, createContextFor } from './routes/entries.mjs';
42
+ // 只读分析接口(/api/analyze):按 provides 找分析插件,一个都没有时降级为魔数判定
43
+ import { handleAnalyze } from './analyze/index.mjs';
44
+ // 取列表显示名(会写展示态缓存,因此与只读的 /api/analyze 分开)
45
+ import { handleDisplayName } from './routes/display-name.mjs';
42
46
 
43
47
  const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
44
48
  const WEB_ROOT = path.join(ROOT, 'src', 'web');
@@ -296,6 +300,10 @@ async function dispatch(req, res, p, url) {
296
300
  if (handleBackgrounds(req, res, p, ctx)) return true;
297
301
  // 条目状态(写读一体):必须在 handleData 之前认领,否则 /api/ 前缀兜底会当未知接口 404
298
302
  if (handleEntries(req, res, p, url, ctx)) return true;
303
+ // 取显示名(会写 config/bundle-display-names.json):async,必须 await,否则 Promise 恒真会吞掉后续路由
304
+ if (await handleDisplayName(req, res, p, ctx)) return true;
305
+ // 只读分析:不依赖资源根,路径直接来自参数;必须在这里认领,否则会被 /api/ 前缀兜底判成未知接口
306
+ if (await handleAnalyze(req, res, p, url, ctx)) return true;
299
307
  // handleData 已 async 化(内部要等扫描):必须 await,否则 Promise 恒真会让所有请求都被它认领
300
308
  if (await handleData(req, res, p, url, ctx)) return true;
301
309
  if (staticRoutes.serveAssets(req, res, p)) return true;
@@ -34,11 +34,21 @@ import { histogramFromObjects, isAssetDependencyHistogram, dependencyReason } fr
34
34
  */
35
35
  /** 未知二进制类型的兜底 MIME(扩展名对照表、Blob 回落、fetch 兜底三处共用一个) */
36
36
  const MIME_OCTET = 'application/octet-stream';
37
- export function createUnpack({ io, state, limits }) {
37
+ export function createUnpack({ io, state, limits, getHost }) {
38
38
  const { say, emit } = io;
39
39
  const { providers, getDiscovered } = state;
40
40
  const { base } = limits;
41
41
 
42
+ /**
43
+ * 取宿主注入面(延迟取值)。
44
+ *
45
+ * 为什么是函数而不是创建时捕获:plugin-host.js 里 `createUnpack(...)` 在前、
46
+ * `const hostApi = {...}` 在后 —— 创建时那个绑定还在 TDZ 里,捕获到就永远拿不到值
47
+ * (页面报 `hostApi is not defined` 正是这条)。改成每次用时才调用,顺序就无所谓了。
48
+ * @returns {object|undefined}
49
+ */
50
+ const hostOf = () => (typeof getHost === 'function' ? getHost() : undefined);
51
+
42
52
  /**
43
53
  * 把各种"字节样"入参归一成 Uint8Array(契约 §1.1 要求的类型)。
44
54
  *
@@ -425,7 +435,7 @@ async function resolveViaProvider(file, bytes) {
425
435
  }
426
436
  let res = null;
427
437
  try {
428
- res = await provider.resolve({ ...file, bytes, host: hostApi });
438
+ res = await provider.resolve({ ...file, bytes, host: hostOf() });
429
439
  } catch (e) {
430
440
  return { ok: false, reason: 'resolve-failed', message: `提供者 ${provider.id} 解析失败:${(e && e.message) || e}` };
431
441
  }
@@ -944,7 +954,7 @@ function providersFor(fileKinds) {
944
954
  */
945
955
  function findProvider(file) {
946
956
  if (!file || typeof file !== 'object') return null;
947
- const probe = { ...file, host: hostApi };
957
+ const probe = { ...file, host: hostOf() };
948
958
  if (file.bytes !== undefined && file.bytes !== null) {
949
959
  const normalized = toUint8Array(file.bytes);
950
960
  if (normalized) probe.bytes = normalized;
@@ -179,6 +179,9 @@ export function createPluginHost(opts = {}) {
179
179
  io: { say: ctx.say, emit: ctx.emit },
180
180
  state: { providers: ctx.providers, getDiscovered: () => ctx.discovered },
181
181
  limits: { base },
182
+ // hostApi 在本函数后面才定义(const),创建时捕获会落在 TDZ 里 ⇒ 必须延迟取值。
183
+ // 闭包引用在**调用时**才求值,所以顺序无所谓。
184
+ getHost: () => hostApi,
182
185
  });
183
186
  const { materialize, fetchFile, providersFor, findProvider, prefilterReason, pool: workerPool } = unpack;
184
187
 
@@ -111,12 +111,59 @@ export function createStageSurface({ root, log } = {}) {
111
111
  /** 取覆盖层内的 canvas(Live2D 渲染目标) */
112
112
  function overlayCanvas() {
113
113
  ensureOverlay();
114
- return document.getElementById(OVERLAY_CANVAS_ID);
114
+ const cv = document.getElementById(OVERLAY_CANVAS_ID);
115
+ watchContextLoss(cv, 'Live2D 面');
116
+ return cv;
115
117
  }
116
118
 
117
119
  /** 取 Spine 面 canvas(舞台里已有的那块,Surface 负责尺寸/DPR) */
118
120
  function spineCanvas() {
119
- return document.getElementById('stage-canvas');
121
+ const cv = document.getElementById('stage-canvas');
122
+ watchContextLoss(cv, 'Spine 面');
123
+ return cv;
124
+ }
125
+
126
+ // ---------------------------------------------------------------- WebGL 上下文丢失 / 恢复
127
+ //
128
+ // 标签页在后台停留较久、或 GPU 压力大时,浏览器会回收 WebGL 上下文。两件事必须做:
129
+ // ① lost 时 `preventDefault()` —— 不做的话浏览器**根本不会**尝试恢复(规范如此),
130
+ // 切回前台就是全白,且 `restoreContext()` 也无效(实测:lost 恒为 true)。
131
+ // ② restored 时重建渲染资源 —— 上下文回来了不代表画面对:纹理/着色器/缓冲随上下文一起丢弃,
132
+ // 实测恢复后读像素仍全为 0(没有任何重绘)。
133
+ //
134
+ // 重建方式是「重新激活当前文档」:走既有 activate 入口,由各渲染面自己重建,
135
+ // Surface 不碰 GL 资源(画布所有权与渲染器职责的既有边界不变)。
136
+ // 全程事件驱动,不依赖任何定时器。
137
+ const contextWatch = new WeakSet();
138
+
139
+ /**
140
+ * 给一块 canvas 挂上下文丢失/恢复监听(同一元素只挂一次)。
141
+ * @param {HTMLCanvasElement|null} canvas
142
+ * @param {string} label 日志里的面名
143
+ */
144
+ function watchContextLoss(canvas, label) {
145
+ if (!canvas || contextWatch.has(canvas)) return;
146
+ contextWatch.add(canvas);
147
+ canvas.addEventListener('webglcontextlost', (event) => {
148
+ // 必须阻止默认行为,否则浏览器不会恢复这个上下文
149
+ event.preventDefault();
150
+ note(`${label}:WebGL 上下文丢失(等浏览器恢复后重建)`, 'warn');
151
+ try { document.documentElement.dataset.contextLost = '1'; } catch { /* 可观测性字段 */ }
152
+ }, false);
153
+ canvas.addEventListener('webglcontextrestored', () => {
154
+ note(`${label}:WebGL 上下文已恢复,重建渲染资源`, 'info');
155
+ try { document.documentElement.dataset.contextLost = '0'; } catch { /* 可观测性字段 */ }
156
+ const current = st.document;
157
+ if (current) {
158
+ // 串行锁在 activate 内部;这里不再并发保护,避免与用户切模型打架
159
+ Promise.resolve()
160
+ .then(() => activate(current))
161
+ .catch((err) => note(`${label}:上下文恢复后重建失败:${(err && err.message) || err}`, 'error'));
162
+ } else {
163
+ // 没有文档(空舞台):只需重画一次背景
164
+ requestRender();
165
+ }
166
+ }, false);
120
167
  }
121
168
 
122
169
  // ---------------------------------------------------------------- 尺寸 / DPR
@@ -0,0 +1,79 @@
1
+ // web/roster/display-name.js —— 列表显示名的"取一次 + 就地更新"
2
+ //
3
+ // 口径(契约 §1.3 / 设计 列表显示名-displayName.md):
4
+ // · 只对**被选中的条目**取一次(不批量、不后台预扫)
5
+ // · 名字由服务端从插件 analyze() 拿到并写缓存;前端只负责"要"和"显示"
6
+ // · 拿到后**就地改文本**,不重建 chars —— 重建会丢展开态、滚动位置与当前选中项
7
+ //
8
+ // 前端不认识任何格式:它只把服务端给的字符串贴到 `.tree-variant-text` 与 `.tree-char-title` 上。
9
+
10
+ /**
11
+ * 取一个条目的显示名(命中缓存时服务端不跑分析)。
12
+ *
13
+ * @param {{base: string, rootId: string, rel: string}} req
14
+ * @returns {Promise<string|null>} 拿不到就是 null(调用方保持原样)
15
+ */
16
+ export async function fetchDisplayName({ base, rootId, rel }) {
17
+ if (!rootId || !rel) return null;
18
+ try {
19
+ const res = await fetch(`${base}/api/entries/display-name`, {
20
+ method: 'POST',
21
+ headers: { 'content-type': 'application/json' },
22
+ body: JSON.stringify({ rootId, rel }),
23
+ });
24
+ if (!res.ok) return null;
25
+ const data = await res.json();
26
+ if (!data || data.ok !== true) return null;
27
+ const name = typeof data.displayName === 'string' ? data.displayName.trim() : '';
28
+ return name || null;
29
+ } catch {
30
+ // 取名字失败不是错误:列表保持旧显示,不弹错、不阻塞
31
+ return null;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * 把名字就地贴到 DOM 上(不重建节点)。
37
+ *
38
+ * 目标:
39
+ * · 该模型自己的变体行 → `.tree-variant-text`
40
+ * · 它所属的角色行 → `.tree-char-title`
41
+ * 两者**必须同时更新**(只改一处会出现"变体名变了、角色标题还是 __data"的割裂)。
42
+ *
43
+ * @param {Document} doc
44
+ * @param {{modelId: string, charKey?: string|null, displayName: string|null}} opts
45
+ * @returns {boolean} 是否真的改了文本
46
+ */
47
+ export function paintDisplayName(doc, { modelId, charKey, displayName }) {
48
+ const name = typeof displayName === 'string' ? displayName.trim() : '';
49
+ if (!doc || !modelId || !name) return false;
50
+ let changed = false;
51
+
52
+ // 变体行:按 modelId 精确匹配(同一角色下可能有多个变体,只改被选中的那条)
53
+ const variantRow = doc.querySelector(`[data-model-id="${cssEscape(modelId)}"]`);
54
+ if (variantRow) {
55
+ const textEl = variantRow.querySelector('.tree-variant-text');
56
+ if (textEl && textEl.textContent !== name) {
57
+ textEl.textContent = name;
58
+ changed = true;
59
+ }
60
+ }
61
+
62
+ // 角色行:标题同步成同一个名字
63
+ if (charKey) {
64
+ const charRow = doc.querySelector(`[data-char-key="${cssEscape(charKey)}"]`);
65
+ if (charRow) {
66
+ const titleEl = charRow.querySelector('.tree-char-title');
67
+ if (titleEl && titleEl.textContent !== name) {
68
+ titleEl.textContent = name;
69
+ changed = true;
70
+ }
71
+ }
72
+ }
73
+ return changed;
74
+ }
75
+
76
+ /** 极简 CSS 属性值转义:只处理会破坏选择器的字符(够用即可,不引依赖) */
77
+ function cssEscape(value) {
78
+ return String(value).replace(/["\\]/g, '\\$&');
79
+ }
@@ -10,6 +10,7 @@
10
10
  // load 提供"点开要加载"的动作,render 提供"改完重画",本文件只做分派。
11
11
 
12
12
  import { saveState, saveLastModel } from './persist.js';
13
+ import { fetchDisplayName, paintDisplayName } from './display-name.js';
13
14
 
14
15
  /**
15
16
  * @param {object} deps 全部由 view 注入
@@ -62,15 +63,53 @@ export function createRosterEvents({
62
63
  render();
63
64
  store.setLastReveal(reveal.revealActive()); // 选中后把这一行滚到可视区(已可见/用户正在滚都会跳过)
64
65
  saveState(state);
66
+ // 选中时顺手取一次显示名(服务端命中缓存就不跑分析)。
67
+ // **不 await**:名字是展示态,晚到几百毫秒不影响装载;但绝不能因为等它而拖慢 onSelect。
65
68
  if (typeof onSelect === 'function') {
66
69
  const hit = modelById.get(modelId);
70
+ void hydrateDisplayName(hit ? hit.model : null, charKey);
67
71
  // 把装载的 promise 交回调用方:冷启动要能等"首个模型真的出来"再放行后面的加载队列,
68
- // 否则队列的整根扫描会和首个模型的资源请求抢同一份磁盘 IO。
72
+ // 否则队列的整根扫描和首个模型的资源请求会抢同一份磁盘 IO。
69
73
  return onSelect(hit ? hit.model : null);
70
74
  }
71
75
  }
72
76
 
73
77
  /** 事件委托:树行是动态生成的,统一在容器上监听一次 */
78
+ /**
79
+ * 取一次显示名并就地贴到列表上(不重建 chars)。
80
+ *
81
+ * 为什么只对选中项取:181 个包全量取名要 2~5 分钟,且大包会 OOM;用户实际只看少数几个。
82
+ * 为什么失败不提示:名字是展示增强,取不到就保持文件名;弹错会把"列表能用"变成"每次点都弹错"。
83
+ * 为什么改 DOM 而不是重画:重画会丢展开态、滚动位置和当前选中项。
84
+ *
85
+ * @param {object|null} model 选中的条目(catalog 里的那条)
86
+ * @param {string} [charKey] 所属角色键(用于同时更新角色行标题)
87
+ */
88
+ async function hydrateDisplayName(model, charKey) {
89
+ if (!model || !model.rootId || !model.rel) return;
90
+ // 已有名字(缓存命中过、或插件当场给了)就不重复请求
91
+ if (typeof model.displayName === 'string' && model.displayName.trim()) return;
92
+ const name = await fetchDisplayName({ base: '', rootId: model.rootId, rel: model.rel });
93
+ if (!name) return;
94
+ model.displayName = name; // 记在内存里:同一会话再点它不必再请求
95
+ // 名字是**分组键的输入**(buildChars 优先用 displayName 分组),所以不能只改文本:
96
+ // 只改文本的话分组结构、角色标题、别名都还是旧值 —— 表现为"刷新浏览器才正确"。
97
+ // 重建会重算分组/标题/别名;展开态与选中项在 store 内按 model id 迁移。
98
+ const group = state.groups.find((g) => g.roots.some((r) => r.id === model.rootId));
99
+ let rebuilt = null;
100
+ try {
101
+ if (group && typeof store.rebuildCharsPreservingExpansion === 'function') {
102
+ rebuilt = store.rebuildCharsPreservingExpansion(group.key);
103
+ }
104
+ } catch { rebuilt = null; }
105
+ if (rebuilt) {
106
+ render(); // 整组重画(展开态已迁移,滚动位置由 reveal 逻辑保持)
107
+ return;
108
+ }
109
+ // 兜底:拿不到分组(或 store 不支持重建)时仍只改文本,保证名字能显示
110
+ paintDisplayName(document, { modelId: model.id, charKey, displayName: name });
111
+ }
112
+
74
113
  function bindEvents() {
75
114
  /** 按行的类型分派到对应动作(鼠标与键盘共用,避免两套逻辑走偏) */
76
115
  function activate(row) {
@@ -217,7 +217,10 @@ export function variantLabel(m) {
217
217
  export function variantText(m, nm) {
218
218
  const dirName = String(m.srcDir || '').split('/').slice(-1)[0] || '';
219
219
  const origName = String(m.name || '');
220
- const text = nm && nm.costume ? nm.costume : (dirName || origName);
220
+ // 回落顺序:工厂给的 displayName → 名表 costume → 目录名 → 文件名。
221
+ // displayName 是 null 时整条链与改造前**逐字节相同**(插件未声明就是这条路径)。
222
+ const given = typeof m.displayName === 'string' ? m.displayName.trim() : '';
223
+ const text = given || (nm && nm.costume ? nm.costume : (dirName || origName));
221
224
  return { text, origName };
222
225
  }
223
226
 
@@ -242,7 +245,10 @@ export function buildChars(models, nameIndex, groupName = '') {
242
245
  } else {
243
246
  stats.miss += 1;
244
247
  }
245
- const groupName = nm ? nm.name : charKeyOf(m.name);
248
+ // 分组键与标题都用显示名:工厂给了 displayName 就用它(同角色的多个包能并到一组),
249
+ // 没给就完全走旧规则(名表 → 从文件名派生的 charKey)—— 未声明时行为不变。
250
+ const given = typeof m.displayName === 'string' ? m.displayName.trim() : '';
251
+ const groupName = given || (nm ? nm.name : charKeyOf(m.name));
246
252
  const key = groupName ? `char:${groupName}|${groupName}` : `char:${groupName}`;
247
253
  if (!charMap.has(key)) {
248
254
  charMap.set(key, {
@@ -187,6 +187,54 @@ export function createRosterStore({ buildChars, nameIndex, onChange } = {}) {
187
187
  return rebuildCharsFor(groupKey);
188
188
  },
189
189
 
190
+ /**
191
+ * 重建分组并**迁移展开态与选中项**。
192
+ *
193
+ * 为什么需要:分组键由显示名派生(`buildChars` 里的 `groupName` 优先用 displayName)。
194
+ * 显示名是**选中后**才取到的,届时分组结构会变 —— 旧 charKey 全部失效。
195
+ * 只改 DOM 文本不重建 ⇒ 分组、角色标题、别名(baseName)都还是旧值,
196
+ * 表现为"刷新浏览器才正确";只重建不迁移 ⇒ 用户展开的角色全被收起。
197
+ * 展开态与选中项都按 **model id** 迁移(charKey 会变,model id 不变)。
198
+ * @param {string} groupKey
199
+ * @returns {object|null} 重建后的 { chars, stats }
200
+ */
201
+ rebuildCharsPreservingExpansion(groupKey) {
202
+ const key = String(groupKey);
203
+ const group = state.groups.find((g) => g.key === key);
204
+ if (!group) return null;
205
+ const before = state.groupChars.get(key);
206
+ const expandedModelIds = new Set();
207
+ for (const c of (before && before.chars) || []) {
208
+ if (!state.expandedChars.has(c.key)) continue; // 角色展开态在 expandedChars(组展开态是 expandedGroups)
209
+ for (const v of c.variants || []) if (v.model && v.model.id) expandedModelIds.add(v.model.id);
210
+ }
211
+ // 旧 charKey 已不属于任何现存角色,先摘掉,避免展开集合里留垃圾
212
+ for (const c of (before && before.chars) || []) state.expandedChars.delete(c.key);
213
+ const built = rebuildCharsFor(key);
214
+ if (!built) return null;
215
+ if (expandedModelIds.size) {
216
+ for (const c of built.chars || []) {
217
+ if ((c.variants || []).some((v) => v.model && expandedModelIds.has(v.model.id))) {
218
+ state.expandedChars.add(c.key);
219
+ }
220
+ }
221
+ }
222
+ const selectedId = state.selected && state.selected.modelId;
223
+ if (selectedId) {
224
+ for (const c of built.chars || []) {
225
+ if ((c.variants || []).some((v) => v.model && v.model.id === selectedId)) {
226
+ state.selected = { ...state.selected, charKey: c.key };
227
+ // 选中项的所属角色必须保持展开:分组键变了,若不补这一下,
228
+ // 用户刚点的行会在重建后"消失"(新 char 默认收起),看起来像点击没生效。
229
+ state.expandedChars.add(c.key);
230
+ break;
231
+ }
232
+ }
233
+ }
234
+ notify();
235
+ return built;
236
+ },
237
+
190
238
  // ---------------------------------------------------------------- 展开态
191
239
  toggleGroup(groupKey) {
192
240
  const key = String(groupKey);