lantern-harness 0.2.2 → 0.2.4
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.
- package/CHANGELOG.md +46 -0
- package/README.md +7 -7
- package/builtin/case-backup-contract.mjs +27 -0
- package/builtin/case-workflow-contract.mjs +158 -0
- package/builtin/session/lh-nav-groups.mjs +33 -1
- package/builtin/session/space-layout.mjs +8 -1
- package/builtin/session/space-skills.mjs +8 -1
- package/cli/mcp-server.mjs +1211 -72
- package/cli/server.mjs +2 -0
- package/dist/500.html +9 -4
- package/dist/_astro/Base.ANghvs5L.css +1 -0
- package/dist/_astro/{Base.astro_astro_type_script_index_0_lang.XUV2H6ea.js → Base.astro_astro_type_script_index_0_lang.f7BIL9Qf.js} +1 -1
- package/dist/_astro/{BusinessMapBoard.mRxl2G3D.js → BusinessMapBoard.CYxHcku_.js} +1 -1
- package/dist/_astro/{CaseExecBoard.Cqkxuf5c.js → CaseExecBoard.CK9aGPmH.js} +1 -1
- package/dist/_astro/CaseExecutionBoard.p6Y23xyH.js +4 -0
- package/dist/_astro/CaseGenerateApp.D5uj5bSb.js +10 -0
- package/dist/_astro/CasesLibrary.CY1PRdzc.js +21 -0
- package/dist/_astro/ChatApp.BnV7drSC.js +1 -0
- package/dist/_astro/ChatApp.CqyrMX90.js +262 -0
- package/dist/_astro/{DashboardBoard.CAJVE2G4.js → DashboardBoard.qgc1s7pG.js} +1 -1
- package/dist/_astro/{DefectSubmitEntry.BzKXJ-zq.js → DefectSubmitEntry.JI85N1-i.js} +1 -1
- package/dist/_astro/{DocsFileBrowser.apKMbGVf.js → DocsFileBrowser.z5JZ74cy.js} +1 -1
- package/dist/_astro/{DocsPager.DMN9-Tjg.js → DocsPager.Dg765uHW.js} +1 -1
- package/dist/_astro/{KnowledgeLibrary.BcoMQeUd.js → KnowledgeLibrary.mkShtVun.js} +1 -1
- package/dist/_astro/{LifeKrTasksBoard.DJU0-QI-.js → LifeKrTasksBoard.DpAwQffE.js} +1 -1
- package/dist/_astro/{LifeKrTodosBoard.GK7KRAO3.js → LifeKrTodosBoard.BIjPiZ8H.js} +1 -1
- package/dist/_astro/{LifeObjectivesBoard.DuKa6Q3k.js → LifeObjectivesBoard.DYwLHPEG.js} +1 -1
- package/dist/_astro/{LifePlanTypeSelect.Cm2lUmnH.js → LifePlanTypeSelect.CYaziESp.js} +1 -1
- package/dist/_astro/{LifeReviewsBoard.BWOOVMtz.js → LifeReviewsBoard.DIxoWBDA.js} +1 -1
- package/dist/_astro/{LifeShared.bY2l01Ha.js → LifeShared.DuFQsMEx.js} +1 -1
- package/dist/_astro/{LifeStagesBoard.CIzxPOJB.js → LifeStagesBoard.DtOri9EW.js} +1 -1
- package/dist/_astro/{LifeYearCycleSelect.BlsyPmmI.js → LifeYearCycleSelect.ByJ9-PGg.js} +1 -1
- package/dist/_astro/{LifeYearPlansBoard.DaA9O08j.js → LifeYearPlansBoard.BQN07wcv.js} +1 -1
- package/dist/_astro/NavLibraries.BO4ezcUc.js +1 -0
- package/dist/_astro/{PluginsPage.B063QIlQ.js → PluginsPage.Cb6977dz.js} +2 -2
- package/dist/_astro/{PmBugsBoard.Cu-v0Gfd.js → PmBugsBoard.Ddl3kqqt.js} +1 -1
- package/dist/_astro/{PmIterationsBoard.CgRzkP-j.js → PmIterationsBoard.BJN7disI.js} +1 -1
- package/dist/_astro/{PmProjectDetail.DVCEh0Lm.js → PmProjectDetail.D78gWhqk.js} +1 -1
- package/dist/_astro/{PmProjectsBoard.z-bQa98r.js → PmProjectsBoard.Bf8VB3t6.js} +1 -1
- package/dist/_astro/PmRequirementsBoard.CDyNHN2a.js +1 -0
- package/dist/_astro/{PmRequirementsBoard.CyfBI0u_.js → PmRequirementsBoard.DarfGIrL.js} +1 -1
- package/dist/_astro/{PmShared.BQVzwsiz.js → PmShared.TOjBbtV8.js} +1 -1
- package/dist/_astro/{ReportsPage.najSzJeT.js → ReportsPage.BXGduuY3.js} +1 -1
- package/dist/_astro/{ReqAnalysisBoard.BQb8dHFD.js → ReqAnalysisBoard.C7V_fEh9.js} +1 -1
- package/dist/_astro/{RequirementBreakdownLibrary.Cn6OV6xt.js → RequirementBreakdownLibrary.DMoeTeqX.js} +1 -1
- package/dist/_astro/{RequirementsLibrary.CqKNFVsP.js → RequirementsLibrary.Iv7zOqWe.js} +1 -1
- package/dist/_astro/{SettingsDialog.db3BpFw0.js → SettingsDialog.CRbfEiyw.js} +1 -1
- package/dist/_astro/SlideOverDrawer.CvyB-quk.js +1 -0
- package/dist/_astro/{SpaceSwitcher.DSUVAPOi.js → SpaceSwitcher.D9bBNQBZ.js} +1 -1
- package/dist/_astro/{TableFieldConfig.72AL-8p-.js → TableFieldConfig.DHj25OKN.js} +1 -1
- package/dist/_astro/{TasksBoard.CCDhCSR7.js → TasksBoard.CXmGdylV.js} +1 -1
- package/dist/_astro/TemplatesLibrary.DsL2q-wp.js +1 -0
- package/dist/_astro/{TestReportsLibrary.fWiEyCRx.js → TestReportsLibrary.BBC1TYgP.js} +1 -1
- package/dist/_astro/{TestStatsBoard.BSUBsWSu.js → TestStatsBoard.VXjP4hu6.js} +1 -1
- package/dist/_astro/{TodosBoard.By5YdlUe.js → TodosBoard.-yKgp06M.js} +1 -1
- package/dist/_astro/UiAutoBoard.BZkPzwi8.js +3 -0
- package/dist/_astro/UiAutoEnvPanel.DrHUOlmH.js +10 -0
- package/dist/_astro/UiAutoGenerationDialog.gypq1zP9.js +12 -0
- package/dist/_astro/UiAutoProjectsPage.Dhzr09E9.js +3 -0
- package/dist/_astro/app-config.BSO5r82v.js +1 -0
- package/dist/_astro/app-version.B7nd7uBP.js +1 -0
- package/dist/_astro/{bash-tools.CS2w8LOb.js → bash-tools.C4DJiRJs.js} +1 -1
- package/dist/_astro/case-fields.C03NY3zC.js +148 -0
- package/dist/_astro/case-gen-run.DQR6uvH5.js +26 -0
- package/dist/_astro/case-prompt.ByLTgz4r.js +2 -0
- package/dist/_astro/{case-review.DFWZkoR9.js → case-review.BodP2jKm.js} +1 -1
- package/dist/_astro/{case-template.Clb7HrDB.js → case-template.CC2eXegU.js} +2 -2
- package/dist/_astro/case-types.BjF1BivA.js +1 -0
- package/dist/_astro/case-workflow-contract.BBQ9bbKL.js +1 -0
- package/dist/_astro/{defect-workbench.CjTb4FDv.js → defect-workbench.DBmohR-y.js} +1 -1
- package/dist/_astro/{hydrate-cache.O4CIma9y.js → hydrate-cache.CMMErx63.js} +1 -1
- package/dist/_astro/{i18n.Cp4so7KR.js → i18n.CEWjL5GX.js} +2 -2
- package/dist/_astro/{open-docs-in-session.BpcAcBSI.js → open-docs-in-session.BoyV6R2A.js} +1 -1
- package/dist/_astro/plugins.ChGmBEkF.js +1 -0
- package/dist/_astro/{project-docs.bB9lQ1Ki.js → project-docs.BRgNjXhG.js} +1 -1
- package/dist/_astro/{req-analysis.C_gARMrB.js → req-analysis.efWkT7Gv.js} +1 -1
- package/dist/_astro/{settings.D02wZj3w.js → settings.BojKNwUC.js} +2 -2
- package/dist/_astro/{spaces-client.BAtG6PkW.js → spaces-client.B28rzu8J.js} +1 -1
- package/dist/_astro/{story-review.DTN91Vl9.js → story-review.Dm9VcR6v.js} +1 -1
- package/dist/_astro/{test-points.C7ZgggQT.js → test-points.BSfPfq8z.js} +1 -1
- package/dist/_astro/ui-auto.LUcREUMe.js +1 -0
- package/dist/_astro/{view-prefs.COAKEQtZ.js → view-prefs.CWc5cQ2q.js} +1 -1
- package/dist/business-map/index.html +10 -5
- package/dist/case-exec/index.html +10 -5
- package/dist/case-execution/index.html +10 -5
- package/dist/cases/api/index.html +988 -0
- package/dist/cases/automation/index.html +988 -0
- package/dist/cases/functional/index.html +988 -0
- package/dist/cases/generate/index.html +10 -5
- package/dist/cases/index.html +1 -1
- package/dist/cases/library/index.html +1 -983
- package/dist/cases/other/index.html +988 -0
- package/dist/cases/performance/index.html +988 -0
- package/dist/dashboard/index.html +10 -5
- package/dist/defect-rules/index.html +10 -5
- package/dist/defect-submit/index.html +10 -5
- package/dist/defect-submit/templates/index.html +10 -5
- package/dist/docs/changelog/index.html +105 -58
- package/dist/docs/install/index.html +12 -6
- package/dist/docs/manual/index.html +62 -40
- package/dist/knowledge/index.html +10 -5
- package/dist/life/kr-tasks/index.html +10 -5
- package/dist/life/kr-todos/index.html +10 -5
- package/dist/life/objectives/index.html +10 -5
- package/dist/life/reviews/index.html +10 -5
- package/dist/life/stages/index.html +10 -5
- package/dist/life/year-plans/index.html +10 -5
- package/dist/plugins/index.html +10 -5
- package/dist/pm/bugs/index.html +10 -5
- package/dist/pm/iterations/index.html +10 -5
- package/dist/pm/projects/detail/index.html +10 -5
- package/dist/pm/projects/index.html +10 -5
- package/dist/pm/requirements/index.html +10 -5
- package/dist/reports/index.html +10 -5
- package/dist/requirement-analysis/index.html +10 -5
- package/dist/requirement-breakdowns/index.html +10 -5
- package/dist/requirements/index.html +10 -5
- package/dist/tasks/index.html +10 -5
- package/dist/templates/index.html +10 -5
- package/dist/test-automation/index.html +10 -5
- package/dist/test-automation/projects/index.html +10 -5
- package/dist/test-reports/index.html +10 -5
- package/dist/test-stats/index.html +10 -5
- package/dist/todos/index.html +10 -5
- package/dist/workbench/index.html +10 -5
- package/docs/Codex-MCP/351/233/206/346/210/220.md +117 -53
- package/docs//344/274/232/350/257/235/346/217/222/344/273/266.md +14 -1
- package/docs//345/205/250/345/261/200/346/217/222/344/273/266.md +5 -1
- package/docs//345/256/211/350/243/205/346/211/213/345/206/214.md +4 -2
- package/docs//346/223/215/344/275/234/346/211/213/345/206/214.md +45 -36
- package/lh-plugins/case-automation/service.mjs +927 -0
- package/lh-plugins/case-automation/store.mjs +231 -0
- package/lh-plugins/case-automation/tables.mjs +115 -0
- package/lh-plugins/case-automation-prompt.mjs +57 -0
- package/lh-plugins/case-execution/assets.mjs +180 -0
- package/lh-plugins/case-execution/files.mjs +123 -23
- package/lh-plugins/case-execution/plans.mjs +318 -0
- package/lh-plugins/case-execution/service.mjs +80 -13
- package/lh-plugins/case-execution-prompt.mjs +4 -1
- package/lh-plugins/lh-case-automation.mjs +169 -0
- package/lh-plugins/lh-case-design.mjs +456 -0
- package/lh-plugins/lh-case-execution.mjs +53 -1
- package/lh-plugins/lh-case-review.mjs +29 -11
- package/lh-plugins/lh-project-docs.mjs +24 -0
- package/lh-plugins/lh-stats.mjs +65 -4
- package/lh-plugins/lh-uiauto.mjs +111 -2
- package/lh-plugins/plugin-prompts.mjs +1 -0
- package/lh-plugins/uiauto-adapters/playwright.mjs +44 -4
- package/lh-plugins/uiauto-adapters/shared.mjs +4 -0
- package/lh-plugins/uiauto-explorer/emit-files.mjs +16 -2
- package/lh-plugins/uiauto-explorer/ir.mjs +3 -0
- package/lh-plugins/uiauto-explorer/merge.mjs +37 -1
- package/lh-plugins/uiauto-explorer/navigation-guard.mjs +255 -0
- package/lh-plugins/uiauto-explorer/runner.mjs +65 -3
- package/lh-plugins/uiauto-explorer/sessions.mjs +29 -1
- package/package.json +1 -1
- package/skills/case-automation-bridge/SKILL.md +27 -0
- package/skills/case-execution/SKILL.md +19 -2
- package/skills/lantern-workflow/SKILL.md +39 -1
- package/dist/_astro/Base.Du_-4L-4.css +0 -1
- package/dist/_astro/CaseExecutionBoard.CjX4CoKd.js +0 -5
- package/dist/_astro/CaseGenerateApp.acgnxl79.js +0 -10
- package/dist/_astro/CasesLibrary.zmzOQwdn.js +0 -21
- package/dist/_astro/ChatApp.Ben9LFra.js +0 -1
- package/dist/_astro/ChatApp.DBi6q7Qv.js +0 -262
- package/dist/_astro/NavLibraries.DVR5Ua-S.js +0 -1
- package/dist/_astro/PmRequirementsBoard.B0W6bsW2.js +0 -1
- package/dist/_astro/SlideOverDrawer.BMg2tce6.js +0 -1
- package/dist/_astro/TemplatesLibrary.peYzrHZ2.js +0 -1
- package/dist/_astro/UiAutoBoard.BGdlp5Sr.js +0 -3
- package/dist/_astro/UiAutoEnvPanel.BUASgPLB.js +0 -10
- package/dist/_astro/UiAutoGenerationDialog.D1PyCgrD.js +0 -12
- package/dist/_astro/UiAutoProjectsPage.B6A9NlVK.js +0 -3
- package/dist/_astro/app-config.Dvfzl5_N.js +0 -1
- package/dist/_astro/app-version.CNpnKIb9.js +0 -1
- package/dist/_astro/case-fields.CmePqYfh.js +0 -148
- package/dist/_astro/case-gen-run.Cvvdv_kv.js +0 -26
- package/dist/_astro/case-prompt.CZ3vWUju.js +0 -2
- package/dist/_astro/plugins.Db9xoFZb.js +0 -1
|
@@ -0,0 +1,927 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { resolveContentRoot } from '../../builtin/session/space-layout.mjs';
|
|
6
|
+
import { resolveModelForSpace } from '../lh-config.mjs';
|
|
7
|
+
import { readPluginPrompt } from '../plugin-prompts.mjs';
|
|
8
|
+
import {
|
|
9
|
+
detectProject,
|
|
10
|
+
readAutomationProjectRun,
|
|
11
|
+
startAutomationProjectRun,
|
|
12
|
+
stopAutomationProjectRun,
|
|
13
|
+
uiautoCachePaths,
|
|
14
|
+
uiautoStorePaths,
|
|
15
|
+
} from '../lh-uiauto.mjs';
|
|
16
|
+
import {
|
|
17
|
+
detectEmitLayout,
|
|
18
|
+
findGeneratedSessionByAutomationCaseId,
|
|
19
|
+
saveGeneratedSession,
|
|
20
|
+
} from '../uiauto-explorer/sessions.mjs';
|
|
21
|
+
import { normalizePlan, PLAN_ACTIONS } from '../uiauto-explorer/plan.mjs';
|
|
22
|
+
import { applyCaseExecutionResult, loadCaseDocument } from '../case-execution/files.mjs';
|
|
23
|
+
import { caseContentFingerprint } from '../case-execution/assets.mjs';
|
|
24
|
+
import { CASE_AUTOMATION_PROMPT_FILE } from '../case-automation-prompt.mjs';
|
|
25
|
+
import { backupFile, fileHash, readTable, writeTableAtomic } from './tables.mjs';
|
|
26
|
+
import {
|
|
27
|
+
readAssessment,
|
|
28
|
+
readAutomationLinks,
|
|
29
|
+
readProjectMap,
|
|
30
|
+
rememberAssessments,
|
|
31
|
+
rememberProjectSelection,
|
|
32
|
+
upsertAutomationLinks,
|
|
33
|
+
writeAssessment,
|
|
34
|
+
writeBatch,
|
|
35
|
+
readBatch,
|
|
36
|
+
automationSummaryForCase,
|
|
37
|
+
} from './store.mjs';
|
|
38
|
+
|
|
39
|
+
const ACTIVE_BATCHES = new Map();
|
|
40
|
+
const AUTOMATION_HEADERS = [
|
|
41
|
+
'自动化用例编号',
|
|
42
|
+
'来源用例文件',
|
|
43
|
+
'来源用例编号',
|
|
44
|
+
'自动化用例标题',
|
|
45
|
+
'引用需求点',
|
|
46
|
+
'前置条件',
|
|
47
|
+
'自动化步骤',
|
|
48
|
+
'预期结果',
|
|
49
|
+
'优先级',
|
|
50
|
+
'可行性',
|
|
51
|
+
'自动化项目',
|
|
52
|
+
'迭代版本',
|
|
53
|
+
'目标迭代文件',
|
|
54
|
+
'测试标签',
|
|
55
|
+
'脚本状态',
|
|
56
|
+
'运行状态',
|
|
57
|
+
'实际结果',
|
|
58
|
+
'报告地址',
|
|
59
|
+
'说明',
|
|
60
|
+
];
|
|
61
|
+
const DECISIONS = new Set(['automatable', 'needs_manual', 'not_automatable']);
|
|
62
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
63
|
+
|
|
64
|
+
const fail = (message, statusCode = 400) => {
|
|
65
|
+
throw Object.assign(new Error(message), { statusCode });
|
|
66
|
+
};
|
|
67
|
+
const clean = (value, max = 4000) => (typeof value === 'string' ? value.trim().slice(0, max) : '');
|
|
68
|
+
|
|
69
|
+
function readJson(file, fallback = null) {
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
72
|
+
} catch {
|
|
73
|
+
return fallback;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function projectRecord(root, projectId) {
|
|
78
|
+
const store = readJson(uiautoStorePaths(root).projectsFile, { projects: [] });
|
|
79
|
+
const project = (store.projects || []).find((item) => item.id === projectId);
|
|
80
|
+
if (!project) fail('自动化项目不存在', 404);
|
|
81
|
+
let health;
|
|
82
|
+
try {
|
|
83
|
+
health = detectProject(project.dir, project.framework);
|
|
84
|
+
} catch {
|
|
85
|
+
fail('自动化项目目录不可用,请重新挂载项目', 409);
|
|
86
|
+
}
|
|
87
|
+
if (!health.exists) fail('自动化项目目录不存在,请重新挂载项目', 409);
|
|
88
|
+
if (health.kind !== 'ui') fail('功能测试用例只能选择 UI 自动化项目', 409);
|
|
89
|
+
const framework = project.framework || health.framework || 'playwright';
|
|
90
|
+
if (framework !== 'playwright') fail('首版脚本生成仅支持 Playwright + TypeScript 项目', 422);
|
|
91
|
+
if (!health.frameworkReady) fail(health.readyHint || '自动化项目运行环境未就绪', 409);
|
|
92
|
+
return { project: { ...project, framework }, health };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function normalizeIteration(raw) {
|
|
96
|
+
let value = clean(raw, 80)
|
|
97
|
+
.replace(/\.spec\.ts$/i, '')
|
|
98
|
+
.replace(/[\\/:*?"<>|]/g, '-')
|
|
99
|
+
.replace(/\s+/g, '-')
|
|
100
|
+
.replace(/^-+|-+$/g, '');
|
|
101
|
+
if (!value) fail('请选择或创建迭代版本');
|
|
102
|
+
if (/^\d/.test(value)) value = `v${value}`;
|
|
103
|
+
return value;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function iterationList(project, health) {
|
|
107
|
+
const layout = detectEmitLayout(project.dir, health.testDir || '');
|
|
108
|
+
const dir = path.join(project.dir, layout.testDir, 'iteration');
|
|
109
|
+
const files = fs.existsSync(dir)
|
|
110
|
+
? fs
|
|
111
|
+
.readdirSync(dir)
|
|
112
|
+
.filter((name) => /\.spec\.ts$/i.test(name))
|
|
113
|
+
.sort((a, b) => a.localeCompare(b, 'zh'))
|
|
114
|
+
: [];
|
|
115
|
+
return {
|
|
116
|
+
testDir: layout.testDir,
|
|
117
|
+
iterationDir: path.join(layout.testDir, 'iteration').replaceAll(path.sep, '/'),
|
|
118
|
+
files: files.map((name) => ({
|
|
119
|
+
name,
|
|
120
|
+
value: `${layout.testDir}/iteration/${name}`.replaceAll(path.sep, '/'),
|
|
121
|
+
})),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function listIterations(root, projectId, casePath = '') {
|
|
126
|
+
const { project, health } = projectRecord(root, projectId);
|
|
127
|
+
const iterations = iterationList(project, health);
|
|
128
|
+
const version = String(path.basename(casePath))
|
|
129
|
+
.match(/v\d+(?:\.\d+)*/i)?.[0]
|
|
130
|
+
?.toLowerCase();
|
|
131
|
+
const suggested =
|
|
132
|
+
iterations.files.find((file) => version && file.name.toLowerCase().includes(version)) ||
|
|
133
|
+
(iterations.files.length === 1 ? iterations.files[0] : null);
|
|
134
|
+
return {
|
|
135
|
+
project: {
|
|
136
|
+
id: project.id,
|
|
137
|
+
name: project.name,
|
|
138
|
+
framework: project.framework,
|
|
139
|
+
kind: health.kind,
|
|
140
|
+
baseURL: project.baseURL || '',
|
|
141
|
+
},
|
|
142
|
+
...iterations,
|
|
143
|
+
suggestedIteration: suggested?.name.replace(/\.spec\.ts$/i, '') || '',
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export async function sourceDocument(root, casePath) {
|
|
148
|
+
const document = await loadCaseDocument(root, casePath);
|
|
149
|
+
const { _parsed, _map, abs, ...publicDocument } = document;
|
|
150
|
+
return {
|
|
151
|
+
...publicDocument,
|
|
152
|
+
cases: publicDocument.cases.map((item) => ({
|
|
153
|
+
...item,
|
|
154
|
+
automation: automationSummaryForCase(root, publicDocument.path, item.id),
|
|
155
|
+
})),
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function projectSelection(root, casePath) {
|
|
160
|
+
return readProjectMap(root).files?.[casePath] || null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function modelCall(settings, messages, signal) {
|
|
164
|
+
const url = new URL(settings.baseURL.replace(/\/+$/, '') + '/chat/completions');
|
|
165
|
+
return fetch(url, {
|
|
166
|
+
method: 'POST',
|
|
167
|
+
headers: {
|
|
168
|
+
'Content-Type': 'application/json',
|
|
169
|
+
Authorization: `Bearer ${settings.apiKey}`,
|
|
170
|
+
},
|
|
171
|
+
body: JSON.stringify({
|
|
172
|
+
model: settings.model,
|
|
173
|
+
messages,
|
|
174
|
+
temperature: 0.1,
|
|
175
|
+
stream: false,
|
|
176
|
+
}),
|
|
177
|
+
signal,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function extractJson(text) {
|
|
182
|
+
const raw = String(text || '').trim();
|
|
183
|
+
const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i)?.[1];
|
|
184
|
+
const candidate = fenced || raw.match(/\{[\s\S]*\}/)?.[0];
|
|
185
|
+
if (!candidate) fail('模型没有返回合法 JSON', 502);
|
|
186
|
+
try {
|
|
187
|
+
return JSON.parse(candidate);
|
|
188
|
+
} catch {
|
|
189
|
+
fail('模型返回的 JSON 无法解析', 502);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function planValid(plan) {
|
|
194
|
+
return (
|
|
195
|
+
plan.length > 0 &&
|
|
196
|
+
plan.length <= 40 &&
|
|
197
|
+
plan.some((step) => ['expect', 'expectUrl'].includes(step.action)) &&
|
|
198
|
+
plan.every((step) => PLAN_ACTIONS.includes(step.action))
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function normalizeAssessments(raw, cases, project, iteration, iterationFile) {
|
|
203
|
+
const results = Array.isArray(raw?.cases) ? raw.cases : [];
|
|
204
|
+
return cases.map((source) => {
|
|
205
|
+
const hit = results.find((item) => clean(item?.sourceCaseId, 100) === source.id);
|
|
206
|
+
const decision = DECISIONS.has(hit?.decision) ? hit.decision : 'needs_manual';
|
|
207
|
+
const automationCases = [];
|
|
208
|
+
const modelCases = Array.isArray(hit?.automationCases) ? hit.automationCases : [];
|
|
209
|
+
for (let index = 0; index < modelCases.length; index += 1) {
|
|
210
|
+
const item = modelCases[index];
|
|
211
|
+
const plan = normalizePlan(item?.plan);
|
|
212
|
+
if (!planValid(plan)) continue;
|
|
213
|
+
const title = clean(item?.title, 240) || source.title;
|
|
214
|
+
// 稳定 ID 由来源用例 + 拆分序号生成,重复评估时仍命中同一条自动化用例。
|
|
215
|
+
const automationCaseId = `AUTO-${crypto
|
|
216
|
+
.createHash('sha256')
|
|
217
|
+
.update(`${source.id}\0${index}`)
|
|
218
|
+
.digest('hex')
|
|
219
|
+
.slice(0, 12)
|
|
220
|
+
.toUpperCase()}`;
|
|
221
|
+
automationCases.push({
|
|
222
|
+
automationCaseId,
|
|
223
|
+
title,
|
|
224
|
+
precondition: clean(item?.precondition, 4000) || source.precondition,
|
|
225
|
+
steps: (Array.isArray(item?.steps) ? item.steps : [])
|
|
226
|
+
.map((step) => clean(step, 1000))
|
|
227
|
+
.filter(Boolean)
|
|
228
|
+
.slice(0, 30),
|
|
229
|
+
expected: clean(item?.expected, 4000) || source.expected,
|
|
230
|
+
priority: /^P[0-3]$/.test(clean(item?.priority, 10))
|
|
231
|
+
? clean(item?.priority, 10)
|
|
232
|
+
: source.priority || 'P2',
|
|
233
|
+
tag:
|
|
234
|
+
clean(item?.tag, 40) ||
|
|
235
|
+
(source.priority === 'P0'
|
|
236
|
+
? '@smoke'
|
|
237
|
+
: source.priority === 'P1'
|
|
238
|
+
? '@regression'
|
|
239
|
+
: '@edge'),
|
|
240
|
+
plan,
|
|
241
|
+
automationTag: `@lantern-${automationCaseId.toLowerCase()}`,
|
|
242
|
+
projectId: project.id,
|
|
243
|
+
projectName: project.name,
|
|
244
|
+
framework: project.framework,
|
|
245
|
+
iteration,
|
|
246
|
+
iterationFile,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
const finalDecision =
|
|
250
|
+
decision === 'automatable' && !automationCases.length ? 'needs_manual' : decision;
|
|
251
|
+
return {
|
|
252
|
+
sourceCaseId: source.id,
|
|
253
|
+
sourceCaseNo: source.no,
|
|
254
|
+
sourceTitle: source.title,
|
|
255
|
+
sourceFingerprint: caseContentFingerprint(source),
|
|
256
|
+
decision: finalDecision,
|
|
257
|
+
reason:
|
|
258
|
+
clean(hit?.reason, 4000) ||
|
|
259
|
+
(finalDecision === 'needs_manual' ? '缺少可执行的 UI Plan 或需要人工条件' : ''),
|
|
260
|
+
risks: (Array.isArray(hit?.risks) ? hit.risks : [])
|
|
261
|
+
.map((risk) => clean(risk, 1000))
|
|
262
|
+
.filter(Boolean)
|
|
263
|
+
.slice(0, 20),
|
|
264
|
+
automationCases,
|
|
265
|
+
};
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export async function assessCases(root, raw) {
|
|
270
|
+
const casePath = clean(raw.casePath, 1000);
|
|
271
|
+
const projectId = clean(raw.projectId, 80);
|
|
272
|
+
const iteration = normalizeIteration(raw.iteration);
|
|
273
|
+
const document = await loadCaseDocument(root, casePath);
|
|
274
|
+
const selected = new Set(Array.isArray(raw.caseIds) ? raw.caseIds.map(String) : []);
|
|
275
|
+
const cases = document.cases.filter((item) => selected.has(item.id));
|
|
276
|
+
if (!cases.length || cases.length !== selected.size) fail('请选择有效的功能用例范围');
|
|
277
|
+
if (cases.length > 100) fail('单次最多评估 100 条用例');
|
|
278
|
+
const { project, health } = projectRecord(root, projectId);
|
|
279
|
+
const iterations = iterationList(project, health);
|
|
280
|
+
const iterationFile = `${iterations.iterationDir}/${iteration}.spec.ts`;
|
|
281
|
+
const skill = readPluginPrompt(CASE_AUTOMATION_PROMPT_FILE, root).trim();
|
|
282
|
+
if (!skill) fail('功能用例转 UI 自动化技能尚未就绪', 422);
|
|
283
|
+
const settings = resolveModelForSpace(root);
|
|
284
|
+
if (!settings.baseURL || !settings.apiKey || !settings.model)
|
|
285
|
+
fail('请先在设置中配置可用模型', 400);
|
|
286
|
+
const controller = new AbortController();
|
|
287
|
+
const timer = setTimeout(() => controller.abort(new Error('模型评估超时')), 90_000);
|
|
288
|
+
let message;
|
|
289
|
+
try {
|
|
290
|
+
const response = await modelCall(
|
|
291
|
+
settings,
|
|
292
|
+
[
|
|
293
|
+
{
|
|
294
|
+
role: 'system',
|
|
295
|
+
content: `${skill}\n\n当前 UI 自动化项目:${project.name},框架:${project.framework},迭代:${iteration},目标文件:${iterationFile}。`,
|
|
296
|
+
},
|
|
297
|
+
{
|
|
298
|
+
role: 'user',
|
|
299
|
+
content: JSON.stringify({
|
|
300
|
+
cases: cases.map((item) => ({
|
|
301
|
+
sourceCaseId: item.id,
|
|
302
|
+
no: item.no,
|
|
303
|
+
title: item.title,
|
|
304
|
+
module: item.module,
|
|
305
|
+
priority: item.priority,
|
|
306
|
+
precondition: item.precondition,
|
|
307
|
+
steps: item.steps,
|
|
308
|
+
expected: item.expected,
|
|
309
|
+
requirementRefs: (item.fields || []).filter((field) =>
|
|
310
|
+
/需求|requirement|reqcite|reqpoint/i.test(field.name),
|
|
311
|
+
),
|
|
312
|
+
})),
|
|
313
|
+
}),
|
|
314
|
+
},
|
|
315
|
+
],
|
|
316
|
+
controller.signal,
|
|
317
|
+
);
|
|
318
|
+
if (!response.ok) {
|
|
319
|
+
const detail = (await response.text().catch(() => '')).slice(0, 500);
|
|
320
|
+
fail(`模型请求失败(HTTP ${response.status})${detail ? `:${detail}` : ''}`, 502);
|
|
321
|
+
}
|
|
322
|
+
const data = await response.json();
|
|
323
|
+
message = data.choices?.[0]?.message?.content || '';
|
|
324
|
+
} catch (error) {
|
|
325
|
+
if (controller.signal.aborted) fail('模型评估超时,请重试', 504);
|
|
326
|
+
throw error;
|
|
327
|
+
} finally {
|
|
328
|
+
clearTimeout(timer);
|
|
329
|
+
}
|
|
330
|
+
const normalized = normalizeAssessments(
|
|
331
|
+
extractJson(message),
|
|
332
|
+
cases,
|
|
333
|
+
project,
|
|
334
|
+
iteration,
|
|
335
|
+
iterationFile,
|
|
336
|
+
);
|
|
337
|
+
const assessment = writeAssessment(root, {
|
|
338
|
+
id: crypto.randomUUID(),
|
|
339
|
+
createdAt: new Date().toISOString(),
|
|
340
|
+
sourcePath: casePath,
|
|
341
|
+
sourceFileHash: document.fileHash,
|
|
342
|
+
projectId,
|
|
343
|
+
projectName: project.name,
|
|
344
|
+
framework: project.framework,
|
|
345
|
+
iteration,
|
|
346
|
+
iterationFile,
|
|
347
|
+
cases: normalized,
|
|
348
|
+
});
|
|
349
|
+
for (const item of normalized) {
|
|
350
|
+
rememberAssessments(root, casePath, item.sourceCaseId, [
|
|
351
|
+
{
|
|
352
|
+
decision: item.decision,
|
|
353
|
+
reason: item.reason,
|
|
354
|
+
automationCaseId: item.automationCases[0]?.automationCaseId || '',
|
|
355
|
+
},
|
|
356
|
+
]);
|
|
357
|
+
}
|
|
358
|
+
rememberProjectSelection(root, casePath, projectId, iteration);
|
|
359
|
+
return { assessment };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function automationFileName(casePath) {
|
|
363
|
+
const ext = path.extname(casePath).toLowerCase();
|
|
364
|
+
const outputExt = ext === '.xls' ? '.xlsx' : ext;
|
|
365
|
+
const stem = path
|
|
366
|
+
.basename(casePath, ext)
|
|
367
|
+
.replace(/_(?:功能|接口|性能|自动化)测试用例(?:_\d{8}-\d{6})?$/i, '');
|
|
368
|
+
return `${stem || '功能用例'}_自动化测试用例${outputExt}`;
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
function automationFileTarget(root, sourcePath) {
|
|
372
|
+
const dir = path.join(resolveContentRoot(root, '用例管理').abs, '自动化测试');
|
|
373
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
374
|
+
return path.join(dir, automationFileName(sourcePath));
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function sourceRefs(item) {
|
|
378
|
+
return (item.fields || [])
|
|
379
|
+
.filter((field) => /需求|requirement|reqcite|reqpoint/i.test(field.name))
|
|
380
|
+
.map((field) => `${field.name}:${field.value}`)
|
|
381
|
+
.join(';');
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
function statusText(status) {
|
|
385
|
+
return (
|
|
386
|
+
{
|
|
387
|
+
connected: '已接入',
|
|
388
|
+
running: '运行中',
|
|
389
|
+
passed: '已通过',
|
|
390
|
+
failed: '运行失败',
|
|
391
|
+
stale: '已过期',
|
|
392
|
+
needs_manual: '需人工辅助',
|
|
393
|
+
}[status] || status
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
export async function applyAssessment(root, raw) {
|
|
398
|
+
const assessment = readAssessment(root, raw.assessmentId);
|
|
399
|
+
if (!assessment) fail('评估结果不存在或已过期', 404);
|
|
400
|
+
const { project } = projectRecord(root, assessment.projectId);
|
|
401
|
+
const iterationAbs = path.resolve(project.dir, assessment.iterationFile);
|
|
402
|
+
const projectRoot = `${path.resolve(project.dir)}${path.sep}`;
|
|
403
|
+
if (!iterationAbs.startsWith(projectRoot)) fail('目标迭代文件路径越界', 400);
|
|
404
|
+
if (!fs.existsSync(iterationAbs)) {
|
|
405
|
+
fs.mkdirSync(path.dirname(iterationAbs), { recursive: true });
|
|
406
|
+
fs.writeFileSync(
|
|
407
|
+
iterationAbs,
|
|
408
|
+
`// ${assessment.iteration} 迭代 UI 自动化用例\n// 由 Lantern 功能用例自动化转换创建,后续测试块会合并到此文件。\n`,
|
|
409
|
+
{ flag: 'wx' },
|
|
410
|
+
);
|
|
411
|
+
}
|
|
412
|
+
const document = await loadCaseDocument(root, assessment.sourcePath);
|
|
413
|
+
if (document.fileHash !== assessment.sourceFileHash) fail('功能用例文件已变化,请重新评估', 409);
|
|
414
|
+
const selected = new Set(
|
|
415
|
+
(Array.isArray(raw.selectedSourceCaseIds) ? raw.selectedSourceCaseIds : []).map(String),
|
|
416
|
+
);
|
|
417
|
+
if (!selected.size) fail('请至少选择一条有效转换结果');
|
|
418
|
+
const chosen = assessment.cases.filter((item) => selected.has(item.sourceCaseId));
|
|
419
|
+
if (!chosen.length) fail('请至少选择一条有效转换结果');
|
|
420
|
+
const target = automationFileTarget(root, assessment.sourcePath);
|
|
421
|
+
const ext = path.extname(target).toLowerCase();
|
|
422
|
+
const existing = await readTable(target, ext);
|
|
423
|
+
const headers = [...new Set([...AUTOMATION_HEADERS, ...existing.headers])];
|
|
424
|
+
const rows = existing.rows.slice();
|
|
425
|
+
const byId = new Map(rows.map((row, index) => [row['自动化用例编号'], index]));
|
|
426
|
+
const links = [];
|
|
427
|
+
const backup = backupFile(target);
|
|
428
|
+
let createdSessions = 0;
|
|
429
|
+
for (const result of chosen) {
|
|
430
|
+
if (!['automatable', 'needs_manual'].includes(result.decision)) continue;
|
|
431
|
+
const source = document.cases.find((item) => item.id === result.sourceCaseId);
|
|
432
|
+
if (!source) continue;
|
|
433
|
+
const candidates =
|
|
434
|
+
result.decision === 'needs_manual'
|
|
435
|
+
? [
|
|
436
|
+
{
|
|
437
|
+
automationCaseId: `AUTO-${crypto
|
|
438
|
+
.createHash('sha256')
|
|
439
|
+
.update(`${source.id}\0manual`)
|
|
440
|
+
.digest('hex')
|
|
441
|
+
.slice(0, 12)
|
|
442
|
+
.toUpperCase()}`,
|
|
443
|
+
title: source.title,
|
|
444
|
+
precondition: source.precondition,
|
|
445
|
+
steps: [source.steps],
|
|
446
|
+
expected: source.expected,
|
|
447
|
+
priority: source.priority || 'P2',
|
|
448
|
+
tag: '@edge',
|
|
449
|
+
plan: [],
|
|
450
|
+
automationTag: '',
|
|
451
|
+
},
|
|
452
|
+
]
|
|
453
|
+
: result.automationCases;
|
|
454
|
+
for (const item of candidates) {
|
|
455
|
+
const row = {
|
|
456
|
+
...Object.fromEntries(headers.map((header) => [header, ''])),
|
|
457
|
+
自动化用例编号: item.automationCaseId,
|
|
458
|
+
来源用例文件: assessment.sourcePath,
|
|
459
|
+
来源用例编号: source.no || '',
|
|
460
|
+
自动化用例标题: item.title,
|
|
461
|
+
引用需求点: sourceRefs(source),
|
|
462
|
+
前置条件: item.precondition,
|
|
463
|
+
自动化步骤: item.steps.join('\n'),
|
|
464
|
+
预期结果: item.expected,
|
|
465
|
+
优先级: item.priority,
|
|
466
|
+
可行性: result.decision === 'automatable' ? '可自动化' : '需人工辅助',
|
|
467
|
+
自动化项目: assessment.projectName,
|
|
468
|
+
迭代版本: assessment.iteration,
|
|
469
|
+
目标迭代文件: assessment.iterationFile,
|
|
470
|
+
测试标签: item.automationTag || '',
|
|
471
|
+
脚本状态: result.decision === 'automatable' ? '待探索' : '需人工补充',
|
|
472
|
+
运行状态: '待运行',
|
|
473
|
+
实际结果: '',
|
|
474
|
+
报告地址: '',
|
|
475
|
+
说明: result.reason,
|
|
476
|
+
};
|
|
477
|
+
const index = byId.get(item.automationCaseId);
|
|
478
|
+
if (index == null) {
|
|
479
|
+
byId.set(item.automationCaseId, rows.length);
|
|
480
|
+
rows.push(row);
|
|
481
|
+
} else {
|
|
482
|
+
rows[index] = { ...rows[index], ...row, 运行状态: rows[index]['运行状态'] || '待运行' };
|
|
483
|
+
}
|
|
484
|
+
let uiSessionId = '';
|
|
485
|
+
if (result.decision === 'automatable') {
|
|
486
|
+
const sourceText = [
|
|
487
|
+
`来源功能用例:${source.no || source.id} ${source.title}`,
|
|
488
|
+
`前置条件:${source.precondition || '无'}`,
|
|
489
|
+
`测试步骤:${source.steps || '无'}`,
|
|
490
|
+
`预期结果:${source.expected || '无'}`,
|
|
491
|
+
].join('\n');
|
|
492
|
+
const sessionBase = uiautoCachePaths(root).dir;
|
|
493
|
+
const existingSession = findGeneratedSessionByAutomationCaseId(
|
|
494
|
+
sessionBase,
|
|
495
|
+
item.automationCaseId,
|
|
496
|
+
);
|
|
497
|
+
const session = saveGeneratedSession(sessionBase, {
|
|
498
|
+
id: existingSession?.id,
|
|
499
|
+
projectId: assessment.projectId,
|
|
500
|
+
title: item.title,
|
|
501
|
+
target: 'ts',
|
|
502
|
+
baseURL: '',
|
|
503
|
+
storageState: '',
|
|
504
|
+
source: sourceText,
|
|
505
|
+
headed: true,
|
|
506
|
+
plan: item.plan,
|
|
507
|
+
status: 'planned',
|
|
508
|
+
automationCaseId: item.automationCaseId,
|
|
509
|
+
automationTag: item.automationTag,
|
|
510
|
+
iteration: assessment.iteration,
|
|
511
|
+
iterationFile: assessment.iterationFile,
|
|
512
|
+
keepAlive: true,
|
|
513
|
+
});
|
|
514
|
+
uiSessionId = session.id;
|
|
515
|
+
if (!existingSession) createdSessions += 1;
|
|
516
|
+
}
|
|
517
|
+
links.push({
|
|
518
|
+
automationCaseId: item.automationCaseId,
|
|
519
|
+
title: item.title,
|
|
520
|
+
source: {
|
|
521
|
+
casePath: assessment.sourcePath,
|
|
522
|
+
caseId: source.id,
|
|
523
|
+
caseNo: source.no,
|
|
524
|
+
title: source.title,
|
|
525
|
+
fingerprint: caseContentFingerprint(source),
|
|
526
|
+
},
|
|
527
|
+
projectId: assessment.projectId,
|
|
528
|
+
projectName: assessment.projectName,
|
|
529
|
+
framework: assessment.framework,
|
|
530
|
+
iteration: assessment.iteration,
|
|
531
|
+
iterationFile: assessment.iterationFile,
|
|
532
|
+
automationFilePath: path
|
|
533
|
+
.relative(resolveContentRoot(root, '用例管理').abs, target)
|
|
534
|
+
.replaceAll(path.sep, '/'),
|
|
535
|
+
tag: item.automationTag,
|
|
536
|
+
uiSessionId,
|
|
537
|
+
status: result.decision === 'automatable' ? 'connected' : 'needs_manual',
|
|
538
|
+
});
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
try {
|
|
542
|
+
const written = await writeTableAtomic(target, ext, headers, rows);
|
|
543
|
+
upsertAutomationLinks(
|
|
544
|
+
root,
|
|
545
|
+
links.map((link) => ({ ...link, automationFileHash: written.fileHash })),
|
|
546
|
+
);
|
|
547
|
+
return {
|
|
548
|
+
ok: true,
|
|
549
|
+
automationFile: path
|
|
550
|
+
.relative(resolveContentRoot(root, '用例管理').abs, target)
|
|
551
|
+
.replaceAll(path.sep, '/'),
|
|
552
|
+
fileHash: written.fileHash,
|
|
553
|
+
backup,
|
|
554
|
+
createdSessions,
|
|
555
|
+
links,
|
|
556
|
+
};
|
|
557
|
+
} catch (error) {
|
|
558
|
+
if (backup && fs.existsSync(backup)) fs.copyFileSync(backup, target);
|
|
559
|
+
throw error;
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
function findLink(root, automationCaseId) {
|
|
564
|
+
return readAutomationLinks(root).items.find((item) => item.automationCaseId === automationCaseId);
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
async function updateAutomationRow(root, link, values) {
|
|
568
|
+
const base = resolveContentRoot(root, '用例管理').abs;
|
|
569
|
+
const file = path.join(base, link.automationFilePath);
|
|
570
|
+
if (!fs.existsSync(file)) return false;
|
|
571
|
+
const ext = path.extname(file).toLowerCase();
|
|
572
|
+
const expected = link.automationFileHash || '';
|
|
573
|
+
if (expected && fileHash(file) !== expected) return false;
|
|
574
|
+
const table = await readTable(file, ext);
|
|
575
|
+
const index = table.rows.findIndex((row) => row['自动化用例编号'] === link.automationCaseId);
|
|
576
|
+
if (index < 0) return false;
|
|
577
|
+
const backup = backupFile(file);
|
|
578
|
+
table.rows[index] = { ...table.rows[index], ...values };
|
|
579
|
+
const written = await writeTableAtomic(file, ext, table.headers, table.rows);
|
|
580
|
+
upsertAutomationLinks(root, [
|
|
581
|
+
{ ...link, ...values, automationFileHash: written.fileHash, backup },
|
|
582
|
+
]);
|
|
583
|
+
return true;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
function runStatus(link, run) {
|
|
587
|
+
if (!run || run.status === 'cancelled' || run.status === 'interrupted') return 'failed';
|
|
588
|
+
if (run.status === 'error' || run.error) return 'failed';
|
|
589
|
+
if (run.flaky > 0) return 'failed';
|
|
590
|
+
return run.status === 'passed' ? 'passed' : 'failed';
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
function projectStore(root) {
|
|
594
|
+
return readJson(uiautoStorePaths(root).projectsFile, { projects: [] });
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function safeProjectFile(project, relativePath) {
|
|
598
|
+
const projectDir = path.resolve(project.dir);
|
|
599
|
+
const abs = path.resolve(projectDir, relativePath);
|
|
600
|
+
if (!abs.startsWith(`${projectDir}${path.sep}`)) return null;
|
|
601
|
+
return abs;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* 自动化链路必须和当前源用例、iteration 文件和脚本块保持一致。
|
|
606
|
+
* 任一来源变化都只标记 stale,不删除历史结果,也不允许旧结果继续回写。
|
|
607
|
+
*/
|
|
608
|
+
export function refreshAutomationLinks(root, document) {
|
|
609
|
+
if (!document?.path) return {};
|
|
610
|
+
const all = readAutomationLinks(root);
|
|
611
|
+
const targets = all.items.filter((item) => item.source?.casePath === document.path);
|
|
612
|
+
if (!targets.length) return {};
|
|
613
|
+
const projects = new Map(
|
|
614
|
+
(projectStore(root).projects || []).map((item) => [String(item.id || ''), item]),
|
|
615
|
+
);
|
|
616
|
+
const cases = new Map(document.cases.map((item) => [item.id, item]));
|
|
617
|
+
const changed = [];
|
|
618
|
+
const refreshed = {};
|
|
619
|
+
for (const link of targets) {
|
|
620
|
+
let staleReason = '';
|
|
621
|
+
const source = cases.get(link.source?.caseId);
|
|
622
|
+
if (!source) {
|
|
623
|
+
staleReason = '来源功能用例已删除或无法匹配';
|
|
624
|
+
} else if (
|
|
625
|
+
link.source?.fingerprint &&
|
|
626
|
+
caseContentFingerprint(source) !== link.source.fingerprint
|
|
627
|
+
) {
|
|
628
|
+
staleReason = '来源功能用例内容已变化';
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
const project = projects.get(link.projectId);
|
|
632
|
+
const automationAbs = link.automationFilePath
|
|
633
|
+
? path.join(resolveContentRoot(root, '用例管理').abs, link.automationFilePath)
|
|
634
|
+
: '';
|
|
635
|
+
if (!staleReason && !project?.dir) {
|
|
636
|
+
staleReason = 'UI 自动化项目不存在或未挂载';
|
|
637
|
+
} else if (!staleReason && (!automationAbs || !fs.existsSync(automationAbs))) {
|
|
638
|
+
staleReason = '自动化用例文件已缺失';
|
|
639
|
+
} else if (!staleReason && !link.iterationFile) {
|
|
640
|
+
staleReason = '自动化用例未绑定目标 iteration 文件';
|
|
641
|
+
} else if (!staleReason) {
|
|
642
|
+
const iterationAbs = safeProjectFile(project, link.iterationFile);
|
|
643
|
+
if (!iterationAbs || !fs.existsSync(iterationAbs)) {
|
|
644
|
+
staleReason = '目标 iteration 文件已缺失';
|
|
645
|
+
} else if (link.scriptPath) {
|
|
646
|
+
const scriptAbs = safeProjectFile(project, link.scriptPath);
|
|
647
|
+
const content =
|
|
648
|
+
scriptAbs && fs.existsSync(scriptAbs) ? fs.readFileSync(scriptAbs, 'utf8') : '';
|
|
649
|
+
const marker = `/* lantern-automation:start ${link.automationCaseId} */`;
|
|
650
|
+
if (!content.includes(marker)) staleReason = 'iteration 文件中的自动化测试块已缺失';
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
let status = link.status;
|
|
655
|
+
let staleReasonNext = link.staleReason || '';
|
|
656
|
+
let lastStableStatus = link.lastStableStatus || '';
|
|
657
|
+
if (staleReason) {
|
|
658
|
+
if (status !== 'stale') lastStableStatus = status || 'connected';
|
|
659
|
+
status = 'stale';
|
|
660
|
+
staleReasonNext = staleReason;
|
|
661
|
+
} else if (status === 'stale') {
|
|
662
|
+
status = lastStableStatus || 'connected';
|
|
663
|
+
staleReasonNext = '';
|
|
664
|
+
lastStableStatus = '';
|
|
665
|
+
}
|
|
666
|
+
const next = {
|
|
667
|
+
...link,
|
|
668
|
+
status,
|
|
669
|
+
staleReason: staleReasonNext,
|
|
670
|
+
lastStableStatus,
|
|
671
|
+
};
|
|
672
|
+
refreshed[link.automationCaseId] = next;
|
|
673
|
+
if (
|
|
674
|
+
next.status !== link.status ||
|
|
675
|
+
next.staleReason !== (link.staleReason || '') ||
|
|
676
|
+
next.lastStableStatus !== (link.lastStableStatus || '')
|
|
677
|
+
) {
|
|
678
|
+
changed.push(next);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
if (changed.length) upsertAutomationLinks(root, changed);
|
|
682
|
+
return refreshed;
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
async function executeBatch(root, batch) {
|
|
686
|
+
batch.status = 'running';
|
|
687
|
+
writeBatch(root, batch);
|
|
688
|
+
const documents = new Map();
|
|
689
|
+
for (const id of batch.automationCaseIds) {
|
|
690
|
+
const link = findLink(root, id);
|
|
691
|
+
const casePath = link?.source?.casePath;
|
|
692
|
+
if (!casePath || documents.has(casePath)) continue;
|
|
693
|
+
const document = await loadCaseDocument(root, casePath).catch(() => null);
|
|
694
|
+
documents.set(casePath, document);
|
|
695
|
+
if (document) refreshAutomationLinks(root, document);
|
|
696
|
+
}
|
|
697
|
+
for (const id of batch.automationCaseIds) {
|
|
698
|
+
if (batch.stop) break;
|
|
699
|
+
let link = findLink(root, id);
|
|
700
|
+
const item = { automationCaseId: id, status: 'running' };
|
|
701
|
+
batch.items.push(item);
|
|
702
|
+
writeBatch(root, batch);
|
|
703
|
+
if (!link) {
|
|
704
|
+
item.status = 'failed';
|
|
705
|
+
item.error = '自动化关联不存在';
|
|
706
|
+
writeBatch(root, batch);
|
|
707
|
+
continue;
|
|
708
|
+
}
|
|
709
|
+
if (link.status === 'stale') {
|
|
710
|
+
item.status = 'failed';
|
|
711
|
+
item.error = '自动化用例已过期';
|
|
712
|
+
writeBatch(root, batch);
|
|
713
|
+
continue;
|
|
714
|
+
}
|
|
715
|
+
if (!link.iterationFile) {
|
|
716
|
+
item.status = 'failed';
|
|
717
|
+
item.error = '缺少 iteration 文件绑定';
|
|
718
|
+
writeBatch(root, batch);
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
link = { ...link, status: 'running' };
|
|
722
|
+
upsertAutomationLinks(root, [link]);
|
|
723
|
+
const started = startAutomationProjectRun(root, {
|
|
724
|
+
projectId: link.projectId,
|
|
725
|
+
taskId: 'full',
|
|
726
|
+
file: link.iterationFile,
|
|
727
|
+
grep: link.tag,
|
|
728
|
+
env: batch.env || '',
|
|
729
|
+
});
|
|
730
|
+
if (started.error) {
|
|
731
|
+
upsertAutomationLinks(root, [
|
|
732
|
+
{ ...link, status: 'failed', error: started.error, latestRunId: '' },
|
|
733
|
+
]);
|
|
734
|
+
item.status = 'failed';
|
|
735
|
+
item.error = started.error;
|
|
736
|
+
writeBatch(root, batch);
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
batch.activeRunId = started.run.id;
|
|
740
|
+
item.runId = started.run.id;
|
|
741
|
+
writeBatch(root, batch);
|
|
742
|
+
let run = started.run;
|
|
743
|
+
while (!batch.stop && run.status === 'running') {
|
|
744
|
+
await sleep(500);
|
|
745
|
+
run = readAutomationProjectRun(root, started.run.id);
|
|
746
|
+
}
|
|
747
|
+
if (batch.stop) {
|
|
748
|
+
stopAutomationProjectRun(started.run.id);
|
|
749
|
+
item.status = 'failed';
|
|
750
|
+
item.error = '用户已停止运行';
|
|
751
|
+
} else {
|
|
752
|
+
const status = runStatus(link, run);
|
|
753
|
+
const tests = Array.isArray(run.tests) ? run.tests : [];
|
|
754
|
+
const matched =
|
|
755
|
+
tests.find((test) => test.automationCaseId === id) ||
|
|
756
|
+
tests.find((test) => Array.isArray(test.tags) && test.tags.includes(link.tag));
|
|
757
|
+
const errors = !matched
|
|
758
|
+
? [`运行报告未找到 automationCaseId ${id} 对应的测试结果`]
|
|
759
|
+
: matched.errors?.length
|
|
760
|
+
? matched.errors
|
|
761
|
+
: run.error
|
|
762
|
+
? [run.error]
|
|
763
|
+
: [];
|
|
764
|
+
const finalStatus = matched ? status : 'failed';
|
|
765
|
+
const actual =
|
|
766
|
+
errors.join('\n') || (finalStatus === 'passed' ? '自动化运行通过' : '自动化运行失败');
|
|
767
|
+
link = {
|
|
768
|
+
...link,
|
|
769
|
+
status: finalStatus,
|
|
770
|
+
latestRunId: run.id,
|
|
771
|
+
reportUrl: run.reportUrl || '',
|
|
772
|
+
logUrl: run.logUrl || '',
|
|
773
|
+
error: errors[0] || '',
|
|
774
|
+
};
|
|
775
|
+
upsertAutomationLinks(root, [link]);
|
|
776
|
+
const rowUpdated = await updateAutomationRow(root, link, {
|
|
777
|
+
运行状态: statusText(finalStatus),
|
|
778
|
+
实际结果: actual,
|
|
779
|
+
报告地址: run.reportUrl || '',
|
|
780
|
+
}).catch(() => false);
|
|
781
|
+
if (!rowUpdated && finalStatus === 'passed') {
|
|
782
|
+
link = {
|
|
783
|
+
...link,
|
|
784
|
+
status: 'failed',
|
|
785
|
+
error: '自动化用例文件已变化,运行结果未能回写',
|
|
786
|
+
};
|
|
787
|
+
upsertAutomationLinks(root, [link]);
|
|
788
|
+
}
|
|
789
|
+
item.status = link.status;
|
|
790
|
+
item.runId = run.id;
|
|
791
|
+
item.reportUrl = run.reportUrl || '';
|
|
792
|
+
item.error = link.error || errors[0] || '';
|
|
793
|
+
}
|
|
794
|
+
batch.activeRunId = '';
|
|
795
|
+
writeBatch(root, batch);
|
|
796
|
+
}
|
|
797
|
+
await syncPassedSources(root, [
|
|
798
|
+
...new Set(
|
|
799
|
+
batch.automationCaseIds.map((id) => findLink(root, id)?.source?.casePath).filter(Boolean),
|
|
800
|
+
),
|
|
801
|
+
]);
|
|
802
|
+
batch.status = batch.stop ? 'stopped' : 'completed';
|
|
803
|
+
writeBatch(root, batch);
|
|
804
|
+
ACTIVE_BATCHES.delete(batch.id);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
export function startBatch(root, raw) {
|
|
808
|
+
const ids = (Array.isArray(raw.automationCaseIds) ? raw.automationCaseIds : [])
|
|
809
|
+
.map(String)
|
|
810
|
+
.filter(Boolean);
|
|
811
|
+
if (!ids.length) fail('请选择要运行的自动化用例');
|
|
812
|
+
if (ACTIVE_BATCHES.size) fail('已有自动化用例正在运行', 409);
|
|
813
|
+
const links = ids.map((id) => findLink(root, id));
|
|
814
|
+
if (links.some((item) => !item)) fail('存在无效的自动化用例');
|
|
815
|
+
const batch = {
|
|
816
|
+
id: crypto.randomUUID(),
|
|
817
|
+
createdAt: new Date().toISOString(),
|
|
818
|
+
status: 'pending',
|
|
819
|
+
env: clean(raw.env, 80),
|
|
820
|
+
automationCaseIds: ids,
|
|
821
|
+
items: [],
|
|
822
|
+
stop: false,
|
|
823
|
+
activeRunId: '',
|
|
824
|
+
};
|
|
825
|
+
ACTIVE_BATCHES.set(batch.id, batch);
|
|
826
|
+
writeBatch(root, batch);
|
|
827
|
+
void executeBatch(root, batch).catch((error) => {
|
|
828
|
+
batch.status = 'error';
|
|
829
|
+
batch.error = error instanceof Error ? error.message : String(error);
|
|
830
|
+
writeBatch(root, batch);
|
|
831
|
+
if (batch.activeRunId) stopAutomationProjectRun(batch.activeRunId);
|
|
832
|
+
ACTIVE_BATCHES.delete(batch.id);
|
|
833
|
+
});
|
|
834
|
+
return batch;
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
export function stopBatch(root, id) {
|
|
838
|
+
const batch = ACTIVE_BATCHES.get(id) || readBatch(root, id);
|
|
839
|
+
if (!batch) fail('运行批次不存在', 404);
|
|
840
|
+
batch.stop = true;
|
|
841
|
+
if (batch.activeRunId) stopAutomationProjectRun(batch.activeRunId);
|
|
842
|
+
writeBatch(root, batch);
|
|
843
|
+
return batch;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
export function getBatch(root, id) {
|
|
847
|
+
const batch = readBatch(root, id);
|
|
848
|
+
if (!batch) fail('运行批次不存在', 404);
|
|
849
|
+
if (['pending', 'running'].includes(batch.status) && !ACTIVE_BATCHES.has(id)) {
|
|
850
|
+
batch.status = 'interrupted';
|
|
851
|
+
batch.error = '本地服务已重启,原自动化运行已中断;可重新发起';
|
|
852
|
+
writeBatch(root, batch);
|
|
853
|
+
}
|
|
854
|
+
return batch;
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
async function syncPassedSources(root, casePaths) {
|
|
858
|
+
for (const casePath of casePaths) {
|
|
859
|
+
const document = await loadCaseDocument(root, casePath).catch(() => null);
|
|
860
|
+
if (!document?.executable) continue;
|
|
861
|
+
refreshAutomationLinks(root, document);
|
|
862
|
+
const items = readAutomationLinks(root).items.filter(
|
|
863
|
+
(item) => item.source?.casePath === casePath,
|
|
864
|
+
);
|
|
865
|
+
const caseIds = [...new Set(items.map((item) => item.source.caseId))];
|
|
866
|
+
for (const caseId of caseIds) {
|
|
867
|
+
const current = items.filter((item) => item.source.caseId === caseId);
|
|
868
|
+
if (!current.length || !current.every((item) => item.status === 'passed')) continue;
|
|
869
|
+
const row = document.cases.find((item) => item.id === caseId);
|
|
870
|
+
if (!row) continue;
|
|
871
|
+
const executor = clean(row.executor, 200);
|
|
872
|
+
const manual =
|
|
873
|
+
executor !== '自动化' &&
|
|
874
|
+
(Boolean(executor) ||
|
|
875
|
+
(clean(row.status, 20) && clean(row.status, 20) !== '待验证') ||
|
|
876
|
+
Boolean(clean(row.executedAt, 80)));
|
|
877
|
+
if (manual) continue;
|
|
878
|
+
const evidence = current
|
|
879
|
+
.map((item) => [item.latestRunId, item.logUrl, item.reportUrl].filter(Boolean).join(' | '))
|
|
880
|
+
.filter(Boolean)
|
|
881
|
+
.join('\n');
|
|
882
|
+
const applied = await applyCaseExecutionResult(root, {
|
|
883
|
+
path: casePath,
|
|
884
|
+
expectedFileHash: document.fileHash,
|
|
885
|
+
rowIndex: row.rowIndex,
|
|
886
|
+
status: '通过',
|
|
887
|
+
actualResult: '自动化脚本正式运行通过',
|
|
888
|
+
executor: '自动化',
|
|
889
|
+
executedAt: new Date().toISOString().replace('T', ' ').slice(0, 19),
|
|
890
|
+
evidence,
|
|
891
|
+
defectNo: row.defectNo,
|
|
892
|
+
}).catch(() => null);
|
|
893
|
+
if (applied) document.fileHash = applied.fileHash;
|
|
894
|
+
}
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
export async function statuses(root, casePath) {
|
|
899
|
+
const document = await loadCaseDocument(root, casePath);
|
|
900
|
+
refreshAutomationLinks(root, document);
|
|
901
|
+
const caseIds = document.cases.map((item) => item.id);
|
|
902
|
+
const store = readAutomationLinks(root);
|
|
903
|
+
const updates = store.items.filter(
|
|
904
|
+
(item) =>
|
|
905
|
+
item.source?.caseId &&
|
|
906
|
+
caseIds.includes(item.source.caseId) &&
|
|
907
|
+
item.source.casePath !== casePath,
|
|
908
|
+
);
|
|
909
|
+
if (updates.length) {
|
|
910
|
+
upsertAutomationLinks(
|
|
911
|
+
root,
|
|
912
|
+
updates.map((item) => ({
|
|
913
|
+
...item,
|
|
914
|
+
source: { ...item.source, casePath },
|
|
915
|
+
})),
|
|
916
|
+
);
|
|
917
|
+
}
|
|
918
|
+
return Object.fromEntries(
|
|
919
|
+
caseIds.map((caseId) => [caseId, automationSummaryForCase(root, casePath, caseId)]),
|
|
920
|
+
);
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
export async function refreshAutomationFile(root, casePath) {
|
|
924
|
+
const document = await loadCaseDocument(root, casePath);
|
|
925
|
+
refreshAutomationLinks(root, document);
|
|
926
|
+
return document;
|
|
927
|
+
}
|