dsh-desktop-statusbar 3.0.4 → 3.0.6

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 (597) hide show
  1. package/README.de.md +267 -0
  2. package/README.en.md +136 -14
  3. package/README.es.md +267 -0
  4. package/README.fr.md +267 -0
  5. package/README.ja.md +267 -0
  6. package/README.md +136 -14
  7. package/README.pt.md +267 -0
  8. package/README.ru.md +267 -0
  9. package/docs/pricing.de.png +0 -0
  10. package/docs/pricing.es.png +0 -0
  11. package/docs/pricing.fr.png +0 -0
  12. package/docs/pricing.ja.png +0 -0
  13. package/docs/pricing.pt.png +0 -0
  14. package/docs/pricing.ru.png +0 -0
  15. package/docs/settings.de.png +0 -0
  16. package/docs/settings.es.png +0 -0
  17. package/docs/settings.fr.png +0 -0
  18. package/docs/settings.ja.png +0 -0
  19. package/docs/settings.pt.png +0 -0
  20. package/docs/settings.ru.png +0 -0
  21. package/lib/balance-api.js +1042 -782
  22. package/lib/client.js +12775 -12364
  23. package/lib/index.js +8340 -7784
  24. package/lib/vendor/zod/LICENSE +21 -0
  25. package/lib/vendor/zod/index.cjs +52 -0
  26. package/lib/vendor/zod/index.js +7 -0
  27. package/lib/vendor/zod/locales/index.cjs +36 -0
  28. package/lib/vendor/zod/locales/index.d.cts +1 -0
  29. package/lib/vendor/zod/locales/index.d.ts +1 -0
  30. package/lib/vendor/zod/locales/index.js +1 -0
  31. package/lib/vendor/zod/locales/package.json +7 -0
  32. package/lib/vendor/zod/mini/index.cjs +51 -0
  33. package/lib/vendor/zod/mini/index.d.cts +3 -0
  34. package/lib/vendor/zod/mini/index.d.ts +3 -0
  35. package/lib/vendor/zod/mini/index.js +3 -0
  36. package/lib/vendor/zod/mini/package.json +7 -0
  37. package/lib/vendor/zod/package.json +147 -0
  38. package/lib/vendor/zod/v3/ZodError.cjs +167 -0
  39. package/lib/vendor/zod/v3/ZodError.d.cts +164 -0
  40. package/lib/vendor/zod/v3/ZodError.d.ts +164 -0
  41. package/lib/vendor/zod/v3/ZodError.js +143 -0
  42. package/lib/vendor/zod/v3/errors.cjs +36 -0
  43. package/lib/vendor/zod/v3/errors.d.cts +5 -0
  44. package/lib/vendor/zod/v3/errors.d.ts +5 -0
  45. package/lib/vendor/zod/v3/errors.js +9 -0
  46. package/lib/vendor/zod/v3/external.cjs +41 -0
  47. package/lib/vendor/zod/v3/external.d.cts +6 -0
  48. package/lib/vendor/zod/v3/external.d.ts +6 -0
  49. package/lib/vendor/zod/v3/external.js +6 -0
  50. package/lib/vendor/zod/v3/helpers/enumUtil.cjs +21 -0
  51. package/lib/vendor/zod/v3/helpers/enumUtil.d.cts +8 -0
  52. package/lib/vendor/zod/v3/helpers/enumUtil.d.ts +8 -0
  53. package/lib/vendor/zod/v3/helpers/enumUtil.js +1 -0
  54. package/lib/vendor/zod/v3/helpers/errorUtil.cjs +28 -0
  55. package/lib/vendor/zod/v3/helpers/errorUtil.d.cts +9 -0
  56. package/lib/vendor/zod/v3/helpers/errorUtil.d.ts +9 -0
  57. package/lib/vendor/zod/v3/helpers/errorUtil.js +6 -0
  58. package/lib/vendor/zod/v3/helpers/parseUtil.cjs +143 -0
  59. package/lib/vendor/zod/v3/helpers/parseUtil.d.cts +78 -0
  60. package/lib/vendor/zod/v3/helpers/parseUtil.d.ts +78 -0
  61. package/lib/vendor/zod/v3/helpers/parseUtil.js +109 -0
  62. package/lib/vendor/zod/v3/helpers/partialUtil.cjs +21 -0
  63. package/lib/vendor/zod/v3/helpers/partialUtil.d.cts +8 -0
  64. package/lib/vendor/zod/v3/helpers/partialUtil.d.ts +8 -0
  65. package/lib/vendor/zod/v3/helpers/partialUtil.js +1 -0
  66. package/lib/vendor/zod/v3/helpers/typeAliases.cjs +21 -0
  67. package/lib/vendor/zod/v3/helpers/typeAliases.d.cts +2 -0
  68. package/lib/vendor/zod/v3/helpers/typeAliases.d.ts +2 -0
  69. package/lib/vendor/zod/v3/helpers/typeAliases.js +1 -0
  70. package/lib/vendor/zod/v3/helpers/util.cjs +156 -0
  71. package/lib/vendor/zod/v3/helpers/util.d.cts +85 -0
  72. package/lib/vendor/zod/v3/helpers/util.d.ts +85 -0
  73. package/lib/vendor/zod/v3/helpers/util.js +133 -0
  74. package/lib/vendor/zod/v3/index.cjs +52 -0
  75. package/lib/vendor/zod/v3/index.d.cts +4 -0
  76. package/lib/vendor/zod/v3/index.d.ts +4 -0
  77. package/lib/vendor/zod/v3/index.js +4 -0
  78. package/lib/vendor/zod/v3/locales/en.cjs +112 -0
  79. package/lib/vendor/zod/v3/locales/en.d.cts +3 -0
  80. package/lib/vendor/zod/v3/locales/en.d.ts +3 -0
  81. package/lib/vendor/zod/v3/locales/en.js +109 -0
  82. package/lib/vendor/zod/v3/package.json +7 -0
  83. package/lib/vendor/zod/v3/standard-schema.cjs +21 -0
  84. package/lib/vendor/zod/v3/standard-schema.d.cts +102 -0
  85. package/lib/vendor/zod/v3/standard-schema.d.ts +102 -0
  86. package/lib/vendor/zod/v3/standard-schema.js +1 -0
  87. package/lib/vendor/zod/v3/types.cjs +3798 -0
  88. package/lib/vendor/zod/v3/types.d.cts +1034 -0
  89. package/lib/vendor/zod/v3/types.d.ts +1034 -0
  90. package/lib/vendor/zod/v3/types.js +3697 -0
  91. package/lib/vendor/zod/v4/classic/checks.cjs +53 -0
  92. package/lib/vendor/zod/v4/classic/checks.d.cts +1 -0
  93. package/lib/vendor/zod/v4/classic/checks.d.ts +1 -0
  94. package/lib/vendor/zod/v4/classic/checks.js +1 -0
  95. package/lib/vendor/zod/v4/classic/coerce.cjs +66 -0
  96. package/lib/vendor/zod/v4/classic/coerce.d.cts +17 -0
  97. package/lib/vendor/zod/v4/classic/coerce.d.ts +17 -0
  98. package/lib/vendor/zod/v4/classic/coerce.js +17 -0
  99. package/lib/vendor/zod/v4/classic/compat.cjs +80 -0
  100. package/lib/vendor/zod/v4/classic/compat.d.cts +48 -0
  101. package/lib/vendor/zod/v4/classic/compat.d.ts +48 -0
  102. package/lib/vendor/zod/v4/classic/compat.js +31 -0
  103. package/lib/vendor/zod/v4/classic/deep-partial.cjs +58 -0
  104. package/lib/vendor/zod/v4/classic/deep-partial.d.cts +14 -0
  105. package/lib/vendor/zod/v4/classic/deep-partial.d.ts +14 -0
  106. package/lib/vendor/zod/v4/classic/deep-partial.js +13 -0
  107. package/lib/vendor/zod/v4/classic/errors.cjs +102 -0
  108. package/lib/vendor/zod/v4/classic/errors.d.cts +29 -0
  109. package/lib/vendor/zod/v4/classic/errors.d.ts +29 -0
  110. package/lib/vendor/zod/v4/classic/errors.js +57 -0
  111. package/lib/vendor/zod/v4/classic/external.cjs +97 -0
  112. package/lib/vendor/zod/v4/classic/external.d.cts +19 -0
  113. package/lib/vendor/zod/v4/classic/external.d.ts +19 -0
  114. package/lib/vendor/zod/v4/classic/external.js +17 -0
  115. package/lib/vendor/zod/v4/classic/from-json-schema.cjs +926 -0
  116. package/lib/vendor/zod/v4/classic/from-json-schema.d.cts +12 -0
  117. package/lib/vendor/zod/v4/classic/from-json-schema.d.ts +12 -0
  118. package/lib/vendor/zod/v4/classic/from-json-schema.js +881 -0
  119. package/lib/vendor/zod/v4/classic/in-out.cjs +82 -0
  120. package/lib/vendor/zod/v4/classic/in-out.d.cts +8 -0
  121. package/lib/vendor/zod/v4/classic/in-out.d.ts +8 -0
  122. package/lib/vendor/zod/v4/classic/in-out.js +36 -0
  123. package/lib/vendor/zod/v4/classic/index.cjs +52 -0
  124. package/lib/vendor/zod/v4/classic/index.d.cts +3 -0
  125. package/lib/vendor/zod/v4/classic/index.d.ts +3 -0
  126. package/lib/vendor/zod/v4/classic/index.js +4 -0
  127. package/lib/vendor/zod/v4/classic/iso.cjs +68 -0
  128. package/lib/vendor/zod/v4/classic/iso.d.cts +7 -0
  129. package/lib/vendor/zod/v4/classic/iso.d.ts +7 -0
  130. package/lib/vendor/zod/v4/classic/iso.js +15 -0
  131. package/lib/vendor/zod/v4/classic/package.json +7 -0
  132. package/lib/vendor/zod/v4/classic/parse.cjs +63 -0
  133. package/lib/vendor/zod/v4/classic/parse.d.cts +44 -0
  134. package/lib/vendor/zod/v4/classic/parse.d.ts +44 -0
  135. package/lib/vendor/zod/v4/classic/parse.js +16 -0
  136. package/lib/vendor/zod/v4/classic/schemas.cjs +1676 -0
  137. package/lib/vendor/zod/v4/classic/schemas.d.cts +816 -0
  138. package/lib/vendor/zod/v4/classic/schemas.d.ts +816 -0
  139. package/lib/vendor/zod/v4/classic/schemas.js +1535 -0
  140. package/lib/vendor/zod/v4/core/api.cjs +1269 -0
  141. package/lib/vendor/zod/v4/core/api.d.cts +335 -0
  142. package/lib/vendor/zod/v4/core/api.d.ts +335 -0
  143. package/lib/vendor/zod/v4/core/api.js +1107 -0
  144. package/lib/vendor/zod/v4/core/checks.cjs +561 -0
  145. package/lib/vendor/zod/v4/core/checks.d.cts +294 -0
  146. package/lib/vendor/zod/v4/core/checks.d.ts +294 -0
  147. package/lib/vendor/zod/v4/core/checks.js +516 -0
  148. package/lib/vendor/zod/v4/core/compile.cjs +1908 -0
  149. package/lib/vendor/zod/v4/core/compile.d.cts +65 -0
  150. package/lib/vendor/zod/v4/core/compile.d.ts +65 -0
  151. package/lib/vendor/zod/v4/core/compile.js +1858 -0
  152. package/lib/vendor/zod/v4/core/core.cjs +167 -0
  153. package/lib/vendor/zod/v4/core/core.d.cts +82 -0
  154. package/lib/vendor/zod/v4/core/core.d.ts +82 -0
  155. package/lib/vendor/zod/v4/core/core.js +141 -0
  156. package/lib/vendor/zod/v4/core/doc.cjs +61 -0
  157. package/lib/vendor/zod/v4/core/doc.d.cts +16 -0
  158. package/lib/vendor/zod/v4/core/doc.d.ts +16 -0
  159. package/lib/vendor/zod/v4/core/doc.js +38 -0
  160. package/lib/vendor/zod/v4/core/errors.cjs +317 -0
  161. package/lib/vendor/zod/v4/core/errors.d.cts +225 -0
  162. package/lib/vendor/zod/v4/core/errors.d.ts +225 -0
  163. package/lib/vendor/zod/v4/core/errors.js +267 -0
  164. package/lib/vendor/zod/v4/core/index.cjs +70 -0
  165. package/lib/vendor/zod/v4/core/index.d.cts +19 -0
  166. package/lib/vendor/zod/v4/core/index.d.ts +19 -0
  167. package/lib/vendor/zod/v4/core/index.js +19 -0
  168. package/lib/vendor/zod/v4/core/json-schema-generator.cjs +122 -0
  169. package/lib/vendor/zod/v4/core/json-schema-generator.d.cts +65 -0
  170. package/lib/vendor/zod/v4/core/json-schema-generator.d.ts +65 -0
  171. package/lib/vendor/zod/v4/core/json-schema-generator.js +99 -0
  172. package/lib/vendor/zod/v4/core/json-schema-processors.cjs +929 -0
  173. package/lib/vendor/zod/v4/core/json-schema-processors.d.cts +65 -0
  174. package/lib/vendor/zod/v4/core/json-schema-processors.d.ts +65 -0
  175. package/lib/vendor/zod/v4/core/json-schema-processors.js +843 -0
  176. package/lib/vendor/zod/v4/core/json-schema.cjs +21 -0
  177. package/lib/vendor/zod/v4/core/json-schema.d.cts +89 -0
  178. package/lib/vendor/zod/v4/core/json-schema.d.ts +89 -0
  179. package/lib/vendor/zod/v4/core/json-schema.js +1 -0
  180. package/lib/vendor/zod/v4/core/memoizer.cjs +360 -0
  181. package/lib/vendor/zod/v4/core/memoizer.d.cts +15 -0
  182. package/lib/vendor/zod/v4/core/memoizer.d.ts +15 -0
  183. package/lib/vendor/zod/v4/core/memoizer.js +311 -0
  184. package/lib/vendor/zod/v4/core/package.json +7 -0
  185. package/lib/vendor/zod/v4/core/parse.cjs +233 -0
  186. package/lib/vendor/zod/v4/core/parse.d.cts +52 -0
  187. package/lib/vendor/zod/v4/core/parse.d.ts +52 -0
  188. package/lib/vendor/zod/v4/core/parse.js +175 -0
  189. package/lib/vendor/zod/v4/core/regexes.cjs +209 -0
  190. package/lib/vendor/zod/v4/core/regexes.d.cts +90 -0
  191. package/lib/vendor/zod/v4/core/regexes.d.ts +90 -0
  192. package/lib/vendor/zod/v4/core/regexes.js +156 -0
  193. package/lib/vendor/zod/v4/core/registries.cjs +75 -0
  194. package/lib/vendor/zod/v4/core/registries.d.cts +35 -0
  195. package/lib/vendor/zod/v4/core/registries.d.ts +35 -0
  196. package/lib/vendor/zod/v4/core/registries.js +51 -0
  197. package/lib/vendor/zod/v4/core/schemas.cjs +2669 -0
  198. package/lib/vendor/zod/v4/core/schemas.d.cts +1273 -0
  199. package/lib/vendor/zod/v4/core/schemas.d.ts +1273 -0
  200. package/lib/vendor/zod/v4/core/schemas.js +2606 -0
  201. package/lib/vendor/zod/v4/core/standard-schema.cjs +21 -0
  202. package/lib/vendor/zod/v4/core/standard-schema.d.cts +126 -0
  203. package/lib/vendor/zod/v4/core/standard-schema.d.ts +126 -0
  204. package/lib/vendor/zod/v4/core/standard-schema.js +1 -0
  205. package/lib/vendor/zod/v4/core/to-json-schema.cjs +681 -0
  206. package/lib/vendor/zod/v4/core/to-json-schema.d.cts +154 -0
  207. package/lib/vendor/zod/v4/core/to-json-schema.d.ts +154 -0
  208. package/lib/vendor/zod/v4/core/to-json-schema.js +651 -0
  209. package/lib/vendor/zod/v4/core/util.cjs +949 -0
  210. package/lib/vendor/zod/v4/core/util.d.cts +278 -0
  211. package/lib/vendor/zod/v4/core/util.d.ts +278 -0
  212. package/lib/vendor/zod/v4/core/util.js +859 -0
  213. package/lib/vendor/zod/v4/core/versions.cjs +27 -0
  214. package/lib/vendor/zod/v4/core/versions.d.cts +5 -0
  215. package/lib/vendor/zod/v4/core/versions.d.ts +5 -0
  216. package/lib/vendor/zod/v4/core/versions.js +5 -0
  217. package/lib/vendor/zod/v4/core/visit.cjs +214 -0
  218. package/lib/vendor/zod/v4/core/visit.d.cts +30 -0
  219. package/lib/vendor/zod/v4/core/visit.d.ts +30 -0
  220. package/lib/vendor/zod/v4/core/visit.js +169 -0
  221. package/lib/vendor/zod/v4/index.cjs +51 -0
  222. package/lib/vendor/zod/v4/index.d.cts +3 -0
  223. package/lib/vendor/zod/v4/index.d.ts +3 -0
  224. package/lib/vendor/zod/v4/index.js +4 -0
  225. package/lib/vendor/zod/v4/locales/ar.cjs +138 -0
  226. package/lib/vendor/zod/v4/locales/ar.d.cts +5 -0
  227. package/lib/vendor/zod/v4/locales/ar.d.ts +4 -0
  228. package/lib/vendor/zod/v4/locales/ar.js +111 -0
  229. package/lib/vendor/zod/v4/locales/az.cjs +137 -0
  230. package/lib/vendor/zod/v4/locales/az.d.cts +5 -0
  231. package/lib/vendor/zod/v4/locales/az.d.ts +4 -0
  232. package/lib/vendor/zod/v4/locales/az.js +110 -0
  233. package/lib/vendor/zod/v4/locales/be.cjs +195 -0
  234. package/lib/vendor/zod/v4/locales/be.d.cts +5 -0
  235. package/lib/vendor/zod/v4/locales/be.d.ts +4 -0
  236. package/lib/vendor/zod/v4/locales/be.js +168 -0
  237. package/lib/vendor/zod/v4/locales/bg.cjs +152 -0
  238. package/lib/vendor/zod/v4/locales/bg.d.cts +5 -0
  239. package/lib/vendor/zod/v4/locales/bg.d.ts +4 -0
  240. package/lib/vendor/zod/v4/locales/bg.js +125 -0
  241. package/lib/vendor/zod/v4/locales/bn.cjs +140 -0
  242. package/lib/vendor/zod/v4/locales/bn.d.cts +5 -0
  243. package/lib/vendor/zod/v4/locales/bn.d.ts +4 -0
  244. package/lib/vendor/zod/v4/locales/bn.js +113 -0
  245. package/lib/vendor/zod/v4/locales/ca.cjs +139 -0
  246. package/lib/vendor/zod/v4/locales/ca.d.cts +5 -0
  247. package/lib/vendor/zod/v4/locales/ca.d.ts +4 -0
  248. package/lib/vendor/zod/v4/locales/ca.js +112 -0
  249. package/lib/vendor/zod/v4/locales/ckb.cjs +160 -0
  250. package/lib/vendor/zod/v4/locales/ckb.d.cts +5 -0
  251. package/lib/vendor/zod/v4/locales/ckb.d.ts +4 -0
  252. package/lib/vendor/zod/v4/locales/ckb.js +133 -0
  253. package/lib/vendor/zod/v4/locales/cs.cjs +143 -0
  254. package/lib/vendor/zod/v4/locales/cs.d.cts +5 -0
  255. package/lib/vendor/zod/v4/locales/cs.d.ts +4 -0
  256. package/lib/vendor/zod/v4/locales/cs.js +116 -0
  257. package/lib/vendor/zod/v4/locales/da.cjs +147 -0
  258. package/lib/vendor/zod/v4/locales/da.d.cts +5 -0
  259. package/lib/vendor/zod/v4/locales/da.d.ts +4 -0
  260. package/lib/vendor/zod/v4/locales/da.js +120 -0
  261. package/lib/vendor/zod/v4/locales/de.cjs +140 -0
  262. package/lib/vendor/zod/v4/locales/de.d.cts +5 -0
  263. package/lib/vendor/zod/v4/locales/de.d.ts +4 -0
  264. package/lib/vendor/zod/v4/locales/de.js +113 -0
  265. package/lib/vendor/zod/v4/locales/el.cjs +139 -0
  266. package/lib/vendor/zod/v4/locales/el.d.cts +5 -0
  267. package/lib/vendor/zod/v4/locales/el.d.ts +4 -0
  268. package/lib/vendor/zod/v4/locales/el.js +112 -0
  269. package/lib/vendor/zod/v4/locales/en.cjs +152 -0
  270. package/lib/vendor/zod/v4/locales/en.d.cts +5 -0
  271. package/lib/vendor/zod/v4/locales/en.d.ts +4 -0
  272. package/lib/vendor/zod/v4/locales/en.js +125 -0
  273. package/lib/vendor/zod/v4/locales/eo.cjs +141 -0
  274. package/lib/vendor/zod/v4/locales/eo.d.cts +5 -0
  275. package/lib/vendor/zod/v4/locales/eo.d.ts +4 -0
  276. package/lib/vendor/zod/v4/locales/eo.js +114 -0
  277. package/lib/vendor/zod/v4/locales/es.cjs +163 -0
  278. package/lib/vendor/zod/v4/locales/es.d.cts +5 -0
  279. package/lib/vendor/zod/v4/locales/es.d.ts +4 -0
  280. package/lib/vendor/zod/v4/locales/es.js +136 -0
  281. package/lib/vendor/zod/v4/locales/fa.cjs +146 -0
  282. package/lib/vendor/zod/v4/locales/fa.d.cts +5 -0
  283. package/lib/vendor/zod/v4/locales/fa.d.ts +4 -0
  284. package/lib/vendor/zod/v4/locales/fa.js +119 -0
  285. package/lib/vendor/zod/v4/locales/fi.cjs +144 -0
  286. package/lib/vendor/zod/v4/locales/fi.d.cts +5 -0
  287. package/lib/vendor/zod/v4/locales/fi.d.ts +4 -0
  288. package/lib/vendor/zod/v4/locales/fi.js +117 -0
  289. package/lib/vendor/zod/v4/locales/fr-CA.cjs +139 -0
  290. package/lib/vendor/zod/v4/locales/fr-CA.d.cts +5 -0
  291. package/lib/vendor/zod/v4/locales/fr-CA.d.ts +4 -0
  292. package/lib/vendor/zod/v4/locales/fr-CA.js +112 -0
  293. package/lib/vendor/zod/v4/locales/fr.cjs +156 -0
  294. package/lib/vendor/zod/v4/locales/fr.d.cts +5 -0
  295. package/lib/vendor/zod/v4/locales/fr.d.ts +4 -0
  296. package/lib/vendor/zod/v4/locales/fr.js +129 -0
  297. package/lib/vendor/zod/v4/locales/gu.cjs +140 -0
  298. package/lib/vendor/zod/v4/locales/gu.d.cts +5 -0
  299. package/lib/vendor/zod/v4/locales/gu.d.ts +4 -0
  300. package/lib/vendor/zod/v4/locales/gu.js +113 -0
  301. package/lib/vendor/zod/v4/locales/he.cjs +248 -0
  302. package/lib/vendor/zod/v4/locales/he.d.cts +5 -0
  303. package/lib/vendor/zod/v4/locales/he.d.ts +4 -0
  304. package/lib/vendor/zod/v4/locales/he.js +221 -0
  305. package/lib/vendor/zod/v4/locales/hi.cjs +138 -0
  306. package/lib/vendor/zod/v4/locales/hi.d.cts +5 -0
  307. package/lib/vendor/zod/v4/locales/hi.d.ts +4 -0
  308. package/lib/vendor/zod/v4/locales/hi.js +111 -0
  309. package/lib/vendor/zod/v4/locales/hr.cjs +153 -0
  310. package/lib/vendor/zod/v4/locales/hr.d.cts +5 -0
  311. package/lib/vendor/zod/v4/locales/hr.d.ts +4 -0
  312. package/lib/vendor/zod/v4/locales/hr.js +126 -0
  313. package/lib/vendor/zod/v4/locales/hu.cjs +140 -0
  314. package/lib/vendor/zod/v4/locales/hu.d.cts +5 -0
  315. package/lib/vendor/zod/v4/locales/hu.d.ts +4 -0
  316. package/lib/vendor/zod/v4/locales/hu.js +113 -0
  317. package/lib/vendor/zod/v4/locales/hy.cjs +185 -0
  318. package/lib/vendor/zod/v4/locales/hy.d.cts +5 -0
  319. package/lib/vendor/zod/v4/locales/hy.d.ts +4 -0
  320. package/lib/vendor/zod/v4/locales/hy.js +158 -0
  321. package/lib/vendor/zod/v4/locales/id.cjs +138 -0
  322. package/lib/vendor/zod/v4/locales/id.d.cts +5 -0
  323. package/lib/vendor/zod/v4/locales/id.d.ts +4 -0
  324. package/lib/vendor/zod/v4/locales/id.js +111 -0
  325. package/lib/vendor/zod/v4/locales/index.cjs +152 -0
  326. package/lib/vendor/zod/v4/locales/index.d.cts +63 -0
  327. package/lib/vendor/zod/v4/locales/index.d.ts +63 -0
  328. package/lib/vendor/zod/v4/locales/index.js +63 -0
  329. package/lib/vendor/zod/v4/locales/is.cjs +141 -0
  330. package/lib/vendor/zod/v4/locales/is.d.cts +5 -0
  331. package/lib/vendor/zod/v4/locales/is.d.ts +4 -0
  332. package/lib/vendor/zod/v4/locales/is.js +114 -0
  333. package/lib/vendor/zod/v4/locales/it.cjs +140 -0
  334. package/lib/vendor/zod/v4/locales/it.d.cts +5 -0
  335. package/lib/vendor/zod/v4/locales/it.d.ts +4 -0
  336. package/lib/vendor/zod/v4/locales/it.js +113 -0
  337. package/lib/vendor/zod/v4/locales/ja.cjs +139 -0
  338. package/lib/vendor/zod/v4/locales/ja.d.cts +5 -0
  339. package/lib/vendor/zod/v4/locales/ja.d.ts +4 -0
  340. package/lib/vendor/zod/v4/locales/ja.js +112 -0
  341. package/lib/vendor/zod/v4/locales/ka.cjs +144 -0
  342. package/lib/vendor/zod/v4/locales/ka.d.cts +5 -0
  343. package/lib/vendor/zod/v4/locales/ka.d.ts +4 -0
  344. package/lib/vendor/zod/v4/locales/ka.js +117 -0
  345. package/lib/vendor/zod/v4/locales/kh.cjs +12 -0
  346. package/lib/vendor/zod/v4/locales/kh.d.cts +5 -0
  347. package/lib/vendor/zod/v4/locales/kh.d.ts +5 -0
  348. package/lib/vendor/zod/v4/locales/kh.js +5 -0
  349. package/lib/vendor/zod/v4/locales/km.cjs +142 -0
  350. package/lib/vendor/zod/v4/locales/km.d.cts +5 -0
  351. package/lib/vendor/zod/v4/locales/km.d.ts +4 -0
  352. package/lib/vendor/zod/v4/locales/km.js +115 -0
  353. package/lib/vendor/zod/v4/locales/kn.cjs +143 -0
  354. package/lib/vendor/zod/v4/locales/kn.d.cts +5 -0
  355. package/lib/vendor/zod/v4/locales/kn.d.ts +4 -0
  356. package/lib/vendor/zod/v4/locales/kn.js +116 -0
  357. package/lib/vendor/zod/v4/locales/ko.cjs +143 -0
  358. package/lib/vendor/zod/v4/locales/ko.d.cts +5 -0
  359. package/lib/vendor/zod/v4/locales/ko.d.ts +4 -0
  360. package/lib/vendor/zod/v4/locales/ko.js +116 -0
  361. package/lib/vendor/zod/v4/locales/lt.cjs +234 -0
  362. package/lib/vendor/zod/v4/locales/lt.d.cts +5 -0
  363. package/lib/vendor/zod/v4/locales/lt.d.ts +4 -0
  364. package/lib/vendor/zod/v4/locales/lt.js +207 -0
  365. package/lib/vendor/zod/v4/locales/mk.cjs +141 -0
  366. package/lib/vendor/zod/v4/locales/mk.d.cts +5 -0
  367. package/lib/vendor/zod/v4/locales/mk.d.ts +4 -0
  368. package/lib/vendor/zod/v4/locales/mk.js +114 -0
  369. package/lib/vendor/zod/v4/locales/ms.cjs +139 -0
  370. package/lib/vendor/zod/v4/locales/ms.d.cts +5 -0
  371. package/lib/vendor/zod/v4/locales/ms.d.ts +4 -0
  372. package/lib/vendor/zod/v4/locales/ms.js +112 -0
  373. package/lib/vendor/zod/v4/locales/ne.cjs +138 -0
  374. package/lib/vendor/zod/v4/locales/ne.d.cts +5 -0
  375. package/lib/vendor/zod/v4/locales/ne.d.ts +4 -0
  376. package/lib/vendor/zod/v4/locales/ne.js +111 -0
  377. package/lib/vendor/zod/v4/locales/nl.cjs +142 -0
  378. package/lib/vendor/zod/v4/locales/nl.d.cts +5 -0
  379. package/lib/vendor/zod/v4/locales/nl.d.ts +4 -0
  380. package/lib/vendor/zod/v4/locales/nl.js +115 -0
  381. package/lib/vendor/zod/v4/locales/nn.cjs +140 -0
  382. package/lib/vendor/zod/v4/locales/nn.d.cts +5 -0
  383. package/lib/vendor/zod/v4/locales/nn.d.ts +4 -0
  384. package/lib/vendor/zod/v4/locales/nn.js +113 -0
  385. package/lib/vendor/zod/v4/locales/no.cjs +140 -0
  386. package/lib/vendor/zod/v4/locales/no.d.cts +5 -0
  387. package/lib/vendor/zod/v4/locales/no.d.ts +4 -0
  388. package/lib/vendor/zod/v4/locales/no.js +113 -0
  389. package/lib/vendor/zod/v4/locales/ota.cjs +141 -0
  390. package/lib/vendor/zod/v4/locales/ota.d.cts +5 -0
  391. package/lib/vendor/zod/v4/locales/ota.d.ts +4 -0
  392. package/lib/vendor/zod/v4/locales/ota.js +114 -0
  393. package/lib/vendor/zod/v4/locales/package.json +7 -0
  394. package/lib/vendor/zod/v4/locales/pl.cjs +141 -0
  395. package/lib/vendor/zod/v4/locales/pl.d.cts +5 -0
  396. package/lib/vendor/zod/v4/locales/pl.d.ts +4 -0
  397. package/lib/vendor/zod/v4/locales/pl.js +114 -0
  398. package/lib/vendor/zod/v4/locales/ps.cjs +146 -0
  399. package/lib/vendor/zod/v4/locales/ps.d.cts +5 -0
  400. package/lib/vendor/zod/v4/locales/ps.d.ts +4 -0
  401. package/lib/vendor/zod/v4/locales/ps.js +119 -0
  402. package/lib/vendor/zod/v4/locales/pt-BR.cjs +170 -0
  403. package/lib/vendor/zod/v4/locales/pt-BR.d.cts +5 -0
  404. package/lib/vendor/zod/v4/locales/pt-BR.d.ts +4 -0
  405. package/lib/vendor/zod/v4/locales/pt-BR.js +143 -0
  406. package/lib/vendor/zod/v4/locales/pt.cjs +169 -0
  407. package/lib/vendor/zod/v4/locales/pt.d.cts +5 -0
  408. package/lib/vendor/zod/v4/locales/pt.d.ts +4 -0
  409. package/lib/vendor/zod/v4/locales/pt.js +142 -0
  410. package/lib/vendor/zod/v4/locales/ro.cjs +149 -0
  411. package/lib/vendor/zod/v4/locales/ro.d.cts +5 -0
  412. package/lib/vendor/zod/v4/locales/ro.d.ts +4 -0
  413. package/lib/vendor/zod/v4/locales/ro.js +122 -0
  414. package/lib/vendor/zod/v4/locales/ru.cjs +195 -0
  415. package/lib/vendor/zod/v4/locales/ru.d.cts +5 -0
  416. package/lib/vendor/zod/v4/locales/ru.d.ts +4 -0
  417. package/lib/vendor/zod/v4/locales/ru.js +168 -0
  418. package/lib/vendor/zod/v4/locales/sk.cjs +143 -0
  419. package/lib/vendor/zod/v4/locales/sk.d.cts +5 -0
  420. package/lib/vendor/zod/v4/locales/sk.d.ts +4 -0
  421. package/lib/vendor/zod/v4/locales/sk.js +116 -0
  422. package/lib/vendor/zod/v4/locales/sl.cjs +141 -0
  423. package/lib/vendor/zod/v4/locales/sl.d.cts +5 -0
  424. package/lib/vendor/zod/v4/locales/sl.d.ts +4 -0
  425. package/lib/vendor/zod/v4/locales/sl.js +114 -0
  426. package/lib/vendor/zod/v4/locales/sv.cjs +142 -0
  427. package/lib/vendor/zod/v4/locales/sv.d.cts +5 -0
  428. package/lib/vendor/zod/v4/locales/sv.d.ts +4 -0
  429. package/lib/vendor/zod/v4/locales/sv.js +115 -0
  430. package/lib/vendor/zod/v4/locales/ta.cjs +142 -0
  431. package/lib/vendor/zod/v4/locales/ta.d.cts +5 -0
  432. package/lib/vendor/zod/v4/locales/ta.d.ts +4 -0
  433. package/lib/vendor/zod/v4/locales/ta.js +115 -0
  434. package/lib/vendor/zod/v4/locales/tg.cjs +144 -0
  435. package/lib/vendor/zod/v4/locales/tg.d.cts +5 -0
  436. package/lib/vendor/zod/v4/locales/tg.d.ts +4 -0
  437. package/lib/vendor/zod/v4/locales/tg.js +117 -0
  438. package/lib/vendor/zod/v4/locales/th.cjs +142 -0
  439. package/lib/vendor/zod/v4/locales/th.d.cts +5 -0
  440. package/lib/vendor/zod/v4/locales/th.d.ts +4 -0
  441. package/lib/vendor/zod/v4/locales/th.js +115 -0
  442. package/lib/vendor/zod/v4/locales/tk.cjs +134 -0
  443. package/lib/vendor/zod/v4/locales/tk.d.cts +5 -0
  444. package/lib/vendor/zod/v4/locales/tk.d.ts +4 -0
  445. package/lib/vendor/zod/v4/locales/tk.js +107 -0
  446. package/lib/vendor/zod/v4/locales/tr.cjs +137 -0
  447. package/lib/vendor/zod/v4/locales/tr.d.cts +5 -0
  448. package/lib/vendor/zod/v4/locales/tr.d.ts +4 -0
  449. package/lib/vendor/zod/v4/locales/tr.js +110 -0
  450. package/lib/vendor/zod/v4/locales/ua.cjs +12 -0
  451. package/lib/vendor/zod/v4/locales/ua.d.cts +5 -0
  452. package/lib/vendor/zod/v4/locales/ua.d.ts +5 -0
  453. package/lib/vendor/zod/v4/locales/ua.js +5 -0
  454. package/lib/vendor/zod/v4/locales/uk.cjs +140 -0
  455. package/lib/vendor/zod/v4/locales/uk.d.cts +5 -0
  456. package/lib/vendor/zod/v4/locales/uk.d.ts +4 -0
  457. package/lib/vendor/zod/v4/locales/uk.js +113 -0
  458. package/lib/vendor/zod/v4/locales/ur.cjs +142 -0
  459. package/lib/vendor/zod/v4/locales/ur.d.cts +5 -0
  460. package/lib/vendor/zod/v4/locales/ur.d.ts +4 -0
  461. package/lib/vendor/zod/v4/locales/ur.js +115 -0
  462. package/lib/vendor/zod/v4/locales/uz.cjs +140 -0
  463. package/lib/vendor/zod/v4/locales/uz.d.cts +5 -0
  464. package/lib/vendor/zod/v4/locales/uz.d.ts +4 -0
  465. package/lib/vendor/zod/v4/locales/uz.js +113 -0
  466. package/lib/vendor/zod/v4/locales/vi.cjs +140 -0
  467. package/lib/vendor/zod/v4/locales/vi.d.cts +5 -0
  468. package/lib/vendor/zod/v4/locales/vi.d.ts +4 -0
  469. package/lib/vendor/zod/v4/locales/vi.js +113 -0
  470. package/lib/vendor/zod/v4/locales/yo.cjs +139 -0
  471. package/lib/vendor/zod/v4/locales/yo.d.cts +5 -0
  472. package/lib/vendor/zod/v4/locales/yo.d.ts +4 -0
  473. package/lib/vendor/zod/v4/locales/yo.js +112 -0
  474. package/lib/vendor/zod/v4/locales/zh-CN.cjs +141 -0
  475. package/lib/vendor/zod/v4/locales/zh-CN.d.cts +5 -0
  476. package/lib/vendor/zod/v4/locales/zh-CN.d.ts +4 -0
  477. package/lib/vendor/zod/v4/locales/zh-CN.js +114 -0
  478. package/lib/vendor/zod/v4/locales/zh-TW.cjs +139 -0
  479. package/lib/vendor/zod/v4/locales/zh-TW.d.cts +5 -0
  480. package/lib/vendor/zod/v4/locales/zh-TW.d.ts +4 -0
  481. package/lib/vendor/zod/v4/locales/zh-TW.js +112 -0
  482. package/lib/vendor/zod/v4/mini/checks.cjs +54 -0
  483. package/lib/vendor/zod/v4/mini/checks.d.cts +1 -0
  484. package/lib/vendor/zod/v4/mini/checks.d.ts +1 -0
  485. package/lib/vendor/zod/v4/mini/checks.js +1 -0
  486. package/lib/vendor/zod/v4/mini/coerce.cjs +71 -0
  487. package/lib/vendor/zod/v4/mini/coerce.d.cts +7 -0
  488. package/lib/vendor/zod/v4/mini/coerce.d.ts +7 -0
  489. package/lib/vendor/zod/v4/mini/coerce.js +22 -0
  490. package/lib/vendor/zod/v4/mini/deep-partial.cjs +58 -0
  491. package/lib/vendor/zod/v4/mini/deep-partial.d.cts +14 -0
  492. package/lib/vendor/zod/v4/mini/deep-partial.d.ts +14 -0
  493. package/lib/vendor/zod/v4/mini/deep-partial.js +13 -0
  494. package/lib/vendor/zod/v4/mini/external.cjs +95 -0
  495. package/lib/vendor/zod/v4/mini/external.d.cts +16 -0
  496. package/lib/vendor/zod/v4/mini/external.d.ts +16 -0
  497. package/lib/vendor/zod/v4/mini/external.js +16 -0
  498. package/lib/vendor/zod/v4/mini/in-out.cjs +82 -0
  499. package/lib/vendor/zod/v4/mini/in-out.d.cts +8 -0
  500. package/lib/vendor/zod/v4/mini/in-out.d.ts +8 -0
  501. package/lib/vendor/zod/v4/mini/in-out.js +36 -0
  502. package/lib/vendor/zod/v4/mini/index.cjs +51 -0
  503. package/lib/vendor/zod/v4/mini/index.d.cts +3 -0
  504. package/lib/vendor/zod/v4/mini/index.d.ts +3 -0
  505. package/lib/vendor/zod/v4/mini/index.js +3 -0
  506. package/lib/vendor/zod/v4/mini/iso.cjs +83 -0
  507. package/lib/vendor/zod/v4/mini/iso.d.cts +22 -0
  508. package/lib/vendor/zod/v4/mini/iso.d.ts +22 -0
  509. package/lib/vendor/zod/v4/mini/iso.js +34 -0
  510. package/lib/vendor/zod/v4/mini/package.json +7 -0
  511. package/lib/vendor/zod/v4/mini/parse.cjs +37 -0
  512. package/lib/vendor/zod/v4/mini/parse.d.cts +1 -0
  513. package/lib/vendor/zod/v4/mini/parse.d.ts +1 -0
  514. package/lib/vendor/zod/v4/mini/parse.js +1 -0
  515. package/lib/vendor/zod/v4/mini/schemas.cjs +1147 -0
  516. package/lib/vendor/zod/v4/mini/schemas.d.cts +480 -0
  517. package/lib/vendor/zod/v4/mini/schemas.d.ts +480 -0
  518. package/lib/vendor/zod/v4/mini/schemas.js +1002 -0
  519. package/lib/vendor/zod/v4/package.json +7 -0
  520. package/lib/vendor/zod/v4-mini/index.cjs +51 -0
  521. package/lib/vendor/zod/v4-mini/index.d.cts +3 -0
  522. package/lib/vendor/zod/v4-mini/index.d.ts +3 -0
  523. package/lib/vendor/zod/v4-mini/index.js +3 -0
  524. package/lib/vendor/zod/v4-mini/package.json +7 -0
  525. package/package.json +84 -72
  526. package/tests/_host-lib.js +50 -0
  527. package/tests/fixtures/holiday-notice-2023.txt +8 -0
  528. package/tests/fixtures/holiday-notice-2024.txt +9 -0
  529. package/tests/fixtures/holiday-notice-2025.txt +8 -0
  530. package/tests/fixtures/holiday-notice-2026.txt +9 -0
  531. package/tests/helpers/client-harness.js +86 -0
  532. package/tests/package.json +3 -0
  533. package/tests/verify-activemodel.js +173 -0
  534. package/tests/verify-balance-api.js +368 -0
  535. package/tests/verify-balance-vendors.js +422 -0
  536. package/tests/verify-balance.js +1041 -0
  537. package/tests/verify-billing-stall.js +404 -0
  538. package/tests/verify-client-hygiene.js +425 -0
  539. package/tests/verify-client-price.mjs +133 -0
  540. package/tests/verify-clock.js +246 -0
  541. package/tests/verify-compaction-usage.js +342 -0
  542. package/tests/verify-context.js +179 -0
  543. package/tests/verify-copy.js +317 -0
  544. package/tests/verify-cost-overflow.js +150 -0
  545. package/tests/verify-deadcode.js +171 -0
  546. package/tests/verify-dev-fixtures.js +850 -0
  547. package/tests/verify-dev-mode.js +659 -0
  548. package/tests/verify-drag-card.js +176 -0
  549. package/tests/verify-fixes.js +520 -0
  550. package/tests/verify-generic-relay.js +487 -0
  551. package/tests/verify-holiday-persist.js +180 -0
  552. package/tests/verify-holiday-route.js +65 -0
  553. package/tests/verify-holiday-update.js +226 -0
  554. package/tests/verify-holiday.js +118 -0
  555. package/tests/verify-holidays.js +91 -0
  556. package/tests/verify-host-guards.mjs +97 -0
  557. package/tests/verify-host.js +461 -0
  558. package/tests/verify-hover.js +619 -0
  559. package/tests/verify-ledger-keep.js +1015 -0
  560. package/tests/verify-ledger-prices.js +238 -0
  561. package/tests/verify-list-layout.js +610 -0
  562. package/tests/verify-magpie-quota.mjs +582 -0
  563. package/tests/verify-migration.js +179 -0
  564. package/tests/verify-model-match.js +306 -0
  565. package/tests/verify-modelrow-scroll.js +669 -0
  566. package/tests/verify-navicon.js +348 -0
  567. package/tests/verify-price-filled.js +831 -0
  568. package/tests/verify-price-parity.js +392 -0
  569. package/tests/verify-prices.js +258 -0
  570. package/tests/verify-pricing.js +161 -0
  571. package/tests/verify-progress-events.js +260 -0
  572. package/tests/verify-provider-fees.js +919 -0
  573. package/tests/verify-relay-settings.js +2447 -0
  574. package/tests/verify-release-age.js +394 -0
  575. package/tests/verify-release.js +200 -0
  576. package/tests/verify-render.js +557 -0
  577. package/tests/verify-reprice.js +127 -0
  578. package/tests/verify-routes.js +215 -0
  579. package/tests/verify-self-update-status.js +155 -0
  580. package/tests/verify-self-update.js +467 -0
  581. package/tests/verify-speed.js +61 -0
  582. package/tests/verify-star-tip.js +156 -0
  583. package/tests/verify-subagent-total.js +1354 -0
  584. package/tests/verify-timing.js +671 -0
  585. package/tests/verify-tips.js +1046 -0
  586. package/tests/verify-tokens.js +230 -0
  587. package/tests/verify-update-duration.js +135 -0
  588. package/tests/verify-update-retry.js +375 -0
  589. package/tests/verify-version.js +127 -0
  590. package/tests/verify-weekend.js +104 -0
  591. package/tests/verify.js +3510 -0
  592. package/tools/shot.cjs +12 -10
  593. package/tools/sync-from-plugin.cjs +63 -22
  594. package/tools/sync-to-plugin.cjs +38 -16
  595. package/tools/test.cjs +53 -17
  596. package/docs/statusbar.en.png +0 -0
  597. package/docs/statusbar.png +0 -0
@@ -0,0 +1,3510 @@
1
+ /**
2
+ * 验证 dsh-desktop-statusbar 的占位与格式改动。
3
+ * 做法:用最小替身加载真实 client.js(window.localStorage / ModuleLoader / React),
4
+ * 从 factory 内部导出被测函数,直接跑真实渲染路径。
5
+ */
6
+ const fs = require('fs');
7
+ const path = require('path');
8
+ const vm = require('vm');
9
+ const assert = require('assert');
10
+
11
+ const PLUGIN = path.join(__dirname, '..', 'lib', 'client.js');
12
+ let code = fs.readFileSync(PLUGIN, 'utf8');
13
+
14
+ // 暴露闭包内的被测符号
15
+ const marker = '\t\texports.apply = apply;';
16
+ assert.ok(code.includes(marker), 'exports.apply marker not found');
17
+ code = code.replace(marker,
18
+ /* `setConfig` 要导出:「总计」那批用例得走**真实改价路径**(设置页改价 = setConfig({models})),
19
+ 手工改 config 是另一条路。`applyTotalFloor` 不再导出 —— 它是「总计」的实现细节,
20
+ 测试只该看渲染出来的文字,不该看它的内部账本(否则又会退化成绕过真实路径的纯函数测试)。
21
+ `rowsPanel` 要导出:它是**唯一**给「标题下色条」定 `dsb-bar` / `dsb-bar-hoverable` 的地方,
22
+ 而令牌面板(tokens)走的是另一条渲染路径(meterBar 里类名硬编码),
23
+ 想真切到那个三元表达式,只能直接把 rowsPanel 调起来渲染。 */
24
+ '\t\texports.__test = { segmentView, segmentText, priceOf, pickPriceKey, compactModelKey, detectLocale, formatDuration, formatSeconds, formatThroughput, SEGMENTS, DEFAULT_SEGMENTS, STORAGE_KEY, DEFAULT_PRICES, DEFAULT_PRICES_USD, PRICE_VERSION, PRICE_RETIRED_PRUNE_VERSION, REFERENCE_RATE, MODEL_PRESENTATION, MODEL_MANUFACTURERS, DEFAULT_CATALOG_ORDER, normalizeCatalogOrder, snapshot, setConfig, StatusBar, SettingsSection, dropIndexAt, moveItem, creditsPanel, BALANCE_COLORS, creditsLabel, formatCredits, plainBoundsOf, clampPlainLeft, plainFits, creditDisplayName, TOOL_BAR_COLORS, rowsPanel, creditsSort, creditsSortGroup, creditsSortDate, LIST_ROWS_PER_COLUMN_MAX };\n' + marker);
25
+
26
+ const store = new Map();
27
+ /* 预置一份"乱序 + 只勾四段 + 非默认币种"的旧配置:出厂默认要从这种状态拉回来 */
28
+ const CONFIG_KEY = 'dsh.desktopStatusBar.v1';
29
+ const MESSY_SEGMENTS = ['cost', 'sessionTime', 'status', 'counts'];
30
+
31
+ /* 官方模型目录数据(docs/official-models.json):价格库播种 / 目录卡 / 恢复默认的期望来源 */
32
+ const OFFICIAL_CATALOG = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'docs', 'official-models.json'), 'utf8'));
33
+ const OFFICIAL_VENDORS = OFFICIAL_CATALOG.vendors;
34
+ /* 厂商默认顺序 = docs/vendor-intelligence-order.json(Artificial Analysis 智力指数,只算公开可用模型):
35
+ 那份数据是顺序的唯一来源,客户端内嵌的 MODEL_MANUFACTURERS 与目录分组都必须跟着它。 */
36
+ const AA_VENDOR_ORDER = JSON.parse(fs.readFileSync(path.join(__dirname, '..', 'docs', 'vendor-intelligence-order.json'), 'utf8'))
37
+ .map((one) => one.vendorId);
38
+ const OFFICIAL_NAMES = [];
39
+ /* 名字顺序按 AA 厂商顺序展开(= 内嵌 MODEL_PRESENTATION 的键序):
40
+ 「恢复默认」的 modelOrder 就是按目录键序追加的,顺序期望必须同源 */
41
+ AA_VENDOR_ORDER.forEach((id) => {
42
+ OFFICIAL_VENDORS.filter((one) => one.id === id)[0].models.forEach((model) => { OFFICIAL_NAMES.push(model.name); });
43
+ });
44
+ const catalogTierOf = (tier) => ({
45
+ input: tier === undefined || tier === null || tier.input === undefined ? null : tier.input,
46
+ cacheRead: tier === undefined || tier === null || tier.cacheRead === undefined ? null : tier.cacheRead,
47
+ cacheWrite: tier === undefined || tier === null || tier.cacheWrite === undefined ? null : tier.cacheWrite,
48
+ output: tier === undefined || tier === null || tier.output === undefined ? null : tier.output
49
+ });
50
+ const catalogEntryOf = (model) => {
51
+ const tiered = model.tiered === true && model.peak !== undefined && model.peak !== null
52
+ && model.offPeak !== undefined && model.offPeak !== null;
53
+ return {
54
+ tiered: tiered,
55
+ currency: model.currency === undefined ? 'CNY' : model.currency,
56
+ peak: catalogTierOf(tiered === true ? model.peak : model),
57
+ offPeak: tiered === true ? catalogTierOf(model.offPeak) : null
58
+ };
59
+ };
60
+ const catalogPriceOf = (model) => {
61
+ const entry = catalogEntryOf(model);
62
+ if (entry.tiered === true) return entry;
63
+ return { tiered: false, currency: entry.currency, peak: entry.peak, offPeak: entry.peak };
64
+ };
65
+
66
+ /* v7:期望值里也带基准价(= 官网原值 + 官网币种,单档条目的 offPeak 用 peak 副本) */
67
+ const catalogEntryWithBase = (model) => {
68
+ const entry = catalogEntryOf(model);
69
+ entry.base = {
70
+ currency: entry.currency,
71
+ peak: entry.peak,
72
+ offPeak: entry.tiered === true ? entry.offPeak : Object.assign({}, entry.peak)
73
+ };
74
+ return entry;
75
+ };
76
+ /* 3.0.4 起官方 USD 源表入价格库:显示值按 REFERENCE_RATE 折成 CNY,base 保留原 USD 值。 */
77
+ const catalogBookEntryOf = (model) => {
78
+ const entry = catalogEntryOf(model);
79
+ const rate = api.REFERENCE_RATE;
80
+ const conv = (v) => (v === null || v === undefined ? null : Math.round(Number(v) * rate * 100) / 100);
81
+ const convTier = (tier) => ({ input: conv(tier.input), cacheRead: conv(tier.cacheRead), cacheWrite: conv(tier.cacheWrite), output: conv(tier.output) });
82
+ const base = {
83
+ currency: entry.currency,
84
+ peak: entry.peak,
85
+ offPeak: entry.tiered === true ? entry.offPeak : Object.assign({}, entry.peak)
86
+ };
87
+ if (entry.currency !== 'USD') return Object.assign({}, entry, { base: base });
88
+ return {
89
+ tiered: entry.tiered,
90
+ currency: 'CNY',
91
+ peak: convTier(entry.peak),
92
+ offPeak: entry.offPeak === null ? null : convTier(entry.offPeak),
93
+ base: base
94
+ };
95
+ };
96
+ store.set(CONFIG_KEY, JSON.stringify({
97
+ version: 5, enabled: true, wrap: false,
98
+ /* task-22 起 `currency` 降级为"**新增条目的默认币种**"(不再是全局计价单位):迁移时用它给已有条目定币种,
99
+ 此后的切换只作用被切的那一条,不改写这里,也不改写别的条目。这里种 CNY 与出厂默认一致。 */
100
+ /* priceVersion 4:不触发官方目录播种,保持这份 fixture 的两条参考价语义(播种另有专门用例) */
101
+ priceVersion: 4, segments: MESSY_SEGMENTS.slice(), currency: 'CNY', models: {}
102
+ }));
103
+ const fakeWindow = {
104
+ /* 「去 GitHub 点 star」按钮点下去要开默认浏览器:这里只记下 window.open 收到了什么 */
105
+ open: (url, target) => { fakeWindow.opened.push([url, target]); },
106
+ opened: [],
107
+ localStorage: {
108
+ getItem: (k) => (store.has(k) ? store.get(k) : null),
109
+ setItem: (k, v) => { store.set(k, v); },
110
+ removeItem: (k) => { store.delete(k); }
111
+ },
112
+ fetch: () => Promise.resolve({ json: () => Promise.resolve({ ok: false, reason: 'test' }) }),
113
+ setInterval: () => 0,
114
+ clearInterval: () => {},
115
+ setTimeout: () => 0,
116
+ clearTimeout: () => {},
117
+ addEventListener: () => {},
118
+ removeEventListener: () => {},
119
+ /* 气泡定位替身:面板宽度与圆圈灰底的左边界由测试按需给(见下面「气泡水平位置」那一段) */
120
+ innerWidth: 1280,
121
+ innerHeight: 800
122
+ };
123
+
124
+ let captured = null;
125
+ /* document 上的事件监听:行为断言要拿到组件**真正挂上去**的那个回调(不是去源码里找字符串),
126
+ 所以这里既记下来、也支持注销(removeEventListener 从同一份表里删)。
127
+ 按事件类型分桶,别的类型(resize / pointer 之类)不受影响。 */
128
+ const docListeners = {};
129
+ const openCatalogVendors = [];
130
+ const sandbox = {
131
+ window: fakeWindow,
132
+ document: {
133
+ querySelector: () => null,
134
+ querySelectorAll: (selector) => (selector === '.dsb-catalog-vendor[open]' ? openCatalogVendors : []),
135
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
136
+ head: { appendChild() {} },
137
+ addEventListener: (type, fn) => {
138
+ if (docListeners[type] === undefined) docListeners[type] = [];
139
+ docListeners[type].push(fn);
140
+ },
141
+ removeEventListener: (type, fn) => {
142
+ const list = docListeners[type] === undefined ? [] : docListeners[type];
143
+ const at = list.indexOf(fn);
144
+ if (at !== -1) list.splice(at, 1);
145
+ }
146
+ },
147
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
148
+ /* 悬停浮层的收起是延后 110ms 的(防相邻格子之间闪断):这里给空壳,不让真定时器吊住进程 */
149
+ setTimeout: () => 0, clearTimeout: () => {}
150
+ };
151
+ sandbox.globalThis = sandbox;
152
+ fakeWindow.__ModuleLoader__ = { load: (entry) => { captured = entry; } };
153
+
154
+ /* React 替身:hooks 按组件分桶保存,点击后重新渲染就能读到最新 state */
155
+ let activeHooks = null;
156
+ function makeHooks() { return { values: [], deps: [], index: 0, pending: [] }; }
157
+ /**
158
+ * 跑一轮渲染。**layout effect 延迟到整棵树建完之后再执行** —— 这是真实 React 的顺序:
159
+ * 渲染 → 挂 DOM(ref 赋值)→ 跑 layout effect。替身若在渲染中途同步跑 effect,
160
+ * 那时子节点还没建出来、ref 还是 null,凡是「先拿节点再量尺寸」的逻辑全都测不到
161
+ * (悬停提示的定位就有这个问题)。
162
+ */
163
+ function withHooks(bucket, fn) {
164
+ const prev = activeHooks;
165
+ activeHooks = bucket;
166
+ bucket.index = 0;
167
+ bucket.pending = [];
168
+ let out;
169
+ try {
170
+ out = fn();
171
+ } finally {
172
+ activeHooks = prev;
173
+ }
174
+ const queued = bucket.pending;
175
+ bucket.pending = [];
176
+ queued.forEach((one) => one());
177
+ return out;
178
+ }
179
+ function hookSlot(init) {
180
+ if (activeHooks === null) return { get: () => undefined, set: () => {} };
181
+ const bucket = activeHooks;
182
+ const at = bucket.index;
183
+ bucket.index += 1;
184
+ if (bucket.values.length <= at) bucket.values[at] = typeof init === 'function' ? init() : init;
185
+ return {
186
+ get: () => bucket.values[at],
187
+ set: (value) => { bucket.values[at] = typeof value === 'function' ? value(bucket.values[at]) : value; }
188
+ };
189
+ }
190
+
191
+ /* 行的假几何:拖动时组件要量各行位置,替身按渲染顺序给递增的 top(每行 40 高) */
192
+ let rowSeq = 0;
193
+ let catalogSeq = 0;
194
+ /* 定位 effect 平时不跑(替身里的 useEffect 只占位),要验气泡坐标的那一段再打开 */
195
+ let runEffects = false;
196
+ /* 气泡面板的宽度与圆圈灰底的左边界:由测试按需改,模拟真实 DOM 量出来的值 */
197
+ let stubTipWidth = 0;
198
+ let stubRingLeft = 120;
199
+ const stubRect = (left, width) => ({ left: left, width: width, right: left + width, top: 700, height: 20, bottom: 720 });
200
+ /* 圆环**按钮**(灰底就是它画的:padding 3px + border-radius 50% → 20px 的圆)。
201
+ 气泡左对齐的基准是它,不是里面那个 14px 的 .dsb-ring SVG。 */
202
+ const stubRing = { getBoundingClientRect: () => stubRect(stubRingLeft, 20) };
203
+ /* 底栏最右那一项(末尾字段):右对齐/宽度上限都按它的右边界算 */
204
+ let stubBarRight = 985;
205
+ const stubLastSeg = { getBoundingClientRect: () => stubRect(stubBarRight - 170, 170) };
206
+ /* 悬停纯文字提示的**自然宽度**。测试按需改大到放不下,用来触发「整组关掉悬停」。 */
207
+ let stubHoverPlainWidth = 60;
208
+ /* 悬停提示定位 effect 要量的三个盒子(宽度够用即可,只关心相对关系):
209
+ 标题行 head(算垂直居中)、标题文字 headline(算水平左界)、色条 bar(算水平右界)。 */
210
+ let stubHeadWidth = 300;
211
+ let stubHeadlineWidth = 60;
212
+ let stubBarWidth = 273;
213
+ /* 工具调用列数自适应的假几何:列网格 nowrap,放不下的表现是**内容宽 > 容器宽**。
214
+ stubWrapOn 时容器只放得下 stubWrapCap 列(stubColWidth 是每列的假宽度)——
215
+ 列数按当前渲染树里的 .dsb-meter-col 数量算,行数每加一档列数就少一档,溢出自然消失。 */
216
+ let stubWrapOn = false;
217
+ let stubWrapCap = 3;
218
+ /* 每列的假宽度:只要"总宽 = 列数 × 它"这个关系成立,取值不影响判定(用 170 与真实列宽同量级) */
219
+ const stubColWidth = 170;
220
+ /** 树里某个类名出现了几次(给气泡的假 querySelectorAll 用) */
221
+ function countClass(node, cls) {
222
+ if (node === null || node === undefined) return 0;
223
+ if (Array.isArray(node)) return node.reduce((sum, one) => sum + countClass(one, cls), 0);
224
+ if (typeof node !== 'object') return 0;
225
+ const className = node.props === undefined || node.props.className === undefined ? '' : String(node.props.className);
226
+ let count = className.split(' ').indexOf(cls) !== -1 ? 1 : 0;
227
+ (node.children || []).forEach((one) => { count += countClass(one, cls); });
228
+ return count;
229
+ }
230
+ /** 树里某个属性出现了几次(给气泡的假 querySelector 用,如 [data-cols-growable]) */
231
+ function countAttr(node, attr) {
232
+ if (node === null || node === undefined) return 0;
233
+ if (Array.isArray(node)) return node.reduce((sum, one) => sum + countAttr(one, attr), 0);
234
+ if (typeof node !== 'object') return 0;
235
+ const props = node.props === undefined || node.props === null ? {} : node.props;
236
+ let count = props[attr] === undefined || props[attr] === null ? 0 : 1;
237
+ (node.children || []).forEach((one) => { count += countAttr(one, attr); });
238
+ return count;
239
+ }
240
+ const reactStub = {
241
+ createElement(type, props, ...children) {
242
+ const node = {
243
+ type,
244
+ props: props === null || props === undefined ? {} : props,
245
+ children: children.flat(Infinity).filter((c) => c !== null && c !== undefined && c !== false)
246
+ };
247
+ const cls = typeof node.props.className === 'string' ? node.props.className.split(' ') : [];
248
+ if (typeof node.props.className === 'string' && node.props.className.indexOf('dsb-row') !== -1) {
249
+ rowSeq += 1;
250
+ const at = rowSeq;
251
+ node.getBoundingClientRect = () => {
252
+ /* 行高 40、行距 48:真实设置页的 .dsb-section 有 gap,替身也得留着这个间隔,
253
+ 否则"按序号×行高推算槽位"这种错法在测试里永远看不出来 */
254
+ const top = 100 + (at - 1) * 48;
255
+ return { top: top, height: 40, bottom: top + 40, left: 0, width: 300 };
256
+ };
257
+ }
258
+ /* 厂商 details 的假几何:目录拖拽按它量槽位(每行 40 高、行距 48) */
259
+ if (typeof node.props.className === 'string' && node.props.className.indexOf('dsb-catalog-vendor') !== -1) {
260
+ catalogSeq += 1;
261
+ const at = catalogSeq;
262
+ const top = 100 + (at - 1) * 48;
263
+ /* details 的高度模拟“展开模型列表”后的整块(远大于摘要行);摘要行固定 44px */
264
+ node.getBoundingClientRect = () => ({ top: top, height: 300, bottom: top + 300, left: 0, width: 300 });
265
+ node.querySelector = (selector) => (selector === '.dsb-catalog-summary'
266
+ ? {
267
+ className: 'dsb-catalog-summary',
268
+ getBoundingClientRect: () => ({ top: top, height: 44, bottom: top + 44, left: 0, width: 300 }),
269
+ cloneNode: function () { return { __cloned: 'summary', className: this.className }; }
270
+ }
271
+ : null);
272
+ }
273
+ /* 气泡面板:宽度由 CSS 的 max-content 决定,替身里由 stubTipWidth 给;
274
+ 同时给一个假的列网格几何,让 toolColumnsOverflow 能按当前渲染树判"横向放不下" */
275
+ if (cls.indexOf('dsb-tip') !== -1) {
276
+ node.getBoundingClientRect = () => stubRect(0, stubTipWidth);
277
+ node.querySelector = (selector) => {
278
+ /* 判据从 `.dsb-meter-tight`(视觉样式)换成 `[data-cols-growable]`(能力标记):
279
+ 技能注入 / 上下文压缩也支持逐档加行了,但它们不能套 tight(长名字会挤在一起),
280
+ 所以「要不要量溢出」不能再靠 tight 判。 */
281
+ if (selector === '[data-cols-growable]') return countAttr(node, 'data-cols-growable') > 0 ? {} : null;
282
+ /* 悬停纯文字提示的定位 effect 要量标题行与色条:
283
+ 分别给一个盒子,才能算出 top(标题行居中)与水平区间(标题右 → 色条右)。 */
284
+ if (selector === '.dsb-meter-head') return { getBoundingClientRect: () => stubRect(0, stubHeadWidth) };
285
+ if (selector === '.dsb-meter-headline') return { getBoundingClientRect: () => stubRect(0, stubHeadlineWidth) };
286
+ if (selector === '.dsb-bar') return { getBoundingClientRect: () => stubRect(0, stubBarWidth) };
287
+ return null;
288
+ };
289
+ /* 工具调用子视图只有一个列网格。列网格是 flex-wrap:nowrap(绝不折行),
290
+ 所以"放不下"的表现是**内容比容器宽**(scrollWidth > clientWidth),不是列被折到下一排。
291
+ 替身按渲染树里的列数造这个几何:每列按 stubColWidth 算总宽,
292
+ 容器只放得下 stubWrapCap 列 —— 列数多于容量就判溢出,行数加上去列数变少就放得下。 */
293
+ node.querySelectorAll = (selector) => {
294
+ if (selector !== '.dsb-meter-cols') return [];
295
+ const total = countClass(node, 'dsb-meter-col');
296
+ if (total < 2) return [];
297
+ return [{
298
+ scrollWidth: total * stubColWidth,
299
+ clientWidth: stubWrapOn === true ? stubWrapCap * stubColWidth : total * stubColWidth
300
+ }];
301
+ };
302
+ }
303
+ /* 状态栏根节点:定位要按它里面的圆圈灰底量左边界,按最右那一项量右边界 */
304
+ if (cls.indexOf('dsb-root') !== -1) {
305
+ node.querySelector = (selector) => (selector === '.dsb-ring-btn' ? stubRing : null);
306
+ node.querySelectorAll = (selector) => (selector === '.dsb-seg' ? [stubLastSeg] : []);
307
+ }
308
+ /* 悬停纯文字提示(.dsb-hover-plain):必须给 `style`,否则 onHoverMove 一进来就
309
+ `if (node.style === undefined) return`,段内移动那条路径**一行都测不到**。
310
+ 宽度只暴露 offsetWidth(布局宽度):提示不再做缩放,替身也就不必模拟
311
+ transform 对 getBoundingClientRect 的影响 —— 那套模拟是缩放时代的产物。 */
312
+ if (cls.indexOf('dsb-hover-plain') !== -1) {
313
+ node.style = {};
314
+ /* 宽度**动态读** stubHoverPlainWidth:用例会在渲染之间改它来模拟「工具名变长」,
315
+ 快照下来就会量到建档时的旧宽度,判定永远不触发(实测踩过)。 */
316
+ Object.defineProperty(node, 'naturalWidth', {
317
+ configurable: true,
318
+ get: () => stubHoverPlainWidth
319
+ });
320
+ node.naturalHeight = 15;
321
+ node.getBoundingClientRect = () => ({
322
+ left: 0, top: 700,
323
+ width: node.naturalWidth,
324
+ height: node.naturalHeight,
325
+ right: node.naturalWidth, bottom: 700 + node.naturalHeight
326
+ });
327
+ /* offsetWidth 是整数 —— 真实浏览器语义 */
328
+ Object.defineProperty(node, 'offsetWidth', {
329
+ configurable: true,
330
+ get: () => Math.round(node.naturalWidth)
331
+ });
332
+ }
333
+ if (typeof node.props.ref === 'function') node.props.ref(node);
334
+ /* 对象 ref 在替身里也要真的挂上节点(只认气泡/根节点这几个,别的 ref 装着别的东西)。
335
+ 每次都更新到最新树:量测(宽度 / 折行)必须量这一遍渲染的结果,首次挂上后就不再更新会量到旧树。 */
336
+ const box = node.props.ref;
337
+ /* 对象 ref 要真的挂上节点:气泡/根节点之外,`.dsb-hover-plain` 也必须挂 ——
338
+ 悬停提示的定位与「放不下就关」判定全靠 hoverRef.current 拿到那个节点,
339
+ 不挂的话 effect 一进来就 `if (node === null) return`,整段逻辑一行都测不到。 */
340
+ const mountable = cls.indexOf('dsb-tip') !== -1 || cls.indexOf('dsb-root') !== -1
341
+ || cls.indexOf('dsb-hover-plain') !== -1;
342
+ if (mountable === true && box !== null && typeof box === 'object') box.current = node;
343
+ return node;
344
+ },
345
+ useState: (init) => {
346
+ const slot = hookSlot(init);
347
+ return [slot.get(), slot.set];
348
+ },
349
+ useEffect: (fn, deps) => {
350
+ const at = activeHooks === null ? -1 : activeHooks.index;
351
+ hookSlot(undefined);
352
+ if (runEffects !== true || typeof fn !== 'function' || at < 0) return;
353
+ /* 依赖数组照 React 的规矩判:不写依赖数组 = 每次渲染都跑;
354
+ 写了就逐项比,全等才跳过 —— 定位那条 effect 少了依赖数组才量得到新宽度 */
355
+ const prev = activeHooks.deps[at];
356
+ const same = Array.isArray(deps) === true && Array.isArray(prev) === true
357
+ && deps.length === prev.length && deps.every((one, index) => one === prev[index]);
358
+ activeHooks.deps[at] = Array.isArray(deps) ? deps.slice() : undefined;
359
+ if (same === true) return;
360
+ fn();
361
+ },
362
+ /* 真 React 一定有 useLayoutEffect(插件用它做绘制前定位)。替身必须提供,
363
+ 否则 useTipLayout 会退回 useEffect,而那条路径在替身里还要额外满足 runEffects 时序 ——
364
+ 更要紧的是:不提供的话「定位 effect」这段在测试里根本不会走,B3/M14 的变异就抓不到。
365
+ 回调**排队到整棵树渲染完之后**再跑(真实 React 顺序:渲染 → 挂 DOM → layout effect),
366
+ 否则 effect 里拿 hoverRef.current 之类的节点引用永远是 null。 */
367
+ useLayoutEffect: (fn, deps) => {
368
+ const at = activeHooks === null ? -1 : activeHooks.index;
369
+ hookSlot(undefined);
370
+ if (runEffects !== true || typeof fn !== 'function' || at < 0) return;
371
+ const prev = activeHooks.deps[at];
372
+ const same = Array.isArray(deps) === true && Array.isArray(prev) === true
373
+ && deps.length === prev.length && deps.every((one, index) => one === prev[index]);
374
+ activeHooks.deps[at] = Array.isArray(deps) ? deps.slice() : undefined;
375
+ if (same === true) return;
376
+ activeHooks.pending.push(fn);
377
+ },
378
+ useRef: (init) => hookSlot({ current: init === undefined ? null : init }).get(),
379
+ useSyncExternalStore: (subscribe, snapshot) => {
380
+ hookSlot(undefined);
381
+ return snapshot();
382
+ },
383
+ useCallback: (fn) => { hookSlot(undefined); return fn; },
384
+ useMemo: (fn) => { hookSlot(undefined); return fn(); },
385
+ Fragment: Symbol('Fragment')
386
+ };
387
+
388
+ vm.createContext(sandbox);
389
+ vm.runInContext(code, sandbox, { filename: 'client.js' });
390
+ assert.ok(captured !== null && captured.id === 'dsh-desktop-statusbar', 'plugin entry not captured');
391
+
392
+ const mod = captured.factory((name) => {
393
+ if (name === 'react') return reactStub;
394
+ throw new Error('unexpected require: ' + name);
395
+ });
396
+ const api = mod.__test;
397
+ assert.ok(api !== undefined, '__test export missing');
398
+
399
+ /* ------------------------------------------------------------------ 替身 i18n */
400
+ const zh = {
401
+ segStatus: '峰谷判断', segCounts: '轮次&步数', segTtft: '首字延迟',
402
+ segContext: '上下文占用',
403
+ segCacheHit: '缓存命中率', segTokens: 'Token计数', segTps: '输出速度', segSessionTime: '运行用时',
404
+ segCost: '会话费用', segLastCost: '本次费用', segBalance: '余额',
405
+ f_status_running: '运行中', f_status_idle: '空闲', f_status_error: '出错',
406
+ f_counts: '{turns} 轮 {steps} 步',
407
+ f_ttft: '首字平均 {duration}', f_cacheHit: '综合命中 {percent}%',
408
+ f_peak: '高峰', f_valley: '低谷', f_approval: '待批准',
409
+ f_tokens: '{total} tokens',
410
+ f_tokensHit: '输入(命中缓存)', f_tokensMiss: '输入(未命中缓存)', f_tokensOut: '输出',
411
+ f_speed: '综合速度 {throughput}t/s', f_sessionTime: '总用时 {duration}',
412
+ f_cost: '总计 {symbol}{cost}', f_lastCost: '本轮 {symbol}{cost}',
413
+ f_balance: '余额 {symbol}{amount}', f_balanceLoading: '余额 查询中', f_balanceFailed: '余额 失败({reason})',
414
+ /* 积分口径的套餐气泡(WorkBuddy):标题 / 月度备注 / 刷新与到期备注 / 剩余数值 */
415
+ tipCreditsTitle: '积分套餐', tipCreditsMonthly: '(每月刷新)', tipCreditsRefresh: ' · {date} 刷新',
416
+ tipCreditsExpire: ' · {date} 到期', tipCreditsRefreshLatest: ' · {date} 刷新(最近)',
417
+ tipCreditsExpireLatest: ' · {date} 到期(最近)', tipCreditsLeft: '剩余 {left} / {total}',
418
+ unitCountTurns: ' 轮', unitCountSteps: ' 步',
419
+ unitCountCalls: ' 次',
420
+ tipCountsTitle: '会话数据', tipCountsSkills: '技能注入', tipCountsToolCalls: '工具调用',
421
+ tipCountsCompactAt: '上下文压缩',
422
+ tipCompactItem: '第{index}次压缩', tipCompactWhere: '第{turn}轮{step}步', tipCompactTurnOnly: '第{turn}轮',
423
+ tipCompactAfter: '第{turn}轮后',
424
+ tipManual: '手动触发',
425
+ unitCost: '', unitSeconds: ' s', unitSpeed: ' t/s', unitMinutes: ' m',
426
+ modelUnknown: '未识别',
427
+ segContextHint: '当前会话的运行状态与上下文占用。',
428
+ secSegments: '数据字段', secPrices: '自定义模型价格', secPreview: '预览(示例数据)',
429
+ secPlatforms: '第三方平台', secPlatformsBadge: '实验性功能',
430
+ secSegmentsHint: '勾选显示;按住拖动调整顺序。',
431
+ intro: '接管对话区底部的统计行。勾选要显示的字段、拖动调整顺序或配置模型费用单价。',
432
+ priceCurrent: '当前会话使用:', priceConfigured: '已配置', priceNotConfigured: '未配置价格,费用段显示横杠占位',
433
+ priceAdd: '添加', priceNewModel: '新模型', priceRemove: '删除', priceEmpty: '价格库为空', reset: '恢复默认设置',
434
+ starRepo: 'GitHub支持', starTip: '你的支持是我最大的动力!请帮我点亮Star吧~',
435
+ holidayUpdateOk: '已写入 {year} 年 {count} 个节假日',
436
+ priceInput: '输入(缓存未命中)', priceCacheRead: '输入(缓存命中)', priceOutput: '输出',
437
+ priceTierPeak: '高峰时段', priceTierOffPeak: '空闲时段', priceTiered: '峰谷计价',
438
+ priceTierAllDay: '全时段',
439
+ priceManufacturerDeepseek: 'DeepSeek', priceManufacturerAnthropic: 'Anthropic',
440
+ priceManufacturerZhipu: '智谱', priceManufacturerAlibaba: '阿里云',
441
+ priceManufacturerOpenai: 'OpenAI', priceManufacturerMoonshot: '月之暗面',
442
+ priceManufacturerGoogle: 'Google', priceManufacturerXai: 'xAI',
443
+ priceManufacturerXiaomi: '小米', priceManufacturerMinimax: 'MiniMax',
444
+ priceManufacturerStepfun: '阶跃星辰', priceManufacturerMuse: 'Meta',
445
+ priceManufacturerCustom: '自定义模型',
446
+ priceModelCount: '{count} 个模型', priceOfficialSource: '官网价格',
447
+ priceCacheWriteTtl: '缓存写入费按期限区分({items});当前用量不含 TTL,因此未计入自动费用。',
448
+ priceDeepSeekPeakOutputUnknown: '抓取到的官方价格行未核实高峰输出价,该字段不参与自动计费。',
449
+ priceZhipuStorageFree: '缓存存储限时免费,单位为元/百万 Token/小时;不等同缓存写入费。',
450
+ priceQwenCacheUnknown: '阿里官方通用说明:显式缓存命中通常按输入价 10%,隐式命中 20%,显式创建 125%;Qwen 绝对缓存单价未核实,未计自动费用。',
451
+ priceCatalogTitle: '官方模型目录', priceCatalogSource: '官方报价',
452
+ priceCatalogRate: '{period}:输入 {input} / 缓存命中 {cacheRead} / 输出 {output} {currency}/百万 Token',
453
+ priceCatalogRegion: '{region}:输入 ¥{input} / 输出 ¥{output} / 百万 Token',
454
+ priceCatalogVariant: '{group}:输入 ¥{input} / 缓存命中 ¥{cacheRead} / 输出 ¥{output} / 百万 Token',
455
+ priceCatalogAudioVariant: '{group} 文本/音频:输入 ¥{input}/¥{audioInput},命中 ¥{cacheRead}/¥{audioCacheRead},输出 ¥{output} / 百万 Token',
456
+ priceCatalogStorage: '缓存存储 ¥{price}/百万 Token/小时(仅展示)',
457
+ priceCatalogAddOfficial: '添加官方价', priceCatalogAddBlank: '添加空白价格条目',
458
+ priceCatalogUseRegion: '使用 {region} 价格', priceCatalogUseRate: '按 {period} 价添加为全天价({currency})',
459
+ priceCatalogEdit: '修改已有价格', priceCatalogUnknown: '未核实',
460
+ priceEdit: '修改', priceSave: '保存', priceCurrency: '币种',
461
+ secPricesHint: '填写你使用的模型单价。', peakNow: '当前处于{period}', offPeakNow: '当前处于{period}',
462
+ peakPeriod: '高峰期', offPeakPeriod: '空闲时段',
463
+ dragHint: '拖动排序', diagChecking: '余额接口:查询中…',
464
+ f_balanceDash: '余额 {symbol}-', balanceAt: '余额数据时间 {time}'
465
+ };
466
+ const t = (key, params) => {
467
+ let out = zh[key] !== undefined ? zh[key] : ('<' + key + '>');
468
+ if (params) out = out.replace(/\{(\w+)\}/g, (m, n) => (n in params ? String(params[n]) : m));
469
+ return out;
470
+ };
471
+ assert.strictEqual(api.detectLocale(t), 'zh', 'locale detection should resolve zh');
472
+
473
+ /* 出厂默认 = 全部段 + 截图顺序;下面所有渲染都用这一份 */
474
+ const FACTORY_ORDER = ['status', 'counts', 'cacheHit', 'tps', 'ttft', 'sessionTime', 'lastCost', 'cost', 'balance'];
475
+ /** sandbox realm 里的数组要转成宿主数组,否则 deepStrictEqual 会因原型不同而失败 */
476
+ const toHost = (arr) => Array.prototype.slice.call(arr);
477
+ assert.strictEqual(api.STORAGE_KEY, CONFIG_KEY, 'storage key 与验证脚本不一致');
478
+ assert.deepStrictEqual(toHost(api.SEGMENTS.map((s) => s.id)), FACTORY_ORDER, 'SEGMENTS 声明顺序应等于出厂顺序');
479
+ assert.deepStrictEqual(toHost(api.DEFAULT_SEGMENTS), FACTORY_ORDER, '出厂默认应是全部段且按截图顺序');
480
+ const MIGRATED_REST = FACTORY_ORDER.filter((id) => MESSY_SEGMENTS.indexOf(id) === -1);
481
+ assert.deepStrictEqual(toHost(api.snapshot().segments), MESSY_SEGMENTS.concat(MIGRATED_REST), '前置:旧配置迁移后段序 = 原顺序 + 补全的段');
482
+ assert.deepStrictEqual(toHost(api.snapshot().hidden), MIGRATED_REST, '前置:迁移把补进来的段标为未勾选');
483
+
484
+ const order = api.DEFAULT_SEGMENTS.slice();
485
+ const render = (src, segs) => (segs || order).map((id) => api.segmentText(id, api.segmentView(id, src, t), t));
486
+
487
+ /* --------------------------------------------------- 空会话:只有余额可查 */
488
+ const emptySrc = {
489
+ stats: undefined, usage: undefined, pressure: undefined,
490
+ sessionModel: undefined, sessionUsage: undefined, timeRange: undefined,
491
+ running: true, partial: null, runningCalls: [], lastAgentError: null,
492
+ timeline: undefined, now: Date.now(),
493
+ balance: { ok: true, total: '5.43', currency: 'CNY' },
494
+ turnUsage: null, currency: 'CNY'
495
+ };
496
+ const bar = render(emptySrc);
497
+ console.log('无数据底栏:', bar.join(' | '));
498
+
499
+ const allSegs = api.SEGMENTS.map((s) => s.id);
500
+ const emptyAll = render({ ...emptySrc, balance: undefined }, allSegs);
501
+ console.log('无数据全段:', emptyAll.join(' | '));
502
+
503
+ const flat = bar.concat(emptyAll);
504
+ assert.ok(!flat.some((x) => x.includes('–') || x.includes('—')), 'placeholder symbol still rendered');
505
+ assert.ok(!flat.some((x) => x.includes('暂无')), 'old placeholder wording still rendered');
506
+ assert.ok(bar[0] === '高峰' || bar[0] === '低谷', 'status segment shows period text, got: ' + bar[0]);
507
+ assert.ok(bar.includes('- 轮 - 步'), 'counts placeholder, got: ' + bar.join(' | '));
508
+ assert.ok(bar.includes('综合命中 - %'), 'cacheHit placeholder, got: ' + bar.join(' | '));
509
+ assert.ok(bar.includes('首字平均 - s'), 'ttft placeholder, got: ' + bar.join(' | '));
510
+ assert.ok(bar.includes('综合速度 -'), 'tps placeholder, got: ' + bar.join(' | '));
511
+ assert.ok(bar.includes('总用时 -m -s'), 'sessionTime placeholder, got: ' + bar.join(' | '));
512
+ /* 会话刚开跑(running)时本轮就该是 0.00;空闲又没数据才退回占位横杠 */
513
+ assert.ok(bar.includes('本轮 -'), 'lastCost shows a dash before the turn produces any call, got: ' + bar.join(' | '));
514
+ const idleBar = render(Object.assign({}, emptySrc, { running: false }));
515
+ /* 空闲又没数据时本轮也给 ¥0.00:底栏长度稳定,不会整段消失 */
516
+ assert.ok(idleBar.some((one) => one.includes('本轮 -')), 'lastCost shows dash when idle without data, got: ' + idleBar.join(' | '));
517
+ /* 总计从第一轮起就显示金额:没有可计价的调用时给 ¥0.00,不用占位横杠(底栏宽度也稳定) */
518
+ assert.ok(emptyAll.some((one) => one.includes('总计 -')), 'cost shows 0.00 without priced calls, got: ' + emptyAll.join(' | '));
519
+ /* 这份 src 没有 sessionModel:非 DeepSeek 会话里余额整段不出现,连占位符都不留 */
520
+ /* 非 DeepSeek 会话:余额段仍在栏里(余额 -),只是不给账户数字 */
521
+ assert.ok(emptyAll.some((one) => one.includes('余额 -')), 'balance stays in the bar for non-DeepSeek sessions, got: ' + emptyAll.join(' | '));
522
+ assert.ok(!emptyAll.some((x) => x.includes('tokens')), 'token 段已并入总计,不该再单独占一段:' + emptyAll.join(' | '));
523
+
524
+ /* ------------------------------------------------------------ 有数据:不变样 */
525
+ /* 时刻必须**钉死**,不能用 Date.now():金额同时取决于「用量」与「发生时刻是高峰还是空闲」,
526
+ deepseek-flash 空闲价是高峰价的一半。用当前时刻会让这条用例一天里有 8 小时失败
527
+ (实测:下午 14:48 跑得 ¥0.46,而期望写的是空闲价的 ¥0.23)。
528
+ 这里固定为北京时间周三 20:00(空闲时段),与期望值 ¥0.23 对应。
529
+ 2026-10-14 是周三;20:00 CST = 12:00 UTC。 */
530
+ const FIXED_NOW = Date.UTC(2026, 9, 14, 12, 0, 0);
531
+ const fullSrc = {
532
+ stats: { turns: 2, steps: 51, llmMs: 125000, toolMs: 45000, ttftMs: 92500, ttftSteps: 10, decodeMs: 13000, decodeTokens: 2963000 },
533
+ usage: { uncachedInputTokens: 29631, cacheReadTokens: 1900000, cacheWriteTokens: 0, outputTokens: 41007 },
534
+ pressure: { pressureTokens: 620000, contextWindow: 1000000 },
535
+ sessionModel: { provider: 'deepseek-official', model: 'deepseek-flash' },
536
+ sessionUsage: {
537
+ models: { 'deepseek-flash': { input: 29631, cacheRead: 1900000, cacheWrite: 0, output: 41007 } },
538
+ calls: [{ at: FIXED_NOW, model: 'deepseek-flash', input: 29631, cacheRead: 1900000, cacheWrite: 0, output: 41007 }],
539
+ current: null, last: null
540
+ },
541
+ running: true, partial: null, runningCalls: [], lastAgentError: null,
542
+ timeline: undefined, now: FIXED_NOW,
543
+ timeRange: { turns: 5400000, since: null, steps: 0, stepSince: null },
544
+ balance: { ok: true, total: '12.34', currency: 'CNY' },
545
+ turnUsage: { input: 29631, cacheRead: 1900000, cacheWrite: 0, output: 41007 },
546
+ currency: 'CNY'
547
+ };
548
+ const cacheHitPanelValues = (current, calls) => {
549
+ const view = api.segmentView('cacheHit', {
550
+ usage: { uncachedInputTokens: 100, cacheReadTokens: 0, cacheWriteTokens: 0 },
551
+ sessionUsage: { current: current, calls: calls },
552
+ subagent: null
553
+ }, t);
554
+ const panel = api.rowsPanel(view.tip, null, { current: null }, {
555
+ id: null, open: () => {}, back: () => {}, rowsPerColumn: 3
556
+ });
557
+ return collectByClass(panel, 'dsb-meter-value').map(textOf);
558
+ };
559
+ const unknownCacheCalls = [
560
+ { input: 100, cacheWrite: 0 },
561
+ { input: 100, cacheRead: null, cacheWrite: 0 },
562
+ { input: 100, cacheRead: 25, cacheWrite: 0 }
563
+ ];
564
+ [
565
+ { input: 100, cacheWrite: 0 },
566
+ { input: 100, cacheRead: undefined, cacheWrite: 0 },
567
+ { input: 100, cacheRead: null, cacheWrite: 0 }
568
+ ].forEach((current) => {
569
+ assert.deepStrictEqual(cacheHitPanelValues(current, unknownCacheCalls), ['-', '20.000%', '20.000%'],
570
+ '未上报的本轮缓存命中显示横杠,缺失/null 调用不参与极值');
571
+ });
572
+ assert.deepStrictEqual(cacheHitPanelValues(
573
+ { input: 100, cacheRead: 0, cacheWrite: 0 },
574
+ unknownCacheCalls.concat([{ input: 100, cacheRead: 0, cacheWrite: 0 }])
575
+ ), ['0.000%', '20.000%', '0.000%'], '真实 cacheRead=0 保留 0% 并纳入最低命中率');
576
+ console.log('缓存命中回归:undefined/null 显示横杠且不参与极值;真实 0 保留为 0.000%');
577
+
578
+ /* task-30:缓存字段没上报的样本不当 0% 命中 —— 极值只统计可信样本;真实 cacheRead=0 仍是真 0% */
579
+ assert.deepStrictEqual(cacheHitPanelValues(
580
+ { input: 100, cacheRead: 0, cacheWrite: 0 },
581
+ [
582
+ { input: 100, cacheWrite: 0 }, /* 缺 cacheRead → 不可信,跳过 */
583
+ { input: 100, cacheRead: '50', cacheWrite: 0 }, /* 非数字 → 跳过 */
584
+ { input: 0, cacheRead: 0, cacheWrite: 0 }, /* 空调用 → 跳过 */
585
+ { input: 100, cacheRead: 25, cacheWrite: 0 } /* 20%:唯一可信样本之外的真实高值 */
586
+ ]), ['0.000%', '20.000%', '20.000%'], '缺字段 / 非数字 / 空调用都不参与极值(不会被当成 0%)');
587
+ assert.deepStrictEqual(cacheHitPanelValues(
588
+ { input: 300, cacheRead: 100, cacheWrite: 0 },
589
+ [
590
+ { input: 100, cacheWrite: 0 },
591
+ { input: 100, cacheRead: 0, cacheWrite: 0 }, /* 真 0%:保留进最低值 */
592
+ { input: 100, cacheRead: 25, cacheWrite: 0 }
593
+ ]), ['25.000%', '20.000%', '0.000%'], '真实上报的 cacheRead=0 仍显示 0%(最低值),本轮 25%');
594
+ /* 平均口径一致:usage 里没有可信的 cacheReadTokens 时给横杠,不把旧数据当 0% */
595
+ const cacheHitAvgText = (usage) => api.segmentText('cacheHit', api.segmentView('cacheHit', {
596
+ usage: usage, sessionUsage: { current: null, calls: [] }, subagent: null
597
+ }, t), t);
598
+ assert.strictEqual(cacheHitAvgText({ uncachedInputTokens: 100, cacheWriteTokens: 0, outputTokens: 10 }), '综合命中 - %',
599
+ '缺 cacheReadTokens 的旧数据:平均命中率给横杠(不算 0%)');
600
+ assert.strictEqual(cacheHitAvgText({ uncachedInputTokens: 300, cacheReadTokens: 100, cacheWriteTokens: 0, outputTokens: 10 }), '综合命中 25.00%',
601
+ '有可信字段时平均命中率照常算(100/(300+100) = 25%)');
602
+
603
+
604
+ const fullBar = render(fullSrc, allSegs);
605
+ console.log('有数据全段:', fullBar.join(' | '));
606
+ assert.ok(!fullBar.some((x) => x.includes(' -')), 'placeholder leaked into data path');
607
+ assert.ok(fullBar.includes('2 轮 51 步'), 'counts value');
608
+ assert.ok(fullBar.includes('首字平均 9.3s'), 'ttft 按秒显示(92500/10 = 9250ms → 9.3s),got: ' + fullBar.join(' | '));
609
+ assert.ok(fullBar.includes('总用时 1h30m'), 'sessionTime switches to h/m, got: ' + fullBar.join(' | '));
610
+ /* 总用时不足一分钟:只给整数秒,不带小数点 */
611
+ const shortSrc = Object.assign({}, fullSrc, { timeRange: { turns: 40400, since: null, steps: 0, stepSince: null } });
612
+ const shortBar = render(shortSrc, allSegs);
613
+ assert.ok(shortBar.includes('总用时 40s'), 'sub-minute sessionTime shows whole seconds, got: ' + shortBar.join(' | '));
614
+ assert.ok(!/总用时 \d+\.\d+s/.test(shortBar.join(' | ')), 'sub-minute sessionTime has no decimal point, got: ' + shortBar.join(' | '));
615
+ assert.ok(/98\.46%/.test(fullBar.join(' | ')), 'cache percent, got: ' + fullBar.join(' | '));
616
+ assert.ok(/\d+t\/s/.test(fullBar.join(' | ')), 'throughput has no space before unit, got: ' + fullBar.join(' | '));
617
+ assert.ok(fullBar.includes('余额 ¥12.34'), 'balance value');
618
+ assert.ok(fullBar.includes('总计 ¥0.23'), 'session cost, got: ' + fullBar.join(' | '));
619
+
620
+ /* ---------------------------------------------------------------- 格式函数 */
621
+ assert.strictEqual(api.formatDuration(0), null, 'zero duration is null');
622
+ assert.strictEqual(api.formatDuration(4500), '5s', 'sub-minute rounds to whole seconds');
623
+ assert.strictEqual(api.formatDuration(27000), '27s', '27s');
624
+ assert.strictEqual(api.formatDuration(455000), '7m35s', '7m35s, no space');
625
+ assert.strictEqual(api.formatDuration(155000), '2m35s', '2m35s');
626
+ assert.strictEqual(api.formatSeconds(9250), '9.3', '9250ms → 9.3s(一位小数)');
627
+ assert.strictEqual(api.formatSeconds(1402.7), '1.4', '小数毫秒四舍五入到一位小数');
628
+ assert.strictEqual(api.formatSeconds(299), '0.3', '不足 0.5 秒也保留一位小数');
629
+ assert.strictEqual(api.formatSeconds(0), null, 'zero ttft is null');
630
+ assert.strictEqual(api.formatDuration(5400000), '1h30m', '1.5h -> 1h30m');
631
+ assert.strictEqual(api.formatDuration(3600000), '1h0m', 'exactly 1h');
632
+ assert.strictEqual(api.formatDuration(3599000), '59m59s', 'just under 1h');
633
+ assert.strictEqual(api.formatDuration(125000), '2m5s', '125s -> 2m5s');
634
+ assert.strictEqual(api.formatDuration(40400), '40s', '40.4s renders as 40s, no decimal');
635
+ assert.strictEqual(api.formatDuration(45500), '46s', 'rounds to the nearest second');
636
+ assert.strictEqual(api.formatThroughput(12345.6), '12346', 'throughput no k abbreviation');
637
+
638
+ /* ---------------------------------------------------- task-28 模型名宽容匹配 */
639
+ /* 会话里的模型名可能带 provider 前缀、分隔符也不一样:`Claude Opus 5-5` / `claude-opus-5-5` /
640
+ `remote-magpie/group/claude-opus-5.5` 都要命中同一个价格键。紧凑串必须完全相等才算命中。 */
641
+ const modelsBeforeMatch = JSON.parse(JSON.stringify(JSON.parse(store.get(CONFIG_KEY)).models));
642
+ const orderBeforeMatch = JSON.parse(JSON.stringify(api.snapshot().modelOrder));
643
+ {
644
+ const matchBook = {
645
+ 'claude-opus-5.5': { tiered: false, currency: 'USD', feeMultiplier: 0.5, peak: { input: 4, cacheRead: 0.2, cacheWrite: 5, output: 20 }, offPeak: null },
646
+ 'deepseek-v4-pro': { tiered: false, currency: 'CNY', peak: { input: 4, cacheRead: 0.1, cacheWrite: 0, output: 12 }, offPeak: null },
647
+ 'deepseek-flash': { tiered: true, currency: 'CNY', peak: { input: 2, cacheRead: 0.04, cacheWrite: 0, output: 8 }, offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 } }
648
+ };
649
+ api.setConfig({ models: matchBook, modelOrder: ['claude-opus-5.5', 'deepseek-v4-pro', 'deepseek-flash'] });
650
+ const oracle = api.priceOf('claude-opus-5.5');
651
+ assert.ok(oracle !== null, '前置:精确键能命中');
652
+ const samePrice = (one) => JSON.parse(JSON.stringify({ peak: one.peak, offPeak: one.offPeak }));
653
+ /* 拼接/前缀/分隔符变体都要命中同一价格(含费用倍率) */
654
+ ['Claude Opus 5-5', 'claude-opus-5-5', 'CLAUDE_OPUS_5.5', 'claude opus 5.5',
655
+ 'remote-magpie/group/claude-opus-5.5', 'Remote-Magpie/group/Claude Opus 5-5'].forEach((name) => {
656
+ const price = api.priceOf(name);
657
+ assert.ok(price !== null, '宽容匹配应命中:' + name);
658
+ assert.deepStrictEqual(samePrice(price), samePrice(oracle), '命中同一价格:' + name);
659
+ assert.strictEqual(price.feeMultiplier, 0.5, '费用倍率同样按条目取:' + name);
660
+ });
661
+ assert.strictEqual(api.pickPriceKey(matchBook, 'remote-magpie/group/claude-opus-5.5'), 'claude-opus-5.5',
662
+ '去 provider 前缀后与价格键紧凑串相等');
663
+ /* 不误配:紧凑串必须**完全相等**(仅前缀/分隔符差异可容忍) */
664
+ assert.strictEqual(api.priceOf('deepseek-v4'), null, 'deepseek-v4 不得命中 deepseek-v4-pro');
665
+ assert.notStrictEqual(api.compactModelKey('deepseek-v4'), api.compactModelKey('deepseek-v4-pro'), '紧凑串不相等(v4 ≠ v4pro)');
666
+ assert.strictEqual(api.priceOf('remote-magpie/group/deepseek-v4'), null, '带前缀的 v4 同样不命中 v4-pro');
667
+ assert.strictEqual(api.compactModelKey('Remote-Magpie/Group/Claude Opus 5-5'), 'claudeopus55', '紧凑串:去前缀 + 只留字母数字');
668
+ assert.strictEqual(api.compactModelKey('---'), '', '纯符号 → 空串(不参与匹配)');
669
+ assert.strictEqual(api.pickPriceKey({ '': { peak: { input: 1, cacheRead: 0, cacheWrite: 0, output: 0 } } }, '!!!'), null,
670
+ '纯符号模型名不会命中空键');
671
+ /* 当前会话模型带前缀:「总计」也要算得出钱(计价走同一套匹配) */
672
+ const prefixedCalls = [{ at: FIXED_NOW, model: 'remote-magpie/group/deepseek-flash', input: 29631, cacheRead: 1900000, cacheWrite: 0, output: 41007 }];
673
+ const prefixedSrc = Object.assign({}, fullSrc, {
674
+ sessionModel: { provider: 'remote-magpie', model: 'remote-magpie/group/deepseek-flash' },
675
+ sessionUsage: { models: {}, calls: prefixedCalls, current: null, last: null }
676
+ });
677
+ assert.ok(render(prefixedSrc, allSegs).some((one) => one.includes('总计 ¥0.23')),
678
+ '会话模型带 provider 前缀时「总计」仍按同一价格算(¥0.23)');
679
+ }
680
+ /* 收尾:恢复用例前的价格库,别污染后面的段 */
681
+ api.setConfig({ models: modelsBeforeMatch, modelOrder: orderBeforeMatch });
682
+
683
+ /* ------------------------------------------------------------ 余额异常分支 */
684
+ /* 余额分支要 DeepSeek 会话才渲染(非 DeepSeek 会话里余额整段不出现) */
685
+ const deepSeekSrc = { ...emptySrc, sessionModel: { provider: 'deepseek-official', model: 'deepseek-flash' } };
686
+ const midBar = render({ ...deepSeekSrc, balance: null }, allSegs);
687
+ console.log('余额查询中:', midBar.join(' | '));
688
+ assert.ok(midBar.includes('余额 -'), 'balance loading shows label + dash, got: ' + midBar.join(' | '));
689
+ const failBar = render({ ...deepSeekSrc, balance: { ok: false, reason: 'fetch-failed' } }, allSegs);
690
+ console.log('余额失败:', failBar.join(' | '));
691
+ assert.ok(failBar.includes('余额 -'), 'balance failure shows label + dash, got: ' + failBar.join(' | '));
692
+
693
+ /* ---------------------------------------------------- WorkBuddy 积分口径 */
694
+ /* 实测 2026-10-07:WorkBuddy 会话的余额是积分,不是钱(不能显示成「余额 ¥177」)。
695
+ 2026-10:宿主额外给 rewards(积分套餐)时,点开是「积分套餐」面板:每个套餐一行 + 一条已用进度条;
696
+ 没有 rewards(旧插件 / 查询中 / 失败)时保持原状 —— 不给 tip、点不开,不弹空气泡。 */
697
+ const wbSrc = { ...emptySrc, sessionModel: { provider: 'workbuddy-ai', model: 'deepseek-v4.1-flash-sg' } };
698
+ const wbBar = render({ ...wbSrc, balance: { ok: true, total: '177', currency: '', isCredits: true } }, allSegs);
699
+ console.log('WorkBuddy 积分:', wbBar.join(' | '));
700
+ assert.ok(wbBar.includes('余额 177'), '积分总数照常显示,got: ' + wbBar.join(' | '));
701
+ assert.ok(!wbBar.includes('¥177'), '积分不带货币符号(不能显示成 ¥177),got: ' + wbBar.join(' | '));
702
+ /* 没有 rewards(旧插件 / 宿主没给):仍然不给 tip。渲染处按 tip !== null 决定 className 与 onClick,
703
+ 没有 tip 就不是可点击项、点不出气泡、悬停也不弹。 */
704
+ const wbView = api.segmentView('balance', { ...wbSrc, balance: { ok: true, total: '177', currency: '', isCredits: true } }, t);
705
+ assert.strictEqual(wbView.tip, undefined, '没有 rewards 时不给气泡(没有可展开的内容,弹空气泡会误以为能点)');
706
+ /* 非空 rewards:给「积分套餐」气泡(credits 面板);值 = 已用/总数。
707
+ 夹具用宿主真实数据(used/total 是原始 number,可能带浮点尾数,客户端要格式化到两位小数去尾零)。
708
+ 顺序按 2.2.2 的三档规则:月度刷新包置顶 → 其余按到期时间升序 → 裂变包置底(本夹具没有裂变包)。 */
709
+ const REWARDS = [
710
+ { name: 'CodeBuddy个人体验版', used: 500, total: 500, expireAt: null, refreshAt: '2026-11-01', monthly: true },
711
+ { name: '拉新权益包', used: 552.42999936, total: 1500, expireAt: '2026-11-07', refreshAt: null, monthly: false },
712
+ { name: 'Bonus Pack', used: 12.389999979999999, total: 250, expireAt: '2026-10-26', monthly: false },
713
+ { name: 'Free Plan Subscription', used: 0, total: 100, refreshAt: '2026-11-01', monthly: true }
714
+ ];
715
+ const wbRewardView = api.segmentView('balance', {
716
+ ...wbSrc,
717
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: REWARDS }
718
+ }, t);
719
+ assert.strictEqual(wbRewardView.tip.kind, 'credits', '积分套餐用 credits 面板(每个套餐一行 + 一条进度条)');
720
+ assert.strictEqual(wbRewardView.tip.title, '积分套餐', '气泡标题走 tipCreditsTitle(中性词)');
721
+ assert.strictEqual(wbRewardView.tip.panel.totalText, '177', '面板右侧显示总积分');
722
+ assert.deepStrictEqual(Array.from(wbRewardView.tip.panel.rewards, (one) => ({ label: one.label, valueText: one.valueText })), [
723
+ { label: '个人体验版 · 11-01 刷新', valueText: '剩余 0 / 500' },
724
+ { label: 'Free Plan Subscription · 11-01 刷新', valueText: '剩余 100 / 100' },
725
+ { label: 'Bonus Pack · 10-26 到期', valueText: '剩余 237.61 / 250' },
726
+ { label: '拉新权益包 · 11-07 到期', valueText: '剩余 947.57 / 1500' }
727
+ ], '月度包显「· MM-DD 刷新」、一次性包显「· MM-DD 到期」;值两位小数去尾零;**月度包置顶、其余按到期升序**;包名保持上游原名(不翻译)');
728
+ /* 进度条比例 = used / total,夹在 0-100;0/100 的套餐不画进度段。
729
+ 索引跟着上面三档排序后的顺序走:0 个人体验版 / 1 Free Plan / 2 Bonus Pack / 3 拉新权益包 */
730
+ const percentOf = (at) => wbRewardView.tip.panel.rewards[at].percent;
731
+ assert.ok(Math.abs(percentOf(0) - 100) < 1e-9, '已用满 → 100%');
732
+ assert.strictEqual(percentOf(1), 0, '已用 0 → 0%(不画进度段)');
733
+ assert.ok(Math.abs(percentOf(2) - (12.389999979999999 / 250) * 100) < 1e-6, 'Bonus Pack 按 used/total 算比例');
734
+ assert.ok(Math.abs(percentOf(3) - (552.42999936 / 1500) * 100) < 1e-6, '拉新权益包按 used/total 算比例');
735
+ /* 渲染层:标题下先一条横杠(复用 .dsb-meter-divider),每个套餐一个块 = 一行 + 一条进度 */
736
+ const creditsTree = api.creditsPanel(wbRewardView.tip.panel, wbRewardView.tip.title, null, { current: null });
737
+ assert.strictEqual(collectByClass(creditsTree, 'dsb-meter-divider').length, 1, '积分套餐气泡标题下有一条横杠');
738
+ const creditsChildren = creditsTree.children || [];
739
+ assert.strictEqual(String(creditsChildren[0].props.className), 'dsb-meter-head', '第一块是标题行');
740
+ assert.strictEqual(String(creditsChildren[1].props.className), 'dsb-meter-divider', '标题行后紧跟横杠');
741
+ assert.ok(String(creditsChildren[2].props.className).indexOf('dsb-credits-list') !== -1, '横杠后才是套餐列表');
742
+ assert.strictEqual(collectByClass(creditsTree, 'dsb-credits-list').length, 1, '列表容器挂 dsb-credits-list(带滚动上限)');
743
+ assert.strictEqual(collectByClass(creditsTree, 'dsb-credit').length, 4, '每个套餐一个块');
744
+ const creditRowNodes = collectByClass(creditsTree, 'dsb-meter-row');
745
+ assert.strictEqual(creditRowNodes.length, 4, '每个套餐一行(包名/备注 + 已用/总量)');
746
+ assert.deepStrictEqual(Array.from(creditRowNodes, (row) => textOf(collectByClass(row, 'dsb-meter-name')[0])),
747
+ ['个人体验版 · 11-01 刷新', 'Free Plan Subscription · 11-01 刷新', 'Bonus Pack · 10-26 到期', '拉新权益包 · 11-07 到期'],
748
+ '行首是包名 + 备注;月度包置顶、其余按到期升序;包名保持上游原名(不翻译)');
749
+ assert.deepStrictEqual(Array.from(creditRowNodes, (row) => textOf(collectByClass(row, 'dsb-meter-value')[0])),
750
+ ['剩余 0 / 500', '剩余 100 / 100', '剩余 237.61 / 250', '剩余 947.57 / 1500'], '行尾是剩余 / 总量');
751
+ /* 进度方向:**灰 = 剩余、从左边起;透明 = 已用、在右**(与余额配额条同一套语义)。
752
+ 用户拍板原话「灰条从左边起」—— 灰条长度 = 剩余额度,越长剩得越多,从左读起一眼就看到。
753
+ 实现只推「宽 > 0」的段(`if (used < 100)` 推灰、`if (used > 0)` 推透明),所以:
754
+ used=0 → 1 段(整条灰 100%,灰代表"剩余")
755
+ 0<used<100 → 2 段(灰剩余 + 透明已用)
756
+ used=100 → 1 段(整条透明,只剩轨道底色)
757
+ 注意 used=100 是**1 段透明**、不是 0 段。 */
758
+ assert.strictEqual(collectByClass(creditsTree, 'dsb-bar').length, 4, '每个套餐都有进度条(0% 也画轨道)');
759
+ const creditSegs = collectByClass(creditsTree, 'dsb-bar-seg');
760
+ const usedPct = (value, total) => (value / total) * 100;
761
+ const pct1000 = (n) => Math.round(n * 1000) / 1000;
762
+ /* 段序跟着上面三档排序后的顺序走:0 个人体验版(100%) / 1 Free Plan(0%) / 2 Bonus / 3 拉新 */
763
+ const expectSegs = [
764
+ { width: 100, color: 'transparent' }, /* 100%:整条透明 */
765
+ { width: 100, color: api.BALANCE_COLORS.topUp }, /* 0%:整条灰 */
766
+ { width: 100 - usedPct(12.389999979999999, 250), color: api.BALANCE_COLORS.topUp }, /* Bonus:剩余(左、灰) */
767
+ { width: usedPct(12.389999979999999, 250), color: 'transparent' }, /* Bonus:已用(右、透明) */
768
+ { width: 100 - usedPct(552.42999936, 1500), color: api.BALANCE_COLORS.topUp }, /* 拉新:剩余(左、灰) */
769
+ { width: usedPct(552.42999936, 1500), color: 'transparent' } /* 拉新:已用(右、透明) */
770
+ ];
771
+ assert.strictEqual(creditSegs.length, expectSegs.length,
772
+ '100% 段 1 段(透明)+ 0% 段 1 段(灰)+ 两个部分套餐各 2 段(灰剩余 + 透明已用)= 6 段');
773
+ assert.deepStrictEqual(Array.from(creditSegs, (one) => one.props.style.backgroundColor),
774
+ expectSegs.map((one) => one.color), '剩余段用余额灰(BALANCE_COLORS.topUp)、已用段透明');
775
+ assert.deepStrictEqual(Array.from(creditSegs, (one) => pct1000(parseFloat(one.props.style.width))),
776
+ expectSegs.map((one) => pct1000(one.width)), '前段宽 = 100 - used%(灰、在最左端)、后段宽 = used%(透明、在右)');
777
+ /* 0% 的套餐(排序后在第 2 位):有轨道、**一段整条灰**(用掉 0 ⇒ 剩余 100%) */
778
+ const zeroCredit = collectByClass(creditsTree, 'dsb-credit')[1];
779
+ assert.strictEqual(collectByClass(zeroCredit, 'dsb-bar').length, 1, '0% 套餐有进度条轨道');
780
+ const zeroSegs = collectByClass(zeroCredit, 'dsb-bar-seg');
781
+ assert.strictEqual(zeroSegs.length, 1, '0% 套餐有 1 段填充(整条灰 = 剩余 100%),不再是空轨道');
782
+ assert.strictEqual(zeroSegs[0].props.style.backgroundColor, api.BALANCE_COLORS.topUp, '那一段是灰');
783
+ assert.strictEqual(pct1000(parseFloat(zeroSegs[0].props.style.width)), 100, '那一段占满整条');
784
+ /* 100% 的套餐(第 1 位):1 段透明 —— 全用完了,没有"剩余"可涂色 */
785
+ const fullCredit = collectByClass(creditsTree, 'dsb-credit')[0];
786
+ const fullSegs = collectByClass(fullCredit, 'dsb-bar-seg');
787
+ assert.strictEqual(fullSegs.length, 1, '100% 套餐有 1 段(透明):实现只推宽 > 0 的段');
788
+ assert.strictEqual(fullSegs[0].props.style.backgroundColor, 'transparent', '那一段透明(整条只剩轨道底色)');
789
+ /* 14 条套餐:列表容器仍是同一个滚动类(CSS 有半屏高度上限),条数照常 */
790
+ const manyRewards = [];
791
+ for (let i = 0; i < 14; i += 1) manyRewards.push({ name: '套餐' + (i + 1), used: i, total: 100, monthly: false });
792
+ const wbMany = api.segmentView('balance', {
793
+ ...wbSrc,
794
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: manyRewards }
795
+ }, t);
796
+ const manyTree = api.creditsPanel(wbMany.tip.panel, wbMany.tip.title, null, { current: null });
797
+ assert.strictEqual(collectByClass(manyTree, 'dsb-credit').length, 14, '14 条套餐都渲染');
798
+ assert.strictEqual(collectByClass(manyTree, 'dsb-credits-list').length, 1, '14 条时仍用带滚动的列表容器(不撑破屏幕)');
799
+
800
+ /* 构造夹具(1 月度 + 1 拉新 + 11 裂变 + 1 Bonus,用于稳定断言;真机 live 是 12 裂变、无 Bonus):
801
+ 公共前缀剥离 + 相邻同名聚合 */
802
+ const realRewards = [
803
+ { name: 'CodeBuddy个人体验版', used: 500, total: 500, expireAt: null, refreshAt: '2026-11-01', monthly: true },
804
+ { name: 'CodeBuddy个人版拉新权益包', used: 552.43, total: 1500, expireAt: '2026-11-07', monthly: false }
805
+ ];
806
+ for (let i = 0; i < 11; i += 1) {
807
+ realRewards.push({
808
+ name: 'CodeBuddy个人版国内运营裂变包',
809
+ used: 0,
810
+ total: 100,
811
+ /* 故意把第一条的到期日放晚:合并后应显示**最近**的 11-07,而不是 12-01 或区间 */
812
+ expireAt: i === 0 ? '2026-12-01' : '2026-11-07',
813
+ monthly: false
814
+ });
815
+ }
816
+ realRewards.push({ name: 'Bonus Pack', used: 12.39, total: 250, expireAt: '2026-10-26', monthly: false });
817
+ const wbReal = api.segmentView('balance', {
818
+ ...wbSrc,
819
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: realRewards }
820
+ }, t);
821
+ const realRows = Array.from(wbReal.tip.panel.rewards);
822
+ assert.deepStrictEqual(realRows.map((one) => one.label), [
823
+ '个人体验版 · 11-01 刷新',
824
+ 'Bonus Pack · 10-26 到期',
825
+ '拉新权益包 · 11-07 到期',
826
+ '运营裂变包×11 · 11-07 到期(最近)'
827
+ ], '14 条真实数据 → 剥前缀后 4 行;**月度包置顶、裂变包置底、其余按到期升序**;聚合行带 ×11 且日期标「(最近)」');
828
+ assert.deepStrictEqual(realRows.map((one) => one.count), [1, 1, 1, 11], '聚合分组记录原始套餐数量');
829
+ assert.ok(realRows[0].label.indexOf('×') === -1 && realRows[0].label.indexOf('(最近)') === -1, '非聚合行不带 ×N / (最近)');
830
+ assert.ok(realRows[1].label.indexOf('×') === -1 && realRows[1].label.indexOf('(最近)') === -1, '非聚合行不带 ×N / (最近)');
831
+ assert.deepStrictEqual(realRows.map((one) => one.valueText), [
832
+ '剩余 0 / 500', '剩余 237.61 / 250', '剩余 947.57 / 1500', '剩余 1100 / 1100'
833
+ ], '相邻同名裂变包 used/total 相加(0/1100)');
834
+ assert.strictEqual(realRows[3].percent, 0, '裂变包合计已用 0 → percent 0(画空轨道)');
835
+ assert.deepStrictEqual(realRows.map((one) => one.name), ['个人体验版', 'Bonus Pack', '拉新权益包', '运营裂变包'],
836
+ '前缀按顺序剥、只剥开头:CodeBuddy → 个人版 → 国内;没有前缀的包名原样保留');
837
+ /* 单条不聚合;不相邻同名不合并(顺序按首次出现位置) */
838
+ const creditRowsOf = (rewards) => Array.from(api.segmentView('balance', {
839
+ ...wbSrc,
840
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: rewards }
841
+ }, t).tip.panel.rewards);
842
+ assert.strictEqual(creditRowsOf([{ name: '单独包', used: 1, total: 2, monthly: false }]).length, 1, '单条不聚合');
843
+ assert.deepStrictEqual(creditRowsOf([
844
+ { name: '同名包', used: 1, total: 10, monthly: false },
845
+ { name: '其它包', used: 2, total: 10, monthly: false },
846
+ { name: '同名包', used: 3, total: 10, monthly: false }
847
+ ]).map((one) => one.name), ['同名包', '其它包', '同名包'], '不相邻的同名包不合并');
848
+ /* 前缀剥离边界:无前缀原样、纯前缀剥空保留原名、可连续剥、大小写不敏感;
849
+ 关键:**不查任何映射表** —— 新包名来了也原样显示,不会因为表里没有而漏翻 */
850
+ assert.deepStrictEqual(creditRowsOf([{ name: 'Bonus Pack', used: 0, total: 1, monthly: false }]).map((one) => one.name),
851
+ ['Bonus Pack'], '国际站英文包名保持原名(不翻译成中文)');
852
+ assert.deepStrictEqual(creditRowsOf([{ name: 'Launch Bonus', used: 0, total: 1, monthly: false }]).map((one) => one.name),
853
+ ['Launch Bonus'], '上游新增的包名(映射表里从来没有过)原样显示,不依赖任何映射表');
854
+ assert.deepStrictEqual(creditRowsOf([{ name: 'CodeBuddy', used: 0, total: 1, monthly: false }]).map((one) => one.name),
855
+ ['CodeBuddy'], '纯前缀剥完为空 → 保留原名');
856
+ assert.deepStrictEqual(creditRowsOf([{ name: 'CodeBuddy个人版国内运营包', used: 0, total: 1, monthly: false }]).map((one) => one.name),
857
+ ['运营包'], '多层前缀可连续剥(CodeBuddy → 个人版 → 国内)');
858
+ assert.deepStrictEqual(creditRowsOf([{ name: 'codebuddy个人版体验包', used: 0, total: 1, monthly: false }]).map((one) => one.name),
859
+ ['体验包'], 'CodeBuddy 前缀大小写不敏感');
860
+ /* 月度包聚合:刷新日期同样取最近一个,并标「(最近)」 */
861
+ assert.deepStrictEqual(creditRowsOf([
862
+ { name: '月度包', used: 1, total: 10, monthly: true, refreshAt: '2026-12-01' },
863
+ { name: '月度包', used: 2, total: 10, monthly: true, refreshAt: '2026-11-01' }
864
+ ]).map((one) => ({ label: one.label, valueText: one.valueText })), [
865
+ { label: '月度包×2 · 11-01 刷新(最近)', valueText: '剩余 17 / 20' }
866
+ ], '月度聚合:刷新日期取最近、带 (最近)、数值合计');
867
+ /* 聚合行下钻:×N 行可点 → 子视图用同样的套餐块(一行 + 进度条)竖排列出原始包,点标题返回 */
868
+ const realTree = api.creditsPanel(wbReal.tip.panel, wbReal.tip.title, null, { current: null }, { id: null, open: () => {}, back: () => {} });
869
+ assert.strictEqual(collectByClass(realTree, 'dsb-credit').length, 4, '根视图 4 个套餐块');
870
+ const clickRows = collectByClass(realTree, 'dsb-meter-row-plain');
871
+ assert.strictEqual(clickRows.length, 1, '只有聚合行(×11)可点');
872
+ assert.ok(textOf(clickRows[0]).indexOf('运营裂变包×11') !== -1, '可点的是聚合行');
873
+ /* 聚合行用独立修饰类:只有 cursor:pointer,不带 .dsb-meter-row-click(那个有悬停灰底) */
874
+ assert.strictEqual(String(clickRows[0].props.className).indexOf('dsb-meter-row-click'), -1,
875
+ '聚合行不挂 .dsb-meter-row-click(不要悬停灰底)');
876
+ assert.strictEqual(collectByClass(realTree, 'dsb-meter-row-click').length, 0, '积分面板里没有任何带灰底胶囊的行');
877
+ let openedCredit = null;
878
+ const captureTree = api.creditsPanel(wbReal.tip.panel, wbReal.tip.title, null, { current: null }, {
879
+ id: null,
880
+ open: (index) => { openedCredit = index; },
881
+ back: () => {}
882
+ });
883
+ collectByClass(captureTree, 'dsb-meter-row-plain')[0].props.onClick({ stopPropagation() {} });
884
+ assert.strictEqual(openedCredit, 3, '点聚合行打开第 3 组(裂变包)的明细 —— 排序后裂变包在最后');
885
+ let backCalls = 0;
886
+ const openTree = api.creditsPanel(wbReal.tip.panel, wbReal.tip.title, null, { current: null }, {
887
+ id: 3,
888
+ open: () => {},
889
+ back: () => { backCalls += 1; }
890
+ });
891
+ /* 子视图与主面板同一套套餐块:每个原始包一块 = 一行 + 一条进度,竖排单列 */
892
+ assert.strictEqual(collectByClass(openTree, 'dsb-credit').length, 11, '子视图每个原始包一个套餐块');
893
+ assert.strictEqual(collectByClass(openTree, 'dsb-bar').length, 11, '每个块都有自己的进度条(0% 也画空轨道)');
894
+ assert.strictEqual(collectByClass(openTree, 'dsb-meter-cols').length, 0, '子视图竖排单列,不分列');
895
+ assert.strictEqual(collectByClass(openTree, 'dsb-credits-list').length, 1, '子视图复用带滚动上限的列表容器');
896
+ assert.strictEqual(textOf(collectByClass(openTree, 'dsb-meter-headline')[0]), '运营裂变包×11',
897
+ '子视图标题 = 聚合行名字 + 数量(×N)');
898
+ /* 下钻标题右侧 = 该组剩余积分(total - used,动态),不是全局总积分 */
899
+ assert.strictEqual(collectByClass(openTree, 'dsb-meter-figures').length, 1, '子视图标题右侧显示该组剩余积分');
900
+ assert.strictEqual(textOf(collectByClass(openTree, 'dsb-meter-figures')[0]), '1100',
901
+ '11 个包各 100、已用 0 → 该组剩余 1100');
902
+ assert.strictEqual(wbReal.tip.panel.rewards[3].remaining, 1100, '分组数据带 remaining = total - used');
903
+ assert.strictEqual(wbReal.tip.panel.rewards[3].remainingText, '1100', '分组数据带 remainingText');
904
+ /* 主面板 head 的全局总积分保持不变 */
905
+ assert.strictEqual(textOf(collectByClass(creditsTree, 'dsb-meter-figures')[0]), '177', '主面板右侧仍是全局总积分 177');
906
+ assert.strictEqual(collectByClass(openTree, 'dsb-meter-back').length, 1, '标题变成返回入口');
907
+ const subRows = collectByClass(openTree, 'dsb-meter-row');
908
+ assert.strictEqual(subRows.length, 11, '11 个原始包各一行');
909
+ assert.strictEqual(collectByClass(subRows[0], 'dsb-meter-row-plain').length, 0, '明细行本身不可再点');
910
+ assert.strictEqual(textOf(collectByClass(subRows[0], 'dsb-meter-name')[0]), '运营裂变包 · 12-01 到期', '明细行显示该包自己的日期');
911
+ assert.strictEqual(textOf(collectByClass(subRows[1], 'dsb-meter-name')[0]), '运营裂变包 · 11-07 到期', '不同到期日的包各显各的');
912
+ assert.deepStrictEqual(Array.from(subRows, (row) => textOf(collectByClass(row, 'dsb-meter-value')[0])),
913
+ new Array(11).fill('剩余 100 / 100'), '明细值是该包真实值,不合计');
914
+ /* 0% 的明细块:有轨道 + **一段整条灰**(灰 = 剩余;用掉 0 ⇒ 剩余 100%)。
915
+ 与主面板那套语义一致(见上面「灰 = 剩余、贴右」那段)。 */
916
+ const subZero = collectByClass(openTree, 'dsb-credit')[0];
917
+ assert.strictEqual(collectByClass(subZero, 'dsb-bar').length, 1, '明细块有进度条轨道');
918
+ const subZeroSegs = collectByClass(subZero, 'dsb-bar-seg');
919
+ assert.strictEqual(subZeroSegs.length, 1, '0% 明细块有 1 段填充(整条灰 = 剩余 100%),不再是空轨道');
920
+ assert.strictEqual(subZeroSegs[0].props.style.backgroundColor, api.BALANCE_COLORS.topUp,
921
+ '那一段是灰(BALANCE_COLORS.topUp,与余额配额条同色)');
922
+ assert.strictEqual(pct1000(parseFloat(subZeroSegs[0].props.style.width)), 100, '那一段占满整条');
923
+ /* 分组保留原始成员明细:raw 名、自己的日期备注、真实 used/total */
924
+ const mergedItems = wbReal.tip.panel.rewards[3].items;
925
+ assert.strictEqual(mergedItems.length, 11, '聚合组保留 11 个原始成员');
926
+ assert.strictEqual(mergedItems[0].name, 'CodeBuddy个人版国内运营裂变包', '明细里保留原始包名');
927
+ assert.deepStrictEqual(Array.from(mergedItems, (one) => one.used), new Array(11).fill(0), '明细 used 是各自真实值');
928
+ collectByClass(openTree, 'dsb-meter-back')[0].props.onClick({ stopPropagation() {} });
929
+ assert.strictEqual(backCalls, 1, '点标题返回套餐列表');
930
+ /* 剩余积分随用量动态计算:两组同名包 total 100+500、used 1+2=3 → 该组剩余 597 */
931
+ const usedWrap = api.segmentView('balance', {
932
+ ...wbSrc,
933
+ balance: {
934
+ ok: true, total: '177', currency: '', isCredits: true,
935
+ rewards: [
936
+ { name: '剩余包', used: 1, total: 100, monthly: false },
937
+ { name: '剩余包', used: 2, total: 500, monthly: false }
938
+ ]
939
+ }
940
+ }, t);
941
+ const usedGroup = usedWrap.tip.panel.rewards[0];
942
+ assert.strictEqual(usedGroup.count, 2, '两组合并成一组');
943
+ assert.strictEqual(usedGroup.used, 3, '已用合计 3');
944
+ assert.strictEqual(usedGroup.total, 600, '总容量合计 600');
945
+ assert.strictEqual(usedGroup.remaining, 597, '剩余 = 600 - 3');
946
+ assert.strictEqual(usedGroup.remainingText, '597', '剩余文本用 formatCredits');
947
+ assert.strictEqual(usedGroup.valueText, '剩余 597 / 600', '行上显示剩余 / 总量(用户要求:不显示已用)');
948
+ const usedOpen = api.creditsPanel(usedWrap.tip.panel, usedWrap.tip.title, null, { current: null }, {
949
+ id: 0, open: () => {}, back: () => {}
950
+ });
951
+ assert.strictEqual(textOf(collectByClass(usedOpen, 'dsb-meter-figures')[0]), '597',
952
+ '下钻标题右侧 = 该组剩余 597(不显示总容量 600、也不是全局 177)');
953
+ assert.deepStrictEqual(Array.from(collectByClass(usedOpen, 'dsb-meter-value'), (one) => textOf(one)),
954
+ ['剩余 99 / 100', '剩余 498 / 500'], '明细仍是各自真实值');
955
+ /* 月度包缺 refreshAt:退回「(每月刷新)」;非月度包没有 expireAt 就不加备注 */
956
+ const wbMonthly = api.segmentView('balance', {
957
+ ...wbSrc,
958
+ balance: {
959
+ ok: true, total: '177', currency: '', isCredits: true,
960
+ rewards: [
961
+ { name: '无刷新日的月度包', used: 1, total: 2, monthly: true, refreshAt: null },
962
+ { name: '没有到期日的一次性包', used: 3, total: 4, monthly: false, expireAt: null }
963
+ ]
964
+ }
965
+ }, t);
966
+ assert.deepStrictEqual(Array.from(wbMonthly.tip.panel.rewards, (one) => one.label),
967
+ ['无刷新日的月度包(每月刷新)', '没有到期日的一次性包'], '月度缺 refreshAt 退回文字备注;一次性没到期日不加备注');
968
+ /* 字段缺失的包跳过;used/total 缺失按 0 处理,不显示半行怪数据 */
969
+ const wbPartial = api.segmentView('balance', {
970
+ ...wbSrc,
971
+ balance: {
972
+ ok: true, total: '177', currency: '', isCredits: true,
973
+ rewards: [null, { name: '' }, { name: '只写名字的包' }, { name: '缺数字的包', used: 5 }]
974
+ }
975
+ }, t);
976
+ assert.deepStrictEqual(Array.from(wbPartial.tip.panel.rewards, (one) => one.label), ['只写名字的包', '缺数字的包'], '无名字的包跳过,其余保留');
977
+ assert.deepStrictEqual(Array.from(wbPartial.tip.panel.rewards, (one) => one.valueText), ['剩余 0 / 0', '剩余 0 / 0'], '缺 used/total 按 0 显示;used=5 但 total=0 时剩余夹到 0(不出负数)');
978
+ assert.deepStrictEqual(Array.from(wbPartial.tip.panel.rewards, (one) => one.percent), [0, 0], 'total 为 0 时进度比例 0');
979
+ /* rewards 空数组:等同于没有 → 不给 tip(不弹空气泡) */
980
+ assert.strictEqual(api.segmentView('balance', {
981
+ ...wbSrc,
982
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: [] }
983
+ }, t).tip, undefined, 'rewards 为空数组时不给气泡');
984
+ /* ------------------------------------------------ 积分套餐排序(三档) */
985
+ /* 用户拍板:① 每月固定刷新的套餐永远第一行;② 裂变包永远最后;③ 其余按过期时间升序。
986
+ 关键约束:**先按原顺序聚合相邻同名包、最后才整体排序** —— 先排会把十几个裂变包
987
+ 按日期打散,聚合成「×N」就失效了。 */
988
+ assert.strictEqual(api.creditsSortGroup({ monthly: true }), 0, '月度刷新包归第 1 档(永远第一行)');
989
+ assert.strictEqual(api.creditsSortGroup({ monthly: false, name: '运营裂变包' }), 2, '裂变包归第 3 档(永远最后)');
990
+ assert.strictEqual(api.creditsSortGroup({ monthly: false, name: '拉新权益包' }), 1, '普通包归第 2 档(按到期时间排)');
991
+ assert.strictEqual(api.creditsSortGroup({ monthly: true, name: '月度裂变包' }), 0,
992
+ '月度优先于裂变:既是月度又是裂变时,月度那档赢(第一行位置不能被挤走)');
993
+ /* 三档同时出现:月度置顶、其余按到期升序、裂变置底(即使裂变包到期最早) */
994
+ assert.deepStrictEqual(creditRowsOf([
995
+ { name: '普通包晚', used: 0, total: 100, monthly: false, expireAt: '2026-12-01' },
996
+ { name: '运营裂变包', used: 0, total: 100, monthly: false, expireAt: '2026-10-01' },
997
+ { name: '普通包早', used: 0, total: 100, monthly: false, expireAt: '2026-10-26' },
998
+ { name: '月度包', used: 0, total: 100, monthly: true, refreshAt: '2026-11-01' }
999
+ ]).map((one) => one.name), ['月度包', '普通包早', '普通包晚', '运营裂变包'],
1000
+ '月度包置顶 → 其余按到期升序(10-26 在 12-01 前)→ 裂变包置底(即使它 10-01 最早到期)');
1001
+ assert.deepStrictEqual(creditRowsOf([
1002
+ { name: '运营裂变包', used: 0, total: 100, monthly: false, expireAt: '2026-01-01' },
1003
+ { name: '普通包', used: 0, total: 100, monthly: false, expireAt: '2026-12-31' }
1004
+ ]).map((one) => one.name), ['普通包', '运营裂变包'],
1005
+ '裂变包的可读性优先于日期:到期再早也排最后');
1006
+ /* 月度档内按刷新日升序;没有日期的排在有日期之后(不猜日期,也不插队) */
1007
+ assert.deepStrictEqual(creditRowsOf([
1008
+ { name: '月度B', used: 0, total: 100, monthly: true, refreshAt: '2026-12-01' },
1009
+ { name: '月度A', used: 0, total: 100, monthly: true, refreshAt: '2026-11-01' },
1010
+ { name: '月度无日期', used: 0, total: 100, monthly: true }
1011
+ ]).map((one) => one.name), ['月度A', '月度B', '月度无日期'],
1012
+ '月度档内按刷新日升序;没有日期的排最后');
1013
+ /* 排序稳定:同档同日期、或都缺日期时保持上游原顺序,界面不会每次刷新跳来跳去 */
1014
+ assert.deepStrictEqual(creditRowsOf([
1015
+ { name: '同B', used: 0, total: 100, monthly: false, expireAt: '2026-11-07' },
1016
+ { name: '同A', used: 0, total: 100, monthly: false, expireAt: '2026-11-07' }
1017
+ ]).map((one) => one.name), ['同B', '同A'], '到期日相同 → 保持上游原顺序');
1018
+ assert.deepStrictEqual(creditRowsOf([
1019
+ { name: '无日期B', used: 0, total: 100, monthly: false },
1020
+ { name: '无日期A', used: 0, total: 100, monthly: false }
1021
+ ]).map((one) => one.name), ['无日期B', '无日期A'], '都没有日期 → 保持上游原顺序');
1022
+ /* 聚合先于排序:11 条裂变包跨两个到期日,排序后仍只出现一行 */
1023
+ const crossDateSplit = [];
1024
+ for (let i = 0; i < 11; i += 1) {
1025
+ crossDateSplit.push({
1026
+ name: '运营裂变包', used: 0, total: 100, monthly: false,
1027
+ expireAt: i % 2 === 0 ? '2026-12-01' : '2026-11-07'
1028
+ });
1029
+ }
1030
+ const crossDateRows = creditRowsOf(crossDateSplit);
1031
+ assert.strictEqual(crossDateRows.length, 1, '11 条裂变包跨两个到期日 → 仍聚合成 1 行(先聚合后排序)');
1032
+ assert.strictEqual(crossDateRows[0].count, 11, '聚合行记录 11 条');
1033
+ assert.strictEqual(crossDateRows[0].label, '运营裂变包×11 · 11-07 到期(最近)',
1034
+ '聚合后取最近到期日 11-07 并标 (最近)');
1035
+ /* 排序函数是纯函数:返回新数组,不改入参 */
1036
+ const sortInput = [
1037
+ { name: '裂变包', monthly: false, expireAt: '2026-01-01' },
1038
+ { name: '月度包', monthly: true, refreshAt: '2026-12-01' }
1039
+ ];
1040
+ const sortSnapshot = sortInput.map((one) => one.name);
1041
+ const sortOutput = api.creditsSort(sortInput);
1042
+ assert.deepStrictEqual(sortInput.map((one) => one.name), sortSnapshot, 'creditsSort 不改入参顺序(返回新数组)');
1043
+ assert.deepStrictEqual(Array.from(sortOutput, (one) => one.name), ['月度包', '裂变包'], '返回的才是排好序的新数组');
1044
+ /* 英文文案:标题 / 月度刷新 / 到期 / 已用 都走英文词表 */
1045
+ const enBalance = {
1046
+ segBalance: 'Balance', f_balance: 'Balance {symbol}{amount}',
1047
+ f_balanceDash: 'Balance {symbol}-',
1048
+ tipCreditsTitle: 'Points packages', tipCreditsMonthly: ' (monthly)', tipCreditsRefresh: ' · refreshes {date}',
1049
+ tipCreditsExpire: ' · expires {date}', tipCreditsRefreshLatest: ' · refreshes {date} (nearest)',
1050
+ tipCreditsExpireLatest: ' · expires {date} (nearest)', tipCreditsLeft: '{left} / {total} left'
1051
+ };
1052
+ const tEnBalance = (key, params) => {
1053
+ let out = enBalance[key] !== undefined ? enBalance[key] : key;
1054
+ if (params) out = out.replace(/\{(\w+)\}/g, (m, n) => (n in params ? String(params[n]) : m));
1055
+ return out;
1056
+ };
1057
+ const wbEn = api.segmentView('balance', {
1058
+ ...wbSrc,
1059
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: REWARDS }
1060
+ }, tEnBalance);
1061
+ assert.strictEqual(wbEn.text, 'Balance 177', '英文界面积分总数不带货币符号');
1062
+ assert.strictEqual(wbEn.tip.title, 'Points packages', '英文标题');
1063
+ assert.deepStrictEqual(Array.from(wbEn.tip.panel.rewards, (one) => one.label), [
1064
+ /* 包名**不跟随界面语言**:上游给什么就显示什么(国内站是中文、国际站是英文),
1065
+ 只剥掉 CodeBuddy/个人版/国内 这些渠道前缀。所以英文界面里出现中文包名是预期行为。
1066
+ 顺序与中文界面同一套三档规则:月度包置顶 → 其余按到期升序 → 裂变包置底。 */
1067
+ '个人体验版 · refreshes 11-01',
1068
+ 'Free Plan Subscription · refreshes 11-01',
1069
+ 'Bonus Pack · expires 10-26',
1070
+ '拉新权益包 · expires 11-07'
1071
+ ], '英文月度「· refreshes MM-DD」/ 一次性「· expires MM-DD」;**月度包置顶、其余按到期升序**;包名保持上游原名(不翻译)');
1072
+ assert.deepStrictEqual(Array.from(wbEn.tip.panel.rewards, (one) => one.valueText), [
1073
+ '0 / 500 left', '100 / 100 left', '237.61 / 250 left', '947.57 / 1500 left'
1074
+ ], '英文「{left} / {total} left」,数字同样两位小数去尾零');
1075
+ /* 英文聚合行:×11 + (nearest) */
1076
+ const wbEnReal = api.segmentView('balance', {
1077
+ ...wbSrc,
1078
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: realRewards }
1079
+ }, tEnBalance);
1080
+ assert.deepStrictEqual(Array.from(wbEnReal.tip.panel.rewards, (one) => one.label), [
1081
+ '个人体验版 · refreshes 11-01',
1082
+ 'Bonus Pack · expires 10-26',
1083
+ '拉新权益包 · expires 11-07',
1084
+ '运营裂变包×11 · expires 11-07 (nearest)'
1085
+ ], '英文聚合行带 ×11 且日期标 (nearest);非聚合行不带;顺序同样月度置顶、裂变包置底');
1086
+ /* 失败态 / 查询中:也要按积分口径显示,别又冒出一个 ¥;没有 rewards 同样不给气泡 */
1087
+ const wbMid = render({ ...wbSrc, balance: null }, allSegs);
1088
+ assert.ok(wbMid.includes('余额 -') && !wbMid.includes('¥'), 'WorkBuddy 查询中也按积分口径(无 ¥),got: ' + wbMid.join(' | '));
1089
+ assert.strictEqual(api.segmentView('balance', { ...wbSrc, balance: null }, t).tip, undefined, '查询中也不给气泡');
1090
+ const wbFail = render({ ...wbSrc, balance: { ok: false, reason: 'no-credits' } }, allSegs);
1091
+ assert.ok(wbFail.includes('余额 -') && !wbFail.includes('¥'), 'WorkBuddy 失败态同样无 ¥,got: ' + wbFail.join(' | '));
1092
+ assert.strictEqual(api.segmentView('balance', { ...wbSrc, balance: { ok: false, reason: 'no-credits' } }, t).tip, undefined, '失败态也不给气泡');
1093
+ /* 非积分平台不受影响:DeepSeek 会话仍带 ¥,且气泡照旧 */
1094
+ assert.ok(fullBar.includes('余额 ¥12.34'), 'DeepSeek 等货币口径仍带 ¥');
1095
+ const dsView = api.segmentView('balance', { ...deepSeekSrc, balance: { ok: true, total: '12.34', currency: 'CNY' } }, t);
1096
+ assert.ok(dsView.tip !== undefined, 'DeepSeek 货币口径仍要有气泡');
1097
+ assert.ok(dsView.tip.rows.length > 0, '货币口径的气泡仍有构成行');
1098
+
1099
+ /* 积分包名**不做任何翻译**:上游给什么就显示什么,只剥渠道前缀。
1100
+ 理由(用户拍板):映射表必然过期 —— 国际站以后出 `Launch Bonus` 这种新包,
1101
+ 表里没覆盖到就漏翻,反而比不翻更糟。保持原名 + 剥前缀最不会错。
1102
+ 实测 region=cn 返回:CodeBuddy个人体验版 / CodeBuddy个人版拉新权益包 / CodeBuddy个人版国内运营裂变包。 */
1103
+ const enRowsOf = (rewards) => Array.from(api.segmentView('balance', {
1104
+ ...wbSrc,
1105
+ balance: { ok: true, total: '177', currency: '', isCredits: true, rewards: rewards }
1106
+ }, tEnBalance).tip.panel.rewards);
1107
+ assert.deepStrictEqual(enRowsOf([
1108
+ { name: 'CodeBuddy个人体验版', used: 1, total: 10, monthly: false },
1109
+ { name: 'CodeBuddy个人版拉新权益包', used: 2, total: 10, monthly: false },
1110
+ { name: 'CodeBuddy个人版国内运营裂变包', used: 3, total: 10, monthly: false }
1111
+ ]).map((one) => one.name), ['个人体验版', '拉新权益包', '运营裂变包'],
1112
+ '英文界面:国内站中文包名剥前缀后**保持中文原名**(不翻成英文)');
1113
+ assert.deepStrictEqual(enRowsOf([
1114
+ { name: 'CodeBuddy个人版国内运营裂变包', used: 1, total: 10, monthly: false },
1115
+ { name: 'CodeBuddy个人版国内运营裂变包', used: 1, total: 10, monthly: false }
1116
+ ]).map((one) => ({ name: one.name, count: one.count })), [{ name: '运营裂变包', count: 2 }],
1117
+ '英文界面:相邻同名包按**剥前缀后**的名字聚合(×N 由 creditsLabel 拼,不在这里)');
1118
+ assert.deepStrictEqual(enRowsOf([{ name: 'Bonus Pack', used: 0, total: 1, monthly: false }]).map((one) => one.name),
1119
+ ['Bonus Pack'], '英文界面:国际站英文包名保持原名');
1120
+ assert.deepStrictEqual(enRowsOf([{ name: 'Launch Bonus', used: 0, total: 1, monthly: false }]).map((one) => one.name),
1121
+ ['Launch Bonus'], '英文界面:上游新增包名原样显示(不靠映射表兜底)');
1122
+ assert.deepStrictEqual(enRowsOf([{ name: '我的CodeBuddy包', used: 0, total: 1, monthly: false }]).map((one) => one.name),
1123
+ ['我的CodeBuddy包'], '前缀出现在中间不剥(只剥开头)');
1124
+ assert.deepStrictEqual(creditRowsOf([{ name: 'Bonus Pack', used: 0, total: 1, monthly: false }]).map((one) => one.name),
1125
+ ['Bonus Pack'], '中文界面:国际站英文包名同样保持原名(不翻成中文)');
1126
+ console.log('积分包名不翻译:两个界面都保持上游原名,只剥渠道前缀');
1127
+
1128
+ /* 包名只做字符串切片、**不再查任何映射表** —— 所以 constructor / toString / __proto__
1129
+ 这类原型键也不会被当对象渲染(白屏风险随映射表一起消失了)。
1130
+ 这里仍钉住「返回值必须是字符串」,防止将来有人把查表逻辑加回来却忘了 hasOwnProperty。 */
1131
+ const PROTOTYPE_KEYS = ['constructor', 'toString', 'valueOf', 'hasOwnProperty', '__proto__'];
1132
+ PROTOTYPE_KEYS.forEach((key) => {
1133
+ const zhName = api.creditDisplayName(key);
1134
+ assert.strictEqual(typeof zhName, 'string',
1135
+ '包名「' + key + '」必须返回字符串(不查表,纯字符串处理),实际 ' + typeof zhName);
1136
+ assert.strictEqual(zhName, key, '原型键名没有前缀可剥,原样返回,实际 ' + zhName);
1137
+ const enName = api.creditDisplayName(key);
1138
+ assert.strictEqual(typeof enName, 'string', '包名「' + key + '」必须返回字符串(与界面语言无关)');
1139
+ assert.strictEqual(enName, key, '原型键名原样返回,实际 ' + enName);
1140
+ });
1141
+ /* 大小写不同的原型键同样安全(剥前缀时才做大小写不敏感比较,其余原样返回) */
1142
+ assert.strictEqual(typeof api.creditDisplayName('CONSTRUCTOR'), 'string',
1143
+ '大写原型键「CONSTRUCTOR」也返回字符串');
1144
+ assert.strictEqual(typeof api.creditDisplayName('TOSTRING'), 'string',
1145
+ '大写原型键「TOSTRING」也返回字符串');
1146
+ /* 正常包名不被原型键防护误伤:任意名字都原样返回(不翻译) */
1147
+ assert.strictEqual(api.creditDisplayName('Bonus Pack'), 'Bonus Pack', '正常英文包名原样返回');
1148
+ assert.strictEqual(api.creditDisplayName('bonus pack'), 'bonus pack', '大小写原样保留(不查表就没有归一化)');
1149
+ assert.strictEqual(api.creditDisplayName('BONUS PACK'), 'BONUS PACK', '全大写写法原样返回');
1150
+ assert.strictEqual(api.creditDisplayName('奖励包'), '奖励包', '中文包名原样返回(不再反向翻成 Bonus Pack)');
1151
+ assert.strictEqual(api.creditDisplayName('免费版订阅'), '免费版订阅',
1152
+ '中文包名原样返回(不再翻成 Free Plan Subscription)');
1153
+ console.log('积分包名:原型键 / 任意包名都返回字符串,不查映射表');
1154
+
1155
+ /* ------------------------------------------------------- 组件与设置页渲染 */
1156
+ function textOf(node) {
1157
+ if (node === null || node === undefined || node === false) return '';
1158
+ if (typeof node === 'string' || typeof node === 'number') return String(node);
1159
+ if (Array.isArray(node)) return node.map(textOf).join('');
1160
+ return textOf(node.children);
1161
+ }
1162
+ const noop = () => {};
1163
+ const props = { t, useProjection: () => undefined, useSession: () => undefined, useSessions: () => undefined, useChat: () => undefined, sessionId: 'verify-session' };
1164
+ const barHooks = makeHooks();
1165
+ const settingsHooks = makeHooks();
1166
+ const renderBar = () => withHooks(barHooks, () => api.StatusBar(props));
1167
+ /* 替身的位置每次渲染都从同一套几何重新开始:真实 DOM 的行本来就不动,
1168
+ 不重置的话「按下时量到的位置」和「下一次渲染量到的位置」会差出好几行。 */
1169
+ const renderSettings = () => {
1170
+ rowSeq = 0;
1171
+ return withHooks(settingsHooks, () => api.SettingsSection(props));
1172
+ };
1173
+ const rendered = textOf(renderBar());
1174
+ console.log('组件渲染:', rendered.replace(/\s+/g, ' ').trim());
1175
+ assert.ok(!rendered.includes('–') && !rendered.includes('—'), 'component still renders placeholder symbol');
1176
+ assert.ok(rendered.includes('- 轮 - 步') && rendered.includes('总用时 -m -s'), 'component placeholder template');
1177
+
1178
+ /* 接管官方状态栏:认自己的标记,不依赖官方组件的构建 hash(DSH 更新会换 hash,2.0.10 踩过) */
1179
+ assert.strictEqual(renderBar().props['data-dsb'], 'bar', '底栏根节点要带 data-dsb 排查标记');
1180
+ const sourceCss = code.slice(code.indexOf('\t\tconst CSS = ['), code.indexOf('].join("");'));
1181
+ assert.ok(sourceCss.includes('> *:not(.dsb-root):not(:has(.dsb-root))'),
1182
+ 'CSS 要同时判自身与后代,否则连自己的行一起藏掉(2.0.10 踩过)');
1183
+ assert.ok(!/\[class\*="/.test(sourceCss), 'CSS 不应再依赖官方组件的构建 hash 类名');
1184
+ console.log('官方状态栏:按 .dsb-root 认自己,隐藏其余');
1185
+
1186
+ const settings = textOf(renderSettings());
1187
+ assert.ok(settings.includes('数据字段'), 'settings section should render');
1188
+ assert.ok(settings.includes('按住拖动调整顺序'), 'settings hint should describe drag reorder');
1189
+ /* task-20:只有第三方平台区块标题带 x² 式上标角标,其他区块标题不带 */
1190
+ const sectionTitles = collectByClass(renderSettings(), 'dsb-sectitle');
1191
+ const badgedSectionTitles = sectionTitles
1192
+ .filter((one) => collectByClass(one, 'dsb-experimental-badge').length > 0);
1193
+ assert.strictEqual(badgedSectionTitles.length, 1, '只有第三方平台区块标题带上标角标');
1194
+ const platformTitle = badgedSectionTitles[0];
1195
+ assert.ok(textOf(platformTitle).includes('第三方平台'), '标题左侧是「第三方平台」');
1196
+ const platformBadge = collectByClass(platformTitle, 'dsb-experimental-badge');
1197
+ assert.strictEqual(platformBadge.length, 1, '标题旁有实验性角标');
1198
+ assert.strictEqual(platformBadge[0].type, 'sup', '角标是 <sup> 上标元素');
1199
+ assert.strictEqual(textOf(platformBadge[0]), '实验性功能', '角标文案是「实验性功能」');
1200
+ assert.ok(textOf(platformTitle).indexOf('第三方平台') < textOf(platformTitle).indexOf('实验性功能'), '角标紧跟在标题文字之后(上标位置)');
1201
+ const badgeCss = /\.dsb-settings \.dsb-experimental-badge\{([^}]*)\}/.exec(sourceCss);
1202
+ assert.ok(badgeCss !== null && /padding:1px 3px/.test(badgeCss[1]) && /font-size:6px/.test(badgeCss[1]) && /line-height:10px/.test(badgeCss[1]) && /vertical-align:super/.test(badgeCss[1]),
1203
+ '实验性功能胶囊保留胶囊造型(含 1px 3px 左右内边距),字号 6px、行高 10px 且仍为上标');
1204
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-platforms-title').length, 0, '旧的 flex 标题行类已删除');
1205
+ console.log('第三方平台标题:标题 + x² 式上标角标(其他区块标题无角标)');
1206
+ /* 需求 8:当前会话使用只显示模型名 —— 先取最后一个 "/" 之后的模型名,再走 displayModelName */
1207
+ const prefixedModelProps = Object.assign({}, props, {
1208
+ useProjection: (key) => (key === 'desktopStatusbarModel'
1209
+ ? { provider: 'remote-magpie', model: 'Remote-Magpie/group/deepseek-Flash' }
1210
+ : undefined)
1211
+ });
1212
+ const prefixedSettingsText = textOf(withHooks(settingsHooks, () => api.SettingsSection(prefixedModelProps)));
1213
+ const currentAt = prefixedSettingsText.indexOf('当前会话使用:');
1214
+ assert.ok(currentAt !== -1, '设置页应有当前会话使用那一行');
1215
+ assert.ok(prefixedSettingsText.slice(currentAt, currentAt + 32).indexOf('DeepSeek-Flash') !== -1,
1216
+ '设置页当前会话使用应只显示模型名(DeepSeek-Flash),实际:' + prefixedSettingsText.slice(currentAt, currentAt + 48));
1217
+ assert.strictEqual(prefixedSettingsText.indexOf('Remote-Magpie'), -1, '不应出现第三方平台前缀');
1218
+ assert.strictEqual(prefixedSettingsText.indexOf('remote-magpie'), -1, '不应出现 provider 前缀');
1219
+ console.log('当前会话使用:第三方平台前缀已去掉(Remote-Magpie/group/deepseek-Flash → DeepSeek-Flash)');
1220
+ assert.ok(!settings.includes('基础'), '设置页不再有「基础」区块');
1221
+ assert.ok(!settings.includes('启用状态栏') && !settings.includes('允许换行'), '启用状态栏 / 允许换行 两个开关已移除');
1222
+ /* task-19:编辑浮层底部自动滚入改成"按底边差值滚最近的可滚祖先 + 下一帧补一次",
1223
+ 不再用浏览器自带的 scrollIntoView(它只保证顶部对齐,且滚不动面板内部的可滚容器)。 */
1224
+ assert.ok(!code.includes('scrollIntoView('), '编辑浮层不该再用 scrollIntoView(task-19 已换实现)');
1225
+ assert.ok(code.includes('function revealBottom(node)'), '底部自动滚入要有独立实现');
1226
+ assert.ok(code.includes('scroller.scrollTop = (typeof scroller.scrollTop === "number" ? scroller.scrollTop : 0) + overflow'),
1227
+ '按"底边 + 余量 − 容器可视底边"的差值加 scrollTop');
1228
+ assert.ok(code.includes('if (overflow <= 0) return;'), '没被遮住时一动不动(不平白往上滚)');
1229
+ assert.ok(code.includes('window.requestAnimationFrame(retry)'), '稳定后补滚一次走 rAF(不是定时器)');
1230
+ /* task-21/task-26/task-14:底边滚入统一成一个钩子 `useRevealBottom(ref, active, extraKey)`,**恰好两处调用**
1231
+ (价格编辑浮层 / 币种菜单);平台编辑区改用自定义 effect(platformRevealLenRef):首次打开 / 切换平台
1232
+ 直接返回不滚,只有同一平台 modelRows 增加才 revealBottom。平台模型下拉已改纯 CSS 行内绝对气泡,
1233
+ 不再走 JS 跟随;气泡、跟手浮层、悬停提示有意不接。 */
1234
+ const revealLines = code.split('\n').filter((one) => one.indexOf('useRevealBottom(') !== -1);
1235
+ assert.strictEqual(revealLines.length, 2,
1236
+ 'useRevealBottom 恰好两处调用(价格浮层 / 条目币种菜单),实际 ' + revealLines.length);
1237
+ assert.strictEqual((code.match(/const useRevealBottom = \(ref, active, extraKey\)/g) || []).length, 1,
1238
+ '只有一份实现(不要各写一份)');
1239
+ assert.ok(code.includes('useRevealBottom(editPopRef, editing !== null'), '第一处:价格编辑浮层(切卡也重滚,含新增自定义模型)');
1240
+ assert.ok(code.includes('useRevealBottom(currencyMenuRef, currencyOpen === true, null)'), '第二处:条目币种菜单');
1241
+ /* 平台编辑区不再接 useRevealBottom,改用 platformRevealLenRef 自定义 effect(task-14):
1242
+ 记录上次平台名 + 模型行数;首次打开 / 切换平台(prev 为空或平台名不同)直接返回不滚,
1243
+ 只有同一平台 modelRows 增加才 revealBottom(保留加模型行的自动露出)。 */
1244
+ assert.ok(!code.includes('useRevealBottom(platformEditRef'),
1245
+ '平台编辑区不该再走 useRevealBottom(task-14 已改成自定义 effect)');
1246
+ assert.ok(code.includes('const platformRevealLenRef = react.useRef(null)'),
1247
+ '平台编辑区用 platformRevealLenRef 记录上次平台名 + 模型行数');
1248
+ assert.ok(code.includes('platformRevealLenRef.current = { name: platformEditing, len: rows.length }'),
1249
+ '记录当前平台名与模型行数,供下次比较');
1250
+ assert.ok(code.includes('if (prev === null || prev.name !== platformEditing || rows.length <= prev.len) return undefined;'),
1251
+ '首次打开 / 切换平台(prev 为空或平台名不同)、以及行数未增加时直接返回,不滚动');
1252
+ assert.ok(code.includes('const retry = () => revealBottom(platformEditRef.current)'),
1253
+ '只有同一平台 modelRows 增加时才 revealBottom(保留加模型行的自动露出)');
1254
+ assert.ok(code.includes('[platformEditing, platformDraft === null ? null : platformDraft.modelRows.length]'),
1255
+ 'effect 依赖平台名与模型行数(打开 / 切换 / 加行都会重算判定)');
1256
+ const wiredRefs = ['editPopRef', 'currencyMenuRef'];
1257
+ revealLines.forEach((one) => {
1258
+ assert.ok(wiredRefs.some((ref) => one.indexOf(ref) !== -1),
1259
+ 'useRevealBottom 只允许接在价格浮层 / 币种菜单上,实际这行:' + one.trim());
1260
+ });
1261
+ ['dsb-tip', 'dsb-drag-card', 'dsb-star-tip'].forEach((cls) => {
1262
+ assert.ok(revealLines.every((one) => one.indexOf(cls) === -1),
1263
+ cls + ' 不该接 useRevealBottom(气泡向上展开、跟手浮层跟指针、悬停提示会抢用户操作)');
1264
+ });
1265
+ assert.strictEqual((code.match(/setInterval\(/g) || []).length, 2, '定时器仍只有两处(时钟 + 余额轮询)');
1266
+ assert.ok(code.includes('className: "dsb-select-menu", role: "listbox", ref: menuRef'),
1267
+ '币种菜单的 ref 挂在**菜单节点**上(不是那个按钮)');
1268
+ assert.ok(code.includes('currencySelect("__entrycur", draft, currencyOpen, setCurrencyOpen, currencyMenuRef'),
1269
+ '条目级选择器把菜单 ref 传进 currencySelect');
1270
+
1271
+ assert.ok(settings.includes('上下文占用'), '设置页要出现上下文占用开关');
1272
+
1273
+ /* ------------------------------------------- 出厂默认:点「恢复默认设置」的顺序与勾选 */
1274
+ /** 设置页里段标题的渲染顺序 */
1275
+ function segmentNames(tree) {
1276
+ const labels = FACTORY_ORDER.map((id) => zh[api.SEGMENTS.filter((s) => s.id === id)[0].label]);
1277
+ const names = [];
1278
+ (function walk(node) {
1279
+ if (node === null || node === undefined || typeof node !== 'object') return;
1280
+ if (Array.isArray(node)) { node.forEach(walk); return; }
1281
+ if (node.type === 'span' && node.props !== undefined && node.props.className === 'dsb-name') {
1282
+ const text = textOf(node);
1283
+ if (labels.indexOf(text) !== -1) names.push(text);
1284
+ }
1285
+ walk(node.children);
1286
+ })(tree);
1287
+ return names;
1288
+ }
1289
+ const factoryLabels = FACTORY_ORDER.map((id) => zh[api.SEGMENTS.filter((s) => s.id === id)[0].label]);
1290
+ assert.notDeepStrictEqual(segmentNames(renderSettings()), factoryLabels, '前置:重置前的设置页顺序应是乱的');
1291
+
1292
+ const resetBtn = (function find(node) {
1293
+ let found = null;
1294
+ (function walk(n) {
1295
+ if (found !== null || n === null || n === undefined || typeof n !== 'object') return;
1296
+ if (Array.isArray(n)) { n.forEach(walk); return; }
1297
+ if (n.type === 'button' && textOf(n) === t('reset')) { found = n; return; }
1298
+ walk(n.children);
1299
+ })(node);
1300
+ return found;
1301
+ })(renderSettings());
1302
+ assert.ok(resetBtn !== null, '设置页应有「恢复默认设置」按钮');
1303
+
1304
+ resetBtn.props.onClick();
1305
+ const saved = JSON.parse(store.get(api.STORAGE_KEY));
1306
+ assert.deepStrictEqual(saved.segments, FACTORY_ORDER, '恢复默认设置后应回到出厂顺序且全部勾选,实际 ' + JSON.stringify(saved.segments));
1307
+ assert.deepStrictEqual(saved.hidden, [], '恢复默认设置应清空未勾选标记');
1308
+ assert.strictEqual(saved.currency, 'CNY', '恢复默认设置应恢复**默认币种**(task-22 起它只是新增条目的默认值)');
1309
+ assert.strictEqual(saved.contextMeter, true, '恢复默认设置应恢复上下文占用开关');
1310
+ assert.deepStrictEqual(segmentNames(renderSettings()), factoryLabels, '恢复默认设置后设置页顺序应等于出厂顺序');
1311
+ console.log('恢复默认设置后:', saved.segments.join(' → '));
1312
+ /* task-10 起「恢复默认」会把官方目录 27 条全部加回;后面的价格卡用例继续按两条参考价基线跑,
1313
+ 这里把主 fixture 还原成迁移前的两条参考价(播种 / 找回的完整行为由后面的目录用例覆盖)。 */
1314
+ const referenceModels = {};
1315
+ Object.keys(api.DEFAULT_PRICES).forEach((name) => {
1316
+ const official = api.DEFAULT_PRICES[name];
1317
+ referenceModels[name] = {
1318
+ tiered: true,
1319
+ currency: 'CNY',
1320
+ peak: JSON.parse(JSON.stringify(official.peak)),
1321
+ offPeak: JSON.parse(JSON.stringify(official.offPeak))
1322
+ };
1323
+ });
1324
+ api.setConfig({ models: referenceModels, modelOrder: Object.keys(api.DEFAULT_PRICES) });
1325
+
1326
+ /* task-25:「恢复默认」**区分两类条目** —— 官方内置(键命中 `DEFAULT_PRICES`)回官方默认价(含被删掉的加回来),
1327
+ 用户自建(键不在官方表里)逐字段不变。fixture 故意:官方 flash 改乱值 + 切成 USD、官方 v4-pro **删掉**、
1328
+ 自建两条(一条含明确填的 0 与 null、都带自己的 currency)。 */
1329
+ {
1330
+ const store2 = new Map();
1331
+ const USER_MODELS = {
1332
+ 'deepseek-flash': {
1333
+ tiered: false,
1334
+ currency: 'USD',
1335
+ peak: { input: 99, cacheRead: 0, cacheWrite: 0, output: 8 },
1336
+ offPeak: { input: 0.02, cacheRead: 0.02, cacheWrite: 0, output: 0.1 }
1337
+ },
1338
+ 'my-own-model': {
1339
+ tiered: true,
1340
+ currency: 'USD',
1341
+ peak: { input: 9, cacheRead: 1, cacheWrite: 0, output: 20 },
1342
+ offPeak: { input: 4.5, cacheRead: 0.5, cacheWrite: 0, output: 10 }
1343
+ },
1344
+ 'zero-model': {
1345
+ tiered: false,
1346
+ currency: 'CNY',
1347
+ peak: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
1348
+ offPeak: { input: null, cacheRead: null, cacheWrite: null, output: null }
1349
+ }
1350
+ };
1351
+ store2.set(CONFIG_KEY, JSON.stringify({
1352
+ version: 5, priceVersion: api.PRICE_VERSION, enabled: true, wrap: false,
1353
+ segments: MESSY_SEGMENTS.slice(), hidden: ['counts'],
1354
+ /* `currency` 只是"新增条目的默认币种";官方顺序那个键**故意排在自建键后面**,验恢复默认会覆盖它 */
1355
+ currency: 'USD', contextMeter: false,
1356
+ modelOrder: ['zzz-first', 'my-own-model', 'deepseek-flash', 'zero-model'],
1357
+ models: USER_MODELS
1358
+ }));
1359
+ let captured2 = null;
1360
+ const window2 = Object.assign({}, fakeWindow, {
1361
+ opened: [],
1362
+ localStorage: {
1363
+ getItem: (k) => (store2.has(k) ? store2.get(k) : null),
1364
+ setItem: (k, v) => { store2.set(k, v); },
1365
+ removeItem: (k) => { store2.delete(k); }
1366
+ }
1367
+ });
1368
+ window2.__ModuleLoader__ = { load: (entry) => { captured2 = entry; } };
1369
+ const sandbox2 = {
1370
+ window: window2,
1371
+ document: {
1372
+ querySelector: () => null,
1373
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
1374
+ head: { appendChild() {} },
1375
+ addEventListener: () => {}, removeEventListener: () => {}
1376
+ },
1377
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
1378
+ setTimeout: () => 0, clearTimeout: () => {}
1379
+ };
1380
+ sandbox2.globalThis = sandbox2;
1381
+ vm.createContext(sandbox2);
1382
+ vm.runInContext(code, sandbox2, { filename: 'client.js' });
1383
+ const api2 = captured2.factory((name) => {
1384
+ if (name === 'react') return reactStub;
1385
+ throw new Error('unexpected require: ' + name);
1386
+ }).__test;
1387
+ const modelsInMemory = api2.snapshot().models; /* 加载后内存里那一份(可能被归一化过,所以拿它当基准) */
1388
+ const customKeys = ['my-own-model', 'zero-model'];
1389
+ const officialKeys = Object.keys(api2.DEFAULT_PRICES);
1390
+ assert.deepStrictEqual(Object.keys(modelsInMemory).sort(), ['deepseek-flash', 'my-own-model', 'zero-model'],
1391
+ '前置:内存里的价格库 = 用户那份(官方 v4-pro 已被删掉,且没被官方参考价合并回来)');
1392
+ /* 恢复默认后:官方键回官方表、自建键逐字段不变、官方键加回来、顺序 = 官方 + 自建 */
1393
+ for (const name of customKeys) {
1394
+ const one = modelsInMemory[name];
1395
+ assert.strictEqual(one.currency !== undefined && one.currency !== null, true,
1396
+ '前置:自建条目自带 currency(' + name + ')');
1397
+ }
1398
+ const officialBefore = JSON.parse(JSON.stringify(modelsInMemory['deepseek-flash']));
1399
+ /* 3.0.4 起:USD 条目显示值折成 CNY,原始 USD 值保存在 base 锚点。 */
1400
+ assert.strictEqual(officialBefore.base.peak.input, 99, '前置:官方 flash 的 USD 基准价仍是 99');
1401
+ assert.strictEqual(officialBefore.base.currency, 'USD', '前置:base 锚点保留 USD');
1402
+ assert.strictEqual(officialBefore.currency, 'CNY', '前置:官方 flash 显示值按 3.0.4 口径折成 CNY');
1403
+ assert.strictEqual(officialBefore.peak.input, Math.round(99 * api2.REFERENCE_RATE * 100) / 100, '前置:显示值 = 99 USD 折 CNY');
1404
+ const hooks2 = makeHooks();
1405
+ const resetBtn2 = (function find(node) {
1406
+ let found = null;
1407
+ (function walk(n) {
1408
+ if (found !== null || n === null || n === undefined || typeof n !== 'object') return;
1409
+ if (Array.isArray(n)) { n.forEach(walk); return; }
1410
+ if (n.type === 'button' && textOf(n) === t('reset')) { found = n; return; }
1411
+ walk(n.children);
1412
+ })(node);
1413
+ return found;
1414
+ })(withHooks(hooks2, () => api2.SettingsSection(props)));
1415
+ assert.ok(resetBtn2 !== null, '(独立沙箱)恢复默认按钮仍在');
1416
+ resetBtn2.props.onClick();
1417
+ const afterReset = JSON.parse(store2.get(CONFIG_KEY));
1418
+ assert.deepStrictEqual(afterReset.segments, FACTORY_ORDER, '界面配置仍要回到出厂顺序');
1419
+ assert.deepStrictEqual(afterReset.hidden, [], '界面配置仍要清空未勾选标记');
1420
+ assert.strictEqual(afterReset.currency, 'CNY', '界面配置仍要回到默认**币种**(task-22 起只是新增条目的默认值)');
1421
+ assert.strictEqual(afterReset.contextMeter, true, '界面配置仍要回到默认开关');
1422
+ /* task-25:官方键回官方默认值、自建键逐字段不变、被删的官方键加回来、顺序 = 官方 + 自建。
1423
+ vm 出来的对象原型与主域不同,deepStrictEqual 会因此失败 —— 两边都先 JSON 化。 */
1424
+ const plain = (value) => JSON.parse(JSON.stringify(value));
1425
+ const seededNames = OFFICIAL_NAMES.filter((name) => api2.DEFAULT_PRICES[name] === undefined);
1426
+ assert.deepStrictEqual(Object.keys(afterReset.models).sort(), officialKeys.concat(seededNames, customKeys).sort(),
1427
+ '恢复默认后价格库 = 官方键 + 官方目录其余模型 + 自建键(被删掉的官方 v4-pro 也加回来了)');
1428
+ /* ① 官方键:逐字段等于官方默认表(含 tiered / 两档 / 官方 0 与 null),币种回 CNY */
1429
+ for (const name of officialKeys) {
1430
+ assert.deepStrictEqual(plain(afterReset.models[name]),
1431
+ {
1432
+ tiered: true, currency: 'CNY',
1433
+ peak: plain(api2.DEFAULT_PRICES[name].peak), offPeak: plain(api2.DEFAULT_PRICES[name].offPeak),
1434
+ /* v7:恢复默认也写基准价(= 官方 CNY 原值) */
1435
+ base: {
1436
+ currency: 'CNY',
1437
+ peak: plain(api2.DEFAULT_PRICES[name].peak),
1438
+ offPeak: plain(api2.DEFAULT_PRICES[name].offPeak)
1439
+ }
1440
+ },
1441
+ '官方条目恢复成官方默认值(' + name + ')');
1442
+ }
1443
+ /* 官方目录(MODEL_PRESENTATION)里的其余模型:按官网价全部加回来,NULL 字段保持 null */
1444
+ OFFICIAL_VENDORS.forEach((vendor) => {
1445
+ vendor.models.forEach((model) => {
1446
+ if (api2.DEFAULT_PRICES[model.name] !== undefined) return;
1447
+ const seededEntry = catalogBookEntryOf(model);
1448
+ assert.deepStrictEqual(plain(afterReset.models[model.name]), plain(seededEntry),
1449
+ '恢复默认按官网价加回官方模型(含基准价):' + model.name);
1450
+ });
1451
+ });
1452
+ assert.deepStrictEqual(plain(afterReset.models['deepseek-v4-pro'].offPeak),
1453
+ { input: 4.5, cacheRead: 0.15, cacheWrite: 0, output: 13.5 }, '加回来的官方条目就是官方价');
1454
+ /* ② 自建键:逐字段不变(含明确填的 0 与 null、以及它自己的 currency) */
1455
+ for (const name of customKeys) {
1456
+ const stripBase = (one) => { const copy = plain(one); delete copy.base; return copy; };
1457
+ assert.deepStrictEqual(stripBase(afterReset.models[name]), stripBase(modelsInMemory[name]),
1458
+ '自建条目逐字段不变(' + name + ',base 单独比)');
1459
+ /* v7:恢复默认把自建条目的 base 补成「当前值 + 当前币种」;
1460
+ 内存里已有 base 的(USD 条目)原样保留,没有的(CNY 条目)按当前值补。 */
1461
+ const expectedBase = modelsInMemory[name].base !== undefined
1462
+ ? plain(modelsInMemory[name].base)
1463
+ : { currency: modelsInMemory[name].currency, peak: plain(modelsInMemory[name].peak), offPeak: plain(modelsInMemory[name].offPeak) };
1464
+ assert.deepStrictEqual(plain(afterReset.models[name].base), expectedBase,
1465
+ '自建条目的 base 锚点在恢复默认后正确(' + name + ')');
1466
+ }
1467
+ assert.strictEqual(afterReset.models['zero-model'].peak.cacheRead, 0, '自建条目明确填的 0 仍是 0');
1468
+ /* 自建条目也是 USD:显示值折 CNY,原始值在 base(上面已逐字段比对)。 */
1469
+ assert.deepStrictEqual(plain(afterReset.models['my-own-model'].peak),
1470
+ { input: 60.68, cacheRead: 6.74, cacheWrite: 0, output: 134.85 }, '自建条目 USD 显示值按 3.0.4 口径折成 CNY');
1471
+ /* ③ 顺序:官方键(官方顺序)在前 + 自建键(原相对顺序)在后 */
1472
+ assert.deepStrictEqual(plain(afterReset.modelOrder), officialKeys.concat(seededNames, customKeys),
1473
+ 'modelOrder = 官方键 + 官方目录其余模型(目录顺序)+ 自建键(原相对顺序)');
1474
+ console.log('恢复默认:界面配置回默认 · 官方键回官方价(含被删的加回)· 自建键逐字段不变 · 顺序 ' + afterReset.modelOrder.join(' → '));
1475
+ }
1476
+
1477
+ /* ------------------------------------------- 价格库:折叠两态 / 峰谷计价 / 草稿 */
1478
+ function collectByClass(tree, className) {
1479
+ const out = [];
1480
+ (function walk(node) {
1481
+ if (node === null || node === undefined || typeof node !== 'object') return;
1482
+ if (Array.isArray(node)) { node.forEach(walk); return; }
1483
+ const cls = node.props === undefined ? undefined : node.props.className;
1484
+ if (typeof cls === 'string' && cls.split(' ').indexOf(className) !== -1) out.push(node);
1485
+ walk(node.children);
1486
+ })(tree);
1487
+ return out;
1488
+ }
1489
+ function findInput(node, type) {
1490
+ let found = null;
1491
+ (function walk(current) {
1492
+ if (found !== null || current === null || current === undefined || typeof current !== 'object') return;
1493
+ if (Array.isArray(current)) { current.forEach(walk); return; }
1494
+ if (current.type === 'input' && current.props.type === type) { found = current; return; }
1495
+ walk(current.children);
1496
+ })(node);
1497
+ return found;
1498
+ }
1499
+ const buttonByLabel = (tree, label) => collectByClass(tree, 'dsb-action').filter((node) => textOf(node) === label)[0];
1500
+ const modelCards = (tree) => collectByClass(tree, 'dsb-model');
1501
+ function freshSettings() {
1502
+ settingsHooks.values.length = 0; /* 清空 state,回到刚打开设置页的样子 */
1503
+ return renderSettings();
1504
+ }
1505
+ const savedModels = () => JSON.parse(store.get(CONFIG_KEY)).models;
1506
+ /* 按显示名取价格卡;价格卡里每个 dsb-field 恰好一个数字输入框。
1507
+ cardByKey 用卡片的 key(= 价格库里的模型名)取,避免去猜显示名的大小写规则。 */
1508
+ const cardByName = (tree, display) => modelCards(tree)
1509
+ .filter((card) => textOf(collectByClass(card, 'dsb-model-name')[0]) === display)[0];
1510
+ const cardByKey = (tree, key) => modelCards(tree).filter((card) => card.props.key === key)[0];
1511
+ /* 输入框展示按两位小数格式化(0.50 / 3.00),比较时归一成数值字符串。 */
1512
+ const numberValues = (card) => collectByClass(card, 'dsb-field')
1513
+ .map((label) => {
1514
+ const raw = findInput(label, 'number').props.value;
1515
+ const text = raw === undefined || raw === null ? '' : String(raw).trim();
1516
+ return text === '' ? '' : String(Number(text));
1517
+ });
1518
+
1519
+ let priceTree = freshSettings();
1520
+ let cards = modelCards(priceTree);
1521
+ assert.strictEqual(cards.length, 2, '价格库应有 2 个默认模型,实际 ' + cards.length);
1522
+ assert.deepStrictEqual(cards.map((card) => textOf(collectByClass(card, 'dsb-model-name')[0])),
1523
+ ['DeepSeek-Flash', 'DeepSeek-V4-Pro'], '模型名应按首字母大写规则显示');
1524
+ assert.strictEqual(collectByClass(priceTree, 'dsb-field').length, 0, '默认收起时不该有价格输入框');
1525
+ assert.ok(buttonByLabel(cards[0], '修改') !== undefined, '收起态应有「修改」');
1526
+ assert.ok(buttonByLabel(cards[0], '删除') !== undefined, '收起态应有「删除」');
1527
+
1528
+ /* 展开:空闲价在上、高峰价在下,每档三栏 */
1529
+ buttonByLabel(cards[0], '修改').props.onClick();
1530
+ priceTree = renderSettings();
1531
+ cards = modelCards(priceTree);
1532
+ const fields = collectByClass(cards[0], 'dsb-field');
1533
+ assert.strictEqual(fields.length, 6, '峰谷两档应各有 3 个输入框,实际 ' + fields.length);
1534
+ assert.deepStrictEqual(collectByClass(cards[0], 'dsb-tier-name').map(textOf), ['空闲时段', '高峰时段'], '空闲时段应在高峰时段之前');
1535
+ assert.deepStrictEqual(fields.slice(0, 3).map(textOf), ['输入(缓存命中)', '输入(缓存未命中)', '输出'], '三栏顺序与文案');
1536
+ assert.ok(buttonByLabel(cards[0], '保存') !== undefined, '展开态应有「保存」');
1537
+
1538
+ /* 取消峰谷计价 → 全天同价,只剩三个输入框 */
1539
+ const tieredLabel = collectByClass(cards[0], 'dsb-inline-check')[0];
1540
+ assert.strictEqual(textOf(tieredLabel), '峰谷计价', '应有峰谷计价勾选');
1541
+ findInput(tieredLabel, 'checkbox').props.onChange({ target: { checked: false } });
1542
+ priceTree = renderSettings();
1543
+ cards = modelCards(priceTree);
1544
+ assert.strictEqual(collectByClass(cards[0], 'dsb-field').length, 3, '全天同价应只有 3 个输入框');
1545
+ assert.deepStrictEqual(collectByClass(cards[0], 'dsb-tier-name').map(textOf), ['全时段'], '全天同价要显示「全时段」档位名(task-19:不再靠"没有档位名"做双边对齐)');
1546
+
1547
+ /* 改值 → 保存 → 写入配置并收起 */
1548
+ findInput(cards[0], 'number').props.onChange({ target: { value: '1.5' } });
1549
+ priceTree = renderSettings();
1550
+ cards = modelCards(priceTree);
1551
+ buttonByLabel(cards[0], '保存').props.onClick();
1552
+ priceTree = renderSettings();
1553
+ cards = modelCards(priceTree);
1554
+ assert.strictEqual(collectByClass(priceTree, 'dsb-field').length, 0, '保存后卡片应收起');
1555
+ assert.ok(buttonByLabel(cards[0], '修改') !== undefined, '收起后应回到「修改」');
1556
+ const flash = savedModels()['deepseek-flash'];
1557
+ assert.strictEqual(flash.tiered, false, '全天同价标记应写入配置');
1558
+ assert.strictEqual(flash.peak.cacheRead, 1.5, '输入(缓存命中) 的值应写入 peak');
1559
+ /* task-25:取消峰谷计价**不丢数据** —— 低谷(offPeak)行的值搬回单档行(计价读 peak),
1560
+ offPeak 原值留在内部不显示;用户误点勾选再取消也能拿回原价。 */
1561
+
1562
+ /* 计价单位(task-22:币种改成**每个条目自带**):
1563
+ ① 条目级选择器在编辑浮层里,切换只换算**被切的那一条**(数值按参考价比例、6 位小数);
1564
+ ② 顶部选择器只管"新增条目的默认币种",一个已有条目都不许动;
1565
+ ③ 全局 `currency` 字段(迁移后的默认值)在两处切换里都不被改写。 */
1566
+ const RATE = 6.742424242424242; /* 人民币 ÷ 该值 = 美元(官方两张参考价表推出来的) */
1567
+ const proCard = modelCards(priceTree).filter((one) => textOf(one).indexOf('V4-Pro') !== -1)[0];
1568
+ buttonByLabel(proCard, '修改').props.onClick();
1569
+ priceTree = renderSettings();
1570
+ assert.strictEqual(collectByClass(priceTree, 'dsb-default-currency').length, 0, '顶部选择器已删除(task-24),条目选择器在浮层里');
1571
+ const entryPick = collectByClass(collectByClass(cardByKey(priceTree, 'deepseek-v4-pro'), 'dsb-edit-pop')[0], 'dsb-currency-pick')[0];
1572
+ assert.ok(entryPick !== undefined, '条目级选择器在**编辑浮层里**(不是顶部那个)');
1573
+ const entryBtn = collectByClass(entryPick, 'dsb-select-btn')[0];
1574
+ assert.strictEqual(textOf(entryBtn), 'CNY', '条目币种初值 = 迁移落下来的默认币种');
1575
+ assert.strictEqual(collectByClass(entryBtn, 'dsb-select-menu').length, 0, '没点开时不渲染菜单');
1576
+ const beforeModels = JSON.parse(store.get(api.STORAGE_KEY)).models;
1577
+ assert.strictEqual(beforeModels['deepseek-v4-pro'].currency, 'CNY', '前置:迁移把已有条目落成显式 currency');
1578
+ entryBtn.props.onClick();
1579
+ priceTree = renderSettings();
1580
+ const usdItem = collectByClass(priceTree, 'dsb-select-item').filter((one) => textOf(one) === 'USD')[0];
1581
+ assert.ok(usdItem !== undefined, '菜单里有 USD');
1582
+ usdItem.props.onClick();
1583
+ const afterEntry = JSON.parse(store.get(api.STORAGE_KEY));
1584
+ assert.strictEqual(afterEntry.models['deepseek-v4-pro'].currency, 'USD', '被切的那一条改成 USD');
1585
+ assert.deepStrictEqual(afterEntry.models['deepseek-v4-pro'].peak,
1586
+ { input: 1.32, cacheRead: 0.044, cacheWrite: 0, output: 3.96 },
1587
+ '官方内置条目切币种 ⇒ 整条换成官方**另一套参考价表**(不是按汇率换算)');
1588
+ assert.deepStrictEqual(afterEntry.models['deepseek-v4-pro'].offPeak,
1589
+ { input: 0.66, cacheRead: 0.022, cacheWrite: 0, output: 1.98 }, '空闲档同样等于官方另一套表');
1590
+ assert.strictEqual(afterEntry.models['deepseek-v4-pro'].tiered, true, 'tiered 标记保留');
1591
+ assert.notStrictEqual(afterEntry.models['deepseek-v4-pro'].peak.input, 1.334831,
1592
+ '不等于按比率算出来的 1.334831(用户明确反对按汇率改数值)');
1593
+ assert.deepStrictEqual(afterEntry.models['deepseek-flash'], beforeModels['deepseek-flash'],
1594
+ '其它条目**逐字段不变**(切换只作用被切的那一条)');
1595
+ assert.strictEqual(afterEntry.currency, 'CNY', '切换条目币种**不改写**默认币种字段');
1596
+ /* 打开着的这张卡立刻显示新币种的数字 */
1597
+ priceTree = renderSettings();
1598
+ const editPop = collectByClass(priceTree, 'dsb-edit-pop')[0];
1599
+ assert.ok(editPop !== undefined, '编辑区渲染成毛玻璃浮层');
1600
+ const shownValues = [];
1601
+ (function walkInputs(node) {
1602
+ if (node === null || node === undefined || typeof node !== 'object') return;
1603
+ if (Array.isArray(node)) { node.forEach(walkInputs); return; }
1604
+ if (node.type === 'input') shownValues.push(node.props.value);
1605
+ walkInputs(node.children);
1606
+ })(editPop);
1607
+ assert.ok(shownValues.indexOf('3.96') !== -1,
1608
+ '正在编辑的这张卡立刻换成官方另一套表的数字,实际 ' + JSON.stringify(shownValues));
1609
+ /* task-24:顶部那个"新增条目的默认币种"选择器**整个删除**(用户说还残留)—— 负断言钉住 */
1610
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-default-currency').length, 0, '顶部默认币种选择器已删除');
1611
+ assert.strictEqual(code.indexOf('dsb-default-currency'), -1, 'CSS/代码里不该再有 dsb-default-currency');
1612
+ assert.strictEqual(code.indexOf('setDefaultCurrency'), -1, 'setDefaultCurrency 已删除');
1613
+ ['defaultCurrencyOpen', 'defaultCurrencyMenuRef', 'defaultCurrencyRef', 'picker.kind'].forEach((gone) => {
1614
+ assert.strictEqual(code.indexOf(gone), -1, '顶部选择器的残留标识不该再出现:' + gone);
1615
+ });
1616
+ const settingsTextNoPick = textOf(renderSettings());
1617
+ assert.strictEqual(settingsTextNoPick.indexOf('默认币种'), -1, '设置页不该再有"默认币种"文字');
1618
+ assert.strictEqual(settingsTextNoPick.indexOf('default currency'), -1, '设置页不该再有 default currency 文字');
1619
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-currency-pick').length, 1, '币种选择器只剩**打开的那张卡浮层里**那一个');
1620
+ /* 改过数值的条目(deepseek-flash 手改过)切币种 ⇒ 数值一字不变、只改 currency */
1621
+ buttonByLabel(cardByKey(priceTree, 'deepseek-flash'), '修改').props.onClick();
1622
+ priceTree = renderSettings();
1623
+ const flashBefore = JSON.parse(store.get(api.STORAGE_KEY)).models['deepseek-flash'];
1624
+ const flashPick = collectByClass(collectByClass(cardByKey(priceTree, 'deepseek-flash'), 'dsb-edit-pop')[0], 'dsb-currency-pick')[0];
1625
+ assert.ok(flashPick !== undefined, '改过数值的条目也有条目级选择器');
1626
+ collectByClass(flashPick, 'dsb-select-btn')[0].props.onClick();
1627
+ priceTree = renderSettings();
1628
+ collectByClass(priceTree, 'dsb-select-item').filter((one) => textOf(one) === 'USD')[0].props.onClick();
1629
+ const flashAfter = JSON.parse(store.get(api.STORAGE_KEY)).models['deepseek-flash'];
1630
+ assert.strictEqual(flashAfter.currency, 'USD', '改过数值的条目:只改币种标记');
1631
+ assert.deepStrictEqual({ peak: flashAfter.peak, offPeak: flashAfter.offPeak, tiered: flashAfter.tiered },
1632
+ { peak: flashBefore.peak, offPeak: flashBefore.offPeak, tiered: flashBefore.tiered },
1633
+ '改过数值的条目切币种 ⇒ 数值一字不变(不按比率换算)');
1634
+ /* task-23:三处新增文案已回退 —— 界面不出现这些文字,后两个 i18n 键连键删除 */
1635
+ const sectionText = textOf(renderSettings());
1636
+ ['每个条目按它自己的币种计价', 'Each entry is priced in its own currency', '新增条目的默认币种', '本条目的币种'].forEach((bad) => {
1637
+ assert.strictEqual(sectionText.indexOf(bad), -1, '设置页不该再出现这段文字:' + bad);
1638
+ });
1639
+ ['priceEntryCurrency', 'priceDefaultCurrency'].forEach((key) => {
1640
+ assert.strictEqual(code.indexOf(key), -1, 'i18n 里这个键(中英)都已删除:' + key);
1641
+ });
1642
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-default-currency').length, 0, '顶部默认币种选择器已删除(task-24)');
1643
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-currency-pick').length, 1, '条目级币种选择器仍在(只是没有文字标签)');
1644
+ console.log('计价单位:条目级切换只换算这一条(¥9→$1.334831)· 其它条目逐字段不变 · 顶部选择器只管新增条目的默认币种');
1645
+ /* task-17:只有**单一币种价格**的模型(USD-only 官方 / 自建)切币种按今日汇率换算(两位小数);
1646
+ 官方双表(deepseek 两条)仍用官方价(上面已断言)。汇率没拿到过时用内置 REFERENCE_RATE 兜底。 */
1647
+ {
1648
+ const RATE = api.REFERENCE_RATE;
1649
+ assert.ok(Number.isFinite(RATE) && RATE > 0, '前置:内置参考汇率可用');
1650
+ const rateSpan = (value) => Math.round(value * RATE * 100) / 100;
1651
+ const modelsBeforeRate = JSON.parse(JSON.stringify(savedModels()));
1652
+ const orderBeforeRate = JSON.parse(JSON.stringify(api.snapshot().modelOrder));
1653
+ api.setConfig({
1654
+ models: Object.assign({}, savedModels(), {
1655
+ 'claude-opus-5.5': { tiered: false, currency: 'USD', peak: { input: 4, cacheRead: 0.2, cacheWrite: 5, output: 20 }, offPeak: null },
1656
+ 'my-usd-model': { tiered: false, currency: 'USD', peak: { input: 1.5, cacheRead: null, cacheWrite: null, output: 3 }, offPeak: null },
1657
+ 'tiny-usd': { tiered: false, currency: 'USD', peak: { input: null, cacheRead: 0.000001, cacheWrite: null, output: null }, offPeak: null }
1658
+ }),
1659
+ modelOrder: orderBeforeRate.concat(['claude-opus-5.5', 'my-usd-model', 'tiny-usd'])
1660
+ });
1661
+ const switchCurrency = (key, code) => {
1662
+ if (collectByClass(cardByKey(priceTree, key), 'dsb-edit-pop')[0] === undefined) {
1663
+ buttonByLabel(cardByKey(priceTree, key), '修改').props.onClick();
1664
+ priceTree = renderSettings();
1665
+ }
1666
+ collectByClass(collectByClass(cardByKey(priceTree, key), 'dsb-edit-pop')[0], 'dsb-select-btn')[0].props.onClick();
1667
+ priceTree = renderSettings();
1668
+ collectByClass(cardByKey(priceTree, key), 'dsb-select-item').filter((one) => textOf(one) === code)[0].props.onClick();
1669
+ priceTree = renderSettings();
1670
+ };
1671
+ priceTree = renderSettings();
1672
+ switchCurrency('claude-opus-5.5', 'CNY');
1673
+ const claudeCny = savedModels()['claude-opus-5.5'];
1674
+ assert.strictEqual(claudeCny.currency, 'CNY', 'USD-only 官方模型切 CNY 后币种为 CNY');
1675
+ assert.deepStrictEqual({ peak: claudeCny.peak },
1676
+ { peak: { input: rateSpan(4), cacheRead: rateSpan(0.2), cacheWrite: rateSpan(5), output: rateSpan(20) } },
1677
+ 'USD-only 官方模型按今日汇率换算到两位小数');
1678
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'claude-opus-5.5')),
1679
+ [String(rateSpan(0.2)), String(rateSpan(4)), String(rateSpan(20))],
1680
+ '编辑气泡里的数字跟着变成换算后的值(不是只改符号)');
1681
+ switchCurrency('claude-opus-5.5', 'USD');
1682
+ const claudeUsd = savedModels()['claude-opus-5.5'];
1683
+ assert.strictEqual(claudeUsd.currency, 'USD', '再切回 USD 币种还原');
1684
+ const CLOUD_ORIGINAL = { input: 4, cacheRead: 0.2, cacheWrite: 5, output: 20 };
1685
+ Object.keys(CLOUD_ORIGINAL).forEach((field) => {
1686
+ assert.ok(Math.abs(claudeUsd.peak[field] - CLOUD_ORIGINAL[field]) <= 0.01,
1687
+ '切回 USD 数值还原(允许两位误差):' + field);
1688
+ });
1689
+ switchCurrency('my-usd-model', 'CNY');
1690
+ const mineCny = savedModels()['my-usd-model'];
1691
+ assert.strictEqual(mineCny.currency, 'CNY', '自建模型切币种同样按汇率换算');
1692
+ assert.strictEqual(mineCny.peak.input, rateSpan(1.5), '自建模型数值按汇率换算');
1693
+ assert.strictEqual(mineCny.peak.cacheRead, null, '没填的格子换算后仍是 null(不造数)');
1694
+ assert.strictEqual(mineCny.peak.output, rateSpan(3), '自建模型输出价同步换算');
1695
+ switchCurrency('tiny-usd', 'CNY');
1696
+ assert.strictEqual(savedModels()['tiny-usd'].peak.cacheRead, 0, '极小价格按纯两位小数四舍五入(不做最小值兜底)');
1697
+ assert.strictEqual(savedModels()['tiny-usd'].peak.input, null, '换算后 null 仍保持 null');
1698
+ /* 极小价格最能暴露「换算 + 两位小数」的漂移:切回 USD 必须精确还原 0.000001 */
1699
+ switchCurrency('tiny-usd', 'USD');
1700
+ assert.deepStrictEqual(savedModels()['tiny-usd'].peak,
1701
+ { input: null, cacheRead: 0.000001, cacheWrite: null, output: null },
1702
+ '切回基准币种用 base 原值还原(0.000001 不许被两位小数洗成 0)');
1703
+ /* v7:切回基准币种逐字段**精确**还原(base 钉死,不靠"允许两位误差") */
1704
+ assert.deepStrictEqual(savedModels()['claude-opus-5.5'].peak, CLOUD_ORIGINAL,
1705
+ 'USD-only 官方模型切回 USD = 官方原值(逐字段精确,不受两位小数舍入影响)');
1706
+ /* 再走一个来回:CNY → USD 仍然精确原值(每回都从 base 换算,不拿上一次的换算值再乘) */
1707
+ switchCurrency('claude-opus-5.5', 'CNY');
1708
+ assert.deepStrictEqual(savedModels()['claude-opus-5.5'].peak,
1709
+ { input: rateSpan(4), cacheRead: rateSpan(0.2), cacheWrite: rateSpan(5), output: rateSpan(20) },
1710
+ '第二次切 CNY:仍从 base 按今日汇率换算');
1711
+ switchCurrency('claude-opus-5.5', 'USD');
1712
+ assert.deepStrictEqual(savedModels()['claude-opus-5.5'].peak, CLOUD_ORIGINAL,
1713
+ '来回切第二次仍是精确原值(基准价钉死、不漂)');
1714
+ switchCurrency('my-usd-model', 'USD');
1715
+ assert.deepStrictEqual(savedModels()['my-usd-model'].peak,
1716
+ { input: 1.5, cacheRead: null, cacheWrite: null, output: 3 },
1717
+ '自建模型切回 USD = 原值(null 保持 null)');
1718
+ /* 用户改过价并保存后:base 随保存更新,切走再切回 = 保存的值(不是旧值、也不是换算漂移值) */
1719
+ {
1720
+ if (collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-edit-pop')[0] === undefined) {
1721
+ buttonByLabel(cardByKey(priceTree, 'my-usd-model'), '修改').props.onClick();
1722
+ priceTree = renderSettings();
1723
+ }
1724
+ const editFields = collectByClass(collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-edit-pop')[0], 'dsb-field');
1725
+ const editedInput = findInput(editFields[1], 'number');
1726
+ assert.ok(editedInput !== undefined, '找得到编辑框里的输入(未命中缓存)价格');
1727
+ editedInput.props.onChange({ target: { value: '2.5' } });
1728
+ priceTree = renderSettings();
1729
+ buttonByLabel(cardByKey(priceTree, 'my-usd-model'), '保存').props.onClick();
1730
+ priceTree = renderSettings();
1731
+ const savedAfterEdit = savedModels()['my-usd-model'];
1732
+ assert.strictEqual(savedAfterEdit.peak.input, 2.5, '改价保存后价格库里是新值');
1733
+ assert.deepStrictEqual(savedAfterEdit.base,
1734
+ { currency: savedAfterEdit.currency, peak: savedAfterEdit.peak, offPeak: savedAfterEdit.offPeak },
1735
+ '保存时同步更新 base = 刚保存的数值 + 当前币种');
1736
+ switchCurrency('my-usd-model', 'CNY');
1737
+ switchCurrency('my-usd-model', 'USD');
1738
+ assert.deepStrictEqual(savedModels()['my-usd-model'].peak,
1739
+ { input: 2.5, cacheRead: null, cacheWrite: null, output: 3 },
1740
+ '改价保存后切走再切回 = 保存的值');
1741
+ }
1742
+ /* 点币种按钮 / 菜单项:必须 stopPropagation(否则事件冒泡到 document 的"点别处"会上收掉气泡) */
1743
+ {
1744
+ priceTree = renderSettings();
1745
+ if (collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-edit-pop')[0] === undefined) {
1746
+ buttonByLabel(cardByKey(priceTree, 'my-usd-model'), '修改').props.onClick();
1747
+ priceTree = renderSettings();
1748
+ }
1749
+ const pickBox = collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-currency-pick')[0];
1750
+ const menuBtn = collectByClass(pickBox, 'dsb-select-btn')[0];
1751
+ const stops = [];
1752
+ const spyEvent = { stopPropagation: () => { stops.push(1); } };
1753
+ menuBtn.props.onClick(spyEvent);
1754
+ priceTree = renderSettings();
1755
+ const cnyItem = collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-select-item').filter((one) => textOf(one) === 'CNY')[0];
1756
+ assert.ok(cnyItem !== undefined, '菜单已展开');
1757
+ cnyItem.props.onClick(spyEvent);
1758
+ assert.strictEqual(stops.length, 2, '币种按钮与菜单项都要 stopPropagation(事件不冒到 document)');
1759
+ priceTree = renderSettings();
1760
+ assert.ok(collectByClass(cardByKey(priceTree, 'my-usd-model'), 'dsb-edit-pop')[0] !== undefined,
1761
+ '点币种菜单项后编辑气泡仍然展开(不会被当点外部收起)');
1762
+ }
1763
+
1764
+ /* 收尾:恢复汇率用例前的价格库,避免污染后续段 */
1765
+ api.setConfig({ models: modelsBeforeRate, modelOrder: orderBeforeRate });
1766
+ priceTree = renderSettings();
1767
+ console.log('币种切换:USD-only 官方/自建按今日汇率换算(两位小数、null 保持、极小值防呆);deepseek 双表仍用官方价');
1768
+ }
1769
+
1770
+
1771
+ /* 点别处收起编辑浮层并丢弃草稿:effect 里挂 document click → 落在浮层外就 cancelEdit。
1772
+ 这里的效果钩子在测试沙箱里是空实现,所以用源码契约守住这两步。 */
1773
+ assert.ok(code.includes('const inside = (event) => {'), '点浮层外面才收起(先判断在不在里面)');
1774
+ assert.ok(code.includes('target.closest(".dsb-model") !== null'), '价格卡里的控件不算"外面"(切币种时编辑区不该被收掉)');
1775
+ assert.ok(code.includes('cancelEdit();'), '收起时丢弃草稿(不保留改了一半的数字)');
1776
+ assert.ok(code.includes('event.stopPropagation();'), '头部按钮拦截冒泡,点保存/修改不会被"点别处"顺手收掉');
1777
+ console.log('编辑浮层:点别处收起并丢弃草稿(契约守住)');
1778
+
1779
+ /* task-25:切换「峰谷计价」不再丢价 —— 勾上把单档价搬到低谷行(高峰 ×2 联动),取消再搬回单档行 */
1780
+ {
1781
+ const baseBook = savedModels();
1782
+ api.setConfig({
1783
+ models: Object.assign({}, baseBook, {
1784
+ 'toggle-model': { tiered: false, currency: 'CNY', peak: { input: 3, cacheRead: 0.5, cacheWrite: 0, output: 6 }, offPeak: null },
1785
+ /* base 回填用例:库里只有基准价、当前格全空 */
1786
+ 'base-only-model': { tiered: false, currency: 'CNY', peak: { input: null, cacheRead: null, cacheWrite: null, output: null }, offPeak: null, base: { currency: 'CNY', peak: { input: 5, cacheRead: 1, cacheWrite: 0, output: 8 }, offPeak: { input: 2.5, cacheRead: 0.5, cacheWrite: 0, output: 4 } } }
1787
+ }),
1788
+ modelOrder: Object.keys(baseBook).concat(['toggle-model', 'base-only-model'])
1789
+ });
1790
+ priceTree = renderSettings();
1791
+ const openEdit = (key) => {
1792
+ if (collectByClass(cardByKey(priceTree, key), 'dsb-edit-pop')[0] === undefined) {
1793
+ buttonByLabel(cardByKey(priceTree, key), '修改').props.onClick();
1794
+ priceTree = renderSettings();
1795
+ }
1796
+ };
1797
+ const tierCheckbox = (key) => findInput(collectByClass(cardByKey(priceTree, key), 'dsb-inline-check')[0], 'checkbox');
1798
+ const tierRows = (key) => collectByClass(cardByKey(priceTree, key), 'dsb-tier')
1799
+ .map((row) => numberValues(row));
1800
+ openEdit('toggle-model');
1801
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'toggle-model')), ['0.5', '3', '6'], '前置:单档价');
1802
+ tierCheckbox('toggle-model').props.onChange({ target: { checked: true } });
1803
+ priceTree = renderSettings();
1804
+ assert.deepStrictEqual(tierRows('toggle-model')[0], ['0.5', '3', '6'], '勾上:原单档价搬到「低谷」行(不是清空)');
1805
+ assert.deepStrictEqual(tierRows('toggle-model')[1], ['1', '6', '12'], '勾上:高峰按低谷 ×2 联动带出');
1806
+ /* 取消:低谷行的值搬回单档行 */
1807
+ tierCheckbox('toggle-model').props.onChange({ target: { checked: false } });
1808
+ priceTree = renderSettings();
1809
+ assert.strictEqual(collectByClass(cardByKey(priceTree, 'toggle-model'), 'dsb-field').length, 3, '取消后回到单档三格');
1810
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'toggle-model')), ['0.5', '3', '6'], '取消:低谷值搬回单档行,价格没丢');
1811
+ /* 两档都填过再取消:单档显示「低谷」值(计价读 peak 单档行) */
1812
+ tierCheckbox('toggle-model').props.onChange({ target: { checked: true } });
1813
+ priceTree = renderSettings();
1814
+ const peakRow = collectByClass(cardByKey(priceTree, 'toggle-model'), 'dsb-tier')[1];
1815
+ const peakInput = findInput(collectByClass(peakRow, 'dsb-field')[1], 'number');
1816
+ peakInput.props.onChange({ target: { value: '9' } });
1817
+ priceTree = renderSettings();
1818
+ tierCheckbox('toggle-model').props.onChange({ target: { checked: false } });
1819
+ priceTree = renderSettings();
1820
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'toggle-model')), ['0.5', '4.5', '6'], '两档填过再取消:单档显示低谷值(改高峰会按 ÷2 联动回低谷)');
1821
+ /* 保存:单档模式只落 peak(= 低谷原值),计价口径不变 */
1822
+ buttonByLabel(cardByKey(priceTree, 'toggle-model'), '保存').props.onClick();
1823
+ priceTree = renderSettings();
1824
+ const savedToggle = savedModels()['toggle-model'];
1825
+ assert.strictEqual(savedToggle.tiered, false, '取消后保存为全天同价');
1826
+ assert.deepStrictEqual(savedToggle.peak, { input: 4.5, cacheRead: 0.5, cacheWrite: 0, output: 6 }, '单档落库的就是低谷行的值(含刚才高峰 ÷2 联动后的 4.5),计价口径不变');
1827
+ /* 空行 + base:勾上时用基准价回填,不造数也不清空 */
1828
+ openEdit('base-only-model');
1829
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'base-only-model')), ['', '', ''], '前置:当前格全空');
1830
+ tierCheckbox('base-only-model').props.onChange({ target: { checked: true } });
1831
+ priceTree = renderSettings();
1832
+ assert.deepStrictEqual(tierRows('base-only-model')[0], ['1', '5', '8'], '空行勾上:低谷行用 base 回填');
1833
+ assert.deepStrictEqual(tierRows('base-only-model')[1], ['2', '10', '16'], '空行勾上:高峰按低谷 ×2 带出');
1834
+ /* 全空且没有 base 的模型:来回切换保持空,不造 0 也不报错 */
1835
+ api.setConfig({ models: Object.assign({}, baseBook, {
1836
+ 'empty-model': { tiered: false, currency: 'CNY', peak: { input: null, cacheRead: null, cacheWrite: null, output: null }, offPeak: null }
1837
+ }), modelOrder: Object.keys(baseBook).concat(['empty-model']) });
1838
+ priceTree = renderSettings();
1839
+ openEdit('empty-model');
1840
+ tierCheckbox('empty-model').props.onChange({ target: { checked: true } });
1841
+ priceTree = renderSettings();
1842
+ assert.deepStrictEqual(tierRows('empty-model'), [['', '', ''], ['', '', '']], '空模型勾上:两档仍全空,不造数');
1843
+ tierCheckbox('empty-model').props.onChange({ target: { checked: false } });
1844
+ priceTree = renderSettings();
1845
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'empty-model')), ['', '', ''], '空模型取消:仍全空,不造数');
1846
+ /* 收尾:恢复原价格库,别污染后面的用例 */
1847
+ api.setConfig({ models: baseBook, modelOrder: Object.keys(baseBook) });
1848
+ priceTree = renderSettings();
1849
+ }
1850
+
1851
+ assert.strictEqual(flash.peak.cacheWrite, 0, '缓存写入不再显示,字段保留 0');
1852
+ assert.strictEqual(flash.peak.output, 4, '未改动的栏位保持「低谷行」的原值(取消勾选搬回的是低谷价)');
1853
+
1854
+ /* 未保存的草稿:切到另一个模型即丢弃 */
1855
+ buttonByLabel(cards[0], '修改').props.onClick();
1856
+ priceTree = renderSettings();
1857
+ findInput(modelCards(priceTree)[0], 'number').props.onChange({ target: { value: '99' } });
1858
+ priceTree = renderSettings();
1859
+ buttonByLabel(modelCards(priceTree)[1], '修改').props.onClick();
1860
+ priceTree = renderSettings();
1861
+ assert.strictEqual(savedModels()['deepseek-flash'].peak.cacheRead, 1.5, '未保存的草稿不应写入配置');
1862
+
1863
+ /* 新添加的模型默认展开 */
1864
+ findInput(priceTree, 'text').props.onChange({ target: { value: 'glm-5.3-flash' } });
1865
+ priceTree = renderSettings();
1866
+ buttonByLabel(priceTree, '添加').props.onClick();
1867
+ priceTree = renderSettings();
1868
+ const added = modelCards(priceTree).filter((card) => textOf(collectByClass(card, 'dsb-model-name')[0]) === 'GLM-5.3-Flash')[0];
1869
+ assert.ok(added !== undefined, '新模型应按 GLM 全大写规则显示');
1870
+ assert.strictEqual(collectByClass(added, 'dsb-field').length, 3, '新模型应默认展开且为单档(3 个输入框)');
1871
+ const customGroup = collectByClass(priceTree, 'dsb-catalog-vendor').filter((one) => one.props.key === '__custom')[0];
1872
+ assert.ok(customGroup !== undefined && customGroup.props.open === true, '自定义模型分组自动展开(details open)');
1873
+ assert.strictEqual(savedModels()['glm-5.3-flash'].tiered, false, '新模型默认不勾峰谷计价');
1874
+ assert.ok(savedModels()['glm-5.3-flash'] !== undefined, '新模型应写入配置');
1875
+ assert.strictEqual(savedModels()['glm-5.3-flash'].currency, 'CNY', '新增条目带默认币种 CNY(顶部选择器已删除,写死 CNY)');
1876
+ assert.strictEqual(collectByClass(priceTree, 'dsb-models').length, 2, '只显示已配置模型的厂商组(deepseek)+ 自定义组,共两个平铺模型容器');
1877
+ assert.deepStrictEqual(modelCards(priceTree).map((card) => textOf(collectByClass(card, 'dsb-model-name')[0])),
1878
+ ['DeepSeek-Flash', 'DeepSeek-V4-Pro', 'GLM-5.3-Flash'], '可计价模型卡应保持配置顺序,新模型应排在最后');
1879
+ /* 需求 1:刚新增的条目展开时三个框留空等用户输入,不预填 0 */
1880
+ assert.deepStrictEqual(numberValues(added), ['', '', ''],
1881
+ '新条目展开时三个框要留空,实际 ' + JSON.stringify(numberValues(added)));
1882
+
1883
+ /* 整数样式的模型名(如 "1")也不能跑到最前 */
1884
+ findInput(priceTree, 'text').props.onChange({ target: { value: '1' } });
1885
+ priceTree = renderSettings();
1886
+ buttonByLabel(priceTree, '添加').props.onClick();
1887
+ priceTree = renderSettings();
1888
+ assert.deepStrictEqual(modelCards(priceTree).map((card) => textOf(collectByClass(card, 'dsb-model-name')[0])),
1889
+ ['DeepSeek-Flash', 'DeepSeek-V4-Pro', 'GLM-5.3-Flash', '1'], '纯数字模型名同样排最后');
1890
+
1891
+ /* 需求 C(task-5,本轮按用户实测反馈改口径):两档所有字段都是空字符串 = 价格先空着
1892
+ ⇒ **条目照样留在价格库里**(用户反馈:新建的自定义模型没填价格,点保存会被自动删掉);
1893
+ 只要明确填过数字(**包括明确填 0**)就写入,空着的格子按 null。
1894
+ 此刻展开的是刚加的那条「1」,草稿全空 —— 正好用来验第一件事。 */
1895
+ const justAdded = cardByName(priceTree, '1');
1896
+ assert.deepStrictEqual(numberValues(justAdded), ['', '', ''],
1897
+ '新加的条目展开时三个框要留空,实际 ' + JSON.stringify(numberValues(justAdded)));
1898
+ buttonByLabel(justAdded, '保存').props.onClick();
1899
+ const blankSaved = savedModels()['1'];
1900
+ assert.ok(blankSaved !== undefined, '一个字都没填就保存 ⇒ 条目仍留在价格库里(不再自动删除)');
1901
+ assert.deepStrictEqual(blankSaved.peak, { input: null, cacheRead: null, cacheWrite: null, output: null },
1902
+ '没填的格子存成 null(不是 0)');
1903
+ assert.deepStrictEqual(blankSaved.offPeak, { input: null, cacheRead: null, cacheWrite: null, output: null },
1904
+ '用户没碰过的那一档整档 null');
1905
+ assert.strictEqual(blankSaved.currency, 'CNY', '新建条目的币种仍是界面默认的 CNY');
1906
+ priceTree = renderSettings();
1907
+ assert.ok(cardByName(priceTree, '1') !== undefined, '保存后卡片仍留在列表里(不再等于取消添加)');
1908
+ assert.deepStrictEqual(modelCards(priceTree).map((card) => textOf(collectByClass(card, 'dsb-model-name')[0])),
1909
+ ['DeepSeek-Flash', 'DeepSeek-V4-Pro', 'GLM-5.3-Flash', '1'], '用户模型卡片列表仍保留刚建的那条');
1910
+
1911
+ /* 明确填一个 0、另一个填 5:条目要写入,填过的格子保数字、没填的格子留 null */
1912
+ const numberInputs = (card) => collectByClass(card, 'dsb-field').map((label) => findInput(label, 'number'));
1913
+ const setNumberField = (key, index, value) => {
1914
+ priceTree = renderSettings();
1915
+ numberInputs(cardByKey(priceTree, key))[index].props.onChange({ target: { value: value } });
1916
+ };
1917
+ findInput(priceTree, 'text').props.onChange({ target: { value: 'zero-kept' } });
1918
+ priceTree = renderSettings();
1919
+ buttonByLabel(priceTree, '添加').props.onClick();
1920
+ priceTree = renderSettings();
1921
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'zero-kept')), ['', '', ''], '新条目草稿同样留空');
1922
+ setNumberField('zero-kept', 0, '0'); /* 缓存命中:明确填 0 */
1923
+ setNumberField('zero-kept', 1, '5'); /* 输入:有值 */
1924
+ priceTree = renderSettings();
1925
+ buttonByLabel(cardByKey(priceTree, 'zero-kept'), '保存').props.onClick();
1926
+ const zeroSaved = savedModels()['zero-kept'];
1927
+ assert.ok(zeroSaved !== undefined, '填过数字就该写入价格库');
1928
+ assert.deepStrictEqual(zeroSaved.peak, { input: 5, cacheRead: 0, cacheWrite: null, output: null },
1929
+ '明确填的 0 保留成数字 0、没填的格子留 null(不再被写成 0)');
1930
+ assert.deepStrictEqual(zeroSaved.offPeak, { input: null, cacheRead: null, cacheWrite: null, output: null },
1931
+ '单档条目里用户没碰过的那一档整档 null');
1932
+ priceTree = renderSettings();
1933
+ buttonByLabel(cardByKey(priceTree, 'zero-kept'), '修改').props.onClick();
1934
+ priceTree = renderSettings();
1935
+ assert.deepStrictEqual(numberValues(cardByKey(priceTree, 'zero-kept')), ['0', '5', ''],
1936
+ '再打开时逐格回显:填过的显示数字(0 也显示 0),没填的留空,实际 '
1937
+ + JSON.stringify(numberValues(cardByKey(priceTree, 'zero-kept'))));
1938
+
1939
+ /* 非 0 的真实数值同样按原样回填,顺序是 缓存命中 / 输入 / 输出(分档时先空闲后高峰) */
1940
+ buttonByLabel(cardByName(priceTree, 'DeepSeek-V4-Pro'), '修改').props.onClick();
1941
+ priceTree = renderSettings();
1942
+ const proStored = savedModels()['deepseek-v4-pro'];
1943
+ const proTierKeys = proStored.tiered === false ? ['peak'] : ['offPeak', 'peak'];
1944
+ const proExpected = [];
1945
+ proTierKeys.forEach((tier) => ['cacheRead', 'input', 'output']
1946
+ .forEach((field) => {
1947
+ const value = proStored[tier][field];
1948
+ proExpected.push(value === null || value === undefined ? '' : String(Math.round(Number(value) * 100) / 100));
1949
+ }));
1950
+ assert.deepStrictEqual(numberValues(cardByName(priceTree, 'DeepSeek-V4-Pro')), proExpected,
1951
+ '编辑已有条目按真实数值回填(' + proTierKeys.join('/') + '),实际 '
1952
+ + JSON.stringify(numberValues(cardByName(priceTree, 'DeepSeek-V4-Pro'))));
1953
+ console.log('价格库草稿:新增留空 / 全空保存保留条目 / 明确填 0 保留 / 已有回填真实数值');
1954
+
1955
+ /* task-17:用户要求只有单一币种价格的模型(含自建)切币种**按今日汇率换算**;
1956
+ 刚填还没保存的草稿值也要一起换算(不是只改标记,也不能把输入清空)。 */
1957
+ buttonByLabel(cardByKey(priceTree, 'zero-kept'), '修改').props.onClick();
1958
+ priceTree = renderSettings();
1959
+ const keptRate = api.REFERENCE_RATE;
1960
+ /* 统一口径:纯两位小数四舍五入(与 lib/client.js 的 roundPrice2 一致) */
1961
+ const keptSpan = (value) => Math.round(value / keptRate * 100) / 100;
1962
+ numberInputs(cardByKey(priceTree, 'zero-kept'))[2].props.onChange({ target: { value: '9' } }); /* 输出=9,还没保存 */
1963
+ priceTree = renderSettings();
1964
+ const keptPick = collectByClass(collectByClass(cardByKey(priceTree, 'zero-kept'), 'dsb-edit-pop')[0], 'dsb-currency-pick')[0];
1965
+ assert.ok(keptPick !== undefined, '自建条目也有条目级币种选择器');
1966
+ collectByClass(keptPick, 'dsb-select-btn')[0].props.onClick();
1967
+ priceTree = renderSettings();
1968
+ collectByClass(priceTree, 'dsb-select-item').filter((one) => textOf(one) === 'USD')[0].props.onClick();
1969
+ priceTree = renderSettings();
1970
+ const keptShown = numberValues(cardByKey(priceTree, 'zero-kept'));
1971
+ assert.deepStrictEqual(keptShown, ['0', String(keptSpan(5)), String(keptSpan(9))],
1972
+ '切币种后框里的数字按今日汇率换算(含没保存的输入),实际 ' + JSON.stringify(keptShown));
1973
+ const keptAfter = savedModels()['zero-kept'];
1974
+ assert.strictEqual(keptAfter.currency, 'USD', '切币种把这一条改成目标币种');
1975
+ assert.deepStrictEqual(keptAfter.peak, { input: keptSpan(5), cacheRead: 0, cacheWrite: null, output: keptSpan(9) },
1976
+ '写回价格库的数值也按汇率换算(没保存的输入一并参与)');
1977
+ buttonByLabel(cardByKey(priceTree, 'zero-kept'), '保存').props.onClick();
1978
+ const keptSaved = savedModels()['zero-kept'];
1979
+ assert.strictEqual(keptSaved.peak.output, keptSpan(9), '保存后落库的就是换算后的值');
1980
+ assert.strictEqual(keptSaved.peak.input, keptSpan(5), '同一档其它格同步换算');
1981
+ assert.strictEqual(keptSaved.peak.cacheRead, 0, '明确填过的 0 仍是数字 0');
1982
+ assert.strictEqual(keptSaved.currency, 'USD', '落库时带上切换后的币种');
1983
+ console.log('切币种按今日汇率换算:自建条目连同未保存的草稿值一起换算(两位小数)并写回价格库');
1984
+
1985
+ console.log('价格库交互:折叠 / 峰谷 / 草稿 / 顺序全部通过');
1986
+
1987
+ /* task-10/16:官方模型默认全部加入价格表(v4 一次性播种),目录里直接显示价格卡;
1988
+ 不再有「点名字加入」;删除后「恢复默认」找回。数据源 docs/official-models.json(27 条 / 10 厂商,Kimi K3 与 Fable 5.2 已收录)。 */
1989
+ {
1990
+ const catalogPlain = (value) => JSON.parse(JSON.stringify(value));
1991
+ /* ① 内嵌目录必须与数据逐字段一致(含厂商顺序) */
1992
+ const catalogExpected = {};
1993
+ OFFICIAL_VENDORS.forEach((vendor) => {
1994
+ vendor.models.forEach((model) => {
1995
+ catalogExpected[model.name] = { manufacturer: vendor.id, price: catalogPriceOf(model) };
1996
+ });
1997
+ });
1998
+ assert.strictEqual(api.PRICE_VERSION, 8, '价格库迁移版本应为 8(v4 播种 / v5 清理 / v6 补播 / v7 基准价 / v8 补 Fable 5.2)');
1999
+ assert.deepStrictEqual(catalogPlain(api.MODEL_MANUFACTURERS), AA_VENDOR_ORDER,
2000
+ '厂商顺序必须 = AA 智力指数顺序(docs/vendor-intelligence-order.json)');
2001
+ assert.deepStrictEqual(catalogPlain(api.MODEL_MANUFACTURERS).slice().sort(), OFFICIAL_VENDORS.map((one) => one.id).sort(),
2002
+ 'AA 顺序里的厂商集合必须与官方目录数据一致(不许漏也不许多)');
2003
+ assert.deepStrictEqual(catalogPlain(api.MODEL_PRESENTATION), catalogExpected,
2004
+ '内嵌目录必须与 docs/official-models.json 逐字段一致');
2005
+ assert.strictEqual(OFFICIAL_NAMES.length, 27, '数据应为 27 条官方模型');
2006
+
2007
+ /* ② 隔离沙箱:模拟老用户(priceVersion 3)→ 加载时按 v4 播种;已有条目一律不动 */
2008
+ const oldConfig = JSON.stringify({
2009
+ version: 6,
2010
+ priceVersion: 3,
2011
+ currency: 'CNY',
2012
+ contextMeter: true,
2013
+ priceConfigured: true,
2014
+ segments: FACTORY_ORDER.slice(),
2015
+ hidden: [],
2016
+ models: {
2017
+ 'deepseek-flash': {
2018
+ tiered: true, currency: 'CNY', feeMultiplier: 2,
2019
+ peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 },
2020
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 }
2021
+ },
2022
+ 'my-catalog-model': {
2023
+ tiered: false, currency: 'USD', feeMultiplier: 3,
2024
+ peak: { input: 7, cacheRead: 0.7, cacheWrite: 0, output: 11 },
2025
+ offPeak: { input: 3.5, cacheRead: 0.35, cacheWrite: 0, output: 5.5 }
2026
+ }
2027
+ },
2028
+ modelOrder: ['deepseek-flash', 'my-catalog-model'],
2029
+ holidayDays: []
2030
+ });
2031
+ const store3 = new Map([[CONFIG_KEY, oldConfig]]);
2032
+ let captured3 = null;
2033
+ const window3 = Object.assign({}, fakeWindow, {
2034
+ opened: [],
2035
+ localStorage: {
2036
+ getItem: (k) => (store3.has(k) ? store3.get(k) : null),
2037
+ setItem: (k, v) => { store3.set(k, v); },
2038
+ removeItem: (k) => { store3.delete(k); }
2039
+ }
2040
+ });
2041
+ window3.__ModuleLoader__ = { load: (entry) => { captured3 = entry; } };
2042
+ const sandbox3 = {
2043
+ window: window3,
2044
+ document: {
2045
+ querySelector: () => null,
2046
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
2047
+ head: { appendChild() {} },
2048
+ addEventListener: () => {}, removeEventListener: () => {}
2049
+ },
2050
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
2051
+ setTimeout: () => 0, clearTimeout: () => {}
2052
+ };
2053
+ sandbox3.globalThis = sandbox3;
2054
+ vm.createContext(sandbox3);
2055
+ vm.runInContext(code, sandbox3, { filename: 'client.js' });
2056
+ const api3 = captured3.factory((name) => {
2057
+ if (name === 'react') return reactStub;
2058
+ throw new Error('unexpected require: ' + name);
2059
+ }).__test;
2060
+ const saved3 = () => JSON.parse(store3.get(CONFIG_KEY)).models;
2061
+ assert.deepStrictEqual(catalogPlain(api3.snapshot().catalogOrder), AA_VENDOR_ORDER.concat(['__custom']),
2062
+ '旧配置没有 catalogOrder → 默认补齐(10 厂商 + 自定义组末尾)');
2063
+ assert.deepStrictEqual(catalogPlain(api3.DEFAULT_CATALOG_ORDER), AA_VENDOR_ORDER.concat(['__custom']),
2064
+ 'DEFAULT_CATALOG_ORDER 应等于厂商顺序 + __custom');
2065
+ const normalizedOrder = toHost(api3.normalizeCatalogOrder(['zhipu', 'unknown', 'zhipu', '__custom', 'deepseek']));
2066
+ assert.deepStrictEqual(normalizedOrder.slice(0, 3), ['zhipu', '__custom', 'deepseek'], 'catalogOrder 迁移保留用户顺序');
2067
+ assert.strictEqual(normalizedOrder.length, 11, 'catalogOrder 覆盖 10 厂商 + __custom');
2068
+ assert.strictEqual(normalizedOrder.indexOf('unknown'), -1, 'catalogOrder 丢弃未知项');
2069
+ assert.strictEqual(normalizedOrder.filter((id) => id === 'zhipu').length, 1, 'catalogOrder 去重');
2070
+ const seeded = api3.snapshot().models;
2071
+ assert.strictEqual(api3.snapshot().priceVersion, 8, '迁移后价格库版本应为 8');
2072
+ OFFICIAL_NAMES.forEach((name) => {
2073
+ assert.ok(seeded[name] !== undefined, '官方模型应默认加入价格库:' + name);
2074
+ });
2075
+ assert.deepStrictEqual(catalogPlain(seeded['deepseek-flash']), {
2076
+ tiered: true, currency: 'CNY', feeMultiplier: 2,
2077
+ peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 },
2078
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 },
2079
+ /* v7:迁移给缺 base 的旧条目补「当前值 + 当前币种」 */
2080
+ base: { currency: 'CNY', peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 }, offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 } },
2081
+ }, '用户改过的官方条目迁移时不许覆盖(含 feeMultiplier)');
2082
+ assert.deepStrictEqual(catalogPlain(seeded['my-catalog-model']), {
2083
+ /* 3.0.4 起 USD 条目显示值折 CNY,原始 USD 值进 base。 */
2084
+ tiered: false, currency: 'CNY', feeMultiplier: 3,
2085
+ peak: { input: 47.2, cacheRead: 4.72, cacheWrite: 0, output: 74.17 },
2086
+ offPeak: { input: 23.6, cacheRead: 2.36, cacheWrite: 0, output: 37.08 },
2087
+ base: { currency: 'USD', peak: { input: 7, cacheRead: 0.7, cacheWrite: 0, output: 11 }, offPeak: { input: 3.5, cacheRead: 0.35, cacheWrite: 0, output: 5.5 } },
2088
+ }, '自建 USD 条目迁移后显示 CNY、原值进 base(含 feeMultiplier)');
2089
+ assert.deepStrictEqual(catalogPlain(seeded['GLM-5.3']), {
2090
+ tiered: false, currency: 'CNY',
2091
+ peak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 },
2092
+ offPeak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 },
2093
+ base: { currency: 'CNY', peak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 }, offPeak: { input: 8, cacheRead: 2, cacheWrite: 0, output: 28 } },
2094
+ }, '未配置过的官方模型按官网价播种(normalizeModels 会把单档 offPeak 归一)');
2095
+ assert.strictEqual(seeded['qwen3.8-flash'].peak.cacheRead, null, '官网未公布的字段保持 null');
2096
+ assert.strictEqual(seeded['deepseek-v4-pro'].peak.input, 9,
2097
+ 'DEFAULT_PRICES 里的键沿用内嵌 CNY 参考价(与恢复默认一致)');
2098
+
2099
+
2100
+ /* ②b v6 补播(老用户自动看到新模型):priceVersion=5 的价格库(官方目录 27 条里缺 kimi-k3)
2101
+ 迁移后自动补上 kimi-k3,已有条目(用户价 / feeMultiplier)一律不动,已下架模型不会被加回来。 */
2102
+ const v6Book = {};
2103
+ OFFICIAL_VENDORS.forEach((vendor) => {
2104
+ vendor.models.forEach((model) => {
2105
+ if (model.name === 'kimi-k3') return;
2106
+ v6Book[model.name] = catalogEntryOf(model);
2107
+ });
2108
+ });
2109
+ v6Book['deepseek-flash'] = {
2110
+ tiered: true, currency: 'CNY', feeMultiplier: 2,
2111
+ peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 },
2112
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 }
2113
+ };
2114
+ v6Book['my-catalog-model'] = {
2115
+ tiered: false, currency: 'USD', feeMultiplier: 3,
2116
+ peak: { input: 7, cacheRead: 0.7, cacheWrite: 0, output: 11 },
2117
+ offPeak: { input: 3.5, cacheRead: 0.35, cacheWrite: 0, output: 5.5 }
2118
+ };
2119
+ const store6 = new Map([[CONFIG_KEY, JSON.stringify({
2120
+ version: 6, priceVersion: 5, currency: 'CNY', models: v6Book,
2121
+ modelOrder: Object.keys(v6Book), holidayDays: []
2122
+ })]]);
2123
+ let captured6 = null;
2124
+ const window6 = Object.assign({}, fakeWindow, {
2125
+ opened: [],
2126
+ localStorage: {
2127
+ getItem: (k) => (store6.has(k) ? store6.get(k) : null),
2128
+ setItem: (k, v) => { store6.set(k, v); },
2129
+ removeItem: (k) => { store6.delete(k); }
2130
+ }
2131
+ });
2132
+ window6.__ModuleLoader__ = { load: (entry) => { captured6 = entry; } };
2133
+ const sandbox6 = {
2134
+ window: window6,
2135
+ document: {
2136
+ querySelector: () => null,
2137
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
2138
+ head: { appendChild() {} },
2139
+ addEventListener: () => {}, removeEventListener: () => {}
2140
+ },
2141
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
2142
+ setTimeout: () => 0, clearTimeout: () => {}
2143
+ };
2144
+ sandbox6.globalThis = sandbox6;
2145
+ vm.createContext(sandbox6);
2146
+ vm.runInContext(code, sandbox6, { filename: 'client.js' });
2147
+ const api6 = captured6.factory((name) => {
2148
+ if (name === 'react') return reactStub;
2149
+ throw new Error('unexpected require: ' + name);
2150
+ }).__test;
2151
+ const backfilled = api6.snapshot().models;
2152
+ assert.strictEqual(api6.snapshot().priceVersion, 8, 'v5 → v8 迁移后版本号升到 8');
2153
+ assert.deepStrictEqual(catalogPlain(backfilled['kimi-k3']), {
2154
+ tiered: false, currency: 'CNY',
2155
+ peak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 },
2156
+ offPeak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 },
2157
+ /* 播种时就带基准价 = 官网原值 + 官网币种 */
2158
+ base: { currency: 'CNY', peak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 }, offPeak: { input: 20, cacheRead: 2, cacheWrite: 20, output: 100 } },
2159
+ }, 'v6 补播:缺失的 kimi-k3 按官网价补进价格库');
2160
+ assert.deepStrictEqual(catalogPlain(backfilled['deepseek-flash']), {
2161
+ tiered: true, currency: 'CNY', feeMultiplier: 2,
2162
+ peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 },
2163
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 },
2164
+ base: { currency: 'CNY', peak: { input: 99, cacheRead: 0.04, cacheWrite: 0, output: 8 }, offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 } },
2165
+ }, 'v6 补播不动用户改过的官方条目(含 feeMultiplier)');
2166
+ assert.deepStrictEqual(catalogPlain(backfilled['my-catalog-model']), {
2167
+ tiered: false, currency: 'CNY', feeMultiplier: 3,
2168
+ peak: { input: 47.2, cacheRead: 4.72, cacheWrite: 0, output: 74.17 },
2169
+ offPeak: { input: 23.6, cacheRead: 2.36, cacheWrite: 0, output: 37.08 },
2170
+ base: { currency: 'USD', peak: { input: 7, cacheRead: 0.7, cacheWrite: 0, output: 11 }, offPeak: { input: 3.5, cacheRead: 0.35, cacheWrite: 0, output: 5.5 } },
2171
+ }, 'v6 补播不动自建条目的语义字段(USD 显示折 CNY、原值进 base)');
2172
+ assert.strictEqual(backfilled['GLM-5.2'], undefined, 'v6 补播不会把已下架的官方模型加回来');
2173
+ assert.deepStrictEqual(Object.keys(backfilled).sort(), OFFICIAL_NAMES.concat(['my-catalog-model']).sort(),
2174
+ 'v6 补播只补当前官方目录缺失项:27 条官方 + 1 条自建');
2175
+ console.log('v6 补播:v5 价格库自动补上 kimi-k3(27 条),用户条目不动、已下架模型不回流');
2176
+
2177
+ /* ②c v8 补播(2026-11-10):老用户 priceVersion=7 的价格库自动补上 Claude Fable 5.2;
2178
+ 用户已有条目(改过的价 / feeMultiplier)逐字段不动,已下架的旧模型不会被加回。 */
2179
+ const v8Book = {};
2180
+ const V8_DELETED_OFFICIAL = 'GLM-5.3';
2181
+ OFFICIAL_VENDORS.forEach((vendor) => {
2182
+ vendor.models.forEach((model) => {
2183
+ if (model.name === 'claude-fable-5.2' || model.name === V8_DELETED_OFFICIAL) return;
2184
+ v8Book[model.name] = catalogBookEntryOf(model);
2185
+ });
2186
+ });
2187
+ /* 用户改过的 fable 5.1(99 USD)入库形态:显示值折 CNY、base 保留原 USD。 */
2188
+ v8Book['claude-fable-5.1'] = {
2189
+ tiered: false, currency: 'CNY', feeMultiplier: 2,
2190
+ peak: { input: 667.5, cacheRead: 1.69, cacheWrite: 84.28, output: 337.12 },
2191
+ offPeak: { input: 667.5, cacheRead: 1.69, cacheWrite: 84.28, output: 337.12 },
2192
+ base: {
2193
+ currency: 'USD',
2194
+ peak: { input: 99, cacheRead: 0.25, cacheWrite: 12.5, output: 50 },
2195
+ offPeak: { input: 99, cacheRead: 0.25, cacheWrite: 12.5, output: 50 }
2196
+ }
2197
+ };
2198
+ const storeV8 = new Map([[CONFIG_KEY, JSON.stringify({
2199
+ version: 6, priceVersion: 7, currency: 'CNY', models: v8Book,
2200
+ modelOrder: Object.keys(v8Book), holidayDays: []
2201
+ })]]);
2202
+ let capturedV8 = null;
2203
+ const windowV8 = Object.assign({}, fakeWindow, {
2204
+ opened: [],
2205
+ localStorage: {
2206
+ getItem: (k) => (storeV8.has(k) ? storeV8.get(k) : null),
2207
+ setItem: (k, v) => { storeV8.set(k, v); },
2208
+ removeItem: (k) => { storeV8.delete(k); }
2209
+ }
2210
+ });
2211
+ windowV8.__ModuleLoader__ = { load: (entry) => { capturedV8 = entry; } };
2212
+ const sandboxV8 = {
2213
+ window: windowV8,
2214
+ document: {
2215
+ querySelector: () => null,
2216
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
2217
+ head: { appendChild() {} },
2218
+ addEventListener: () => {}, removeEventListener: () => {}
2219
+ },
2220
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
2221
+ setTimeout: () => 0, clearTimeout: () => {}
2222
+ };
2223
+ sandboxV8.globalThis = sandboxV8;
2224
+ vm.createContext(sandboxV8);
2225
+ vm.runInContext(code, sandboxV8, { filename: 'client.js' });
2226
+ const apiV8 = capturedV8.factory((name) => {
2227
+ if (name === 'react') return reactStub;
2228
+ throw new Error('unexpected require: ' + name);
2229
+ }).__test;
2230
+ const upgraded = apiV8.snapshot().models;
2231
+ const fable52 = OFFICIAL_VENDORS.filter((one) => one.id === 'anthropic')[0].models.filter((one) => one.name === 'claude-fable-5.2')[0];
2232
+ const fable52Price = catalogBookEntryOf(fable52);
2233
+ /* normalizeModels 会把单档条目的 offPeak 补成 peak 副本(官网单档价)。 */
2234
+ fable52Price.offPeak = Object.assign({}, fable52Price.peak);
2235
+ assert.strictEqual(apiV8.snapshot().priceVersion, 8, 'v7 → v8 迁移后版本号升到 8');
2236
+ assert.deepStrictEqual(catalogPlain(upgraded['claude-fable-5.2']), catalogPlain(fable52Price),
2237
+ 'v8 补播:老用户 priceVersion 7 自动出现 Claude Fable 5.2(官网价 + 基准价)');
2238
+ assert.deepStrictEqual(catalogPlain(upgraded['claude-fable-5.1']), catalogPlain(v8Book['claude-fable-5.1']),
2239
+ 'v8 补播不覆盖用户已有条目(fable 5.1 的改价 + feeMultiplier 保留)');
2240
+ assert.strictEqual(upgraded['GLM-5.2'], undefined, 'v8 补播不会把已下架的旧模型加回来');
2241
+ assert.strictEqual(upgraded[V8_DELETED_OFFICIAL], undefined, 'v8 补播不会把用户主动删除的当前官方模型加回来');
2242
+ assert.deepStrictEqual(Object.keys(upgraded).sort(), OFFICIAL_NAMES.filter((name) => name !== V8_DELETED_OFFICIAL).sort(),
2243
+ 'v8 补播只补本次新增的 Fable 5.2,不重播整个官方目录');
2244
+ console.log('v8 补播:priceVersion 7 老用户自动出现 Fable 5.2,已有价格/删除项不被覆盖或加回');
2245
+
2246
+ /* ③ 目录渲染:10 厂商按 AA 智力指数排序、每个官方模型直接是价格卡,没有可点名字 */
2247
+ const hooks3 = makeHooks();
2248
+ const catalogTree = withHooks(hooks3, () => api3.SettingsSection(props));
2249
+ const catalogVendors = collectByClass(catalogTree, 'dsb-catalog-vendor');
2250
+ assert.deepStrictEqual(catalogVendors.map((one) => one.props.key), AA_VENDOR_ORDER.concat(['__custom']),
2251
+ '目录按 AA 智力指数顺序分组(自定义组在最后)');
2252
+ assert.strictEqual(collectByClass(catalogTree, 'dsb-catalog-pick').length, 0, '目录里不再有可点模型名');
2253
+ /* 用户第 8 轮:目录标题与「N 个模型」计数一并删掉 */
2254
+ assert.strictEqual(collectByClass(catalogTree, 'dsb-catalog-title').length, 0, '「官方模型目录」标题已删除');
2255
+ assert.strictEqual(collectByClass(catalogTree, 'dsb-catalog-count').length, 0, '「N 个模型」计数已删除');
2256
+ assert.strictEqual(textOf(catalogTree).indexOf('官方模型目录'), -1, '界面上不出现「官方模型目录」');
2257
+ assert.strictEqual(textOf(catalogTree).indexOf('个模型'), -1, '界面上不出现「个模型」');
2258
+ const catalogVendorByKey = (tree, key) => collectByClass(tree, 'dsb-catalog-vendor').filter((one) => one.props.key === key)[0];
2259
+ OFFICIAL_VENDORS.forEach((vendor) => {
2260
+ const node = catalogVendorByKey(catalogTree, vendor.id);
2261
+ assert.ok(node !== undefined, '厂商分组缺失:' + vendor.id);
2262
+ const names = vendor.models.map((one) => one.name);
2263
+ assert.deepStrictEqual(collectByClass(node, 'dsb-model').map((one) => one.props.key), names,
2264
+ '厂商组里按数据顺序列出该厂商的官方模型卡:' + vendor.id);
2265
+ names.forEach((name) => {
2266
+ const card = collectByClass(node, 'dsb-model').filter((one) => one.props.key === name)[0];
2267
+ assert.ok(buttonByLabel(card, t('priceEdit')) !== undefined, '价格卡有「修改」:' + name);
2268
+ assert.ok(buttonByLabel(card, t('priceRemove')) !== undefined, '价格卡有「删除」:' + name);
2269
+ });
2270
+ assert.strictEqual(collectByClass(node, 'dsb-catalog-pick').length, 0, '组内无点名字按钮:' + vendor.id);
2271
+ assert.strictEqual(collectByClass(node, 'dsb-catalog-source').length, 0, '不再有来源链接:' + vendor.id);
2272
+ assert.strictEqual(collectByClass(node, 'dsb-catalog-rate').length, 0, '不再有费率说明:' + vendor.id);
2273
+ assert.strictEqual(collectByClass(node, 'dsb-catalog-actions').length, 0, '不再有添加按钮容器:' + vendor.id);
2274
+ assert.strictEqual(collectByClass(node, 'dsb-action').length, names.length * 2, '每张卡只有修改/删除:' + vendor.id);
2275
+ });
2276
+ const customVendor3 = catalogVendorByKey(catalogTree, '__custom');
2277
+ assert.ok(customVendor3 !== undefined, '自建模型进入自定义分组');
2278
+ assert.deepStrictEqual(collectByClass(customVendor3, 'dsb-model').map((one) => one.props.key), ['my-catalog-model']);
2279
+ assert.strictEqual(findInput(catalogTree, 'text').props.placeholder, t('priceNewModel'), '自定义模型输入框保留');
2280
+
2281
+ /* ④ 删除 → 行消失;恢复默认 → 按官网价找回,自建条目与 feeMultiplier 保留 */
2282
+ const zhipuNode = catalogVendorByKey(catalogTree, 'zhipu');
2283
+ const glmCard = collectByClass(zhipuNode, 'dsb-model').filter((one) => one.props.key === 'GLM-5.3')[0];
2284
+ buttonByLabel(glmCard, t('priceRemove')).props.onClick();
2285
+ assert.strictEqual(saved3()['GLM-5.3'], undefined, '删除后价格库里不再有该官方模型');
2286
+ let nextTree = withHooks(hooks3, () => api3.SettingsSection(props));
2287
+ assert.deepStrictEqual(collectByClass(catalogVendorByKey(nextTree, 'zhipu'), 'dsb-model').map((one) => one.props.key),
2288
+ ['GLM-5.3-Flash', 'GLM-5.3-FlashX'], '被删除的官方模型不再显示');
2289
+ const resetBtn3 = (function find(node) {
2290
+ let found = null;
2291
+ (function walk(n) {
2292
+ if (found !== null || n === null || n === undefined || typeof n !== 'object') return;
2293
+ if (Array.isArray(n)) { n.forEach(walk); return; }
2294
+ if (n.type === 'button' && textOf(n) === t('reset')) { found = n; return; }
2295
+ walk(n.children);
2296
+ })(node);
2297
+ return found;
2298
+ })(nextTree);
2299
+ assert.ok(resetBtn3 !== null, '恢复默认按钮仍在');
2300
+ resetBtn3.props.onClick();
2301
+ nextTree = withHooks(hooks3, () => api3.SettingsSection(props));
2302
+ const glmModel = OFFICIAL_VENDORS.filter((one) => one.id === 'zhipu')[0].models.filter((one) => one.name === 'GLM-5.3')[0];
2303
+ assert.deepStrictEqual(catalogPlain(saved3()['GLM-5.3']), catalogPlain(catalogEntryWithBase(glmModel)),
2304
+ '恢复默认把删掉的官方模型按官网价找回');
2305
+ assert.ok(saved3()['my-catalog-model'] !== undefined, '恢复默认保留自建条目');
2306
+ assert.strictEqual(saved3()['my-catalog-model'].feeMultiplier, 3, '恢复默认保留自建条目的费用倍率');
2307
+ assert.deepStrictEqual(collectByClass(catalogVendorByKey(nextTree, 'zhipu'), 'dsb-model').map((one) => one.props.key),
2308
+ ['GLM-5.3', 'GLM-5.3-Flash', 'GLM-5.3-FlashX'], '恢复默认后目录行回来');
2309
+ console.log('目录播种:27 条官方模型默认在价格表;目录只有价格卡;删除后行消失;恢复默认找回');
2310
+ }
2311
+
2312
+ /* 需求 6:用户要求删除的两条官方默认模型(MiniMax-M3.1-Flash / step-5-preview)
2313
+ 要从老用户 config.models 里清掉。v8 起 PRICE_RETIRED_PRUNE_VERSION 与 PRICE_VERSION 同步,
2314
+ 价格库版本 7 的老用户升级时清理一次。 */
2315
+ {
2316
+ const staleBook = {
2317
+ 'MiniMax-M3.1-Flash': {
2318
+ tiered: false, currency: 'CNY',
2319
+ peak: { input: 1, cacheRead: 0, cacheWrite: 0, output: 2 },
2320
+ offPeak: { input: 1, cacheRead: 0, cacheWrite: 0, output: 2 }
2321
+ },
2322
+ 'step-5-preview': {
2323
+ tiered: false, currency: 'CNY',
2324
+ peak: { input: 3, cacheRead: 0, cacheWrite: 0, output: 6 },
2325
+ offPeak: { input: 3, cacheRead: 0, cacheWrite: 0, output: 6 }
2326
+ },
2327
+ 'my-custom-model': {
2328
+ tiered: false, currency: 'USD',
2329
+ peak: { input: 7, cacheRead: 0, cacheWrite: 0, output: 9 },
2330
+ offPeak: { input: 7, cacheRead: 0, cacheWrite: 0, output: 9 }
2331
+ }
2332
+ };
2333
+ const storeRetired = new Map([[CONFIG_KEY, JSON.stringify({
2334
+ version: 6, priceVersion: api.PRICE_VERSION - 1, currency: 'CNY',
2335
+ models: staleBook, modelOrder: Object.keys(staleBook), holidayDays: []
2336
+ })]]);
2337
+ let capturedRetired = null;
2338
+ const windowRetired = Object.assign({}, fakeWindow, {
2339
+ opened: [],
2340
+ localStorage: {
2341
+ getItem: (k) => (storeRetired.has(k) ? storeRetired.get(k) : null),
2342
+ setItem: (k, v) => { storeRetired.set(k, v); },
2343
+ removeItem: (k) => { storeRetired.delete(k); }
2344
+ }
2345
+ });
2346
+ windowRetired.__ModuleLoader__ = { load: (entry) => { capturedRetired = entry; } };
2347
+ const sandboxRetired = {
2348
+ window: windowRetired,
2349
+ document: {
2350
+ querySelector: () => null,
2351
+ createElement: () => ({ dataset: {}, style: {}, appendChild() {} }),
2352
+ head: { appendChild() {} },
2353
+ addEventListener: () => {}, removeEventListener: () => {}
2354
+ },
2355
+ console, Promise, Date, Math, JSON, Object, Array, Number, String, Boolean, Symbol, Set, Map, Error,
2356
+ setTimeout: () => 0, clearTimeout: () => {}
2357
+ };
2358
+ sandboxRetired.globalThis = sandboxRetired;
2359
+ vm.createContext(sandboxRetired);
2360
+ vm.runInContext(code, sandboxRetired, { filename: 'client.js' });
2361
+ const apiRetired = capturedRetired.factory((name) => {
2362
+ if (name === 'react') return reactStub;
2363
+ throw new Error('unexpected require: ' + name);
2364
+ }).__test;
2365
+ assert.strictEqual(apiRetired.PRICE_VERSION, 8, '价格库迁移版本应为 8');
2366
+ assert.strictEqual(apiRetired.PRICE_RETIRED_PRUNE_VERSION, 8, '清理门槛应为 8');
2367
+ assert.strictEqual(apiRetired.snapshot().priceVersion, 8, 'v7 → v8 迁移后价格库版本升到 8');
2368
+ const pruned = apiRetired.snapshot().models;
2369
+ assert.strictEqual(pruned['MiniMax-M3.1-Flash'], undefined, 'MiniMax-M3.1-Flash 应从老用户价格库清掉');
2370
+ assert.strictEqual(pruned['step-5-preview'], undefined, 'step-5-preview 应从老用户价格库清掉');
2371
+ assert.ok(pruned['my-custom-model'] !== undefined, '用户自建条目不受影响');
2372
+ console.log('价格库迁移:MiniMax-M3.1-Flash / step-5-preview 已从老用户配置清除(v7 → v8 清理一次)');
2373
+ }
2374
+
2375
+ /* ------------------------------------------- 段勾选:取消勾选后留在原位 */
2376
+ settingsHooks.values.length = 0;
2377
+ let segTree = renderSettings();
2378
+ const namesBefore = collectByClass(segTree, 'dsb-name').map(textOf);
2379
+ const cacheRow = collectByClass(segTree, 'dsb-row')
2380
+ .filter((row) => textOf(collectByClass(row, 'dsb-name')[0]) === zh.segCacheHit)[0];
2381
+ assert.ok(cacheRow !== undefined, '设置页应有缓存命中率那一行');
2382
+ findInput(cacheRow, 'checkbox').props.onChange({ target: { checked: false } });
2383
+ const afterToggle = JSON.parse(store.get(CONFIG_KEY));
2384
+ assert.deepStrictEqual(afterToggle.hidden, ['cacheHit'], '取消勾选应写进 hidden');
2385
+ assert.strictEqual(afterToggle.segments.indexOf('cacheHit'), FACTORY_ORDER.indexOf('cacheHit'), '取消勾选后段序位置不变');
2386
+ segTree = renderSettings();
2387
+ assert.deepStrictEqual(collectByClass(segTree, 'dsb-name').map(textOf), namesBefore, '取消勾选后设置页顺序应保持不变');
2388
+ const barAfterToggle = textOf(renderBar()).replace(/\s+/g, ' ');
2389
+ assert.ok(!barAfterToggle.includes('缓存命中'), '取消勾选的段不应再出现在底栏,实际:' + barAfterToggle);
2390
+ console.log('段勾选:取消后仍在原位');
2391
+
2392
+ /* ------------------------------------ 拖动:自绘 + 松手才落盘(原生 DnD 会吃掉滚轮) */
2393
+ /* 落点算法先单独测:纯函数,不碰 DOM。
2394
+ 9 个槽位、行高 40、行距 48(行间有 gap)→ 中线 216/264/312/.../552 */
2395
+ const slotList = (tops) => tops.map((top) => ({ top: top, height: 40 }));
2396
+ const nine = slotList([148, 196, 244, 292, 340, 388, 436, 484, 532]);
2397
+ assert.strictEqual(api.dropIndexAt(nine, 0, 0, 148, 216), 0, '下边界刚好到中线不换位');
2398
+ assert.strictEqual(api.dropIndexAt(nine, 0, 0, 148, 217), 1, '压过第一行中线 → 索引 1');
2399
+ assert.strictEqual(api.dropIndexAt(nine, 0, 0, 148, 545), 7, 'gap 累积不会让影子提前落到最后一行');
2400
+ assert.strictEqual(api.dropIndexAt(nine, 0, 0, 148, 553), 8, '再压一点才落到最后一行');
2401
+ assert.strictEqual(api.dropIndexAt(nine, 0, 5, 300, 340), 3, '上边界举过上一行中线 → 索引 3');
2402
+ assert.strictEqual(api.dropIndexAt(nine, 100, 0, 148, 645), 7, '页面滚动 100px 后判定照样成立');
2403
+ assert.deepStrictEqual(api.moveItem(['a', 'b', 'c', 'd'], 0, 2), ['b', 'c', 'a', 'd'], 'moveItem 落位正确');
2404
+ console.log('落点算法:边界压过中线即换位,gap 与滚动都不影响');
2405
+
2406
+ settingsHooks.values.length = 0;
2407
+ let dragTree = renderSettings();
2408
+ let dragRows = collectByClass(dragTree, 'dsb-row');
2409
+ assert.strictEqual(dragRows.length, 10, '上下文占用 1 行 + 段 9 行,实际 ' + dragRows.length);
2410
+ assert.strictEqual(dragRows[0].props.onPointerDown, undefined, '上下文占用固定在栏首,不参与拖拽');
2411
+ const rowByKey = (rows, key) => rows.filter((row) => row.props.key === key)[0];
2412
+ const beforeDrag = JSON.parse(store.get(CONFIG_KEY)).segments;
2413
+ /* 只有右侧六个点能抓:点行内其他位置不该起浮层 */
2414
+ rowByKey(dragRows, 'status').props.onPointerDown({
2415
+ button: 0, clientY: 160, pointerId: 9,
2416
+ target: { tagName: 'SPAN', className: 'dsb-check' },
2417
+ currentTarget: {}
2418
+ });
2419
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-drag-card').length, 0, '点行内空白不启动拖动');
2420
+ /* 按住六点往下拖 90px:下边界越过下面两行的中线 → 落到索引 2 */
2421
+ rowByKey(dragRows, 'status').props.onPointerDown({
2422
+ button: 0, clientY: 160, pointerId: 1,
2423
+ target: { tagName: 'SPAN', className: 'dsb-handle' },
2424
+ currentTarget: {}
2425
+ });
2426
+ dragTree = renderSettings();
2427
+ dragRows = collectByClass(dragTree, 'dsb-row');
2428
+ assert.strictEqual(collectByClass(dragTree, 'dsb-drag-card').length, 1, '跟手的浮层已经起来');
2429
+ assert.ok(String(rowByKey(dragRows, 'status').props.className).indexOf('dsb-dragging') !== -1, '原位留的是淡影');
2430
+ rowByKey(dragRows, 'status').props.onPointerMove({ clientY: 250 });
2431
+ assert.deepStrictEqual(JSON.parse(store.get(CONFIG_KEY)).segments, beforeDrag, '拖动过程中不落盘');
2432
+ dragTree = renderSettings();
2433
+ dragRows = collectByClass(dragTree, 'dsb-row');
2434
+ assert.deepStrictEqual(dragRows.slice(1).map((row) => row.props.key),
2435
+ ['counts', 'cacheHit', 'status', 'tps', 'ttft', 'sessionTime', 'lastCost', 'cost', 'balance'],
2436
+ '拖动中就按落点排好,实际 ' + JSON.stringify(dragRows.slice(1).map((row) => row.props.key)));
2437
+ rowByKey(dragRows, 'status').props.onPointerUp({});
2438
+ assert.deepStrictEqual(JSON.parse(store.get(CONFIG_KEY)).segments,
2439
+ ['counts', 'cacheHit', 'status', 'tps', 'ttft', 'sessionTime', 'lastCost', 'cost', 'balance'],
2440
+ '松手才落盘,实际 ' + JSON.stringify(JSON.parse(store.get(CONFIG_KEY)).segments));
2441
+ assert.strictEqual(collectByClass(renderSettings(), 'dsb-drag-card').length, 0, '松手后浮层收掉');
2442
+ console.log('拖动:浮层跟手 / 原位留影 / 松手才落盘');
2443
+
2444
+ /* ------------------------------------------------ 价格目录厂商拖拽(3.0.4 基线未实现) */
2445
+ {
2446
+ settingsHooks.values.length = 0;
2447
+ catalogSeq = 0;
2448
+ const catalogDragTree = renderSettings();
2449
+ const catalogVendorNodes = collectByClass(catalogDragTree, 'dsb-catalog-vendor');
2450
+ assert.ok(catalogVendorNodes.length > 0, '官方厂商目录已渲染');
2451
+ assert.strictEqual(collectByClass(catalogDragTree, 'dsb-catalog-handle').length, 0, '3.0.4 基线无厂商拖拽把手');
2452
+ assert.strictEqual(collectByClass(catalogDragTree, 'dsb-handle').filter((one) => String(one.props.className).indexOf('dsb-catalog-handle') !== -1).length, 0, '厂商行不渲染拖拽把手');
2453
+ assert.strictEqual(collectByClass(catalogDragTree, 'dsb-drag-card').length, 0, '3.0.4 基线无厂商拖拽浮层');
2454
+ console.log('厂商目录:3.0.4 基线无拖拽把手/浮层(目录顺序固定)');
2455
+ }
2456
+
2457
+ /* 厂商目录:点目录外收起全部展开项,点目录内不关 */
2458
+ {
2459
+ const clickBefore = (docListeners.click === undefined ? [] : docListeners.click).slice();
2460
+ settingsHooks.values.length = 0;
2461
+ /* useEffect 替身默认不跑;这里显式开启,才能拿到组件注册在 document 上的 click 回调 */
2462
+ runEffects = true;
2463
+ renderSettings();
2464
+ runEffects = false;
2465
+ const added = (docListeners.click === undefined ? [] : docListeners.click)
2466
+ .filter((fn) => clickBefore.indexOf(fn) === -1);
2467
+ assert.strictEqual(added.length, 1, '设置页应挂且只挂一个厂商目录 click 监听,实际 ' + added.length + ' 个');
2468
+ const onCatalogDocClick = added[0];
2469
+ const v1 = { open: true };
2470
+ const v2 = { open: true };
2471
+ openCatalogVendors.push(v1, v2);
2472
+ const inside = { closest: (selector) => (selector === '.dsb-price-catalog' ? {} : null) };
2473
+ onCatalogDocClick({ target: inside });
2474
+ assert.strictEqual(v1.open, true, '点目录内不关闭厂商分组');
2475
+ assert.strictEqual(v2.open, true, '点目录内不关闭第二个厂商分组');
2476
+ const outside = { closest: () => null };
2477
+ onCatalogDocClick({ target: outside });
2478
+ assert.strictEqual(v1.open, false, '点目录外关闭厂商分组');
2479
+ assert.strictEqual(v2.open, false, '点目录外关闭全部展开的厂商分组');
2480
+ openCatalogVendors.length = 0;
2481
+ (docListeners.click === undefined ? [] : docListeners.click.slice()).forEach((fn) => {
2482
+ if (clickBefore.indexOf(fn) === -1) sandbox.document.removeEventListener('click', fn);
2483
+ });
2484
+ console.log('厂商目录:点目录外收起全部展开项;点目录内不关');
2485
+ }
2486
+
2487
+ /* ------------------------------------------------ 跟手浮层必须 portal 到 body */
2488
+ /* 实测 2026-10-07(真机 + 无头 Chrome 复现):壁纸引擎给设置面板挂了 backdrop-filter
2489
+ (body[data-we-glass-window] [role="dialog"]:has([data-slot="settings.section"])),
2490
+ 而非 none 的 backdrop-filter 会让该元素成为 position:fixed 后代的**包含块** ——
2491
+ 浮层于是改成相对设置面板定位(实测偏移 dx=220/dy=80),又被面板的 overflow:hidden 裁掉。
2492
+ 修法是 portal 到 body。这里用一个能 portal 的替身渲染一次,锁住这条路径。 */
2493
+ {
2494
+ const portalCalls = [];
2495
+ const bodyNode = { nodeType: 1, tagName: 'BODY' };
2496
+ const domStub = {
2497
+ createPortal: (node, container) => {
2498
+ portalCalls.push({ node: node, container: container });
2499
+ return { type: '__portal', props: { node: node, container: container }, children: [] };
2500
+ }
2501
+ };
2502
+ const mod2 = captured.factory((name) => {
2503
+ if (name === 'react') return reactStub;
2504
+ if (name === 'react-dom') return domStub;
2505
+ throw new Error('unexpected require: ' + name);
2506
+ });
2507
+ const api2 = mod2.__test;
2508
+ /* document.body 要存在,代码才会走 portal 分支 */
2509
+ const prevBody = sandbox.document.body;
2510
+ sandbox.document.body = bodyNode;
2511
+ try {
2512
+ const rows2 = collectByClass(withHooks(settingsHooks, () => api2.SettingsSection(props)), 'dsb-row');
2513
+ rowByKey(rows2, 'status').props.onPointerDown({
2514
+ button: 0, clientY: 160, pointerId: 9,
2515
+ target: { tagName: 'SPAN', className: 'dsb-handle' },
2516
+ currentTarget: {}
2517
+ });
2518
+ withHooks(settingsHooks, () => api2.SettingsSection(props));
2519
+ assert.strictEqual(portalCalls.length, 1, '拖动浮层走 createPortal 渲染,实际调用 ' + portalCalls.length + ' 次');
2520
+ assert.strictEqual(portalCalls[0].container, bodyNode, 'portal 容器必须是 document.body(脱离被 backdrop-filter 改锚的祖先)');
2521
+ assert.ok(String(portalCalls[0].node.props.className).indexOf('dsb-drag-card') !== -1, 'portal 里送的是浮层节点');
2522
+ /* 浮层内部那几件也要跟着过去,否则 portal 后它们会失去样式 */
2523
+ const inner = collectByClass(portalCalls[0].node, 'dsb-check');
2524
+ assert.strictEqual(inner.length, 1, '浮层里带着勾选框(它的样式已挂到 .dsb-drag-card 名下)');
2525
+ } finally {
2526
+ sandbox.document.body = prevBody;
2527
+ }
2528
+ /* 收尾:把这次拖动结束掉,免得影响后面的用例 */
2529
+ const rows3 = collectByClass(withHooks(settingsHooks, () => api2.SettingsSection(props)), 'dsb-row');
2530
+ rowByKey(rows3, 'status').props.onPointerUp({});
2531
+ console.log('拖动浮层:portal 到 body(避开 backdrop-filter 包含块),内部样式随行');
2532
+ }
2533
+
2534
+ /* 指针已被系统吞掉(微信截屏那种):左键其实已松开,再收到移动就按取消处理 */
2535
+ settingsHooks.values.length = 0;
2536
+ const keptOrder = JSON.parse(store.get(CONFIG_KEY)).segments;
2537
+ dragTree = renderSettings();
2538
+ dragRows = collectByClass(dragTree, 'dsb-row');
2539
+ rowByKey(dragRows, 'status').props.onPointerDown({
2540
+ button: 0, clientY: 160, pointerId: 2,
2541
+ target: { tagName: 'SPAN', className: 'dsb-handle' },
2542
+ currentTarget: {}
2543
+ });
2544
+ dragTree = renderSettings();
2545
+ dragRows = collectByClass(dragTree, 'dsb-row');
2546
+ rowByKey(dragRows, 'status').props.onPointerMove({ clientY: 320, buttons: 0 });
2547
+ dragTree = renderSettings();
2548
+ assert.strictEqual(collectByClass(dragTree, 'dsb-drag-card').length, 0, '左键已松开时浮层立刻收掉');
2549
+ assert.deepStrictEqual(JSON.parse(store.get(CONFIG_KEY)).segments, keptOrder, '打断算取消,不写配置');
2550
+ console.log('拖动被打断:回原位,不落盘');
2551
+
2552
+ /* 底部只剩「去 GitHub 点 star」+「恢复默认设置」(恢复默认在后),版本号贴右;
2553
+ 设置页不再有「更新节假峰谷」按钮(改为每年 12/31 自动更新,见 StatusBar 时钟 effect) */
2554
+ const footTree = renderSettings();
2555
+ const foot = collectByClass(footTree, 'dsb-foot')[0];
2556
+ assert.ok(foot !== undefined, '底部区存在');
2557
+ assert.deepStrictEqual(collectByClass(foot, 'dsb-action').map((one) => one.props.key), ['__star', '__reset'],
2558
+ '底部按钮顺序:去 GitHub / 恢复默认(恢复默认在后)');
2559
+ assert.strictEqual(collectByClass(footTree, 'dsb-current-act').length, 0, '价格卡行右端不再有动作区');
2560
+ assert.strictEqual(textOf(footTree).indexOf('更新节假峰谷'), -1, '设置页不再出现「更新节假峰谷」');
2561
+ assert.strictEqual(textOf(footTree).indexOf('已写入'), -1, '设置页不再出现节假日状态文案');
2562
+ const star = buttonByLabel(footTree, 'GitHub支持');
2563
+ assert.ok(star !== undefined, 'GitHub 支持按钮文案与词条一致');
2564
+ /* 悬停提示:毛玻璃沿用 .dsb-tip,文字是那句邀请,左边界贴按钮左边界(left:0 由样式保证) */
2565
+ const starWrap = collectByClass(foot, 'dsb-star-wrap')[0];
2566
+ assert.ok(starWrap !== undefined, '按钮外层有定位容器');
2567
+ const starTip = collectByClass(starWrap, 'dsb-star-tip')[0];
2568
+ assert.ok(starTip !== undefined, '悬停提示节点存在');
2569
+ assert.strictEqual(textOf(starTip), '你的支持是我最大的动力!请帮我点亮Star吧~', '提示文案');
2570
+ assert.ok(String(starTip.props.className).indexOf('dsb-tip') !== -1, '提示沿用主气泡那套毛玻璃材质');
2571
+ assert.deepStrictEqual(collectByClass(starWrap, 'dsb-action').map((one) => one.props.key), ['__star'], '外层里是那颗按钮');
2572
+ assert.strictEqual(starWrap.children[0].props.key, '__startip', '提示在按钮前面');
2573
+ fakeWindow.opened.length = 0;
2574
+ star.props.onClick();
2575
+ assert.deepStrictEqual(fakeWindow.opened, [['https://github.com/raphael-y7/dsh-desktop-statusbar', '_blank']],
2576
+ '点 star 按钮开项目主页(实际 ' + JSON.stringify(fakeWindow.opened) + ')');
2577
+ console.log('底部:去 GitHub + 恢复默认(后者在后);更新节假峰谷按钮已删除;star 点击开项目主页');
2578
+
2579
+ /* 会话数据气泡:三行都能点开下钻(技能注入 / 工具调用 / 压缩次数)。
2580
+ 点开是同一个气泡换内容 —— 标题变成子视图名、内容换成明细列表,点标题回上一层。
2581
+ 老的「悬停技能注入弹二次气泡」已去掉,这里顺带守住它不再回来。 */
2582
+ const progressView = {
2583
+ turn: 3, turnSteps: 2, toolCalls: 12,
2584
+ toolCounts: { read: 7, edit: 3, pwsh: 2 },
2585
+ /* 契约:每注入一次记一条 `{ name, manual }`;ponytail 注入两次、其中一次是用户手动调用 */
2586
+ skills: [
2587
+ { name: 'ponytail', manual: false },
2588
+ { name: 'my-dow-theory', manual: false },
2589
+ { name: 'ponytail', manual: true }
2590
+ ],
2591
+ /* 全局提示词(~/.dsh/AGENTS.md 这类):也算一次注入,并计入那一行的数 */
2592
+ globalInstruction: 'AGENTS.md',
2593
+ compactCount: 2, compactTurn: 32, compactStep: 2,
2594
+ /* 只给成功的压缩;第二条是用户手动压缩:轮间压缩没有 turn,by afterTurn 记「第20轮后」,
2595
+ 名字后带上标星号(星号后置) */
2596
+ compacts: [
2597
+ { turn: 12, step: 3, manual: false, afterTurn: null },
2598
+ { turn: null, step: null, manual: true, afterTurn: 20 }
2599
+ ]
2600
+ };
2601
+ const withProgress = (progress) => Object.assign({}, props, {
2602
+ useProjection: (key) => {
2603
+ if (key === 'desktopStatusbarProgress') return progress;
2604
+ /* 轮次项要有官方 sessionStats 才出现(没步数就整段不显示) */
2605
+ return key === 'sessionStats' ? { turns: 3, steps: 12 } : undefined;
2606
+ }
2607
+ });
2608
+ const skillProps = withProgress(progressView);
2609
+ const clickEvent = () => ({
2610
+ currentTarget: { getBoundingClientRect: () => ({ left: 200, top: 700, width: 80, height: 20, right: 280 }) },
2611
+ stopPropagation: noop
2612
+ });
2613
+ /* 指定触发项位置的事件:验「居中会越界」这类要控制触发项离底栏两端多远 */
2614
+ const clickAt = (left, width) => ({
2615
+ currentTarget: { getBoundingClientRect: () => ({ left: left, top: 700, width: width, height: 20, right: left + width }) },
2616
+ stopPropagation: noop
2617
+ });
2618
+ const renderCounts = (progress) => withHooks(barHooks, () => api.StatusBar(progress === undefined ? skillProps : withProgress(progress)));
2619
+ const panelTitle = (tree) => {
2620
+ const head = collectByClass(tree, 'dsb-meter-headline')[0];
2621
+ return head === undefined ? '' : textOf(head);
2622
+ };
2623
+ const rowAt = (tree, label) => collectByClass(tree, 'dsb-meter-row').filter((one) => textOf(one).indexOf(label) !== -1)[0];
2624
+ const listRows = (tree) => collectByClass(tree, 'dsb-meter-row').map((one) => ({
2625
+ name: textOf(collectByClass(one, 'dsb-meter-name')[0]),
2626
+ value: textOf(collectByClass(one, 'dsb-meter-value')[0])
2627
+ }));
2628
+
2629
+ barHooks.values.length = 0;
2630
+ const countsCell = collectByClass(renderCounts(), 'dsb-seg-click').filter((one) => one.props.key === '__segcounts')[0];
2631
+ assert.ok(countsCell !== undefined, '轮次项可点开');
2632
+ countsCell.props.onClick(clickEvent());
2633
+ let tree = renderCounts();
2634
+ assert.strictEqual(panelTitle(tree), '会话数据', '根视图标题仍是会话数据');
2635
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-tight').length, 0, '根视图不收紧间隙(仍是 5ch)');
2636
+ const skillRow = rowAt(tree, '技能注入');
2637
+ assert.ok(skillRow !== undefined, '会话数据气泡里有技能注入那一行');
2638
+ assert.deepStrictEqual(listRows(tree).map((one) => one.name), ['上下文压缩', '技能注入', '工具调用'], '行序:上下文压缩 → 技能注入 → 工具调用');
2639
+ /* bf350be 起:技能注入数 = 列表里**不同技能**的个数(含 AGENTS.md),不再按注入次数重复计数。 */
2640
+ assert.deepStrictEqual(listRows(tree).map((one) => one.value), ['2', '3', '12'], '三个数都不带单位;技能注入按不同技能计数(ponytail 两次=1 + my-dow-theory + AGENTS.md = 3)');
2641
+ assert.strictEqual(typeof skillRow.props.onMouseEnter, 'undefined', '技能注入那行不再有悬停回调');
2642
+ assert.strictEqual(typeof skillRow.props.onClick, 'function', '技能注入那行可点开');
2643
+ assert.ok(textOf(skillRow).indexOf('›') === -1, '可点行不带箭头(只靠底色与光标表示可点)');
2644
+
2645
+
2646
+ /* 点开技能注入 → 同一个气泡换成子视图,不再有二次气泡 */
2647
+ skillRow.props.onClick(clickEvent());
2648
+ tree = renderCounts();
2649
+ assert.strictEqual(panelTitle(tree), '技能注入', '子视图标题变成技能注入');
2650
+ assert.ok(collectByClass(tree, 'dsb-meter-back').length > 0, '子视图标题可点返回');
2651
+ assert.ok(textOf(collectByClass(tree, 'dsb-meter-back')[0]).indexOf('‹') === -1, '返回入口不带箭头');
2652
+ assert.strictEqual(collectByClass(tree, 'dsb-hovercard').length, 0, '不再出现二次气泡');
2653
+ assert.deepStrictEqual(listRows(tree).map((one) => one.name), ['AGENTS.md', 'ponytail*', 'my-dow-theory'],
2654
+ '全局提示词 AGENTS.md 固定第一、不参与技能排序;其余按名字长短(ponytail 8 < my-dow-theory 13);手动调用的 ponytail 星号在**名字后面**,实际 ' + JSON.stringify(listRows(tree)));
2655
+ assert.deepStrictEqual(listRows(tree).map((one) => one.value), ['', '', ''],
2656
+ '技能注入只列名字、不显示次数(次数只在排序里用到;AGENTS.md 同样不显示)');
2657
+ /* 星号是上标节点:给读屏一个「手动触发」名称(role=img + aria-label),视觉仍只有 * */
2658
+ const skillStars = collectByClass(tree, 'dsb-sup');
2659
+ assert.strictEqual(skillStars.length, 1, '只有手动调用过的那一行带星号');
2660
+ assert.strictEqual(skillStars[0].props['aria-label'], '手动触发', '星号读屏名称是「手动触发」');
2661
+ assert.strictEqual(skillStars[0].props.role, 'img', '星号带 img 角色,aria-label 才生效');
2662
+ assert.strictEqual(skillStars[0].props['aria-hidden'], undefined, '星号不再对读屏隐藏');
2663
+ assert.strictEqual(textOf(skillStars[0]), '*', '星号节点内容是 *');
2664
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-cols').length, 0, '三个技能不分列');
2665
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-tight').length, 0, '技能注入子视图不收紧间隙');
2666
+ console.log('技能注入子视图:', listRows(tree).map((one) => one.name).join(' / '));
2667
+
2668
+ /* 点标题返回上一层 */
2669
+ collectByClass(tree, 'dsb-meter-back')[0].props.onClick(clickEvent());
2670
+ tree = renderCounts();
2671
+ assert.strictEqual(panelTitle(tree), '会话数据', '点标题回到会话数据');
2672
+ assert.deepStrictEqual(listRows(tree).map((one) => one.name), ['上下文压缩', '技能注入', '工具调用'], '根视图仍是那三行');
2673
+
2674
+ /* 工具调用子视图:原生英文名 + 按名字长度升序、同长度按次数降序,带次数与单位 */
2675
+ rowAt(tree, '工具调用').props.onClick(clickEvent());
2676
+ tree = renderCounts();
2677
+ assert.strictEqual(panelTitle(tree), '工具调用', '工具调用子视图标题');
2678
+ /* toolCounts = { read: 7, edit: 3, pwsh: 2 }:三个名字都是 4 个字符,
2679
+ 同长度按次数降序 ⇒ read 7 > edit 3 > pwsh 2(手算后写死,不借实现的排序函数) */
2680
+ assert.deepStrictEqual(listRows(tree), [
2681
+ { name: 'read', value: '7 次' },
2682
+ { name: 'edit', value: '3 次' },
2683
+ { name: 'pwsh', value: '2 次' }
2684
+ ], '工具名直接用原生英文名,按名字长度升序、同长度按次数降序,实际 ' + JSON.stringify(listRows(tree)));
2685
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-tight').length, 1, '工具调用子视图挂 dsb-meter-tight(间隙收到 1ch)');
2686
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-full').length, 0, '不再有英文整行块');
2687
+ /* 标题下的横杠换成彩色分段条:第一段用浅色 01、宽度 = 次数 ÷ 总次数;每段带悬浮提示 */
2688
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-divider').length, 0, '工具调用子视图不再用普通分隔线');
2689
+ const toolBar = collectByClass(tree, 'dsb-bar')[0];
2690
+ assert.ok(toolBar !== undefined, '工具调用子视图标题下有分段条');
2691
+ const toolSegs = collectByClass(toolBar, 'dsb-bar-seg');
2692
+ assert.strictEqual(toolSegs.length, 3, '3 个工具 = 3 段');
2693
+ assert.strictEqual(toolSegs[0].props.style.backgroundColor, '#FFBFD1', '第 1 段用浅色 01');
2694
+ assert.strictEqual(toolSegs[1].props.style.backgroundColor, '#FFC5AB', '第 2 段用浅色 02');
2695
+ assert.strictEqual(toolSegs[2].props.style.backgroundColor, '#F4D06A', '第 3 段用浅色 03');
2696
+ const widthOf = (one) => Math.round(parseFloat(one.props.style.width) * 1000) / 1000;
2697
+ assert.deepStrictEqual(Array.from(toolSegs, widthOf), [Math.round((7 / 12) * 100 * 1000) / 1000, 25, Math.round((2 / 12) * 100 * 1000) / 1000],
2698
+ '段宽 = 该工具次数 ÷ 总次数(read 7 / edit 3 / pwsh 2)');
2699
+ assert.strictEqual(toolSegs[0].props.title, undefined, '彩条段不再用浏览器原生 title(改插件浮层)');
2700
+ assert.strictEqual(typeof toolSegs[0].props.onMouseEnter, 'function', '彩条段挂插件自己的悬停回调');
2701
+ console.log('工具调用子视图:', listRows(tree).map((one) => one.name + ' ' + one.value).join(' / '));
2702
+ /* 其它子视图仍是普通分隔线 */
2703
+ collectByClass(tree, 'dsb-meter-back')[0].props.onClick(clickEvent());
2704
+ rowAt(renderCounts(), '技能注入').props.onClick(clickEvent());
2705
+ tree = renderCounts();
2706
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-divider').length, 1, '技能注入子视图仍是普通分隔线');
2707
+ assert.strictEqual(collectByClass(tree, 'dsb-bar').length, 0, '技能注入子视图没有分段条');
2708
+
2709
+ /* 压缩次数子视图:逐条列出每次压缩落在第几轮第几步(中文序数) */
2710
+ collectByClass(tree, 'dsb-meter-back')[0].props.onClick(clickEvent());
2711
+ tree = renderCounts();
2712
+ rowAt(tree, '上下文压缩').props.onClick(clickEvent());
2713
+ tree = renderCounts();
2714
+ assert.strictEqual(panelTitle(tree), '上下文压缩', '上下文压缩子视图标题');
2715
+ assert.strictEqual(collectByClass(tree, 'dsb-meter-tight').length, 0, '上下文压缩子视图不收紧间隙');
2716
+ assert.deepStrictEqual(listRows(tree), [
2717
+ { name: '第一次压缩', value: '第12轮3步' },
2718
+ /* 手动压缩的星号在**名字后面**(「第二次压缩*」),与技能列表统一;
2719
+ 轮间压缩没有 turn,落点用 afterTurn 显示「第20轮后」而不是横杠 */
2720
+ { name: '第二次压缩*', value: '第20轮后' }
2721
+ ], '压缩明细按发生顺序逐条列(手动压缩星号后置),实际 ' + JSON.stringify(listRows(tree)));
2722
+ assert.strictEqual(collectByClass(tree, 'dsb-sup').length, 1, '手动压缩那条带一个上标星号');
2723
+ console.log('上下文压缩子视图:', listRows(tree).map((one) => one.name + ' ' + one.value).join(' / '));
2724
+
2725
+ /* 分列:每一竖列最多三行,超过就多开一竖列(默认档;工具调用那档折行时由 DOM 量测换成四行) */
2726
+ const manyTools = (n) => {
2727
+ const names = ['pwsh', 'read', 'write', 'edit', 'glob', 'grep', 'todo_write', 'skill',
2728
+ 'subagent', 'present', 'web_search', 'web_fetch', 'workflow', 'job_list', 'job_output'];
2729
+ const counts = {};
2730
+ for (let i = 0; i < n; i += 1) counts[names[i]] = i + 1;
2731
+ return { turn: 1, turnSteps: 1, toolCalls: n, toolCounts: counts, skills: [], globalInstruction: null, compactCount: 0, compactTurn: null, compactStep: null, compacts: [] };
2732
+ };
2733
+ const openTools = (progress) => {
2734
+ barHooks.values.length = 0;
2735
+ const cell = collectByClass(renderCounts(progress), 'dsb-seg-click').filter((one) => one.props.key === '__segcounts')[0];
2736
+ cell.props.onClick(clickEvent());
2737
+ rowAt(renderCounts(progress), '工具调用').props.onClick(clickEvent());
2738
+ return renderCounts(progress);
2739
+ };
2740
+ const columnsOf = (tree) => collectByClass(tree, 'dsb-meter-col');
2741
+ assert.strictEqual(columnsOf(openTools(manyTools(3))).length, 0, '3 行正好一列,不分列');
2742
+ const twoCols = openTools(manyTools(4));
2743
+ assert.strictEqual(columnsOf(twoCols).length, 2, '4 行开两列(每列最多三行)');
2744
+ assert.strictEqual(collectByClass(twoCols, 'dsb-meter-row').length, 4, '两列合起来还是 4 行');
2745
+ const fiveCols = openTools(manyTools(13));
2746
+ assert.strictEqual(columnsOf(fiveCols).length, 5, '13 行开五列');
2747
+ assert.ok(columnsOf(fiveCols).every((one) => collectByClass(one, 'dsb-meter-row').length <= 3), '每列不超过三行');
2748
+ assert.strictEqual(collectByClass(fiveCols, 'dsb-meter-row').length, 13, '五列合起来还是 13 行');
2749
+ console.log('分列:3 行一列 / 4 行两列 / 13 行五列,每列最多三行');
2750
+
2751
+ /* 长短混合的工具名全部进同一个列网格(不再有「整行块」):短名多、长名也照常分列 */
2752
+ const mixedTools = openTools({
2753
+ turn: 1, turnSteps: 1, toolCalls: 12,
2754
+ toolCounts: { pwsh: 4, read: 3, write: 2, edit: 1, mcp__demo__search: 6, custom_tool: 5 },
2755
+ skills: [], globalInstruction: null, compactCount: 0, compactTurn: null, compactStep: null, compacts: []
2756
+ });
2757
+ assert.strictEqual(collectByClass(mixedTools, 'dsb-meter-full').length, 0, '没有英文整行块:全部统一列网格');
2758
+ assert.strictEqual(collectByClass(mixedTools, 'dsb-meter-split').length, 0, '没有分列 + 整行块的外层');
2759
+ assert.strictEqual(collectByClass(mixedTools, 'dsb-meter-cols').length, 1, '只有一个列网格');
2760
+ assert.strictEqual(collectByClass(mixedTools, 'dsb-meter-row').length, 6, '6 个工具都在网格里');
2761
+ assert.ok(String(collectByClass(mixedTools, 'dsb-tip')[0].props.className).indexOf('dsb-meter-wide') !== -1, '分列时气泡走宽档');
2762
+ const mixedOrder = collectByClass(mixedTools, 'dsb-meter-name').map(textOf);
2763
+ assert.deepStrictEqual(mixedOrder, ['pwsh', 'read', 'edit', 'write', 'custom_tool', 'mcp__demo__search'],
2764
+ '按名字长度升序(4 字组内按次数降序:pwsh 4 > read 3 > edit 1)→ 长名排在后面,实际 ' + JSON.stringify(mixedOrder));
2765
+ console.log('工具调用混合长短名:', mixedOrder.join(' / '));
2766
+
2767
+ /* 不再按中文名合并:bash / pwsh / ops_bash 是不同工具,各占一行 */
2768
+ const mergedTools = openTools({
2769
+ turn: 1, turnSteps: 1, toolCalls: 10,
2770
+ toolCounts: { pwsh: 2, bash: 5, ops_bash: 3, read: 1 },
2771
+ skills: [], globalInstruction: null, compactCount: 0, compactTurn: null, compactStep: null, compacts: []
2772
+ });
2773
+ assert.deepStrictEqual(collectByClass(mergedTools, 'dsb-meter-row').map((one) => ({
2774
+ name: textOf(collectByClass(one, 'dsb-meter-name')[0]),
2775
+ value: textOf(collectByClass(one, 'dsb-meter-value')[0])
2776
+ })), [
2777
+ { name: 'bash', value: '5 次' },
2778
+ { name: 'pwsh', value: '2 次' },
2779
+ { name: 'read', value: '1 次' },
2780
+ { name: 'ops_bash', value: '3 次' }
2781
+ ], '原生工具名各自一行(4 字组:bash 5 > pwsh 2 > read 1;ops_bash 更长排最后),不再合并成「命令行」');
2782
+ console.log('原生工具名不合并:', collectByClass(mergedTools, 'dsb-meter-name').map(textOf).join(' / '));
2783
+
2784
+ /* 气泡水平位置:以触发项自身居中(替身里触发项是 200~280,中线 240),
2785
+ 再夹在「圆圈灰底的左边」与视口右边之间。换子视图后宽度变了必须重算 ——
2786
+ 沿用上一个宽度就会偏到一边(2026-10-04 报过这个毛病)。 */
2787
+ const tipLeft = () => {
2788
+ const pos = barHooks.values.filter((one) => one !== null && typeof one === 'object'
2789
+ && typeof one.left === 'number' && typeof one.bottom === 'number')[0];
2790
+ return pos === undefined ? null : pos.left;
2791
+ };
2792
+ runEffects = true;
2793
+ try {
2794
+ /* 替身里的 effect 是在渲染过程中就地跑的,节点 ref 要到这一遍渲染结束才挂上,
2795
+ 所以状态一变就渲染两遍:第一遍挂节点,第二遍才量得到宽度。 */
2796
+ const paint = () => { renderCounts(); return renderCounts(); };
2797
+ const panelMaxWidth = () => {
2798
+ const panel = collectByClass(renderCounts(), 'dsb-tip')[0];
2799
+ return panel === undefined || panel.props.style === undefined ? undefined : panel.props.style.maxWidth;
2800
+ };
2801
+ const openSeg = (key, event) => {
2802
+ barHooks.values.length = 0;
2803
+ collectByClass(renderCounts(), 'dsb-seg-click').filter((one) => one.props.key === key)[0]
2804
+ .props.onClick(event === undefined ? clickEvent() : event);
2805
+ paint();
2806
+ };
2807
+ /* 基准:圆环按钮(灰底)左边 120,气泡自带 0.5px 描边 → border-box 至少 120.5,可见边 120 */
2808
+ stubRingLeft = 120;
2809
+ stubBarRight = 985;
2810
+ stubTipWidth = 160;
2811
+ openSeg('__segcounts');
2812
+ assert.strictEqual(tipLeft(), 160, '根视图:触发项中线 240 − 半宽 80 = 160,实际 ' + tipLeft());
2813
+ stubTipWidth = 100;
2814
+ rowAt(renderCounts(), '技能注入').props.onClick(clickEvent());
2815
+ paint();
2816
+ assert.strictEqual(tipLeft(), 190, '换子视图后按新宽度重新居中(240 − 50),实际 ' + tipLeft());
2817
+ /* 居中会越过灰圆左边:贴上去,可见左边缘正好压在灰圆左边(300) */
2818
+ stubRingLeft = 300;
2819
+ stubTipWidth = 400;
2820
+ paint();
2821
+ assert.strictEqual(tipLeft(), 300.5, '左边界贴灰圆(border-box 300.5),实际 ' + tipLeft());
2822
+ assert.strictEqual(tipLeft() - 0.5, 300, '可见左边缘 = 300 = 圆环按钮灰底左边');
2823
+ /* 右边界:可见右边缘压在最右那一项灰底的右边(985) */
2824
+ stubRingLeft = 120;
2825
+ stubTipWidth = 400;
2826
+ openSeg('__segbalance', clickAt(900, 85));
2827
+ assert.strictEqual(tipLeft(), 985 - 0.5 - 400, '末尾项可见右边缘压在自己灰底右边(984.5 − 400),实际 ' + tipLeft());
2828
+ assert.strictEqual(tipLeft() + 400 + 0.5, 985, '可见右边缘 = 985(含 0.5 描边)');
2829
+ /* 气泡比底栏还宽:宽度上限 = 两侧可见边之间的跨度(984.5 − 120.5 = 864) */
2830
+ stubTipWidth = 975;
2831
+ openSeg('__segcounts');
2832
+ assert.strictEqual(panelMaxWidth(), '864px', '超宽气泡按两侧可见边之间的跨度压宽度,实际 ' + panelMaxWidth());
2833
+ assert.strictEqual(tipLeft(), 120.5, '超宽气泡可见左边缘压在灰圆左边,实际 ' + tipLeft());
2834
+ console.log('气泡水平位置:根视图 160 / 换子视图后 190 / 越界贴灰圆 300.5(可见边 300)/ 末尾项可见右边 985 / 超宽上限 864px');
2835
+
2836
+ /* 工具调用自适应:一排放不下(横向溢出)时每列行数 3→4→5 逐档加,直到放得下;
2837
+ 返回上一层再点进来要回到默认 3 行(重置),不能带着上一次的 5 行。
2838
+ 替身里的假几何:stubWrapOn 时列网格容器只放得下 stubWrapCap 列,列数多过它就是"放不下"
2839
+ (nowrap 之后不会再折行,溢出是唯一表现 —— 见 toolColumnsOverflow)。 */
2840
+ stubWrapOn = true;
2841
+ stubWrapCap = 3;
2842
+ barHooks.values.length = 0;
2843
+ const wrappedProgress = manyTools(13);
2844
+ collectByClass(renderCounts(wrappedProgress), 'dsb-seg-click').filter((one) => one.props.key === '__segcounts')[0]
2845
+ .props.onClick(clickEvent());
2846
+ renderCounts(wrappedProgress);
2847
+ rowAt(renderCounts(wrappedProgress), '工具调用').props.onClick(clickEvent());
2848
+ /* 每渲染一遍只升一档,多渲染几遍让它收敛:5 行时 13 个工具正好 3 列,不再超过每排 3 列 */
2849
+ for (let i = 0; i < 6; i += 1) renderCounts(wrappedProgress);
2850
+ const wrappedCols = columnsOf(renderCounts(wrappedProgress));
2851
+ /* 替身里的 layout effect 量到的是上一帧的树(真实 React 在提交后量当前帧),因此会多升一档:
2852
+ 最终是每列 6 行(6/6/1)、三个列正好一排放得下;「恰好停在第 5 行」由
2853
+ verify-list-layout 的纯函数收敛用例精确钉住(那里没有这一帧延迟)。 */
2854
+ assert.strictEqual(wrappedCols.length, 3, '13 个工具 + 每排最多 3 列:逐档加到一排放得下,收成一排 3 列,实际 ' + wrappedCols.length);
2855
+ assert.ok(wrappedCols.every((one) => collectByClass(one, 'dsb-meter-row').length <= 6), '一排放得下后不再继续加行(替身最多多升一档到 6 行)');
2856
+ /* 重置:返回再进来,行数回默认 3 */
2857
+ stubWrapOn = false;
2858
+ collectByClass(renderCounts(wrappedProgress), 'dsb-meter-back')[0].props.onClick(clickEvent());
2859
+ renderCounts(wrappedProgress);
2860
+ rowAt(renderCounts(wrappedProgress), '工具调用').props.onClick(clickEvent());
2861
+ const resetCols = columnsOf(renderCounts(wrappedProgress));
2862
+ assert.strictEqual(resetCols.length, 5, '返回后行数重置回 3:13 个工具 → 5 列,实际 ' + resetCols.length);
2863
+ assert.ok(resetCols.every((one) => collectByClass(one, 'dsb-meter-row').length <= 3), '每列回到不超过 3 行');
2864
+ console.log('工具调用自适应:放不下时逐档加行直到放得下;返回后重置回 3 行');
2865
+ } finally {
2866
+ runEffects = false;
2867
+ stubTipWidth = 0;
2868
+ stubRingLeft = 120;
2869
+ stubWrapOn = false;
2870
+ stubWrapCap = 3;
2871
+ barHooks.values.length = 0;
2872
+ }
2873
+
2874
+ /* ---------------------------- 气泡 Portal 到 body 之后:点气泡内部不能把气泡关掉 */
2875
+ /* **行为断言**(不是源码字面量检查):气泡经 createPortal 挂到 body 后就不在 rootRef 里了,
2876
+ 「点别处收起」的那个 document click 处理器必须同时判 tipRef,否则点气泡内部会被当成
2877
+ "点在外面"、气泡立刻消失(现有用例全绿也抓不到,因为谁都没真的点过 document)。
2878
+ 做法分三步,全部落在真实渲染路径上:
2879
+ ① 给 react-dom 一个**等价就地渲染**的 createPortal(node => node),让代码真的走
2880
+ portal 分支 —— 而不是因为拿不到 react-dom 退回就地渲染、把这条路径绕过去;
2881
+ ② 给「底栏根节点」和「气泡节点」两个真实替身节点各打一个 contains 桩:两个返回值
2882
+ 分别可控(根节点一律不认、气泡只认"内部节点"),以此模拟 portal 之后的 DOM 事实;
2883
+ ③ 从 document 上取到**组件自己注册的** click 回调并直接触发,再看状态:
2884
+ 点气泡内部 → 气泡仍在;点真正的外面 → 气泡被关(对照组,证明 close 路径真的会跑)。 */
2885
+ {
2886
+ const portalHooks = makeHooks();
2887
+ const modPortal = captured.factory((name) => {
2888
+ if (name === 'react') return reactStub;
2889
+ /* 等价就地渲染:节点原样返回,Portal 分支照样被走到 */
2890
+ if (name === 'react-dom') return { createPortal: (node) => node };
2891
+ throw new Error('unexpected require: ' + name);
2892
+ });
2893
+ const apiPortal = modPortal.__test;
2894
+ /* 状态一变就渲染两遍:第一遍挂节点、第二遍才量得到宽度(与其它定位用例同一习惯) */
2895
+ const paintPortal = () => {
2896
+ withHooks(portalHooks, () => apiPortal.StatusBar(skillProps));
2897
+ return withHooks(portalHooks, () => apiPortal.StatusBar(skillProps));
2898
+ };
2899
+ const clickBefore = (docListeners.click === undefined ? [] : docListeners.click).slice();
2900
+ runEffects = true;
2901
+ try {
2902
+ /* ① 照现有用例的写法点开「会话数据」气泡 */
2903
+ withHooks(portalHooks, () => apiPortal.StatusBar(skillProps));
2904
+ collectByClass(withHooks(portalHooks, () => apiPortal.StatusBar(skillProps)), 'dsb-seg-click')
2905
+ .filter((one) => one.props.key === '__segcounts')[0].props.onClick(clickEvent());
2906
+ let portalTree = paintPortal();
2907
+ assert.strictEqual(collectByClass(portalTree, 'dsb-tip').length, 1, '前提:气泡已展开');
2908
+
2909
+ /* ② 气泡开着时,组件应当把 click 处理器挂到 document 上。这里拿到的就是它注册的
2910
+ 那个函数本体 —— 断言的是"有没有挂、挂着的行为对不对",不是源码里有没有那行字。 */
2911
+ const added = (docListeners.click === undefined ? [] : docListeners.click)
2912
+ .filter((fn) => clickBefore.indexOf(fn) === -1);
2913
+ assert.strictEqual(added.length, 1,
2914
+ '气泡展开后 document 上应挂且只挂一个 click 监听,实际 ' + added.length + ' 个');
2915
+ const onDocClick = added[0];
2916
+
2917
+ /* ③ 两个 contains 分开打桩:根节点永远不认这个目标,气泡节点认"内部节点" */
2918
+ const rootNode = collectByClass(portalTree, 'dsb-root')[0];
2919
+ const panelNode = collectByClass(portalTree, 'dsb-tip')[0];
2920
+ const tipInner = { what: '气泡内部的节点' };
2921
+ const farAway = { what: '真正的外面' };
2922
+ const asked = [];
2923
+ rootNode.contains = (target) => { asked.push('root'); return target === null; };
2924
+ panelNode.contains = (target) => { asked.push('panel'); return target === tipInner; };
2925
+ assert.strictEqual(rootNode.contains(tipInner), false, '前提:目标不在底栏根节点里');
2926
+ assert.strictEqual(panelNode.contains(tipInner), true, '前提:目标在气泡节点里');
2927
+ asked.length = 0;
2928
+
2929
+ /* 点气泡内部:不能被当成点在外面 */
2930
+ onDocClick({ target: tipInner });
2931
+ portalTree = paintPortal();
2932
+ assert.strictEqual(collectByClass(portalTree, 'dsb-tip').length, 1,
2933
+ '点气泡内部不该关闭气泡(tipRef 判定被删后会立刻消失)');
2934
+ assert.strictEqual(panelTitle(portalTree), '会话数据', '点气泡内部后气泡仍停在原视图');
2935
+ assert.deepStrictEqual(asked, ['root', 'panel'],
2936
+ 'onDocClick 要先判底栏根、再判气泡(两个 contains 都被问到),实际问过 ' + JSON.stringify(asked));
2937
+
2938
+ /* 对照组:点在真正的外面(两个 contains 都不认)⇒ 气泡必须关掉。
2939
+ 这一条保证上面那条不是"回调压根没跑"的恒真断言。 */
2940
+ assert.ok((docListeners.click === undefined ? [] : docListeners.click).indexOf(onDocClick) !== -1,
2941
+ '前提:触发的仍是组件注册在 document 上的那个监听');
2942
+ const rootNode2 = collectByClass(portalTree, 'dsb-root')[0];
2943
+ const panelNode2 = collectByClass(portalTree, 'dsb-tip')[0];
2944
+ rootNode2.contains = () => false;
2945
+ panelNode2.contains = () => false;
2946
+ onDocClick({ target: farAway });
2947
+ const closedTree = paintPortal();
2948
+ assert.strictEqual(collectByClass(closedTree, 'dsb-tip').length, 0,
2949
+ '对照组:点在气泡外面要关闭气泡(close 路径真的会被触发)');
2950
+ console.log('气泡 Portal:点气泡内部不关;点外面关(对照组)');
2951
+ } finally {
2952
+ runEffects = false;
2953
+ /* 摘掉这段自己挂上去的监听,别让后面的用例受它影响 */
2954
+ (docListeners.click === undefined ? [] : docListeners.click.slice()).forEach((fn) => {
2955
+ if (clickBefore.indexOf(fn) === -1) sandbox.document.removeEventListener('click', fn);
2956
+ });
2957
+ portalHooks.values.length = 0;
2958
+ }
2959
+ }
2960
+
2961
+ /* 工具调用彩条的悬停提示:**没有气泡**,只显示一行文字(工具名 + 占比),跟鼠标。
2962
+ 用一套独立 hooks,避免悬停状态漏到其它用例。 */
2963
+ const hoverHooks = makeHooks();
2964
+ const paintHover = () => withHooks(hoverHooks, () => api.StatusBar(skillProps));
2965
+ collectByClass(paintHover(), 'dsb-seg-click').filter((one) => one.props.key === '__segcounts')[0].props.onClick(clickEvent());
2966
+ rowAt(paintHover(), '工具调用').props.onClick(clickEvent());
2967
+ const hovTree = paintHover();
2968
+ const hovSegs = collectByClass(hovTree, 'dsb-bar-seg');
2969
+ assert.ok(hovSegs.length === 3, '工具彩条有 3 段');
2970
+ assert.strictEqual(hovSegs[0].props.title, undefined, '不再有浏览器原生 title');
2971
+ assert.strictEqual(typeof hovSegs[0].props.onMouseMove, 'function', '色段挂 onMouseMove(提示跟着鼠标走)');
2972
+ const hoverColorClass = String(collectByClass(hovTree, 'dsb-bar')[0].props.className);
2973
+ assert.ok(hoverColorClass.indexOf('dsb-bar-hoverable') !== -1, '工具彩条挂 hoverable 类(悬停凸起动效)');
2974
+ /* 反面断言:悬停放大**只在工具调用这个下钻子视图**启用。
2975
+ 只测正面(indexOf 命中)挡不住"判据放宽"—— 把 `opened !== null && opened.tight === true`
2976
+ 改成 `opened !== null`(或 `tight !== false`)后,其它带色条的视图会冒出不该有的放大动效,
2977
+ 而正面断言照样绿(审查 C 的 M10 / M13 变异就是这么存活的)。
2978
+
2979
+ ⚠ 必须挑**真的走那个三元表达式**的视图。三类要分清:
2980
+ · 令牌面板(cost / lastCost)走 `tokenPanel` → `meterBar`,类名是**硬编码**的 "dsb-bar",
2981
+ 根本不经过那个三元 —— 拿它断言等于空转(第一版就写错了,实测 M10/M13 仍绿);
2982
+ · 技能注入 / 上下文压缩子视图根本不画色条(没有 segments);
2983
+ · **总用时(sessionTime)根视图**才是对的:它 `kind: "rows"` 且带 `segments`。
2984
+ 但它在 StatusBar 里要 host 的 `desktopStatusbarActiveTime` 投影(这里没那份夹具,
2985
+ 强喂会把这条断言变成空转),所以直接调 `rowsPanel` 渲染同一份 tip ——
2986
+ 它正是那个三元表达式所在的函数,`sub.id === null` ⇒ 必须拿到普通 "dsb-bar"。 */
2987
+ const timeTipForProbe = api.segmentView('sessionTime', {
2988
+ stats: { ttftMs: 2000, decodeMs: 1000, toolMs: 45000 },
2989
+ timeRange: { turns: 5400000, since: null, steps: 0, stepSince: null },
2990
+ now: FIXED_NOW, subagent: null
2991
+ }, t).tip;
2992
+ assert.ok(Array.isArray(timeTipForProbe.segments) && timeTipForProbe.segments.length > 0,
2993
+ '前置:总用时 tip 确实带 segments(否则这条反面断言是空转)');
2994
+ const rootBarPanel = api.rowsPanel(timeTipForProbe, null, { current: null }, {
2995
+ id: null, open: () => {}, back: () => {}, rowsPerColumn: 3
2996
+ });
2997
+ const rootBars = collectByClass(rootBarPanel, 'dsb-bar');
2998
+ assert.strictEqual(rootBars.length, 1, '总用时根视图有 1 条分段条,实际 ' + rootBars.length);
2999
+ assert.strictEqual(String(rootBars[0].props.className), 'dsb-bar',
3000
+ '根视图(总用时)色条的 className 必须严格等于 dsb-bar,实际「'
3001
+ + String(rootBars[0].props.className) + '」—— 悬停放大只允许出现在工具调用子视图');
3002
+ console.log('悬停放大只在工具调用子视图:根视图色条严格等于 dsb-bar');
3003
+ /* 工具彩条自己的类名也要**严格等于**两个词的组合:
3004
+ 光写 indexOf 的话,改成 "dsb-bar dsb-bar-hoverable-legacy" 这种(CSS 选择器不再命中、
3005
+ 动效彻底失效)也照样通过 —— 审查 C 的 P4 变异就是这么存活的。 */
3006
+ assert.strictEqual(String(collectByClass(hovTree, 'dsb-bar')[0].props.className), 'dsb-bar dsb-bar-hoverable',
3007
+ '工具彩条的 className 严格等于「dsb-bar dsb-bar-hoverable」(不是只含这个名字)');
3008
+ const hovEvent = (x, y) => ({ stopPropagation() {}, clientX: x, clientY: y });
3009
+ hovSegs[0].props.onMouseEnter(hovEvent(200, 500));
3010
+ const hoverTree = paintHover();
3011
+ assert.strictEqual(collectByClass(hoverTree, 'dsb-hovercard').length, 0, '悬停不再弹气泡');
3012
+ const collectVisibleHoverPlain = (tree) => collectByClass(tree, 'dsb-hover-plain').filter((node) =>
3013
+ String(node.props.className).split(' ').indexOf('dsb-hover-plain-probe') === -1);
3014
+ const plain = collectVisibleHoverPlain(hoverTree)[0];
3015
+ assert.ok(plain !== undefined, '悬停后出现纯文字提示');
3016
+ assert.strictEqual(textOf(plain), 'read 58.33%', '纯文字内容 = 工具名 + 占比(read 7/12,两位小数),实际 ' + textOf(plain));
3017
+ assert.strictEqual(plain.props.onClick, undefined, '文字提示不可点、不拦截鼠标');
3018
+ /* 在同一个色段里横向移动:提示不消失、内容不变(onHoverMove 直接改 DOM 坐标,不触发重渲染) */
3019
+ hovSegs[0].props.onMouseMove(hovEvent(260, 500));
3020
+ assert.strictEqual(collectVisibleHoverPlain(paintHover()).length, 1, '段内移动时提示保持存在、不闪断');
3021
+ assert.strictEqual(textOf(collectVisibleHoverPlain(paintHover())[0]), 'read 58.33%',
3022
+ '段内移动后提示内容不变');
3023
+ hovSegs[1].props.onMouseEnter(hovEvent(400, 500));
3024
+ assert.strictEqual(textOf(collectVisibleHoverPlain(paintHover())[0]), 'edit 25.00%',
3025
+ '第二段 = edit 3/12 = 25.00%');
3026
+ console.log('工具彩条悬停提示:read 58.33% / edit 25.00%(无气泡、跟鼠标、段内移动不闪断)');
3027
+
3028
+ /* --------------------- 端到端:放不下就整组不显示(走真实链路,不是只喂 rowsPanel)
3029
+ 这条守的是**接线**:量宽度 → plainFits 判定 → setHoverPlainOff(true) → 传给 rowsPanel →
3030
+ 所有段都不挂 onMouseEnter。审查发现只测 rowsPanel 契约时,把 `hoverSuppressed: hoverPlainOff`
3031
+ 改成恒 false(功能整体失效)50 个测试仍全绿 —— 所以必须走 StatusBar 真实渲染。
3032
+
3033
+ 做法:把提示的自然宽度调到远超可用区间(stubHoverPlainWidth),触发一次悬停让 layout effect
3034
+ 量出来并判定;下一帧重新渲染,这时色条段就**不该**再挂 onMouseEnter。 */
3035
+ /* --------------------- 接线守门:放不下就整组不显示(不依赖替身的 effect 时序)
3036
+ 审查发现:只测 `rowsPanel` 契约时,把 StatusBar 里 `hoverSuppressed: hoverPlainOff`
3037
+ 改成恒 `false`(用户要的功能整体失效)50 个测试仍全绿 —— 因为那条接线没人守。
3038
+ 替身的 layout effect 时序和真实 React 有差异(渲染中途 vs 挂完 DOM),
3039
+ 硬凑端到端会变成调试替身;这里改用**静态接线断言**,能精确抓住那类错误。
3040
+ 行为本身的边界由前面 plainFits 那组断言守住。 */
3041
+ const wiringSource = code.replace(/\/\*[\s\S]*?\*\//g, '');
3042
+ const hoverSuppressedAt = wiringSource.indexOf('hoverSuppressed:');
3043
+ assert.ok(hoverSuppressedAt !== -1, 'StatusBar 里必须把开关传给 rowsPanel(hoverSuppressed)');
3044
+ const hoverSuppressedArg = wiringSource.slice(hoverSuppressedAt, hoverSuppressedAt + 120);
3045
+ assert.ok(/hoverSuppressed:\s*hoverPlainOff\b/.test(hoverSuppressedArg),
3046
+ 'hoverSuppressed 必须接 hoverPlainOff(不是恒 false / 恒 true),实际片段:' + hoverSuppressedArg.slice(0, 80));
3047
+ /* 复位的**每一条路径**都必须在场。这不是"数够两处就行"的静态计数 ——
3048
+ 审查实测过:只覆盖「气泡变 null」时,换字段(tipId 直接切换、不经过 null)会让
3049
+ 本次会话的工具名悬停永久失效。四条路径缺一条都是真 bug:
3050
+ ① 判出放不下 → 置 true
3051
+ ② 同气泡内重新放得下 → 复位
3052
+ ③ 关气泡(tipId → null)→ 复位
3053
+ ④ 换字段(toggleTip)/ 进出子视图(open / back)→ 复位 */
3054
+ assert.ok(/setHoverPlainOff\(true\)/.test(wiringSource), '判出放不下时必须 setHoverPlainOff(true)');
3055
+ assert.ok(/setHoverPlainOff\(false\)/.test(wiringSource),
3056
+ '必须有 setHoverPlainOff(false) 复位 —— 否则碰到一次长工具名后,悬停永久失效');
3057
+ const resetAll = [];
3058
+ let resetAt = wiringSource.indexOf('setHoverPlainOff(false)');
3059
+ while (resetAt !== -1) {
3060
+ resetAll.push(resetAt);
3061
+ resetAt = wiringSource.indexOf('setHoverPlainOff(false)', resetAt + 1);
3062
+ }
3063
+ assert.ok(resetAll.length >= 3,
3064
+ '复位至少要覆盖三处:同气泡重新放得下 / 关气泡 / 换字段或进出子视图,实际 ' + resetAll.length + ' 处');
3065
+ const resetNearClose = resetAll.some((at) => {
3066
+ const around = wiringSource.slice(Math.max(0, at - 300), at + 100);
3067
+ return around.indexOf('setHoverCard(null)') !== -1;
3068
+ });
3069
+ assert.ok(resetNearClose, '必须有一处复位写在「气泡关闭就清空悬停状态」的 effect 里(setHoverCard(null) 附近)');
3070
+ /* 换字段那条路径:toggleTip 里必须有复位(tipId 直接从 "counts" 切到 "cost",不经过 null) */
3071
+ const toggleAt = wiringSource.indexOf('const toggleTip =');
3072
+ assert.ok(toggleAt !== -1, '找得到 toggleTip(点字段切换气泡)');
3073
+ assert.ok(wiringSource.slice(toggleAt, toggleAt + 800).indexOf('setHoverPlainOff(false)') !== -1,
3074
+ 'toggleTip 换字段时必须复位 hoverPlainOff —— 缺这条的话:碰到一次长工具名后,'
3075
+ + '点任何一个状态栏字段都会让本次会话的工具名悬停永久失效(审查实测的死锁)');
3076
+ /* 子视图 open / back 也要复位 */
3077
+ const openAt = wiringSource.indexOf('open: (index) => {');
3078
+ const backAt = wiringSource.indexOf('back: () => {');
3079
+ assert.ok(openAt !== -1 && backAt !== -1, '找得到子视图的 open / back');
3080
+ assert.ok(wiringSource.slice(openAt, openAt + 300).indexOf('setHoverPlainOff(false)') !== -1,
3081
+ '进入子视图(open)时必须复位 hoverPlainOff');
3082
+ assert.ok(wiringSource.slice(backAt, backAt + 300).indexOf('setHoverPlainOff(false)') !== -1,
3083
+ '从子视图返回(back)时必须复位 hoverPlainOff');
3084
+ console.log('悬停接线:hoverSuppressed = hoverPlainOff;置 true 与四条复位路径(放得下 / 关气泡 / 换字段 / 进出子视图)都在');
3085
+
3086
+ /* task-37:悬停文字必须 Portal 到 document.body,且 z-index 高于气泡面板(105)——
3087
+ 否则它会被 body 级的气泡整块盖住,界面表现就是「悬停什么都不显示」。 */
3088
+ assert.ok(wiringSource.indexOf('createPortal(hoverPlainNode, document.body)') !== -1,
3089
+ '悬停文字必须 Portal 到 document.body(与气泡面板同一套 Portal 路径)');
3090
+ const plainZ = /\.dsb-hover-plain\{[^}]*z-index:(\d+)/.exec(code);
3091
+ const tipZ = /\.dsb-tip\{[^}]*z-index:(\d+)/.exec(code);
3092
+ assert.ok(plainZ !== null && tipZ !== null, '找不到 .dsb-hover-plain / .dsb-tip 的 z-index');
3093
+ assert.ok(Number(plainZ[1]) > Number(tipZ[1]),
3094
+ '悬停文字 z-index(' + plainZ[1] + ')必须高于气泡面板(' + tipZ[1] + ')');
3095
+
3096
+ /* task-35:悬停文字画在**气泡内部** —— 水平夹在气泡边界内 8px、垂直也夹在气泡矩形内 */
3097
+ assert.ok(wiringSource.indexOf('const bounds = plainBoundsOf(titleBox, panelBox, window.innerWidth);') !== -1,
3098
+ '可用范围 = 标题右边界+间距 → 气泡右边界-8(提示不压标题、不出气泡)');
3099
+ assert.ok(wiringSource.indexOf('headBox.top + headBox.height / 2 - textHeight / 2') !== -1,
3100
+ '垂直位置 = 标题行垂直中心(同一行居中对齐)');
3101
+
3102
+ /* 恢复路径(用户实测「完全不弹提示」的根因):气泡**自己**变长 / 变宽也必须重测。
3103
+ 旧实现只有 window resize 会 bump tipTick,气泡内容变多撑宽面板后没有任何信号,
3104
+ 于是一次「放不下」就把本次会话的整组悬停永久关死。 */
3105
+ assert.ok(/new ResizeObserver\(/.test(wiringSource), '必须用 ResizeObserver 盯气泡尺寸变化');
3106
+ const observerAt2 = wiringSource.indexOf('new ResizeObserver(');
3107
+ const observerSlice = wiringSource.slice(observerAt2, observerAt2 + 260);
3108
+ assert.ok(/setTipTick\(/.test(observerSlice), 'ResizeObserver 回调必须 bump tipTick 触发重测,实际片段:' + observerSlice.slice(0, 160));
3109
+ assert.ok(observerSlice.indexOf('observer.observe(') !== -1, '必须 observe 气泡节点,否则收不到尺寸变化');
3110
+ assert.ok(/observer\.disconnect\(\)/.test(wiringSource), '气泡关闭时必须 disconnect,别留观察者');
3111
+ assert.ok(/if \(hoverPlainOff === true\) setHoverPlainOff\(false\);/.test(wiringSource),
3112
+ '重新量出「放得下」时必须复位 hoverPlainOff —— 缺这条就是用户实测的永久静音');
3113
+ console.log('悬停恢复:ResizeObserver 盯气泡尺寸 → tipTick 重测 → 放得下时整组恢复(不再永久静音)');
3114
+
3115
+ /* ---------------------------------------------- 悬停文字放不下就不显示(取代缩放)
3116
+ 用户拍板:工具名很长、气泡不够长时,**所有**工具名的悬停提示一律不出现,
3117
+ 不是只关掉那个超长的、也不是缩小硬塞进去。所以这里守两件事:
3118
+ ① plainFits 判的是「放得下吗」,边界值卡准;
3119
+ ② 实现里**不许再有缩放**(scale / transform:scale 一条都不留)——
3120
+ 变异回"缩小硬塞"时立刻红。 */
3121
+ /* 剥掉注释再断言:注释里也会写 plainFitScale / transform:scale 这些字样(解释为什么不这么做),
3122
+ 不剥的话把实现改回去时那些字样仍在窗口里,断言照样绿(实测变异存活)。 */
3123
+ const codeNoComments = code
3124
+ .replace(/\/\*[\s\S]*?\*\//g, '')
3125
+ .replace(/(^|[^:'"\\])\/\/[^\n]*/g, '$1');
3126
+ const fitBoundsForPlain = api.plainBoundsOf({ right: 120 }, { left: 0, right: 400 }, 1280); /* 可用 132..392 = 260 */
3127
+ assert.strictEqual(api.plainFits(260, fitBoundsForPlain, 1280), true, '刚好放满:算放得下');
3128
+ assert.strictEqual(api.plainFits(100, fitBoundsForPlain, 1280), true, '明显放得下:算放得下');
3129
+ assert.strictEqual(api.plainFits(261, fitBoundsForPlain, 1280), false,
3130
+ '多 1px 就放不下 → 返回 false(提示该关掉,不是缩小)');
3131
+ assert.strictEqual(api.plainFits(600, fitBoundsForPlain, 1280), false,
3132
+ '长 MCP 工具名(自然宽 600 > 可用 260)→ 放不下');
3133
+ /* 退化输入一律当"放得下":量不出来就别关,宁可显示也不误伤 */
3134
+ assert.strictEqual(api.plainFits(0, fitBoundsForPlain, 1280), true, '宽度为 0(还没量到)→ 当放得下');
3135
+ assert.strictEqual(api.plainFits(NaN, fitBoundsForPlain, 1280), true, '宽度是 NaN → 当放得下');
3136
+ assert.strictEqual(api.plainFits(999, null, 0), true, '没有 bounds 也没有视口信息 → 当放得下');
3137
+ assert.strictEqual(api.plainFits(999, { min: 400, max: 300 }, 1280), true, '区间为负(无处可放)→ 当放得下,交给夹取兜底');
3138
+ /* 结构层:缩放必须已被彻底移除 —— 不许再出现缩放比例,也不许写 transform: scale */
3139
+ assert.strictEqual(api.plainFitScale, undefined, 'plainFitScale 已删除(放不下就关,不再算缩放比例)');
3140
+ assert.strictEqual(/plainFitScale/.test(codeNoComments), false,
3141
+ '实现里不许再出现 plainFitScale —— 那是"缩小硬塞"的旧路径');
3142
+ assert.strictEqual(/transform:\s*"scale\(/.test(codeNoComments), false,
3143
+ '悬停提示的样式里不许再写 transform: scale(不再缩放文字)');
3144
+ assert.strictEqual(/hoverPos\.scale/.test(codeNoComments), false,
3145
+ 'hoverPos 不再携带 scale 字段(缩放状态已移除)');
3146
+ /* 判据必须走 plainFits:找到调用处,确认它决定的是"关掉"而不是"缩小" */
3147
+ const fitsCallAt = codeNoComments.search(/plainFits\(\s*[A-Za-z_$][\w$]*\s*,\s*bounds\s*,\s*window\.innerWidth\s*\)/);
3148
+ assert.ok(fitsCallAt !== -1, '定位 effect 里必须调用 plainFits 判断放不放得下');
3149
+ const fitsCall = codeNoComments.slice(fitsCallAt, fitsCallAt + 400);
3150
+ assert.ok(fitsCall.indexOf('setHoverPlainOff(true)') !== -1,
3151
+ 'plainFits 返回 false 时必须关掉整组悬停提示(setHoverPlainOff(true)),实际片段:' + fitsCall.slice(0, 260));
3152
+ console.log('悬停文字:放不下就整组不显示(plainFits 边界已钉住),缩放逻辑已彻底移除');
3153
+ /* 复位,别影响后面的用例 */
3154
+ stubHoverPlainWidth = 60;
3155
+ stubBarWidth = 273;
3156
+ stubHeadlineWidth = 60;
3157
+
3158
+ /* 悬停文字的可用范围:左 = 标题文字右边界 + 间距(不压标题),右 = 气泡右边界 - 8 */
3159
+ /* 注意:这些对象来自 vm 沙箱,原型与本进程不同,用跨 realm 安全的 JSON 比较 */
3160
+ const bounds = { min: 132, max: 392 };
3161
+ assert.strictEqual(JSON.stringify(api.plainBoundsOf({ right: 120 }, { left: 0, right: 400 }, 1280)), JSON.stringify({ min: 132, max: 392 }),
3162
+ '范围 = 标题右边界+12 → 气泡右边界-8');
3163
+ assert.strictEqual(JSON.stringify(api.plainBoundsOf(null, { left: 0, right: 400 }, 1280)), JSON.stringify({ min: 8, max: 392 }),
3164
+ '拿不到标题:左边界退回气泡内边距 8');
3165
+ assert.strictEqual(JSON.stringify(api.plainBoundsOf({ right: 120 }, { left: 0, right: 5000 }, 1280)), JSON.stringify({ min: 132, max: 1272 }),
3166
+ '气泡右边界超过视口时按视口夹');
3167
+ assert.strictEqual(api.plainBoundsOf({ right: 120 }, null, 1280), null,
3168
+ '拿不到气泡几何:返回 null(交给夹取/视口兜底)');
3169
+ assert.strictEqual(api.plainBoundsOf(null, { left: 400, right: 300 }, 1280), null,
3170
+ '气泡右边界已越过左边界(区间为负):返回 null');
3171
+ assert.strictEqual(api.plainBoundsOf({ right: 400 }, { left: 0, right: 300 }, 1280), null,
3172
+ '标题右边界越过气泡右边界(无处可放):返回 null');
3173
+
3174
+ /* clampPlainLeft:夹进给定范围(没有范围时只夹视口) */
3175
+ assert.strictEqual(api.clampPlainLeft(0, 60, bounds, 1280), 132, '夹进范围左边界、不压标题');
3176
+ assert.strictEqual(api.clampPlainLeft(500, 60, bounds, 1280), 332, '文字右边界不越过范围右边界(392-60)');
3177
+ assert.strictEqual(api.clampPlainLeft(300, 60, null, 1280), 300, '没有范围时只夹视口');
3178
+ /* 退化分支:没有视口宽度(viewportWidth <= 0)时两句兜底必须都走到 */
3179
+ assert.strictEqual(api.clampPlainLeft(500, 60, null, 0), 500,
3180
+ '没有视口、没有范围:left 原样返回居中值(不能贴死在左边界)');
3181
+ assert.strictEqual(api.clampPlainLeft(3, 60, null, 0), 8,
3182
+ '没有视口时仍要守住左边距 8px,实际 ' + api.clampPlainLeft(3, 60, null, 0));
3183
+ console.log('悬停文字范围:标题右边界+间距 → 气泡右边界-8;垂直与标题行居中对齐');
3184
+
3185
+ /* 悬停文字「放不下就整组不显示」的断言见本文件前面那段(搜 plainFits):
3186
+ 缩放功能已被移除,这里不再有"缩小到能放下"的用例。 */
3187
+
3188
+ /* ===================================== 总计:增量式记账(走真实渲染路径)======
3189
+ 用户拍板的口径:**每条调用只算一次钱、算完固化,之后永不重算**;
3190
+ 没价的模型记「欠账」,补上价只补算那部分。
3191
+
3192
+ 这一批**必须走真实渲染路径** —— 这是重点,别退回成"手工构造 hold 直接调纯函数":
3193
+ 每拍都调 `api.segmentView('cost', src)`,`src.totalHold` 复用**同一个对象**(模拟 useRef 跨渲染),
3194
+ 断言取的是**渲染出来的文字**(用户看到的那个数)。
3195
+
3196
+ 为什么不能手工传参数:那会绕过 client.js 里「组装 calls → 逐条结算 → overflow / 队友 / 欠账」
3197
+ 那段真实写入路径。实测代价(2026-10-18 审查 C):旧实现里「切分基准漂移」写错后
3198
+ 总计会永久冻结在旧值,而当时 24 个测试全绿 —— 就是因为测试全在纯函数层面打转。 */
3199
+
3200
+ /** 一拍:走真实渲染路径跑一次「总计」,返回渲染文字与其中金额。 */
3201
+ const TICK_OFF = FIXED_NOW; /* 北京时间周三 20:00(空闲) */
3202
+ const TICK_PEAK = Date.UTC(2026, 9, 15, 3, 0, 0); /* 北京时间周四 11:00(高峰) */
3203
+ /**
3204
+ * 干净的出厂人民币价格库(用例之间复位用)。
3205
+ *
3206
+ * 为什么不直接取 `api.snapshot().models`:那是**模块级 config**,前面「设置页改价」那一大段用例
3207
+ * 已经往里加过 GLM-5.3-Flash、纯数字键 "1"、把 deepseek-flash 改成 USD 等等 —— 拿它当基准会把
3208
+ * 别人的改动带进来。这里按 DEFAULT_PRICES 重建一份,只看官方 CNY 价。
3209
+ *
3210
+ * 必须用 Object.assign 逐个展开:DEFAULT_PRICES 来自 vm 沙箱 realm,
3211
+ * 跨 realm 的对象直接嵌进来会让深层比较失败(原型不同)。
3212
+ */
3213
+ const tickTier = (tier) => ({
3214
+ input: tier.input, cacheRead: tier.cacheRead, cacheWrite: tier.cacheWrite, output: tier.output
3215
+ });
3216
+ const tickOfficial = (name) => {
3217
+ const raw = api.DEFAULT_PRICES[name];
3218
+ return { tiered: true, currency: 'CNY', peak: tickTier(raw.peak), offPeak: tickTier(raw.offPeak) };
3219
+ };
3220
+ const TICK_BASE_MODELS = Object.assign({},
3221
+ { 'deepseek-flash': tickOfficial('deepseek-flash') },
3222
+ { 'deepseek-v4-pro': tickOfficial('deepseek-v4-pro') });
3223
+ /** 空账本:形状与 StatusBar 里 useRef 初始化的那份一致。
3224
+ * `debts` 是 **Map**(不是普通对象):模型名是上游给的任意字符串,
3225
+ * `__proto__` 这类键在普通对象上会变成设原型、静默丢失欠账。 */
3226
+ const tickHold = () => ({
3227
+ sessionId: null, seen: new Map(), cost: 0, tokens: null,
3228
+ priced: false, subCostSettled: 0, debts: new Map()
3229
+ });
3230
+ /** 一条调用:output 250,000 token = 0.25M。空闲 4 元/M ⇒ ¥1.00;高峰 8 元/M ⇒ ¥2.00。 */
3231
+ const tickCall = (at, model, units) => ({
3232
+ at: at, model: model, input: 0, cacheRead: 0, cacheWrite: 0, output: 250000 * units
3233
+ });
3234
+ const tickCost = (hold, opts) => {
3235
+ const o = opts === undefined ? {} : opts;
3236
+ /* 改价走真实路径:设置页改价就是 setConfig({ models }),priceOf 读的就是这份 */
3237
+ if (o.models !== undefined) api.setConfig({ models: o.models });
3238
+ const book = api.snapshot().models;
3239
+ const view = api.segmentView('cost', {
3240
+ sessionUsage: {
3241
+ models: book,
3242
+ calls: o.calls === undefined ? [] : o.calls,
3243
+ overflow: o.overflow,
3244
+ /* 压缩摘要的 token 累计(宿主新字段):总计用量要把这部分加上 */
3245
+ summaryParts: o.summaryParts
3246
+ },
3247
+ sessionModel: { provider: 'deepseek-official', model: 'deepseek-flash' },
3248
+ usage: o.usage,
3249
+ subagent: o.subagent === undefined ? null : o.subagent,
3250
+ currency: 'CNY', defaultCurrency: 'CNY', models: book,
3251
+ now: o.now === undefined ? TICK_OFF : o.now,
3252
+ sessionId: o.sessionId === undefined ? 'tick-session-a' : o.sessionId,
3253
+ totalHold: hold
3254
+ }, t);
3255
+ const text = api.segmentText('cost', view, t, 'CNY');
3256
+ const hit = typeof text === 'string' ? /¥(-?[\d.]+)/.exec(text) : null;
3257
+ return { text: text, money: hit === null ? null : Number(hit[1]) };
3258
+ };
3259
+
3260
+ /* ---- 场景 1:正常增长(每条只算一次;重渲染、乱序、同毫秒、滚动窗口都不重不漏)---- */
3261
+ api.setConfig({ models: TICK_BASE_MODELS });
3262
+ const growHold = tickHold();
3263
+ const growCallA = tickCall(TICK_OFF, 'deepseek-flash', 1);
3264
+ const growCallB = tickCall(TICK_OFF + 1000, 'deepseek-flash', 2);
3265
+ const growCallC = tickCall(TICK_PEAK + 1000, 'deepseek-flash', 1);
3266
+ let growTick = tickCost(growHold, { calls: [growCallA] });
3267
+ assert.strictEqual(growTick.text, '总计 ¥1.00', '第 1 条空闲调用 = ¥1.00,实际 ' + growTick.text);
3268
+ growTick = tickCost(growHold, { calls: [growCallA, growCallB] });
3269
+ assert.strictEqual(growTick.text, '总计 ¥3.00', '新增 1 条 ¥2.00 → ¥3.00,实际 ' + growTick.text);
3270
+ growTick = tickCost(growHold, { calls: [growCallA, growCallB, growCallC] });
3271
+ assert.strictEqual(growTick.text, '总计 ¥5.00', '再新增 1 条高峰 ¥2.00 → ¥5.00,实际 ' + growTick.text);
3272
+ /* 同一份数据再渲染:一条都不许重复计费(用户看到的总计不能自己往上跳) */
3273
+ growTick = tickCost(growHold, { calls: [growCallA, growCallB, growCallC] });
3274
+ assert.strictEqual(growTick.text, '总计 ¥5.00', '同数据重渲染不得重复计费,实际 ' + growTick.text);
3275
+ /* calls **不保证按 at 升序**(真实日志里就有 [22:00, 10:00, 10:00]):
3276
+ 乱序到达的调用必须全部计入 —— 任何"只往后推时间游标"的写法都会漏掉后到的早调用。 */
3277
+ const disorderHold = tickHold();
3278
+ const disorderLate = tickCall(TICK_OFF, 'deepseek-flash', 1); /* 空闲 ¥1.00 */
3279
+ const disorderEarly = tickCall(TICK_OFF - 36000000, 'deepseek-flash', 1); /* 10 小时前 = 周三 10:00 高峰 ¥2.00 */
3280
+ let disorderTick = tickCost(disorderHold, { calls: [disorderLate, disorderEarly] });
3281
+ assert.strictEqual(disorderTick.text, '总计 ¥3.00', '乱序到达的两条都要计入(¥1 + ¥2),实际 ' + disorderTick.text);
3282
+ /* 同一毫秒的并行调用(指纹完全相同):靠"出现次数"去重,只记"见过/没见过"会漏掉第二条 */
3283
+ const sameMsHold = tickHold();
3284
+ const sameMsCall = tickCall(TICK_OFF, 'deepseek-flash', 1);
3285
+ let sameMsTick = tickCost(sameMsHold, { calls: [sameMsCall] });
3286
+ assert.strictEqual(sameMsTick.text, '总计 ¥1.00', '同毫秒第 1 条 ¥1.00,实际 ' + sameMsTick.text);
3287
+ sameMsTick = tickCost(sameMsHold, { calls: [sameMsCall, sameMsCall] });
3288
+ assert.strictEqual(sameMsTick.text, '总计 ¥2.00', '同一毫秒再来一条同参数调用也要计入,实际 ' + sameMsTick.text);
3289
+ /* calls 是滚动窗口:队首会被 host 的 MAX_CALLS 丢弃。用**下标**切分会整体错位、扣错钱。 */
3290
+ const windowHold = tickHold();
3291
+ const windowA = tickCall(TICK_OFF, 'deepseek-flash', 1);
3292
+ const windowB = tickCall(TICK_OFF + 1000, 'deepseek-flash', 1);
3293
+ const windowC = tickCall(TICK_OFF + 2000, 'deepseek-flash', 1);
3294
+ let windowTick = tickCost(windowHold, { calls: [windowA, windowB] });
3295
+ assert.strictEqual(windowTick.text, '总计 ¥2.00', '窗口内前两条 ¥2.00,实际 ' + windowTick.text);
3296
+ windowTick = tickCost(windowHold, { calls: [windowB, windowC] });
3297
+ assert.strictEqual(windowTick.text, '总计 ¥3.00', '队首被丢弃后只补算新增那条,实际 ' + windowTick.text);
3298
+ console.log('总计记账:¥1→¥3→¥5 / 重渲染不重复 / 乱序、同毫秒、滚动窗口都不重不漏');
3299
+
3300
+ /* ---- 场景 2:改价(改价前已花的钱不动,改价后的新调用按新价)---- */
3301
+ api.setConfig({ models: TICK_BASE_MODELS });
3302
+ const priceHold = tickHold();
3303
+ const priceCallA = tickCall(TICK_OFF, 'deepseek-flash', 1);
3304
+ let priceTick = tickCost(priceHold, { calls: [priceCallA] });
3305
+ assert.strictEqual(priceTick.text, '总计 ¥1.00', '改价前按旧价算 ¥1.00,实际 ' + priceTick.text);
3306
+ /* 空闲输出价 4 → 1 元/M:同一条调用按新价只值 ¥0.25 */
3307
+ const TICK_CHEAP = {
3308
+ 'deepseek-flash': {
3309
+ tiered: true, currency: 'CNY',
3310
+ peak: { input: 0.5, cacheRead: 0.01, cacheWrite: 0, output: 2 },
3311
+ offPeak: { input: 0.25, cacheRead: 0.005, cacheWrite: 0, output: 1 }
3312
+ }
3313
+ };
3314
+ priceTick = tickCost(priceHold, { calls: [priceCallA], models: TICK_CHEAP });
3315
+ assert.strictEqual(priceTick.text, '总计 ¥1.00', '改价前已经花掉的钱不许变(不能被新价重算成 ¥0.25),实际 ' + priceTick.text);
3316
+ const priceCallB = tickCall(TICK_OFF + 1000, 'deepseek-flash', 1);
3317
+ priceTick = tickCost(priceHold, { calls: [priceCallA, priceCallB], models: TICK_CHEAP });
3318
+ assert.strictEqual(priceTick.text, '总计 ¥1.25', '改价后的新调用按新价 ¥0.25(1 + 0.25),实际 ' + priceTick.text);
3319
+ console.log('总计记账:改价后历史 ¥1.00 不动 / 新调用按新价 ¥0.25');
3320
+
3321
+ /* ---- 场景 3:无价 → 补价(先记欠账给横杠,补价后补算,重渲染不重复补)---- */
3322
+ /* 剥掉注释再断言(注释里也提到 debts: {} 这种反例写法) */
3323
+ const codeNoCommentsForDebts = code
3324
+ .replace(/\/\*[\s\S]*?\*\//g, '')
3325
+ .replace(/(^|[^:'\"\\\\])\/\/[^\n]*/g, '');
3326
+ api.setConfig({ models: TICK_BASE_MODELS });
3327
+ const debtHold = tickHold();
3328
+ /* 账本里的欠账**必须是 Map**,不能是普通对象:模型名是上游给的任意字符串,
3329
+ `__proto__` 这类键在普通对象上会变成设原型、静默丢失,`Object.keys` 遍历不到,
3330
+ 补价时永远结算不回来(总计永久少算)。`seen` 也是 Map —— 两者形状应当一致。
3331
+ 这条断言是给"以后有人把它改回 {}"准备的护栏(改回去立刻红)。 */
3332
+ assert.ok(debtHold.debts instanceof Map, '前置:账本的 debts 必须是 Map(不是普通对象)');
3333
+ /* 生产代码里的那两处初始化也必须是 Map —— 测试自己的 tickHold 对,
3334
+ 不代表 client.js 里那两份也对(变异只改生产代码时,上面那条断言抓不到)。
3335
+ 必须断言**两处都是** Map 且**不存在** `debts: {}`:只断言"至少有一处是 Map"
3336
+ 抓不到"只把其中一处改回去"的变异(实测存活过)。 */
3337
+ assert.strictEqual((codeNoCommentsForDebts.match(/debts: new Map\(\)/g) || []).length, 2,
3338
+ 'client.js 里两处 debts 初始化都必须是 new Map()(applyTotalFloor 新建账本 + totalHoldRef)');
3339
+ assert.strictEqual((codeNoCommentsForDebts.match(/debts: \{\}/g) || []).length, 0,
3340
+ 'client.js 里不许出现 debts: {}(普通对象会丢 __proto__ 这类键的欠账)');
3341
+ const debtCallA = tickCall(TICK_OFF, 'my-model', 1);
3342
+ const debtCallB = tickCall(TICK_OFF + 1000, 'my-model', 1);
3343
+ let debtTick = tickCost(debtHold, { calls: [debtCallA, debtCallB] });
3344
+ assert.strictEqual(debtTick.text, '总计 -', '一条都算不出价时给横杠(不是 ¥0.00),实际 ' + debtTick.text);
3345
+ assert.ok(debtHold.debts.has('my-model'),
3346
+ '无价模型必须记进欠账,实际 ' + JSON.stringify(Array.from(debtHold.debts.keys())));
3347
+ /* 补价:my-model 空闲输出 4 元/M ⇒ 每条 ¥1.00,两条 ¥2.00 */
3348
+ const TICK_WITH_MY = {
3349
+ 'deepseek-flash': TICK_BASE_MODELS['deepseek-flash'],
3350
+ 'my-model': {
3351
+ tiered: true, currency: 'CNY',
3352
+ peak: { input: 2, cacheRead: 0.04, cacheWrite: 0, output: 8 },
3353
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 }
3354
+ }
3355
+ };
3356
+ debtTick = tickCost(debtHold, { calls: [debtCallA, debtCallB], models: TICK_WITH_MY });
3357
+ assert.strictEqual(debtTick.text, '总计 ¥2.00', '补价后欠账要补算出来(2 条 × ¥1.00),实际 ' + debtTick.text);
3358
+ assert.strictEqual(debtHold.debts.size, 0, '补算完欠账应清空');
3359
+ /* 再渲染一拍:不能重复补算 */
3360
+ debtTick = tickCost(debtHold, { calls: [debtCallA, debtCallB], models: TICK_WITH_MY });
3361
+ assert.strictEqual(debtTick.text, '总计 ¥2.00', '欠账补算不得重复(重渲染仍是 ¥2.00),实际 ' + debtTick.text);
3362
+ console.log('总计记账:无价给横杠并记欠账 / 补价后补算 ¥2.00 / 重渲染不重复补');
3363
+
3364
+ /* ---- 场景 3b:模型名撞 JS 原型属性(`__proto__` / `constructor`)----
3365
+ 欠账账本若用普通对象,`debts['__proto__'] = slot` 是**设置原型**而不是加键,
3366
+ `Object.keys` 遍历不到 → 补价时永远结算不回来,总计永久少算。
3367
+ `constructor` / `toString` 更隐蔽:读到的是原型上的函数,代码把函数当字典用
3368
+ "碰巧能跑",但那是巧合不是设计。账本必须是 Map(或空原型对象)。 */
3369
+ api.setConfig({ models: TICK_BASE_MODELS });
3370
+ [/* __proto__ 单独放在下面测(它过不了 setConfig 的 Object.assign 这一步,见说明) */'constructor', 'toString', 'hasOwnProperty'].forEach((weirdName) => {
3371
+ const weirdHold = tickHold();
3372
+ const weirdCall = tickCall(TICK_OFF, weirdName, 1);
3373
+ let weirdTick = tickCost(weirdHold, { calls: [weirdCall] });
3374
+ assert.strictEqual(weirdTick.text, '总计 -',
3375
+ weirdName + ':无价时应给横杠,实际 ' + weirdTick.text);
3376
+ assert.ok(weirdHold.debts.has(weirdName),
3377
+ weirdName + ':欠账必须真的记进账本(普通对象上 __proto__ 会静默丢失),实际 '
3378
+ + JSON.stringify(Array.from(weirdHold.debts.keys())));
3379
+ /* 补价:输出 4 元/M × 0.25M = ¥1.00 */
3380
+ const weirdModels = Object.assign({}, TICK_BASE_MODELS, {
3381
+ [weirdName]: {
3382
+ tiered: true, currency: 'CNY',
3383
+ peak: { input: 2, cacheRead: 0.04, cacheWrite: 0, output: 8 },
3384
+ offPeak: { input: 1, cacheRead: 0.02, cacheWrite: 0, output: 4 }
3385
+ }
3386
+ });
3387
+ weirdTick = tickCost(weirdHold, { calls: [weirdCall], models: weirdModels });
3388
+ assert.strictEqual(weirdTick.text, '总计 ¥1.00',
3389
+ weirdName + ':补价后必须补算出 ¥1.00(原型键上丢了欠账就会是横杠),实际 ' + weirdTick.text);
3390
+ assert.strictEqual(weirdHold.debts.size, 0, weirdName + ':补算完欠账应清空');
3391
+ });
3392
+ console.log('总计记账:模型名 __proto__ / constructor / toString / hasOwnProperty 都能正常记欠账并补算');
3393
+
3394
+ /* ---- 场景 4:队友(子智能体)只加增量、不重复加;换会话不残留 ---- */
3395
+ api.setConfig({ models: TICK_BASE_MODELS });
3396
+ const subHold = tickHold();
3397
+ const subCallA = tickCall(TICK_OFF, 'deepseek-flash', 1);
3398
+ const subTen = { ok: true, total: { cost: 10, tokens: { cacheRead: 0, input: 0, cacheWrite: 0, output: 0 } } };
3399
+ const subFifteen = { ok: true, total: { cost: 15, tokens: { cacheRead: 0, input: 0, cacheWrite: 0, output: 0 } } };
3400
+ let subTick = tickCost(subHold, { calls: [subCallA], subagent: { session: subTen, turn: null } });
3401
+ assert.strictEqual(subTick.text, '总计 ¥11.00', '本会话 ¥1.00 + 队友 ¥10.00,实际 ' + subTick.text);
3402
+ subTick = tickCost(subHold, { calls: [subCallA], subagent: { session: subTen, turn: null } });
3403
+ assert.strictEqual(subTick.text, '总计 ¥11.00', '重渲染时队友金额不得重复加(用户实测的闪烁就是它),实际 ' + subTick.text);
3404
+ subTick = tickCost(subHold, { calls: [subCallA], subagent: { session: subFifteen, turn: null } });
3405
+ assert.strictEqual(subTick.text, '总计 ¥16.00', '队友涨到 ¥15.00 时只补 ¥5.00 增量,实际 ' + subTick.text);
3406
+ /* 队友请求失败(整段拿不到):显示不许回退 —— 用户实测 20 秒内 ¥2.66 → ¥92.37 就是这个 */
3407
+ subTick = tickCost(subHold, { calls: [subCallA], subagent: null });
3408
+ assert.strictEqual(subTick.text, '总计 ¥16.00', '队友请求失败时显示不得回退(防闪),实际 ' + subTick.text);
3409
+ /* 换会话:上个会话的调用与队友金额都不得带过来(旧实现在这里会把上会话队友永久算进来) */
3410
+ const switchCall = tickCall(TICK_OFF + 5000, 'deepseek-flash', 2);
3411
+ const switchTick = tickCost(subHold, { calls: [switchCall], subagent: null, sessionId: 'tick-session-b' });
3412
+ assert.strictEqual(switchTick.text, '总计 ¥2.00', '换会话后账本清空、只剩本会话 ¥2.00,实际 ' + switchTick.text);
3413
+ console.log('总计记账:队友只加增量 ¥11→¥16 / 失败不回退 / 换会话无残留');
3414
+
3415
+ /* ---- 场景 5:overflow(被 host 截断的老调用)只在建账那一拍计入一次 ---- */
3416
+ api.setConfig({ models: TICK_BASE_MODELS });
3417
+ const overHold = tickHold();
3418
+ const overCallA = tickCall(TICK_OFF, 'deepseek-flash', 1);
3419
+ const overBucket = {
3420
+ 'deepseek-flash': {
3421
+ peak: { input: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
3422
+ offPeak: { input: 0, cacheRead: 0, cacheWrite: 0, output: 250000 }
3423
+ }
3424
+ };
3425
+ let overTick = tickCost(overHold, { calls: [overCallA], overflow: overBucket });
3426
+ assert.strictEqual(overTick.text, '总计 ¥2.00', 'calls ¥1.00 + overflow ¥1.00,实际 ' + overTick.text);
3427
+ overTick = tickCost(overHold, { calls: [overCallA], overflow: overBucket });
3428
+ assert.strictEqual(overTick.text, '总计 ¥2.00', 'overflow 不得每拍重复计入,实际 ' + overTick.text);
3429
+ console.log('总计记账:overflow 只在建账那拍计一次(¥2.00 不涨)');
3430
+
3431
+ /* ---- 场景 5b:总计**用量**要含压缩摘要(端到端,走真实 segmentView)----
3432
+ 背景:「总计费用」是我们逐条算的、含摘要;「总计用量」原本只读官方 tokenUsage 投影,
3433
+ 官方只折 assistant 事件、**不含摘要** → 同一个气泡里两个数字口径不一致。
3434
+ 用户拍板:官方投影继续用,只把摘要这部分额外加上。
3435
+ 这条用例必须走**真实的 segmentView('cost', ...)** 并读 tip.panel.totalText ——
3436
+ 只测 summaryTokenParts / mergeTokenParts 这些纯函数抓不到「客户端忘了把摘要加进去」
3437
+ 这个变异(实测纯函数用例下该变异存活)。 */
3438
+ const sumUsage = { uncachedInputTokens: 1000, cacheReadTokens: 2000, cacheWriteTokens: 0, outputTokens: 3000 };
3439
+ const sumParts = { input: 100000, cacheRead: 50000, cacheWrite: 0, output: 40000 };
3440
+ const sumView = (withSummary) => api.segmentView('cost', {
3441
+ sessionUsage: {
3442
+ models: api.snapshot().models, calls: [],
3443
+ summaryParts: withSummary === true ? sumParts : undefined
3444
+ },
3445
+ sessionModel: { provider: 'deepseek-official', model: 'deepseek-flash' },
3446
+ usage: sumUsage, subagent: null,
3447
+ currency: 'CNY', defaultCurrency: 'CNY', models: api.snapshot().models,
3448
+ now: TICK_OFF, sessionId: 'tick-session-sum', totalHold: tickHold()
3449
+ }, t);
3450
+ const textOfPanel = (view) => (view === null || view.tip === undefined ? null : view.tip.panel.totalText);
3451
+ /* 官方投影三段之和 = 1000 + 2000 + 3000 = 6,000 */
3452
+ assert.strictEqual(textOfPanel(sumView(false)), '6,000', '没有摘要时总计用量 = 官方投影之和,实际 ' + textOfPanel(sumView(false)));
3453
+ /* 摘要四段换成三段 = cached 50000 + missInput 100000 + output 40000 = 190,000 */
3454
+ assert.strictEqual(textOfPanel(sumView(true)), '196,000',
3455
+ '有摘要时总计用量 = 官方投影 6,000 + 摘要 190,000 = 196,000,实际 ' + textOfPanel(sumView(true)));
3456
+ console.log('总计用量含摘要:6,000 → 196,000(多出的正好是摘要那 190,000)');
3457
+
3458
+ /* ---- 场景 6:已结算指纹集合有上限(长会话内存不能无限增长)---- */
3459
+ const manyCalls = [];
3460
+ for (let i = 0; i < 9000; i += 1) manyCalls.push(tickCall(TICK_OFF + i * 1000, 'deepseek-flash', 1));
3461
+ const manyHold = tickHold();
3462
+ const manyTick = tickCost(manyHold, { calls: manyCalls });
3463
+ assert.ok(manyHold.seen.size <= 8000, '已结算指纹集合必须有上限(SEEN_LIMIT=8000),实际 ' + manyHold.seen.size);
3464
+ assert.strictEqual(manyTick.money, 9000, '9000 条 × ¥1.00 = ¥9000,金额不受上限影响,实际 ' + manyTick.money);
3465
+ console.log('总计记账:9000 条调用后指纹集合仍 ≤ 8000,金额正确 ¥9000.00');
3466
+
3467
+ /* ---- 场景 7:指纹上限的**跨拍**行为(上限真正的作用在下一拍)----
3468
+ 关键前提:**单拍喂入的调用数不可能超过 MAX_CALLS(4000)** —— host 的 calls 就是那个上限。
3469
+ 而 SEEN_LIMIT=8000 正好是它的两倍,所以「这一拍还在窗口里的调用」的指纹永远不会被淘汰,
3470
+ 跨拍重算时必然全部命中、不会重复计费。下面用**真实规模**(4000 条 = MAX_CALLS)验证。
3471
+
3472
+ 若把 SEEN_LIMIT 调到小于单拍调用数,淘汰就会误伤仍在窗口里的指纹 → 第二拍重复计费。
3473
+ 这正是 M05 要盯的边界:这条用例同时是 SEEN_LIMIT 的**下界证明**(必须 ≥ MAX_CALLS)。 */
3474
+ const manyHold2 = tickHold();
3475
+ const realMax = manyCalls.slice(0, 4000); /* MAX_CALLS 规模 */
3476
+ const manyCallsB = realMax.map((one) => Object.assign({}, one));
3477
+ let manyTick2 = tickCost(manyHold2, { calls: manyCallsB });
3478
+ assert.strictEqual(manyTick2.money, 4000, '第一拍 4000 条(= MAX_CALLS)= ¥4000,实际 ' + manyTick2.money);
3479
+ manyTick2 = tickCost(manyHold2, { calls: manyCallsB });
3480
+ assert.strictEqual(manyTick2.money, 4000,
3481
+ '第二拍喂同一批 4000 条时不得重复计费,实际 ' + manyTick2.money);
3482
+ assert.strictEqual(manyTick2.text, '总计 ¥4000.00', '第二拍金额文本不变,实际 ' + manyTick2.text);
3483
+ assert.ok(manyHold2.seen.size <= 8000, '指纹集合仍在上限内,实际 ' + manyHold2.seen.size);
3484
+ console.log('总计记账:指纹上限跨拍不重复计费(4000 条 = MAX_CALLS,第二拍仍 ¥4000.00)');
3485
+
3486
+ /* 用例改了模块级价格库,还回去(后面的设置页用例仍按出厂价跑) */
3487
+ api.setConfig({ models: TICK_BASE_MODELS });
3488
+
3489
+ /* 需求 9:设置页不再有「更新节假峰谷」按钮与状态文案(改为 StatusBar 时钟自动更新,
3490
+ 时机与写配置行为由 verify-holiday-update.js 覆盖)。 */
3491
+ const quietTree = freshSettings();
3492
+ assert.strictEqual(collectByClass(quietTree, 'dsb-current-act').length, 0, '设置页不再有节假日动作区');
3493
+ assert.strictEqual(textOf(quietTree).indexOf('更新节假峰谷'), -1, '设置页不再出现「更新节假峰谷」');
3494
+ assert.strictEqual(textOf(quietTree).indexOf('已写入'), -1, '设置页不再出现节假日状态文案');
3495
+ console.log('节假日:设置页按钮与状态文案已删除(改为每年 12/31 自动更新)');
3496
+ console.log('\nALL CHECKS PASSED');
3497
+
3498
+
3499
+
3500
+
3501
+
3502
+
3503
+
3504
+
3505
+
3506
+
3507
+
3508
+
3509
+
3510
+