dsh-uitest 2.1.4 → 2.3.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.
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,14 +26,15 @@ 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 { acquireLock, createBatch, deleteBatch, listBatches, mergeBatchRuns, patchBatch, readBatch, readCaseRuns, readEvents, refreshBatchSummary, saveBatch, withBatchLock } from './store.mjs';
33
33
  import { finishEntry, queueForBatch, stopAllQueued } from './queue.mjs';
34
- import { summarizeCaseRuns } from './model.mjs';
35
- import { requestBatchStop, requestCasePrioritize, requestCaseStopInBatch, requeueCase, runBatch } from './runner.mjs';
36
- import { applyBatchWriteback, previewBatchWriteback } from './writeback.mjs';
34
+ import { summarizeCaseRuns, normalizeStudioCase } from './model.mjs';
35
+ import { requestBatchStop, requestCasePrioritize, requestCaseStopInBatch, requeueCase, resumeBatch, runBatch } from './runner.mjs';
36
+ import { applyBatchWriteback, applyDocumentWriteback, previewBatchWriteback, previewDocumentWriteback } from './writeback.mjs';
37
+ import { deleteDocumentRecord, setDocumentArchived } from './documents.mjs';
37
38
  import { appendRunFeedback, getRunFeedback, latestRunFeedback, readRunFeedbacks } from '../lib/run-feedback.mjs';
38
39
 
39
40
  const PREFIX = '/api/uitest/studio';
