dsh-uitest 2.1.4 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,262 @@
1
+ // 文档对象策略层:归属视图、来源/用例文件状态、分组与回写目标。
2
+ // 文档身份存 docs.json;用例是否存在仍以用例库为准,caseIds 只是拥有关系账本。
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+
6
+ import { normalizeDocumentRecord } from '../lib/cases-import.mjs';
7
+ import { UitestError, formatDate, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
8
+ import { readDocs, updateDocs } from './store.mjs';
9
+
10
+ function asArray(value) {
11
+ return Array.isArray(value) ? value : [];
12
+ }
13
+
14
+ function caseDocId(caseItem) {
15
+ return String(caseItem?.docId || caseItem?.source?.docId || '');
16
+ }
17
+
18
+ function caseIdOf(caseItem) {
19
+ return String(caseItem?.tcId || caseItem?.id || '');
20
+ }
21
+
22
+ function caseKey(value) {
23
+ return String(value || '').toLowerCase();
24
+ }
25
+
26
+ export function documentRegistry(config) {
27
+ const store = readDocs(config);
28
+ return {
29
+ version: Number(store.version) || 1,
30
+ updatedAt: store.updatedAt || '',
31
+ docs: asArray(store.docs).map(normalizeDocumentRecord),
32
+ };
33
+ }
34
+
35
+ export function findDocument(config, { docId = '', docKey = '', sourcePath = '' } = {}) {
36
+ const { docs } = documentRegistry(config);
37
+ if (docId) return docs.find((doc) => doc.id === String(docId)) || null;
38
+ const key = normalizeDocKey(docKey);
39
+ if (key) {
40
+ const hit = docs.find((doc) => doc.docKey === key || normalizeDocKey(doc.name) === key);
41
+ if (hit) return hit;
42
+ }
43
+ if (sourcePath) {
44
+ const abs = path.resolve(config.projectDir, String(sourcePath));
45
+ return docs.find((doc) => [doc.sourcePath, doc.generatedPath]
46
+ .filter(Boolean)
47
+ .some((value) => path.resolve(config.projectDir, value) === abs)) || null;
48
+ }
49
+ return null;
50
+ }
51
+
52
+ /**
53
+ * 按 id → docKey → sourcePath 的顺序 upsert 一条文档记录,并去重。
54
+ * 命中旧记录时保留它的 id,改名不会换身份。
55
+ * reconcile 在锁内拿到磁盘上的旧记录,供调用方决定哪些字段以磁盘为准。
56
+ */
57
+ export function saveDocumentRecord(config, record, { reconcile = null } = {}) {
58
+ const input = normalizeDocumentRecord(record);
59
+ return updateDocs(config, (store) => {
60
+ const docs = asArray(store.docs).map(normalizeDocumentRecord);
61
+ const byId = docs.find((doc) => doc.id === input.id) || null;
62
+ const byKey = input.docKey ? docs.find((doc) => doc.docKey === input.docKey) || null : null;
63
+ const byPath = input.sourcePath
64
+ ? docs.find((doc) => doc.sourcePath && path.resolve(doc.sourcePath) === path.resolve(input.sourcePath)) || null
65
+ : null;
66
+ const existing = byId || byKey || byPath;
67
+ const base = reconcile ? reconcile(existing, input) : { ...(existing || {}), ...input };
68
+ const saved = normalizeDocumentRecord({
69
+ ...base,
70
+ id: existing?.id || input.id,
71
+ importedAt: existing?.importedAt || input.importedAt || nowIso(),
72
+ updatedAt: nowIso(),
73
+ });
74
+ store.docs = [saved, ...docs.filter((doc) => {
75
+ if (doc.id === saved.id) return false;
76
+ if (saved.docKey && doc.docKey === saved.docKey) return false;
77
+ if (saved.sourcePath && doc.sourcePath && path.resolve(doc.sourcePath) === path.resolve(saved.sourcePath)) return false;
78
+ return true;
79
+ })];
80
+ return saved;
81
+ });
82
+ }
83
+
84
+ export function documentSourceState(doc) {
85
+ const sourcePath = String(doc?.sourcePath || '');
86
+ if (!sourcePath) return 'missing';
87
+ try {
88
+ return fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile() ? 'ready' : 'missing';
89
+ } catch {
90
+ return 'missing';
91
+ }
92
+ }
93
+
94
+ export function documentWritebackPath(config, doc, date = formatDate(new Date())) {
95
+ const dir = path.join(config.paths.uitestDir, 'studio', 'writeback', doc.id);
96
+ const name = slug(doc.name || doc.id, 60) + '-执行结果-' + String(date || '').replace(/-/g, '') + '.xlsx';
97
+ return path.join(dir, name);
98
+ }
99
+
100
+ export function documentCaseFile(config, doc) {
101
+ if (!doc) return '';
102
+ if (doc.kind === 'xlsx') {
103
+ return doc.writeback?.targetPath || documentWritebackPath(config, doc);
104
+ }
105
+ return doc.generatedPath || '';
106
+ }
107
+
108
+ export function documentCaseFileState(config, doc) {
109
+ if (!doc) return 'missing';
110
+ if (doc.kind === 'xlsx') {
111
+ if (!doc.writeback?.targetPath) return 'pending';
112
+ return fs.existsSync(doc.writeback.targetPath) ? 'ready' : 'missing';
113
+ }
114
+ const file = documentCaseFile(config, doc);
115
+ if (!file) return 'missing';
116
+ const abs = path.isAbsolute(file) ? file : path.resolve(config.projectDir, file);
117
+ try {
118
+ return fs.existsSync(abs) && fs.statSync(abs).isFile() ? 'ready' : 'missing';
119
+ } catch {
120
+ return 'missing';
121
+ }
122
+ }
123
+
124
+ export function documentCounts(doc, cases, { deletedCaseIds = [] } = {}) {
125
+ const linked = asArray(cases).filter((item) => caseDocId(item) === doc.id);
126
+ const visible = new Set(linked.map((item) => caseKey(caseIdOf(item))));
127
+ const deleted = new Set(asArray(deletedCaseIds).map(caseKey));
128
+ let tombstoned = 0;
129
+ let stale = 0;
130
+ for (const id of doc.caseIds || []) {
131
+ const key = caseKey(id);
132
+ if (!key || visible.has(key)) continue;
133
+ if (deleted.has(key)) tombstoned += 1;
134
+ else stale += 1;
135
+ }
136
+ return {
137
+ visibleCount: linked.length,
138
+ tombstonedCount: tombstoned,
139
+ staleCount: stale,
140
+ ownedCount: linked.length + tombstoned,
141
+ cases: linked,
142
+ };
143
+ }
144
+
145
+ function statusCountsOf(cases) {
146
+ const counts = { total: cases.length, passed: 0, partial: 0, failed: 0, blocked: 0, untested: 0, running: 0 };
147
+ for (const item of cases) {
148
+ const key = Object.hasOwn(counts, item?.status) && item.status !== 'total' ? item.status : 'untested';
149
+ counts[key] += 1;
150
+ }
151
+ return counts;
152
+ }
153
+
154
+ function lastRunOf(cases) {
155
+ let last = null;
156
+ for (const item of cases) {
157
+ const run = item?.lastRun;
158
+ if (!run) continue;
159
+ if (!last || String(run.at || '') > String(last.at || '')) {
160
+ last = {
161
+ caseId: caseIdOf(item),
162
+ status: run.status || '',
163
+ at: run.at || '',
164
+ batchId: run.batchId || '',
165
+ };
166
+ }
167
+ }
168
+ return last;
169
+ }
170
+
171
+ export function documentView(config, doc, cases, { deletedCaseIds = [] } = {}) {
172
+ const record = normalizeDocumentRecord(doc);
173
+ const counts = documentCounts(record, cases, { deletedCaseIds });
174
+ return {
175
+ id: record.id,
176
+ docKey: record.docKey,
177
+ name: record.name,
178
+ kind: record.kind,
179
+ sourcePath: record.sourcePath,
180
+ generatedPath: record.generatedPath,
181
+ caseFile: documentCaseFile(config, record),
182
+ sourceState: documentSourceState(record),
183
+ caseFileState: documentCaseFileState(config, record),
184
+ visibleCount: counts.visibleCount,
185
+ ownedCount: counts.ownedCount,
186
+ tombstonedCount: counts.tombstonedCount,
187
+ staleCount: counts.staleCount,
188
+ version: record.version,
189
+ mode: record.mode,
190
+ importedAt: record.importedAt,
191
+ updatedAt: record.updatedAt,
192
+ lastRead: record.lastRead,
193
+ writeback: record.writeback,
194
+ diff: record.diff,
195
+ statusCounts: statusCountsOf(counts.cases),
196
+ lastRun: lastRunOf(counts.cases),
197
+ };
198
+ }
199
+
200
+ export function groupCasesByDocument(docs, cases) {
201
+ const groups = asArray(docs).map((doc) => {
202
+ const record = normalizeDocumentRecord(doc);
203
+ return { doc: record, cases: [] };
204
+ });
205
+ const byId = new Map(groups.map((group) => [group.doc.id, group]));
206
+ const unassigned = [];
207
+ for (const item of asArray(cases)) {
208
+ const group = byId.get(caseDocId(item));
209
+ if (group) group.cases.push(item);
210
+ else unassigned.push(item);
211
+ }
212
+ return { groups, unassigned };
213
+ }
214
+
215
+ export function documentWriteTarget(config, doc, date = formatDate(new Date())) {
216
+ if (!doc) return { kind: 'none', reason: 'DOC_NOT_FOUND' };
217
+ if (doc.kind === 'markdown' || doc.kind === 'json') {
218
+ const file = doc.generatedPath || '';
219
+ if (!file) return { kind: 'none', path: '', reason: 'DOC_CASE_FILE_MISSING' };
220
+ return { kind: doc.kind, path: file, sourcePath: doc.sourcePath || '', sourceState: documentSourceState(doc) };
221
+ }
222
+ if (doc.kind === 'xlsx') {
223
+ const target = documentWritebackPath(config, doc, date);
224
+ const sourceState = documentSourceState(doc);
225
+ return {
226
+ kind: 'xlsx',
227
+ path: target,
228
+ sourcePath: doc.sourcePath || '',
229
+ sourceState,
230
+ reason: sourceState === 'ready' ? '' : 'DOC_SOURCE_MISSING',
231
+ };
232
+ }
233
+ return { kind: 'none', path: '', reason: 'DOC_KIND_UNSUPPORTED' };
234
+ }
235
+
236
+ /** 锁内按 id 修改单条文档记录;回调拿到的是磁盘上的最新记录。 */
237
+ export function updateDocumentRecord(config, docId, mutate) {
238
+ const id = String(docId || '');
239
+ return updateDocs(config, (store) => {
240
+ const docs = asArray(store.docs).map(normalizeDocumentRecord);
241
+ const index = docs.findIndex((doc) => doc.id === id);
242
+ if (index < 0) throw new UitestError('文档不存在:' + id, { code: 'DOC_NOT_FOUND', detail: { docId: id } });
243
+ const current = { ...docs[index] };
244
+ const next = mutate(current) || current;
245
+ const saved = normalizeDocumentRecord({ ...next, id: docs[index].id, updatedAt: nowIso() });
246
+ docs[index] = saved;
247
+ store.docs = docs;
248
+ return saved;
249
+ });
250
+ }
251
+
252
+ /**
253
+ * 回写只能做锁内读改写。调用方手里的文档快照可能已经落后于并发的
254
+ * 重新导读/导入,整条覆盖会回滚 version、lastRead 与 caseIds。
255
+ */
256
+ export function recordDocumentWriteback(config, doc, summary) {
257
+ const docId = typeof doc === 'string' ? doc : doc?.id;
258
+ return updateDocumentRecord(config, docId, (current) => ({
259
+ ...current,
260
+ writeback: { ...summary, at: summary?.at || nowIso() },
261
+ }));
262
+ }
package/studio/host.mjs CHANGED
@@ -9,7 +9,7 @@ import { normalizeEvidenceFile } from '../lib/results.mjs';
9
9
  import { resolveRequestProject, listWorkspaces, defaultProjectPath, HostError, hostError, readFlows } from '../host/state.mjs';
10
10
  import { ensureDir, writeFileAtomic, nowIso } from '../lib/util.mjs';
11
11
  import { pickPath } from '../host/pick-path.mjs';
12
- import { centralBackfillCategories, centralBrowse, centralDeleteEpisode, centralEpisode, centralExtract, centralExtractions, centralSearch, centralSemanticIndex, centralStatus } from '../lib/knowledge-central.mjs';
12
+ import { centralBackfillCategories, centralBrowse, centralDeleteEpisode, centralEpisode, centralExtract, centralExtractions, centralPipelineStatus, centralSearch, centralSemanticIndex, centralStatus } from '../lib/knowledge-central.mjs';
13
13
  import { importKnowledgeToCentral } from '../lib/knowledge-central-import.mjs';
14
14
  import {
15
15
  deleteKnowledgeDocumentLocal,
@@ -26,10 +26,10 @@ import { buildStudioPlan, compactPlan } from './plan.mjs';
26
26
  import { accountsPayload, deleteAccount, importAccountsText, saveAccount, setDefaultAccount } from './accounts.mjs';
27
27
  import { readLiveInfo } from './live.mjs';
28
28
  import { readAgentLive } from './agent-live.mjs';
29
- import { importDocument } from './import.mjs';
29
+ import { importDocument, reReadDocument } from './import.mjs';
30
30
  import { defaultExportDir, exportCasesWorkbook, exportResultsWorkbook } from './export.mjs';
31
31
  import { buildStudioSnapshot, batchSummary } from './snapshot.mjs';
32
- import { createBatch, deleteBatch, listBatches, mergeBatchRuns, patchBatch, readBatch, readCaseRuns, readDocs, readEvents, refreshBatchSummary, saveBatch, withBatchLock } from './store.mjs';
32
+ import { createBatch, deleteBatch, listBatches, mergeBatchRuns, patchBatch, readBatch, readCaseRuns, readEvents, refreshBatchSummary, saveBatch, withBatchLock } from './store.mjs';
33
33
  import { finishEntry, queueForBatch, stopAllQueued } from './queue.mjs';
34
34
  import { summarizeCaseRuns } from './model.mjs';
35
35
  import { requestBatchStop, requestCasePrioritize, requestCaseStopInBatch, requeueCase, runBatch } from './runner.mjs';
@@ -86,9 +86,11 @@ function errorResponse(error) {
86
86
  const code = error?.code || 'INTERNAL';
87
87
  let status = error instanceof HostError ? error.status || 400 : 500;
88
88
  if (code === 'BATCH_NOT_FOUND' || code === 'CASE_NOT_FOUND' || code === 'IMPORT_PATH_NOT_FOUND' || code === 'FLOW_NOT_FOUND') status = 404;
89
+ else if (code === 'DOC_NOT_FOUND') status = 404;
89
90
  else if (code === 'PROJECT_NOT_FOUND') status = 404;
90
91
  else if (code === 'FLOW_FORBIDDEN') status = 403;
91
92
  else if (code === 'WRITEBACK_BUSY' || code === 'JOB_CONFLICT' || code === 'ACCOUNT_EXISTS') status = 409;
93
+ else if (code === 'DOC_SOURCE_MISSING' || code === 'DOC_CASE_FILE_MISSING' || code === 'DOC_KIND_UNSUPPORTED') status = 409;
92
94
  else if (code === 'CASE_NOT_ACTIVE' || code === 'CASE_NOT_QUEUED') status = 409;
93
95
  else if (code === 'ACCOUNT_NOT_FOUND' || code === 'ACCOUNT_DOC_NOT_FOUND') status = 404;
94
96
  else if (code === 'NO_PICKER' || code === 'PICKER_UNAVAILABLE') status = 501;
@@ -100,7 +102,11 @@ function errorResponse(error) {
100
102
  else if (String(code).startsWith('EXPORT_')) status = 400;
101
103
  else if (String(code).startsWith('IMPORT_') || String(code).startsWith('ACCOUNT') || code === 'FLOW_REQUIRED' || code === 'FLOW_NOT_CASE' || code === 'BATCH_ID_INVALID' || code === 'CASE_REQUIRED' || code === 'BATCH_REQUIRED' || code === 'CASE_NOT_IN_BATCH' || code === 'NO_RUNNABLE_CASES') status = 400;
102
104
  const message = String(error?.message || error || '未知错误');
103
- return jsonResponse(status, { ok: false, error: { code, message } });
105
+ const payload = { ok: false, error: { code, message } };
106
+ if (error?.detail && typeof error.detail === 'object' && Object.keys(error.detail).length) {
107
+ payload.error.detail = error.detail;
108
+ }
109
+ return jsonResponse(status, payload);
104
110
  }
105
111
 
106
112
  async function readBody(request, { maxBytes = MAX_BODY } = {}) {
@@ -760,6 +766,13 @@ async function handleCentralExtractions(ctx, request) {
760
766
  return centralRouteResponse(result, 'KNOWLEDGE_EXTRACTIONS_FAILED');
761
767
  }
762
768
 
769
+ async function handleCentralPipeline(ctx, request) {
770
+ const url = new URL(request.url, 'http://localhost');
771
+ const { config } = projectFor(ctx, url.searchParams.get('project') || '');
772
+ const result = await centralPipelineStatus(config, { groupId: url.searchParams.get('groupId') || '' });
773
+ return centralRouteResponse(result, 'KNOWLEDGE_PIPELINE_FAILED');
774
+ }
775
+
763
776
  async function handleCentralEpisode(ctx, request) {
764
777
  const url = new URL(request.url, 'http://localhost');
765
778
  const { config } = projectFor(ctx, url.searchParams.get('project') || '');
@@ -1290,7 +1303,27 @@ async function handleCasePrioritize(ctx, request) {
1290
1303
  function handleDocs(ctx, request) {
1291
1304
  const url = new URL(request.url, 'http://localhost');
1292
1305
  const { config } = projectFor(ctx, url.searchParams.get('project') || '');
1293
- return ok({ docs: readDocs(config).docs || [] });
1306
+ return ok({ docs: buildStudioSnapshot(config).docs });
1307
+ }
1308
+
1309
+ async function handleDocsReRead(ctx, request) {
1310
+ const body = await readBody(request);
1311
+ const { config } = projectFor(ctx, body.project || '');
1312
+ const busy = activeBatchResponse(config);
1313
+ if (busy) return busy;
1314
+ const mode = body.mode === 'overwrite' ? 'overwrite' : body.mode === 'merge' ? 'merge' : '';
1315
+ const result = await reReadDocument(config, { docId: String(body.docId || ''), mode });
1316
+ return ok({
1317
+ doc: result.doc,
1318
+ docs: result.docs || (result.doc ? [result.doc] : []),
1319
+ diff: result.diff || null,
1320
+ diffSummary: result.diffSummary || null,
1321
+ caseCount: (result.cases || []).length,
1322
+ cases: result.cases || [],
1323
+ warnings: result.warnings || [],
1324
+ resultReapplied: result.resultReapplied === true,
1325
+ snapshot: buildStudioSnapshot(config),
1326
+ });
1294
1327
  }
1295
1328
 
1296
1329
  export function registerStudioRoutes({ ctx, panel }) {
@@ -1337,6 +1370,7 @@ export function registerStudioRoutes({ ctx, panel }) {
1337
1370
  ['/knowledge/central/categories', ['POST'], (request) => handleCentralCategories(ctx, request)],
1338
1371
  ['/knowledge/central/extract', ['POST'], (request) => handleCentralExtract(ctx, request)],
1339
1372
  ['/knowledge/central/extractions', ['GET'], (request) => handleCentralExtractions(ctx, request)],
1373
+ ['/knowledge/central/pipeline', ['GET'], (request) => handleCentralPipeline(ctx, request)],
1340
1374
  ['/knowledge/central/semantic-index', ['POST'], (request) => handleCentralSemanticIndex(ctx, request)],
1341
1375
  ['/knowledge/central/episode', ['GET'], (request) => handleCentralEpisode(ctx, request)],
1342
1376
  ['/knowledge/central/import', ['POST'], (request) => handleCentralImport(ctx, request)],
@@ -1349,6 +1383,7 @@ export function registerStudioRoutes({ ctx, panel }) {
1349
1383
  ['/doctor', ['GET', 'POST'], (request) => handleDoctor(ctx, request)],
1350
1384
  ['/shot', ['GET', 'HEAD'], (request) => handleShot(ctx, request)],
1351
1385
  ['/docs', ['GET'], (request) => handleDocs(ctx, request)],
1386
+ ['/docs/re-read', ['POST'], (request) => handleDocsReRead(ctx, request)],
1352
1387
  ];
1353
1388
  const disposers = [];
1354
1389
  for (const [suffix, methods, handler] of routes) {
package/studio/import.mjs CHANGED
@@ -8,17 +8,21 @@ import path from 'node:path';
8
8
  import {
9
9
  clearCaseTombstones,
10
10
  deleteCases,
11
+ docIdForKey,
11
12
  importCases,
12
13
  keepDocumentCases,
13
14
  loadImportedCases,
14
15
  loadProjectCases,
16
+ normalizeDocumentRecord,
15
17
  rekeyDocumentCases,
16
18
  removeDocumentCases,
17
19
  removeDocumentOverrides,
18
20
  } from '../lib/cases-import.mjs';
19
21
  import { UitestError, ensureDir, normalizeDocKey, nowIso, slug } from '../lib/util.mjs';
22
+ import { findDocument, saveDocumentRecord, updateDocumentRecord } from './documents.mjs';
20
23
  import { dataNeedsFromText, normalizeStudioCase, splitNatural } from './model.mjs';
21
- import { readDocs, saveDocs } from './store.mjs';
24
+ import { readDocs } from './store.mjs';
25
+ import { acquireWritebackLock, writeDocumentResults } from './writeback.mjs';
22
26
 
23
27
  const TEXT_EXT = new Set(['.md', '.markdown', '.txt']);
24
28
  const XLSX_EXT = new Set(['.xlsx']);
@@ -41,11 +45,6 @@ for (const [field, aliases] of Object.entries(FIELD_ALIASES)) {
41
45
  for (const alias of aliases) ALIAS_LOOKUP.set(alias.toLowerCase(), field);
42
46
  }
43
47
 
44
- /** 文档对象 identity:名称归一化(大小写、空白、扩展名不敏感)。 */
45
- function docIdForKey(docKey) {
46
- return 'doc-' + crypto.createHash('sha1').update(String(docKey)).digest('hex').slice(0, 10);
47
- }
48
-
49
48
  /** 用例内容摘要:覆盖导入时用来区分「更新」与「未变」。来源路径不属于用例内容。 */
50
49
  export function digestCase(caseItem) {
51
50
  const remark = String(caseItem?.remark ?? '')
@@ -429,22 +428,16 @@ function sameFile(a, b) {
429
428
  function findPreviousDoc(config, { docKey, sourcePath }) {
430
429
  const store = readDocs(config);
431
430
  const key = normalizeDocKey(docKey);
432
- return (store.docs || []).find((item) => {
433
- const itemKey = item.docKey || normalizeDocKey(item.name);
434
- return itemKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
431
+ return (store.docs || []).map(normalizeDocumentRecord).find((item) => {
432
+ return item.docKey === key || normalizeDocKey(item.name) === key || (sourcePath && item.sourcePath === sourcePath);
435
433
  }) || null;
436
434
  }
437
435
 
438
- function saveDocRecord(config, record) {
439
- const store = readDocs(config);
440
- const key = record.docKey || normalizeDocKey(record.name);
441
- const docs = (store.docs || []).filter((item) => {
442
- const itemKey = item.docKey || normalizeDocKey(item.name);
443
- return itemKey !== key && normalizeDocKey(item.name) !== key && item.sourcePath !== record.sourcePath;
444
- });
445
- docs.unshift({ ...record, docKey: key, id: record.id || docIdForKey(key) });
446
- saveDocs(config, { ...store, version: 2, docs, updatedAt: nowIso() });
447
- return docs[0];
436
+ function findTargetDoc(config, docId) {
437
+ if (!docId) return null;
438
+ const doc = findDocument(config, { docId });
439
+ if (!doc) throw new UitestError('文档不存在:' + docId, { code: 'DOC_NOT_FOUND', detail: { docId } });
440
+ return doc;
448
441
  }
449
442
 
450
443
  function digestsForCases(cases) {
@@ -517,7 +510,7 @@ function compactDiff(diff) {
517
510
  * mode=merge 保留文档中已移除的旧用例;mode=overwrite 以当前文档为准删除旧用例。
518
511
  * @returns {Promise<{doc:object, docs:object[], cases:object[], warnings:object[], diff:object}>}
519
512
  */
520
- export async function importDocument(config, { file, name = '', mode = 'merge', originalName = '' } = {}) {
513
+ export async function importDocument(config, { file, name = '', mode = 'merge', originalName = '', docId = '' } = {}) {
521
514
  const sourcePath = path.resolve(config.projectDir, String(file || ''));
522
515
  if (!fs.existsSync(sourcePath)) throw new UitestError('路径不存在:' + sourcePath, { code: 'IMPORT_PATH_NOT_FOUND' });
523
516
  const stat = fs.statSync(sourcePath);
@@ -547,10 +540,11 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
547
540
  }
548
541
  if (stat.size > MAX_BYTES) throw new UitestError('文件超过 20MB 上限:' + sourcePath, { code: 'IMPORT_TOO_LARGE' });
549
542
  const ext = path.extname(sourcePath).toLowerCase();
550
- const docName = name || path.basename(sourcePath, ext);
543
+ const explicitDoc = findTargetDoc(config, docId);
544
+ const docName = name || explicitDoc?.name || path.basename(sourcePath, ext);
551
545
  const docKey = normalizeDocKey(docName) || normalizeDocKey(path.basename(sourcePath, ext)) || 'document';
552
546
  const overwrite = mode === 'overwrite';
553
- const previousDoc = findPreviousDoc(config, { docKey, sourcePath });
547
+ const previousDoc = explicitDoc || findPreviousDoc(config, { docKey, sourcePath });
554
548
  const previousIds = Array.isArray(previousDoc?.caseIds) ? previousDoc.caseIds.map(String) : [];
555
549
  const previousLibrary = new Map(loadProjectCases(config).cases.map((item) => [String(item.tcId), item]));
556
550
  const previousDigests = { ...digestsForIds(config, previousIds, previousLibrary), ...(previousDoc?.digests || {}) };
@@ -687,7 +681,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
687
681
  }
688
682
 
689
683
  const ownedIds = overwrite ? newIds : [...new Set([...previousIds, ...newIds])];
690
- const doc = saveDocRecord(config, {
684
+ const doc = await saveDocumentRecord(config, {
691
685
  id: previousDoc?.id || docIdForKey(docKey),
692
686
  docKey,
693
687
  name: docName,
@@ -695,7 +689,7 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
695
689
  originalName: originalName || previousDoc?.originalName || '',
696
690
  generatedPath,
697
691
  kind: XLSX_EXT.has(ext) ? 'xlsx' : JSON_EXT.has(ext) ? 'json' : 'markdown',
698
- importedAt: nowIso(),
692
+ importedAt: previousDoc?.importedAt || nowIso(),
699
693
  updatedAt: nowIso(),
700
694
  count: ownedIds.length,
701
695
  lastCount: newIds.length,
@@ -706,17 +700,121 @@ export async function importDocument(config, { file, name = '', mode = 'merge',
706
700
  diff: compactDiff(diff),
707
701
  digests: overwrite ? newDigests : { ...(previousDoc?.digests || {}), ...newDigests },
708
702
  warnings: (warnings || []).slice(0, 5).map((item) => String(item?.message || item).slice(0, 240)),
703
+ lastRead: previousDoc?.lastRead || null,
704
+ writeback: previousDoc?.writeback || null,
705
+ }, {
706
+ // 导入字段算自导入前快照。锁内重读后版本按磁盘递增,并保留并发重新导读/回写的状态。
707
+ reconcile: (existing, input) => (existing
708
+ ? {
709
+ ...input,
710
+ version: (Number(existing.version) || 0) + 1,
711
+ lastRead: existing.lastRead ?? input.lastRead,
712
+ writeback: existing.writeback ?? input.writeback,
713
+ }
714
+ : input),
709
715
  });
716
+ const stamped = cases.map((item) => ({
717
+ ...item,
718
+ source: {
719
+ ...item.source,
720
+ docId: doc.id,
721
+ docKey: doc.docKey,
722
+ docName: doc.name,
723
+ docKind: doc.kind,
724
+ },
725
+ }));
710
726
  return {
711
727
  doc,
712
728
  docs: [doc],
713
- cases: cases.map((item) => normalizeStudioCase(item)),
729
+ cases: stamped.map((item) => normalizeStudioCase(item)),
714
730
  warnings,
715
731
  diff,
716
732
  diffSummary: compactDiff(diff),
717
733
  };
718
734
  }
719
735
 
736
+ /**
737
+ * 重新导读:按文档 id 重读存储的源文件,保留文档身份;源文件缺失时不改任何状态。
738
+ * Markdown 重新生成用例文件后会尽力重放最近一次结果回写。
739
+ * 全程持有回写锁:重新导读会重写用例文件,不能和批次回写互相覆盖。
740
+ */
741
+ export async function reReadDocument(config, { docId = '', mode = '', reapplyResults = true } = {}) {
742
+ const lock = await acquireWritebackLock(config);
743
+ try {
744
+ const doc = findTargetDoc(config, docId);
745
+ if (!doc) throw new UitestError('缺少文档 id', { code: 'DOC_NOT_FOUND', detail: { docId } });
746
+ const sourcePath = String(doc.sourcePath || '');
747
+ let sourceReady = false;
748
+ try {
749
+ sourceReady = Boolean(sourcePath) && fs.existsSync(sourcePath) && fs.statSync(sourcePath).isFile();
750
+ } catch {
751
+ sourceReady = false;
752
+ }
753
+ if (!sourceReady) {
754
+ throw new UitestError('文档源文件不存在:' + (sourcePath || '(未记录)'), {
755
+ code: 'DOC_SOURCE_MISSING',
756
+ detail: { docId: doc.id, path: sourcePath },
757
+ });
758
+ }
759
+ const imported = await importDocument(config, {
760
+ file: sourcePath,
761
+ name: doc.name,
762
+ mode: mode || doc.mode || 'merge',
763
+ originalName: doc.originalName || '',
764
+ docId: doc.id,
765
+ });
766
+ const lastRead = {
767
+ at: nowIso(),
768
+ version: imported.doc.version,
769
+ sourcePath,
770
+ diff: imported.diffSummary || null,
771
+ };
772
+ let nextDoc = await updateDocumentRecord(config, imported.doc.id, (current) => ({
773
+ ...current,
774
+ lastRead,
775
+ updatedAt: lastRead.at,
776
+ }));
777
+ const warnings = [...(imported.warnings || [])];
778
+ let resultReapplied = false;
779
+ const recorded = imported.doc.writeback;
780
+ if (reapplyResults && recorded?.batchId && Number(recorded.results) > 0 && imported.doc.kind !== 'xlsx') {
781
+ const survivingIds = loadProjectCases(config).cases
782
+ .filter((item) => item.source?.docId === imported.doc.id)
783
+ .map((item) => String(item.tcId));
784
+ try {
785
+ const reapplied = await writeDocumentResults(config, {
786
+ docId: imported.doc.id,
787
+ batchId: recorded.batchId,
788
+ caseIds: survivingIds,
789
+ });
790
+ if (reapplied.writeback) {
791
+ resultReapplied = true;
792
+ nextDoc = findDocument(config, { docId: imported.doc.id }) || nextDoc;
793
+ } else {
794
+ warnings.push({
795
+ code: 'WRITEBACK_REAPPLY_SKIPPED',
796
+ message: '最近一次回写的批次结果已不存在,用例文件已重新导读但未带回结果块',
797
+ });
798
+ }
799
+ } catch (error) {
800
+ warnings.push({
801
+ code: 'WRITEBACK_REAPPLY_FAILED',
802
+ message: '重新回写最近结果失败,用例文件已重新导读:' + String(error.message || error),
803
+ });
804
+ }
805
+ }
806
+ return {
807
+ ...imported,
808
+ doc: nextDoc,
809
+ docs: [nextDoc],
810
+ warnings,
811
+ resultReapplied,
812
+ };
813
+ } finally {
814
+ lock.release();
815
+ }
816
+ }
817
+
720
818
  /** 从当前用例库读取统一形态;用于 UI 与批次。 */
721
819
  export function loadStudioCases(config, { flows = [] } = {}) {
722
820
  const loaded = loadProjectCases(config);
@@ -743,6 +841,7 @@ export function loadStudioCases(config, { flows = [] } = {}) {
743
841
  })),
744
842
  summary: loaded.summary,
745
843
  warnings: loaded.warnings,
844
+ deletedCaseIds: loaded.deletedCaseIds || [],
746
845
  counts: {
747
846
  config: loaded.configCount,
748
847
  markdown: loaded.markdownCount,
package/studio/model.mjs CHANGED
@@ -150,6 +150,9 @@ export function normalizeStudioCase(caseItem, { flow = null, preconditionFlows =
150
150
  expected: String(caseItem?.expected || ''),
151
151
  remark: String(caseItem?.remark || ''),
152
152
  source: caseItem?.source || null,
153
+ docId: String(caseItem?.docId || caseItem?.source?.docId || ''),
154
+ docName: String(caseItem?.docName || caseItem?.source?.docName || ''),
155
+ docKind: String(caseItem?.docKind || caseItem?.source?.docKind || ''),
153
156
  mode: inferCaseMode(caseItem, { hasFlow: Boolean(flow) }),
154
157
  flow: flow
155
158
  ? {
@@ -9,7 +9,8 @@ import { readFlows } from '../host/state.mjs';
9
9
  import { loadStudioCases } from './import.mjs';
10
10
  import { knowledgeSnapshot } from './knowledge.mjs';
11
11
  import { readRunFeedbacks } from '../lib/run-feedback.mjs';
12
- import { listBatches, mergeBatchRuns, readCaseRuns, readDocs } from './store.mjs';
12
+ import { listBatches, mergeBatchRuns, readCaseRuns } from './store.mjs';
13
+ import { documentRegistry, documentView } from './documents.mjs';
13
14
  import { accountsPayload } from './accounts.mjs';
14
15
  import { statusFromRun } from './model.mjs';
15
16
 
@@ -127,7 +128,8 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
127
128
  const activeRuns = active ? mergeBatchRuns(active, readCaseRuns(config, active.id)) : [];
128
129
  const activeById = new Map(activeRuns.map((run) => [String(run.caseId), run]));
129
130
 
130
- const cases = studio.cases.slice(0, caseLimit).map((item) => {
131
+ // 文档视图和用例行共用完整用例库的状态:先切片会让文档汇总漏掉真实结果。
132
+ const enriched = studio.cases.map((item) => {
131
133
  const result = latest.get(String(item.tcId));
132
134
  const activeRun = activeById.get(String(item.tcId));
133
135
  const runKnowledge = knowledgeByCase.get(String(item.tcId)) || null;
@@ -178,6 +180,7 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
178
180
  lastFeedback: feedbackByCase.get(String(item.tcId)) || null,
179
181
  };
180
182
  });
183
+ const cases = enriched.slice(0, caseLimit);
181
184
 
182
185
  const counts = {
183
186
  total: studio.cases.length,
@@ -190,29 +193,13 @@ export function buildStudioSnapshot(config, { caseLimit = 400, batchLimit = 30 }
190
193
  untested: cases.filter((item) => item.status === 'untested').length,
191
194
  running: cases.filter((item) => item.status === 'running').length,
192
195
  feedback: feedbackByCase.size,
196
+ unassigned: studio.cases.filter((item) => !item.docId && !item.source?.docId).length,
193
197
  };
194
198
  const knowledge = knowledgeSnapshot(config, { limit: 100 });
195
- const visibleIds = new Set(studio.cases.map((item) => String(item.tcId)));
196
- const docs = (readDocs(config).docs || []).map((doc) => {
197
- const caseIds = Array.isArray(doc.caseIds) ? doc.caseIds : [];
198
- const visibleCount = caseIds.length ? caseIds.filter((id) => visibleIds.has(String(id))).length : (Number(doc.count) || 0);
199
- return {
200
- id: doc.id,
201
- docKey: doc.docKey || '',
202
- name: doc.name || '',
203
- sourcePath: doc.sourcePath || '',
204
- generatedPath: doc.generatedPath || '',
205
- kind: doc.kind || '',
206
- count: visibleCount,
207
- importedCount: Number(doc.count) || caseIds.length,
208
- lastCount: doc.lastCount ?? caseIds.length,
209
- version: doc.version || 1,
210
- mode: doc.mode || 'merge',
211
- importedAt: doc.importedAt || '',
212
- updatedAt: doc.updatedAt || doc.importedAt || '',
213
- diff: doc.diff || null,
214
- };
215
- });
199
+ // 文档视图必须基于完整用例库计算,先切片会让文档看起来缺用例。
200
+ const docs = documentRegistry(config).docs.map((doc) => documentView(config, doc, enriched, {
201
+ deletedCaseIds: studio.deletedCaseIds || [],
202
+ }));
216
203
  return {
217
204
  project: config.projectDir,
218
205
  capabilities: { importUpload: true, accountsImport: true, caseDelete: true, export: true },