lantern-harness 0.1.29 → 0.1.32

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 (105) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/500.html +4 -4
  3. package/dist/_astro/{Base.BbqRC8BF.css → Base.9LLJ6KVG.css} +1 -1
  4. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.4j--gBo-.js +2 -0
  5. package/dist/_astro/CaseExecBoard.CTuf_Nom.js +1 -0
  6. package/dist/_astro/CaseGenerateApp.18SE0dLJ.js +10 -0
  7. package/dist/_astro/CasesLibrary.C-T3VrPa.js +24 -0
  8. package/dist/_astro/ChatApp.BpFXgd8K.js +226 -0
  9. package/dist/_astro/{DashboardBoard.DAUPgVh3.js → DashboardBoard.B5Qo5Y3e.js} +2 -2
  10. package/dist/_astro/DocsFileBrowser.DnxVsmed.js +1 -0
  11. package/dist/_astro/DocsPager.CnXEnQqa.js +1 -0
  12. package/dist/_astro/{KnowledgeLibrary.DKci9jN8.js → KnowledgeLibrary.DARUegK8.js} +1 -1
  13. package/dist/_astro/{NavLibraries.BybmHnXn.js → NavLibraries.FAj9zUuq.js} +1 -1
  14. package/dist/_astro/PluginsPage.DKPA2zw8.js +1 -0
  15. package/dist/_astro/{PluginsPage.CYqe0xYq.js → PluginsPage.F0oMYJri.js} +2 -2
  16. package/dist/_astro/{PmBugsBoard.DVhrHxD2.js → PmBugsBoard.uNPzbw-N.js} +1 -1
  17. package/dist/_astro/{PmIterationsBoard.BQPHdbpp.js → PmIterationsBoard.CjR8L71i.js} +1 -1
  18. package/dist/_astro/{PmProjectDetail.DZmqbZLO.js → PmProjectDetail.Cpug99Lt.js} +1 -1
  19. package/dist/_astro/{PmProjectsBoard.tk8cI-lO.js → PmProjectsBoard.VLqrwucj.js} +1 -1
  20. package/dist/_astro/PmRequirementsBoard.B5ypu68O.js +1 -0
  21. package/dist/_astro/PmRequirementsBoard.CdP4gEzq.js +1 -0
  22. package/dist/_astro/{PmShared.DRYCFoRc.js → PmShared.ChKKU3Ww.js} +1 -1
  23. package/dist/_astro/PromptsLibrary.BlWPVm1Z.js +1 -0
  24. package/dist/_astro/{ReportsPage.B7MOskzc.js → ReportsPage.iSM5TWMq.js} +1 -1
  25. package/dist/_astro/ReqAnalysisBoard.CeQbq7Qh.js +39 -0
  26. package/dist/_astro/{RequirementsLibrary._OviMClB.js → RequirementsLibrary.X89V8-QF.js} +1 -1
  27. package/dist/_astro/{SettingsDialog.F2HdD5v4.js → SettingsDialog.BlokCWBn.js} +1 -1
  28. package/dist/_astro/{SpaceSwitcher.DQOG363O.js → SpaceSwitcher.MmSkP3wb.js} +1 -1
  29. package/dist/_astro/TagSelect.UUXgkMqJ.js +1 -0
  30. package/dist/_astro/TasksBoard.Z8rBCO1F.js +1 -0
  31. package/dist/_astro/{TemplatesLibrary.CEVQPDDz.js → TemplatesLibrary.DBHSAPQ0.js} +1 -1
  32. package/dist/_astro/TestStatsBoard.BtqoPuLc.js +1 -0
  33. package/dist/_astro/TodosBoard.ETI63YgA.js +1 -0
  34. package/dist/_astro/{UiAutoBoard.DegcBc_3.js → UiAutoBoard.DxrlgvI7.js} +1 -1
  35. package/dist/_astro/app-config.Bg6v8zQQ.js +1 -0
  36. package/dist/_astro/app-version.CLOjRiPN.js +1 -0
  37. package/dist/_astro/{bash-tools.D4DBYc9k.js → bash-tools.cciCC33C.js} +1 -1
  38. package/dist/_astro/case-exec.BLqTXR7U.js +1 -0
  39. package/dist/_astro/case-gen-run.BNNfA12U.js +22 -0
  40. package/dist/_astro/{case-review.DlCarphW.js → case-review.s1w_mD4l.js} +1 -1
  41. package/dist/_astro/{case-types.B6MLX3iE.js → case-types.CJ5PHz59.js} +1 -1
  42. package/dist/_astro/{hydrate-cache.C0F0L04c.js → hydrate-cache.B7--LFB_.js} +1 -1
  43. package/dist/_astro/{i18n.ele1lM9e.js → i18n.CH6ZNsHf.js} +1 -1
  44. package/dist/_astro/{open-docs-in-session.D608wzlx.js → open-docs-in-session.DQ2_5fkC.js} +1 -1
  45. package/dist/_astro/plugins.SqANn3ZB.js +1 -0
  46. package/dist/_astro/req-analysis.Dbe_gqPz.js +24 -0
  47. package/dist/_astro/{settings.DbhUT6Ao.js → settings.Cu00if4D.js} +2 -2
  48. package/dist/_astro/spaces-client.Czm-VPh5.js +1 -0
  49. package/dist/_astro/{story-review.SqNsPiZE.js → story-review.CNZnYMvW.js} +2 -2
  50. package/dist/_astro/test-stats.Cf3_L4wu.js +1 -0
  51. package/dist/_astro/{view-prefs.DkS1ldnh.js → view-prefs.SdItxolG.js} +1 -1
  52. package/dist/case-exec/index.html +5 -5
  53. package/dist/cases/generate/index.html +5 -5
  54. package/dist/cases/library/index.html +5 -5
  55. package/dist/dashboard/index.html +5 -5
  56. package/dist/docs/changelog/index.html +88 -35
  57. package/dist/docs/install/index.html +4 -4
  58. package/dist/docs/manual/index.html +44 -16
  59. package/dist/knowledge/index.html +5 -5
  60. package/dist/plugins/index.html +5 -5
  61. package/dist/pm/bugs/index.html +5 -5
  62. package/dist/pm/iterations/index.html +5 -5
  63. package/dist/pm/projects/detail/index.html +5 -5
  64. package/dist/pm/projects/index.html +5 -5
  65. package/dist/pm/requirements/index.html +5 -5
  66. package/dist/prompts/index.html +5 -5
  67. package/dist/reports/index.html +5 -5
  68. package/dist/requirement-analysis/index.html +5 -5
  69. package/dist/requirements/index.html +5 -5
  70. package/dist/tasks/index.html +5 -5
  71. package/dist/templates/index.html +5 -5
  72. package/dist/test-automation/index.html +5 -5
  73. package/dist/test-stats/index.html +5 -5
  74. package/dist/todos/index.html +5 -5
  75. package/dist/workbench/index.html +5 -5
  76. package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +36 -12
  77. package/lh-plugins/lh-case-review.mjs +159 -0
  78. package/lh-plugins/lh-config.mjs +9 -0
  79. package/lh-plugins/lh-req-analysis.mjs +66 -6
  80. package/lh-plugins/lh-stats.mjs +308 -16
  81. package/package.json +1 -1
  82. package/dist/_astro/Base.astro_astro_type_script_index_0_lang.C_hJAznE.js +0 -2
  83. package/dist/_astro/CaseExecBoard.cl2Od7av.js +0 -1
  84. package/dist/_astro/CaseGenerateApp.nE3RR7bV.js +0 -10
  85. package/dist/_astro/CasesLibrary.BkQY421S.js +0 -21
  86. package/dist/_astro/ChatApp.BULN48Ml.js +0 -226
  87. package/dist/_astro/DocsFileBrowser.BdpWp8zQ.js +0 -1
  88. package/dist/_astro/DocsPager.D55FTK9d.js +0 -1
  89. package/dist/_astro/PluginsPage.DiPg_D8e.js +0 -1
  90. package/dist/_astro/PmRequirementsBoard.BjC9CEFr.js +0 -1
  91. package/dist/_astro/PmRequirementsBoard.CtuavIey.js +0 -1
  92. package/dist/_astro/PromptsLibrary.fKp4NWWW.js +0 -1
  93. package/dist/_astro/ReqAnalysisBoard.CcRTrBPY.js +0 -39
  94. package/dist/_astro/TagSelect.B9W63KWq.js +0 -1
  95. package/dist/_astro/TasksBoard.Uj4XWtWz.js +0 -1
  96. package/dist/_astro/TestStatsBoard.CO4JMh4N.js +0 -1
  97. package/dist/_astro/TodosBoard.BkszTn-p.js +0 -1
  98. package/dist/_astro/app-config.DAIyT--R.js +0 -1
  99. package/dist/_astro/app-version.p8P81lR6.js +0 -1
  100. package/dist/_astro/case-exec.BipZCK6G.js +0 -1
  101. package/dist/_astro/case-gen-run.Byxy6M5X.js +0 -22
  102. package/dist/_astro/plugins.Di6uuouN.js +0 -1
  103. package/dist/_astro/req-analysis.CIZ_cIJQ.js +0 -23
  104. package/dist/_astro/spaces-client.OuJPy3GP.js +0 -1
  105. package/dist/_astro/test-stats.MEm3K2rB.js +0 -1