@@ -86,10 +87,13 @@ function errorResponse(error) {
86
87
  const code = error?.code || 'INTERNAL';
87
88
  let status = error instanceof HostError ? error.status || 400 : 500;
88
89
  if (code === 'BATCH_NOT_FOUND' || code === 'CASE_NOT_FOUND' || code === 'IMPORT_PATH_NOT_FOUND' || code === 'FLOW_NOT_FOUND') status = 404;
90
+ else if (code === 'DOC_NOT_FOUND') status = 404;
89
91
  else if (code === 'PROJECT_NOT_FOUND') status = 404;
90
92
  else if (code === 'FLOW_FORBIDDEN') status = 403;
91
93
  else if (code === 'WRITEBACK_BUSY' || code === 'JOB_CONFLICT' || code === 'ACCOUNT_EXISTS') status = 409;
94
+ else if (code === 'DOC_SOURCE_MISSING' || code === 'DOC_CASE_FILE_MISSING' || code === 'DOC_KIND_UNSUPPORTED' || code === 'DOC_SOURCE_IN_USE' || code === 'DOC_CASE_FILE_STALE' || code === 'DOCS_INVALID') status = 409;
92
95
  else if (code === 'CASE_NOT_ACTIVE' || code === 'CASE_NOT_QUEUED') status = 409;
96
+ else if (code === 'BATCH_ACTIVE' || code === 'BATCH_NOT_STOPPED' || code === 'NOTHING_TO_RESUME') status = 409;
93
97
  else if (code === 'ACCOUNT_NOT_FOUND' || code === 'ACCOUNT_DOC_NOT_FOUND') status = 404;
94
98
  else if (code === 'NO_PICKER' || code === 'PICKER_UNAVAILABLE') status = 501;
95
99
  else if (String(code).startsWith('PROJECT_') || code === 'PICKER_FAILED' || code === 'PICK_PATH_FAILED') status = 400;
@@ -100,7 +104,11 @@ function errorResponse(error) {
100
104
  else if (String(code).startsWith('EXPORT_')) status = 400;
101
105
  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
106
  const message = String(error?.message || error || '未知错误');
103
- return jsonResponse(status, { ok: false, error: { code, message } });
107
+ const payload = { ok: false, error: { code, message } };
108
+ if (error?.detail && typeof error.detail === 'object' && Object.keys(error.detail).length) {
109
+ payload.error.detail = error.detail;
110
+ }
111
+ return jsonResponse(status, payload);
104
112
  }
105
113
 
106
114
  async function readBody(request, { maxBytes = MAX_BODY } = {}) {
@@ -320,6 +328,8 @@ function handleCase(ctx, request) {
320
328
  }
321
329
  return ok({
322
330
  case: found.case,
331
+ // 执行抽屉按需取用例定义;归一化后前端不必再理解原始表格字段。
332
+ studio: normalizeStudioCase(found.case, { flow, preconditionFlows }),
323
333
  flow: flow ? { name: flow.name, title: flow.title, file: flow.file, tags: flow.tags || [], steps } : null,
324
334
  preconditionFlows: preconditionFlows.map((item) => ({ name: item.name, title: item.title, file: item.file, provides: item.provides || [], cases: item.cases || [] })),
325
335
  });
@@ -432,6 +442,7 @@ async function handleImport(ctx, request) {
432
442
  file: body.file,
433
443
  name: body.name || '',
434
444
  mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
445
+ docId: String(body.docId || ''),
435
446
  });
436
447
  return ok({
437
448
  doc: result.doc,
@@ -450,7 +461,7 @@ async function handleImportUpload(ctx, request) {
450
461
  const { config } = projectFor(ctx, body.project || '');
451
462
  const name = path.basename(String(body.name || 'upload.xlsx'));
452
463
  const ext = path.extname(name).toLowerCase();
453
- if (!['.md', '.markdown', '.txt', '.xlsx', '.json'].includes(ext)) {
464
+ if (!['.md', '.markdown', '.txt', '.xlsx', '.csv', '.json'].includes(ext)) {
454
465
  throw hostError(400, 'IMPORT_UNSUPPORTED', '暂不支持该文件类型:' + ext);
455
466
  }
456
467
  const encoded = String(body.dataBase64 || '');
@@ -467,12 +478,13 @@ async function handleImportUpload(ctx, request) {
467
478
  const safeName = name.replace(/[^\p{L}\p{N}._-]+/gu, '_');
468
479
  const uploadFile = path.join(uploadDir, Date.now() + '-' + safeName);
469
480
  fs.writeFileSync(uploadFile, buffer);
470
- const docName = String(body.docName || path.basename(name, ext));
481
+ const docName = String(body.docName || (body.docId ? '' : path.basename(name, ext)));
471
482
  const result = await importDocument(config, {
472
483
  file: uploadFile,
473
484
  name: docName,
474
485
  originalName: name,
475
486
  mode: body.mode === 'overwrite' ? 'overwrite' : 'merge',
487
+ docId: String(body.docId || ''),
476
488
  });
477
489
  return ok({
478
490
  doc: result.doc,
@@ -625,6 +637,27 @@ async function handleStop(ctx, panel, request) {
625
637
  return ok({ stopped: requested, batch: batchDetail(config, id) });
626
638
  }
627
639
 
640
+ async function handleBatchResume(ctx, panel, request) {
641
+ const body = await readBody(request);
642
+ const { config } = projectFor(ctx, body.project || '');
643
+ const id = String(body.id || '');
644
+ if (!id) throw hostError(400, 'BATCH_REQUIRED', '缺少批次 id');
645
+ const busy = activeBatchResponse(config);
646
+ if (busy) return busy;
647
+ const result = await resumeBatch({ config, batchId: id, panel });
648
+ const logger = ctx?.logger || null;
649
+ Promise.resolve()
650
+ .then(() => runBatch({ config, batchId: id, panel, logger }))
651
+ .catch((error) => {
652
+ try {
653
+ patchBatch(config, id, { status: 'failed', error: String(error.message || error) });
654
+ } catch {
655
+ /* 状态更新失败不阻断响应 */
656
+ }
657
+ });
658
+ return ok({ resumed: result.resumed, batch: batchDetail(config, id) });
659
+ }
660
+
628
661
  async function handleBatchDelete(ctx, request) {
629
662
  const body = await readBody(request);
630
663
  const { config } = projectFor(ctx, body.project || '');
@@ -760,6 +793,13 @@ async function handleCentralExtractions(ctx, request) {
760
793
  return centralRouteResponse(result, 'KNOWLEDGE_EXTRACTIONS_FAILED');
761
794
  }
762
795
 
796
+ async function handleCentralPipeline(ctx, request) {
797
+ const url = new URL(request.url, 'http://localhost');
798
+ const { config } = projectFor(ctx, url.searchParams.get('project') || '');
799
+ const result = await centralPipelineStatus(config, { groupId: url.searchParams.get('groupId') || '' });
800
+ return centralRouteResponse(result, 'KNOWLEDGE_PIPELINE_FAILED');
801
+ }
802
+
763
803
  async function handleCentralEpisode(ctx, request) {
764
804
  const url = new URL(request.url, 'http://localhost');
765
805
  const { config } = projectFor(ctx, url.searchParams.get('project') || '');
@@ -1148,14 +1188,23 @@ function handleShot(ctx, request) {
1148
1188
  const file = url.searchParams.get('file') || '';
1149
1189
  if (!file) throw hostError(400, 'FILE_REQUIRED', '缺少 file');
1150
1190
  const abs = path.isAbsolute(file) ? path.resolve(file) : path.resolve(config.paths.outputDir, file);
1151
- const allowed = [path.resolve(config.projectDir), path.resolve(config.paths.outputDir)];
1152
- if (!allowed.some((root) => abs === root || abs.startsWith(root + path.sep))) {
1153
- throw hostError(403, 'FILE_FORBIDDEN', '只能读取项目目录内的证据文件');
1154
- }
1155
1191
  if (!fs.existsSync(abs) || !fs.statSync(abs).isFile()) throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
1156
- const ext = path.extname(abs).toLowerCase();
1157
- const type = ext === '.png' ? 'image/png' : ext === '.jpg' || ext === '.jpeg' ? 'image/jpeg' : ext === '.webp' ? 'image/webp' : ext === '.md' ? 'text/markdown; charset=utf-8' : 'application/octet-stream';
1158
- return new Response(fs.readFileSync(abs), { headers: { 'content-type': type, 'cache-control': 'no-store' } });
1192
+ // 证据只从输出目录读取;按 realpath 判断,阻止软链接逃逸到账号/文档等配置。
1193
+ let root = path.resolve(config.paths.outputDir);
1194
+ let real = abs;
1195
+ try {
1196
+ root = fs.realpathSync(root);
1197
+ real = fs.realpathSync(abs);
1198
+ } catch {
1199
+ throw hostError(404, 'FILE_NOT_FOUND', '文件不存在:' + file);
1200
+ }
1201
+ if (real !== root && !real.startsWith(root + path.sep)) {
1202
+ throw hostError(403, 'FILE_FORBIDDEN', '只能读取输出目录内的证据图片');
1203
+ }
1204
+ const ext = path.extname(real).toLowerCase();
1205
+ const types = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
1206
+ if (!types[ext]) throw hostError(403, 'FILE_FORBIDDEN', '只能读取证据图片');
1207
+ return new Response(fs.readFileSync(real), { headers: { 'content-type': types[ext], 'cache-control': 'no-store' } });
1159
1208
  }
1160
1209
 
1161
1210
  async function handleFeedback(ctx, request) {
@@ -1290,7 +1339,76 @@ async function handleCasePrioritize(ctx, request) {
1290
1339
  function handleDocs(ctx, request) {
1291
1340
  const url = new URL(request.url, 'http://localhost');
1292
1341
  const { config } = projectFor(ctx, url.searchParams.get('project') || '');
1293
- return ok({ docs: readDocs(config).docs || [] });
1342
+ return ok({ docs: buildStudioSnapshot(config).docs });
1343
+ }
1344
+
1345
+ async function handleDocsReRead(ctx, request) {
1346
+ const body = await readBody(request);
1347
+ const { config } = projectFor(ctx, body.project || '');
1348
+ const busy = activeBatchResponse(config);
1349
+ if (busy) return busy;
1350
+ const mode = body.mode === 'overwrite' ? 'overwrite' : body.mode === 'merge' ? 'merge' : '';
1351
+ const result = await reReadDocument(config, { docId: String(body.docId || ''), mode });
1352
+ return ok({
1353
+ doc: result.doc,
1354
+ docs: result.docs || (result.doc ? [result.doc] : []),
1355
+ diff: result.diff || null,
1356
+ diffSummary: result.diffSummary || null,
1357
+ caseCount: (result.cases || []).length,
1358
+ cases: result.cases || [],
1359
+ warnings: result.warnings || [],
1360
+ resultReapplied: result.resultReapplied === true,
1361
+ snapshot: buildStudioSnapshot(config),
1362
+ });
1363
+ }
1364
+
1365
+ async function handleDocsArchive(ctx, request) {
1366
+ const body = await readBody(request);
1367
+ const { config } = projectFor(ctx, body.project || '');
1368
+ const docId = String(body.docId || '');
1369
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1370
+ const doc = await setDocumentArchived(config, docId, body.archived !== false);
1371
+ return ok({ doc, docs: [doc], snapshot: buildStudioSnapshot(config) });
1372
+ }
1373
+
1374
+ async function handleDocsDelete(ctx, request) {
1375
+ const body = await readBody(request);
1376
+ const { config } = projectFor(ctx, body.project || '');
1377
+ const busy = activeBatchResponse(config);
1378
+ if (busy) return busy;
1379
+ const docId = String(body.docId || '');
1380
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1381
+ const lock = acquireLock(config, 'writeback');
1382
+ try {
1383
+ const doc = await deleteDocumentRecord(config, docId);
1384
+ return ok({
1385
+ doc,
1386
+ deleted: true,
1387
+ docId: doc.id,
1388
+ name: doc.name,
1389
+ caseCount: Array.isArray(doc.caseIds) ? doc.caseIds.length : 0,
1390
+ snapshot: buildStudioSnapshot(config),
1391
+ });
1392
+ } finally {
1393
+ lock.release();
1394
+ }
1395
+ }
1396
+
1397
+ async function handleDocsWriteback(ctx, request) {
1398
+ const body = await readBody(request);
1399
+ const { config } = projectFor(ctx, body.project || '');
1400
+ const busy = activeBatchResponse(config);
1401
+ if (busy) return busy;
1402
+ const docId = String(body.docId || '');
1403
+ if (!docId) throw hostError(400, 'DOC_REQUIRED', '缺少 docId');
1404
+ const options = {
1405
+ batchId: String(body.batchId || ''),
1406
+ caseIds: Array.isArray(body.caseIds) ? body.caseIds.map(String) : [],
1407
+ };
1408
+ const result = body.dryRun === true
1409
+ ? await previewDocumentWriteback(config, docId, options)
1410
+ : await applyDocumentWriteback(config, docId, options);
1411
+ return ok({ ...result, snapshot: buildStudioSnapshot(config) });
1294
1412
  }
1295
1413
 
1296
1414
  export function registerStudioRoutes({ ctx, panel }) {
@@ -1316,6 +1434,7 @@ export function registerStudioRoutes({ ctx, panel }) {
1316
1434
  ['/plan', ['POST'], (request) => handlePlan(ctx, request)],
1317
1435
  ['/batch', ['GET', 'POST'], (request) => (request.method === 'GET' ? handleBatchGet(ctx, request) : handleCreateBatch(ctx, panel, request))],
1318
1436
  ['/batch/stop', ['POST'], (request) => handleStop(ctx, panel, request)],
1437
+ ['/batch/resume', ['POST'], (request) => handleBatchResume(ctx, panel, request)],
1319
1438
  ['/batch/case/stop', ['POST'], (request) => handleCaseStop(ctx, panel, request)],
1320
1439
  ['/batch/case/prioritize', ['POST'], (request) => handleCasePrioritize(ctx, request)],
1321
1440
  ['/batch/delete', ['POST'], (request) => handleBatchDelete(ctx, request)],
@@ -1337,6 +1456,7 @@ export function registerStudioRoutes({ ctx, panel }) {
1337
1456
  ['/knowledge/central/categories', ['POST'], (request) => handleCentralCategories(ctx, request)],
1338
1457
  ['/knowledge/central/extract', ['POST'], (request) => handleCentralExtract(ctx, request)],
1339
1458
  ['/knowledge/central/extractions', ['GET'], (request) => handleCentralExtractions(ctx, request)],
1459
+ ['/knowledge/central/pipeline', ['GET'], (request) => handleCentralPipeline(ctx, request)],
1340
1460
  ['/knowledge/central/semantic-index', ['POST'], (request) => handleCentralSemanticIndex(ctx, request)],
1341
1461
  ['/knowledge/central/episode', ['GET'], (request) => handleCentralEpisode(ctx, request)],
1342
1462
  ['/knowledge/central/import', ['POST'], (request) => handleCentralImport(ctx, request)],
@@ -1349,6 +1469,10 @@ export function registerStudioRoutes({ ctx, panel }) {
1349
1469
  ['/doctor', ['GET', 'POST'], (request) => handleDoctor(ctx, request)],
1350
1470
  ['/shot', ['GET', 'HEAD'], (request) => handleShot(ctx, request)],
1351
1471
  ['/docs', ['GET'], (request) => handleDocs(ctx, request)],
1472
+ ['/docs/re-read', ['POST'], (request) => handleDocsReRead(ctx, request)],
1473
+ ['/docs/archive', ['POST'], (request) => handleDocsArchive(ctx, request)],
1474
+ ['/docs/delete', ['POST'], (request) => handleDocsDelete(ctx, request)],
1475
+ ['/docs/writeback', ['POST'], (request) => handleDocsWriteback(ctx, request)],
1352
1476
  ];
1353
1477
  const disposers = [];
1354
1478
  for (const [suffix, methods, handler] of routes) {