@@ -460,6 +460,106 @@ export async function appendSheetRows(abs, rows, headers) {
460
460
  fs.writeFileSync(abs, out);
461
461
  }
462
462
 
463
+ /* --------------------------- 整表重排写回 --------------------------- */
464
+
465
+ /** md 用例表定位:表头行 + 分隔行 + 表体末行;找不到返回 null */
466
+ function findMarkdownCaseTable(lines) {
467
+ for (let i = 0; i < lines.length - 1; i += 1) {
468
+ const line = lines[i];
469
+ if (!line.trim().startsWith('|')) continue;
470
+ if (!isSepLine(lines[i + 1])) continue;
471
+ let end = i + 1;
472
+ while (end + 1 < lines.length && lines[end + 1].trim().startsWith('|')) end += 1;
473
+ return { header: i, sep: i + 1, end };
474
+ }
475
+ // 没有分隔行的手写表格:退回「表头含用例字样」的第一行
476
+ for (let i = 0; i < lines.length; i += 1) {
477
+ if (!lines[i].includes('|') || !lines[i].includes('用例')) continue;
478
+ let end = i;
479
+ while (end + 1 < lines.length && lines[end + 1].trim().startsWith('|')) end += 1;
480
+ return { header: i, sep: i, end };
481
+ }
482
+ return null;
483
+ }
484
+
485
+ function isSepLine(line) {
486
+ return /^\s*\|?[\s:|-]+\|?\s*$/.test(line) && /-+/.test(line);
487
+ }
488
+
489
+ /**
490
+ * md / csv 整表写回:只替换用例表体。
491
+ * - md 保留表头、对齐行、表格前后的说明 / 备注段落
492
+ * - csv 保留表头行与 BOM
493
+ */
494
+ export function rewriteTextRows(abs, ext, rows, headers) {
495
+ const raw = fs.readFileSync(abs, 'utf8');
496
+ const sep = raw.includes('\r\n') ? '\r\n' : '\n';
497
+ const body = rows.map((r) =>
498
+ ext === '.md'
499
+ ? `| ${headers.map((h) => mdCell(r[h])).join(' | ')} |`
500
+ : headers.map((h) => csvCell(r[h])).join(','),
501
+ );
502
+
503
+ if (ext !== '.md') {
504
+ const bom = raw.startsWith('\uFEFF') ? '\uFEFF' : '';
505
+ const lines = raw.replace(/^\uFEFF/, '').split(/\r?\n/);
506
+ const headerIdx = lines.findIndex((l) => l.trim());
507
+ if (headerIdx < 0) {
508
+ fs.writeFileSync(
509
+ abs,
510
+ `${bom}${headers.map(csvCell).join(',')}${sep}${body.join(sep)}${sep}`,
511
+ 'utf8',
512
+ );
513
+ return;
514
+ }
515
+ const head = lines[headerIdx];
516
+ fs.writeFileSync(abs, `${bom}${head}${sep}${body.join(sep)}${sep}`, 'utf8');
517
+ return;
518
+ }
519
+
520
+ const lines = raw.split(/\r?\n/);
521
+ const table = findMarkdownCaseTable(lines);
522
+ if (!table) {
523
+ const head = `| ${headers.map(mdCell).join(' | ')} |`;
524
+ const align = `| ${headers.map(() => '---').join(' | ')} |`;
525
+ const trimmed = raw.replace(/[\r\n]+$/, '');
526
+ const prefix = trimmed.trim() ? `${trimmed}${sep}${sep}` : '';
527
+ fs.writeFileSync(abs, `${prefix}${head}${sep}${align}${sep}${body.join(sep)}${sep}`, 'utf8');
528
+ return;
529
+ }
530
+ const next = [...lines.slice(0, table.sep + 1), ...body, ...lines.slice(table.end + 1)];
531
+ fs.writeFileSync(abs, next.join(sep), 'utf8');
532
+ }
533
+
534
+ /** xlsx / xls 整表写回:保留首个工作表与表头,只覆盖数据行(已提前备份) */
535
+ export async function rewriteSheetRows(abs, rows, headers) {
536
+ const mod = await import('xlsx');
537
+ const xlsx = mod.default ?? mod;
538
+ const book = xlsx.read(fs.readFileSync(abs), { type: 'buffer', cellDates: true });
539
+ const sheetName = book.SheetNames[0];
540
+ if (!sheetName) throw Object.assign(new Error('用例文件里没有工作表'), { statusCode: 422 });
541
+ const sheet = book.Sheets[sheetName];
542
+ const range = xlsx.utils.decode_range(sheet['!ref'] ?? 'A1:A1');
543
+ // 先清掉旧数据行,避免新行数变少时残留尾巴
544
+ for (let r = 1; r <= range.e.r; r += 1) {
545
+ for (let c = 0; c <= range.e.c; c += 1) {
546
+ delete sheet[xlsx.utils.encode_cell({ r, c })];
547
+ }
548
+ }
549
+ rows.forEach((row, i) => {
550
+ headers.forEach((h, c) => {
551
+ const v = String(row[h] ?? '');
552
+ if (!v) return;
553
+ sheet[xlsx.utils.encode_cell({ r: i + 1, c })] = { t: 's', v };
554
+ });
555
+ });
556
+ sheet['!ref'] = xlsx.utils.encode_range({
557
+ s: { r: 0, c: 0 },
558
+ e: { r: Math.max(0, rows.length), c: Math.max(range.e.c, headers.length - 1) },
559
+ });
560
+ fs.writeFileSync(abs, xlsx.write(book, { bookType: 'xlsx', type: 'buffer' }));
561
+ }
562
+
463
563
  /* ------------------------------ HTTP ------------------------------ */
464
564
 
465
565
  function sendJson(res, status, body) {
@@ -702,9 +802,68 @@ async function reviewRoutes(req, res, root, tail, query) {
702
802
  });
703
803
  }
704
804
 
805
+ if (await rewriteRoute(req, res, root, tail)) return;
806
+
705
807
  return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
706
808
  }
707
809
 
810
+ /** 整表重排:按客户端排好序的行覆盖原文件,写前备份 */
811
+ async function rewriteRoute(req, res, root, tail) {
812
+ if (tail !== '/rewrite') return false;
813
+ if ((req.method || 'GET') !== 'POST') return false;
814
+ const body = JSON.parse((await readBody(req)) || '{}');
815
+ const rel = text(body.path, 400);
816
+ if (!rel) {
817
+ sendJson(res, 400, { ok: false, error: '缺少用例文件路径' });
818
+ return true;
819
+ }
820
+ const headers = strList(body.headers, 40, 60);
821
+ if (!headers.length) {
822
+ sendJson(res, 400, { ok: false, error: '缺少用例字段' });
823
+ return true;
824
+ }
825
+ const rows = (Array.isArray(body.rows) ? body.rows : []).slice(0, 5000).map((r) => {
826
+ const out = {};
827
+ for (const h of headers) out[h] = typeof r?.[h] === 'string' ? r[h] : String(r?.[h] ?? '');
828
+ return out;
829
+ });
830
+ if (!rows.length) {
831
+ sendJson(res, 400, { ok: false, error: '没有要写入的用例' });
832
+ return true;
833
+ }
834
+ const abs = caseFileAbs(root, rel);
835
+ if (!fs.existsSync(abs)) {
836
+ sendJson(res, 404, { ok: false, error: `用例文件不存在:${rel}` });
837
+ return true;
838
+ }
839
+ const ext = path.extname(abs).toLowerCase();
840
+ if (!['.md', '.markdown', '.csv', '.xlsx', '.xls'].includes(ext)) {
841
+ sendJson(res, 415, { ok: false, error: `暂不支持写回 ${ext || '(无扩展名)'} 文件` });
842
+ return true;
843
+ }
844
+ const backup = backupCaseFile(root, abs);
845
+ if (ext === '.xlsx' || ext === '.xls') await rewriteSheetRows(abs, rows, headers);
846
+ else rewriteTextRows(abs, ext === '.csv' ? '.csv' : '.md', rows, headers);
847
+
848
+ // 重排后用例编号变了,旧评审结论里的编号对不上:清掉这一份的评审 / 补全结果
849
+ const store = readStore(root);
850
+ const idx = store.files.findIndex((x) => x.path === rel);
851
+ if (idx >= 0) {
852
+ store.files[idx].review = null;
853
+ store.files[idx].blindspot = null;
854
+ store.files[idx].hash = hashOfFile(abs) || store.files[idx].hash;
855
+ store.files[idx].updatedAt = new Date().toISOString();
856
+ writeStore(root, store);
857
+ }
858
+
859
+ const backupRel = path
860
+ .relative(resolveContentRoot(root, CASES_DIR_NAME).abs, backup)
861
+ .split(path.sep)
862
+ .join('/');
863
+ sendJson(res, 200, { ok: true, path: rel, rows: rows.length, backup: backupRel });
864
+ return true;
865
+ }
866
+
708
867
  async function blindspotRoutes(req, res, root, tail, query) {
709
868
  const method = req.method || 'GET';
710
869
 
@@ -307,6 +307,7 @@ export function lhConfigPlugin() {
307
307
  return sendJson(res, 200, {
308
308
  ok: true,
309
309
  config,
310
+ configTarget: root,
310
311
  apiKey: readApiKey(root, config),
311
312
  paths: {
312
313
  defaults: defaultsPath(root),
@@ -318,6 +319,14 @@ export function lhConfigPlugin() {
318
319
 
319
320
  if (url === PREFIX && req.method === 'PUT') {
320
321
  const body = JSON.parse((await readBody(req)) || '{}');
322
+ const configTarget =
323
+ typeof body.configTarget === 'string' ? path.resolve(body.configTarget) : '';
324
+ if (!configTarget || configTarget !== path.resolve(root)) {
325
+ return sendJson(res, 409, {
326
+ ok: false,
327
+ error: '数据空间已切换,已拒绝旧空间的配置写入,请刷新页面后重试',
328
+ });
329
+ }
321
330
  const defaults = readJson(defaultsPath(root), {});
322
331
  const incoming = body.config ?? body;
323
332
  const merged = sanitizeForLocalWrite(mergeWithDefaults(defaults, incoming));
@@ -98,20 +98,80 @@ export function reqDocsDir(spaceDir) {
98
98
  return resolveContentRoot(spaceDir, REQ_DOCS_DIR_NAME).abs;
99
99
  }
100
100
 
101
+ /** 解开 mammoth 输出的 HTML 实体,避免正文里留下 `&amp;` 之类 */
102
+ function decodeHtmlEntities(text) {
103
+ return String(text ?? '')
104
+ .replace(/&nbsp;/g, ' ')
105
+ .replace(/&lt;/g, '<')
106
+ .replace(/&gt;/g, '>')
107
+ .replace(/&quot;/g, '"')
108
+ .replace(/&#39;|&apos;/g, "'")
109
+ .replace(/&#x([0-9a-f]+);/gi, (_m, hex) => String.fromCodePoint(parseInt(hex, 16)))
110
+ .replace(/&#(\d+);/g, (_m, dec) => String.fromCodePoint(Number(dec)))
111
+ .replace(/&amp;/g, '&');
112
+ }
113
+
114
+ /** 内联片段压成单行纯文本(标题、列表项用) */
115
+ function htmlInlineText(html) {
116
+ return decodeHtmlEntities(String(html ?? '').replace(/<[^>]+>/g, ''))
117
+ .replace(/\s+/g, ' ')
118
+ .trim();
119
+ }
120
+
121
+ /** 标题层级 → Markdown:docx 的 1–6 级统一压到 `#`/`##`/`###`(前端按 2–3 级切章节) */
122
+ function headingToMarkdown(level, inner) {
123
+ const text = htmlInlineText(inner);
124
+ if (!text) return '';
125
+ const hashes = '#'.repeat(Math.min(3, Math.max(1, Number(level) || 1)));
126
+ return `\n\n${hashes} ${text}\n`;
127
+ }
128
+
101
129
  /**
102
- * Word(docx)正文抽取:按段落 + 表格拼成纯文本。
103
- * 标题层级压成 `#` / `##`,方便前端按 `^## ` 切分章节。
130
+ * Word(docx)正文抽取:按标题 / 段落 / 表格拼成纯文本,标题层级压成 `#` / `##` / `###`。
131
+ * 用 `convertToHtml` 而不是 `extractRawText`:后者会丢掉标题样式,文档结构一没了,
132
+ * 拆解就只能退回按【短名】猜条目(表头里的【提出人】也会被当成需求标题)。
104
133
  */
105
134
  async function extractDocx(fileAbs) {
106
135
  const { default: mammoth } = await import('mammoth');
107
136
  // 传 buffer 而不是路径:数据空间路径常带中文,交给库自己拼路径容易读不到
108
- const { value } = await mammoth.extractRawText({ buffer: fs.readFileSync(fileAbs) });
109
- const lines = String(value ?? '')
137
+ const buffer = fs.readFileSync(fileAbs);
138
+ const { value } = await mammoth.convertToHtml({ buffer });
139
+ const text = String(value ?? '')
140
+ // 图片是 base64 data URI,正文用不上且会撑爆上下文,直接丢
141
+ .replace(/<img[^>]*>/g, '')
142
+ .replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/g, (_m, level, inner) =>
143
+ headingToMarkdown(level, inner),
144
+ )
145
+ .replace(/<li[^>]*>([\s\S]*?)<\/li>/g, (_m, inner) => {
146
+ const line = htmlInlineText(inner);
147
+ return line ? `\n- ${line}` : '';
148
+ })
149
+ // 表格:一行一条,单元格用 ` | ` 隔开,保留字段对照关系
150
+ .replace(/<\/tr>/g, '\n')
151
+ .replace(/<\/t[dh]>/g, ' | ')
152
+ .replace(/<br\s*\/?>/g, '\n')
153
+ .replace(/<\/(p|div|section)>/g, '\n')
154
+ .replace(/<[^>]+>/g, '')
155
+ .split('\n')
156
+ .map((line) =>
157
+ decodeHtmlEntities(line)
158
+ .replace(/[ \t\u3000]+/g, ' ')
159
+ .trim(),
160
+ )
161
+ .filter((line, index, all) => line || all[index - 1])
162
+ .join('\n')
163
+ .replace(/\n{3,}/g, '\n\n')
164
+ .trim();
165
+ if (text) return text;
166
+ // 正文全在文本框 / 图片里时 HTML 可能为空,退回纯文本抽取
167
+ const raw = await mammoth.extractRawText({ buffer });
168
+ return String(raw.value ?? '')
110
169
  .replace(/\r\n?/g, '\n')
111
170
  .split('\n')
112
171
  .map((line) => line.trim())
113
- .filter((line, index, all) => line || all[index - 1]);
114
- return lines.join('\n').trim();
172
+ .filter((line, index, all) => line || all[index - 1])
173
+ .join('\n')
174
+ .trim();
115
175
  }
116
176
 
117
177
  /** Excel 正文抽取:每个工作表一个 `## 工作表名` 章节 + CSV 正文 */
@@ -8,11 +8,17 @@
8
8
  * ```
9
9
  * 跟空间走、不跟 git 走;被拖进导航分组时目录也会跟着进分组文件夹。
10
10
  *
11
- * 「当前剩余用例」「执行比例」是派生值,不落库:
11
+ * 「已执行用例」按「用例总数 − 待执行用例」自动算(老记录里 executed 为 0 也照样补齐),
12
+ * 「当前剩余用例」「执行比例」是派生值,都不依赖落库里的旧值:
13
+ * 已执行用例 = 用例总数 − 待执行用例
12
14
  * 当前剩余用例 = 用例总数 − 已执行用例
13
- * 执行比例 = 已执行用例 ÷ 用例总数
15
+ * 执行比例 = 1 − 当前剩余用例 ÷ 项目基线
16
+ * 项目基线 = 该项目最早一条记录(日期最早、同日按创建时间)的用例总数:
17
+ * 同一项目每天新增一行时,新行的总数就是上一轮的剩余量,只有最早那条代表原始规模。
14
18
  * 测试统计的维度 / 用例执行统计的项目名称都是可选项列表,
15
- * 新建时用户可以直接输入新值(“查找或创建选项”),服务端顺手并入列表。
19
+ * 新建时用户可以直接输入新值(“查找或创建选项”),服务端顺手并入列表;
20
+ * 下拉里还能重命名(引用它的记录一起改名)与删除(仅限没被记录引用的),
21
+ * 列表顺序按创建时间倒序(时间存在 `dimensionCreatedAt` / `projectCreatedAt`)。
16
22
  */
17
23
  import crypto from 'node:crypto';
18
24
  import fs from 'node:fs';
@@ -104,6 +110,167 @@ function mergeOptions(existing, incoming) {
104
110
  return out;
105
111
  }
106
112
 
113
+ /**
114
+ * 选项 -> 创建时间(用例执行统计的项目名称用 `projectCreatedAt`,
115
+ * 测试统计的维度用 `dimensionCreatedAt`)。
116
+ * 落库时顺带记一份,这样即使某个选项的记录被删光,它的创建时间也还在、
117
+ * 排序不会跳;老文件没有这份映射时用最早那条记录的 `createdAt` 兜底,
118
+ * 读一次就补全并写回。
119
+ */
120
+ function createdAtKey(kind) {
121
+ return kind === 'testStats' ? 'dimensionCreatedAt' : 'projectCreatedAt';
122
+ }
123
+
124
+ function normalizeCreatedAt(raw) {
125
+ if (!raw || typeof raw !== 'object') return {};
126
+ const out = {};
127
+ for (const [name, at] of Object.entries(raw)) {
128
+ const key = text(name, 120);
129
+ const value = text(at, 40);
130
+ if (key && value) out[key] = value;
131
+ }
132
+ return out;
133
+ }
134
+
135
+ /**
136
+ * 按创建时间倒序:最新创建的在最上面(与表格「日期最新在最上面」同一习惯);
137
+ * 没有创建时间的(历史脏数据)排在最后,彼此之间保持原有顺序(用原下标做稳定兜底)。
138
+ */
139
+ function sortByCreatedAt(names, createdAt) {
140
+ return names
141
+ .map((name, index) => ({ name, index, at: createdAt[name] ?? '' }))
142
+ .sort((a, b) => {
143
+ // 没有创建时间的排最后,避免它们插到新选项前面
144
+ if (a.at !== b.at && (!a.at || !b.at)) return a.at ? -1 : 1;
145
+ if (a.at !== b.at) return a.at < b.at ? 1 : -1;
146
+ return a.index - b.index;
147
+ })
148
+ .map((x) => x.name);
149
+ }
150
+
151
+ /** 一条记录用了哪些选项(项目名称是单选字段,维度是单选数组) */
152
+ function optionValuesOf(kind, item) {
153
+ if (kind === 'testStats') return item.dimensions;
154
+ return item.project ? [item.project] : [];
155
+ }
156
+
157
+ /**
158
+ * 整理选项列表:补齐记录里用到但列表缺的选项、补全创建时间,
159
+ * 最后按创建时间倒序(最新的在最上面)。返回排好序的列表与对应的时间映射。
160
+ */
161
+ function arrangeOptions(kind, rawOptions, rawCreatedAt, items) {
162
+ const maxLen = kind === 'testStats' ? 40 : 120;
163
+ const names = uniqueTexts(rawOptions, 200, maxLen);
164
+ const createdAt = normalizeCreatedAt(rawCreatedAt);
165
+ // 记录按创建时间升序:先出现的就是先创建的
166
+ const ordered = [...items].sort((a, b) =>
167
+ String(a.createdAt ?? '').localeCompare(String(b.createdAt ?? '')),
168
+ );
169
+ for (const item of ordered) {
170
+ for (const value of optionValuesOf(kind, item)) {
171
+ if (!value) continue;
172
+ if (!names.includes(value)) names.push(value);
173
+ const known = createdAt[value];
174
+ // 只在缺失或发现更早的记录时更新,避免记录被改动后把创建时间往后推
175
+ if (!known || String(item.createdAt) < known) createdAt[value] = item.createdAt;
176
+ }
177
+ }
178
+ const sorted = sortByCreatedAt(names, createdAt);
179
+ // 只保留仍在列表里的选项,避免删掉的名字一直挂在文件里
180
+ const keep = {};
181
+ for (const name of sorted) {
182
+ if (createdAt[name]) keep[name] = createdAt[name];
183
+ }
184
+ return { options: sorted, createdAt: keep };
185
+ }
186
+
187
+ /** 新加进列表的选项记下创建时间(已存在的不覆盖) */
188
+ function rememberOptionCreatedAt(kind, store, values) {
189
+ const key = createdAtKey(kind);
190
+ if (!store[key]) store[key] = {};
191
+ const now = new Date().toISOString();
192
+ for (const value of values) {
193
+ if (value && !store[key][value]) store[key][value] = now;
194
+ }
195
+ }
196
+
197
+ /**
198
+ * 写入前重新排一遍选项:新增 / 改名 / 删除之后调用,
199
+ * 保证落盘的内容和接口返回的顺序都是「创建时间倒序」,而不是靠下次读取才纠正。
200
+ */
201
+ function refreshOptionOrder(kind, store) {
202
+ const key = createdAtKey(kind);
203
+ const arranged = arrangeOptions(kind, optionsOf(kind, store), store[key], store.items);
204
+ setOptions(kind, store, arranged.options);
205
+ store[key] = arranged.createdAt;
206
+ }
207
+
208
+ /** 选项列表(测试统计维度 / 用例执行统计项目名称) */
209
+ function optionsOf(kind, store) {
210
+ return kind === 'testStats' ? store.dimensions : store.projects;
211
+ }
212
+
213
+ function setOptions(kind, store, next) {
214
+ if (kind === 'testStats') store.dimensions = next;
215
+ else store.projects = next;
216
+ }
217
+
218
+ /** 某选项被多少条记录引用(删除前用来拦截) */
219
+ function optionUsage(kind, store, name) {
220
+ if (kind === 'testStats') {
221
+ return store.items.filter((item) => item.dimensions.includes(name)).length;
222
+ }
223
+ return store.items.filter((item) => item.project === name).length;
224
+ }
225
+
226
+ /**
227
+ * 重命名选项:原位替换(保持创建时间位置),与已有同名时合并去重;
228
+ * 同时把引用它的记录一起改名,避免记录指向一个不存在的选项。返回改动的记录数。
229
+ */
230
+ function renameOption(kind, store, from, to) {
231
+ setOptions(
232
+ kind,
233
+ store,
234
+ mergeOptions(
235
+ [],
236
+ optionsOf(kind, store).map((x) => (x === from ? to : x)),
237
+ ),
238
+ );
239
+ if (kind === 'caseExec') {
240
+ const createdAt = store.projectCreatedAt ?? {};
241
+ // 时间跟着改名走;若目标名称已存在,保留更早的那个创建时间
242
+ const moved = createdAt[from];
243
+ delete createdAt[from];
244
+ if (moved && (!createdAt[to] || moved < createdAt[to])) createdAt[to] = moved;
245
+ store.projectCreatedAt = createdAt;
246
+ }
247
+ // 维度的创建时间同样跟着改名走
248
+ if (kind === 'testStats') {
249
+ const createdAt = store.dimensionCreatedAt ?? {};
250
+ const moved = createdAt[from];
251
+ delete createdAt[from];
252
+ if (moved && (!createdAt[to] || moved < createdAt[to])) createdAt[to] = moved;
253
+ store.dimensionCreatedAt = createdAt;
254
+ }
255
+ const now = new Date().toISOString();
256
+ let replaced = 0;
257
+ store.items = store.items.map((item) => {
258
+ if (kind === 'testStats') {
259
+ if (!item.dimensions.includes(from)) return item;
260
+ replaced += 1;
261
+ return {
262
+ ...item,
263
+ dimensions: item.dimensions.map((d) => (d === from ? to : d)),
264
+ updatedAt: now,
265
+ };
266
+ }
267
+ if (item.project !== from) return item;
268
+ replaced += 1;
269
+ return { ...item, project: to, draft: false, updatedAt: now };
270
+ });
271
+ return replaced;
272
+ }
273
+
107
274
  function storeFile(root, kind) {
108
275
  const dir = kind === 'testStats' ? TEST_STATS_DIR_NAME : CASE_EXEC_DIR_NAME;
109
276
  const file = kind === 'testStats' ? TEST_STATS_STORE_FILE : CASE_EXEC_STORE_FILE;
@@ -115,11 +282,17 @@ function newId(kind) {
115
282
  }
116
283
 
117
284
  function testStatsDefaults() {
118
- return { version: VERSION, dimensions: [...DEFAULT_TEST_DIMENSIONS], items: [] };
285
+ return {
286
+ version: VERSION,
287
+ dimensions: [...DEFAULT_TEST_DIMENSIONS],
288
+ /** 维度名称 -> 创建时间(下拉按创建时间倒序,最新创建的在最上面) */
289
+ dimensionCreatedAt: {},
290
+ items: [],
291
+ };
119
292
  }
120
293
 
121
294
  function caseExecDefaults() {
122
- return { version: VERSION, projects: [], items: [] };
295
+ return { version: VERSION, projects: [], projectCreatedAt: {}, items: [] };
123
296
  }
124
297
 
125
298
  /**
@@ -181,14 +354,21 @@ function normalizeStore(kind, raw) {
181
354
  : [];
182
355
  if (kind === 'testStats') {
183
356
  const used = items.flatMap((x) => x.dimensions);
184
- base.dimensions = mergeOptions(DEFAULT_TEST_DIMENSIONS, [
185
- ...uniqueTexts(raw.dimensions),
186
- ...used,
187
- ]);
357
+ // 维度名称按创建时间倒序:最新创建的在最上面,老数据缺的按记录创建时间补进来
358
+ const arranged = arrangeOptions(
359
+ kind,
360
+ mergeOptions(DEFAULT_TEST_DIMENSIONS, [...uniqueTexts(raw.dimensions), ...used]),
361
+ raw.dimensionCreatedAt,
362
+ items,
363
+ );
364
+ base.dimensions = arranged.options;
365
+ base.dimensionCreatedAt = arranged.createdAt;
188
366
  base.items = items;
189
367
  } else {
190
- const used = items.map((x) => x.project);
191
- base.projects = mergeOptions(uniqueTexts(raw.projects, 200, 120), used);
368
+ // 项目名称按创建时间倒序:最新创建的在最上面,老数据缺的名称按记录创建时间补进来
369
+ const arranged = arrangeOptions(kind, raw.projects, raw.projectCreatedAt, items);
370
+ base.projects = arranged.options;
371
+ base.projectCreatedAt = arranged.createdAt;
192
372
  base.items = items;
193
373
  }
194
374
  return base;
@@ -308,7 +488,107 @@ export function lhStatsPlugin() {
308
488
  return sendJson(res, 200, { ok: true, ...store });
309
489
  }
310
490
 
311
- // 「+ 添加记录」的空占位行也要落库,否则刷新就没了。
491
+ // 选项级操作(项目名称 / 测试统计维度):重命名 / 删除整条选项。
492
+ // 必须放在记录的 PUT / DELETE 之前,否则 'options' 会被当成记录 id。
493
+ if (itemId === 'options' && method !== 'GET') {
494
+ const isDim = kind === 'testStats';
495
+ const label = isDim ? '维度名称' : '项目名称';
496
+ const maxLen = isDim ? 40 : 120;
497
+ const body = JSON.parse((await readBody(req)) || '{}');
498
+ const store = readStore(root, kind);
499
+ const options = optionsOf(kind, store);
500
+
501
+ if (method === 'PUT') {
502
+ const from = text(body.from, maxLen);
503
+ const to = text(body.to, maxLen);
504
+ if (!from || !to) {
505
+ return sendJson(res, 400, { ok: false, error: `缺少原${label}或新${label}` });
506
+ }
507
+ if (!options.includes(from)) {
508
+ return sendJson(res, 404, { ok: false, error: `${label}不存在` });
509
+ }
510
+ const replaced = from === to ? 0 : renameOption(kind, store, from, to);
511
+ if (from !== to) {
512
+ refreshOptionOrder(kind, store);
513
+ writeStore(root, kind, store);
514
+ }
515
+ return sendJson(res, 200, {
516
+ ok: true,
517
+ replaced,
518
+ items: store.items,
519
+ ...optionsPayload(kind, store),
520
+ });
521
+ }
522
+
523
+ if (method === 'DELETE') {
524
+ const name = text(body.name, maxLen);
525
+ if (!name) return sendJson(res, 400, { ok: false, error: `缺少${label}` });
526
+ if (!options.includes(name)) {
527
+ return sendJson(res, 404, { ok: false, error: `${label}不存在` });
528
+ }
529
+ // 还被记录引用时不允许删,避免记录指向一个不存在的选项
530
+ const inUse = optionUsage(kind, store, name);
531
+ if (inUse > 0) {
532
+ return sendJson(res, 409, {
533
+ ok: false,
534
+ inUse,
535
+ error: `还有 ${inUse} 条记录在用这个${label},先改掉再删除`,
536
+ });
537
+ }
538
+ setOptions(
539
+ kind,
540
+ store,
541
+ options.filter((x) => x !== name),
542
+ );
543
+ const key = createdAtKey(kind);
544
+ if (store[key]) delete store[key][name];
545
+ refreshOptionOrder(kind, store);
546
+ writeStore(root, kind, store);
547
+ return sendJson(res, 200, {
548
+ ok: true,
549
+ removed: 1,
550
+ items: store.items,
551
+ ...optionsPayload(kind, store),
552
+ });
553
+ }
554
+
555
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
556
+ }
557
+
558
+ // 整组改周期:一个项目只有一个开始 / 结束日期,父行改一次写穿该项目的全部
559
+ // 统计记录(逐条 PUT 会互相覆盖)。
560
+ if (kind === 'caseExec' && itemId === 'project-cycle' && method !== 'GET') {
561
+ if (method !== 'PUT')
562
+ return sendJson(res, 405, { ok: false, error: 'Method Not Allowed' });
563
+ const body = JSON.parse((await readBody(req)) || '{}');
564
+ const name = text(body.name, 120);
565
+ if (!name) return sendJson(res, 400, { ok: false, error: '缺少项目名称' });
566
+ const store = readStore(root, kind);
567
+ const targets = store.items.filter((x) => x.project === name);
568
+ if (!targets.length) {
569
+ return sendJson(res, 404, { ok: false, error: '项目名称不存在或还没有统计记录' });
570
+ }
571
+ const startDate = dateOr(body.startDate, targets[0].startDate);
572
+ const endDate = dateOr(body.endDate, targets[0].endDate);
573
+ if (startDate && endDate && endDate < startDate) {
574
+ return sendJson(res, 400, { ok: false, error: '结束日期不能早于开始日期' });
575
+ }
576
+ const now = new Date().toISOString();
577
+ let updated = 0;
578
+ store.items = store.items.map((item) => {
579
+ if (item.project !== name) return item;
580
+ if (item.startDate === startDate && item.endDate === endDate) return item;
581
+ updated += 1;
582
+ return { ...item, startDate, endDate, updatedAt: now };
583
+ });
584
+ if (updated > 0) writeStore(root, kind, store);
585
+ return sendJson(res, 200, {
586
+ ok: true,
587
+ updated,
588
+ items: store.items,
589
+ ...optionsPayload(kind, store),
590
+ });
591
+ }
312
592
  // 打开插件 / 进入页面时也会调一次 sync:没有数据就什么都不写,
313
593
  // 避免只是开个开关就在数据空间里铺出空目录和空文件。
314
594
  if (method === 'POST' && itemId === 'sync') {
@@ -342,15 +622,23 @@ export function lhStatsPlugin() {
342
622
  }
343
623
  store.items.push(...created);
344
624
  if (kind === 'testStats') {
345
- store.dimensions = mergeOptions(
346
- store.dimensions,
347
- created.flatMap((x) => x.dimensions),
348
- );
625
+ const values = created.flatMap((x) => x.dimensions);
626
+ store.dimensions = mergeOptions(store.dimensions, values);
627
+ rememberOptionCreatedAt(kind, store, values);
628
+ // 新建的维度创建时间最新,排到最上面
629
+ refreshOptionOrder(kind, store);
349
630
  } else {
350
631
  store.projects = mergeOptions(
351
632
  store.projects,
352
633
  created.map((x) => x.project),
353
634
  );
635
+ rememberOptionCreatedAt(
636
+ kind,
637
+ store,
638
+ created.map((x) => x.project),
639
+ );
640
+ // 新建的项目创建时间最新,排到最上面
641
+ refreshOptionOrder(kind, store);
354
642
  }
355
643
  writeStore(root, kind, store);
356
644
  return sendJson(res, 200, {
@@ -378,8 +666,12 @@ export function lhStatsPlugin() {
378
666
  store.items[idx] = next;
379
667
  if (kind === 'testStats') {
380
668
  store.dimensions = mergeOptions(store.dimensions, next.dimensions);
669
+ rememberOptionCreatedAt(kind, store, next.dimensions);
670
+ refreshOptionOrder(kind, store);
381
671
  } else {
382
672
  store.projects = mergeOptions(store.projects, [next.project]);
673
+ rememberOptionCreatedAt(kind, store, [next.project]);
674
+ refreshOptionOrder(kind, store);
383
675
  }
384
676
  writeStore(root, kind, store);
385
677
  return sendJson(res, 200, {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lantern-harness",
3
- "version": "0.1.29",
3
+ "version": "0.1.32",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "AI 工作台:对话与插件工具、内容库、模板库、会话记忆,数据留在本机。",