Merge pull request #211 from yunyingk/mac15/diagnose-simulation-dx-improvements
Refine simulation DX, diagnose fields extraction, and test rule mapping
This commit is contained in:
10 files changed
+231
-22
No files matched your search
@@ -78,11 +78,17 @@ export async function handleCorpBindings(
|
||||
}
|
||||
|
||||
if (prodCorp.testCorpId && prodCorp.testCorpId !== testCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除生产企业「${prodCorp.name}」(${prodCorp.id}) 与原测试企业「${prodCorp.testCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(prodCorp.testCorpId, { prodCorpId: undefined });
|
||||
} catch {}
|
||||
}
|
||||
if (testCorp.prodCorpId && testCorp.prodCorpId !== prodCorp.id) {
|
||||
console.error(
|
||||
`⚠️ [bind-test] 检测到冲突:已强制解除测试企业「${testCorp.name}」(${testCorp.id}) 与原生产企业「${testCorp.prodCorpId}」的绑定关联。`
|
||||
);
|
||||
try {
|
||||
updateCorpConfig(testCorp.prodCorpId, { testCorpId: undefined });
|
||||
} catch {}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { executeApprovalRunsReplay, type ReplayRecordsQuery } from "../../../dom
|
||||
import { selectCorp } from "../../helpers.js";
|
||||
import { CliError, confirmationRequired, usageError } from "../../errors.js";
|
||||
import { booleanOption, numberOption, stringOption } from "../../parser.js";
|
||||
import { printJson } from "../../printer.js";
|
||||
import { outputOptions, printJson } from "../../printer.js";
|
||||
import type { ParsedArgs } from "../../types.js";
|
||||
|
||||
export { buildTestHosecloudOutboundName } from "../../../domains/seal/test-sync.js";
|
||||
@@ -50,7 +50,16 @@ export async function handleCorpSync(
|
||||
`seal-use corps sync-test ${prodCorp.id} --yes`
|
||||
);
|
||||
}
|
||||
printJson(await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true }));
|
||||
const result = await syncTestEnterprise(prodCorp, testCorp, { versionName, execute: true });
|
||||
const targetVersion = (result as { target?: { publishedVersion?: { versionNumber?: number; versionName?: string; rulesCount?: number } } })?.target?.publishedVersion;
|
||||
const rulesList = (result as { ruleMapping?: unknown[] })?.ruleMapping ?? [];
|
||||
console.error(
|
||||
`✅ 测试企业同步完成: 生产「${prodCorp.name}」(${prodCorp.id}) -> 测试「${testCorp.name}」(${testCorp.id})\n` +
|
||||
`📦 已发布测试版本: v${targetVersion?.versionNumber ?? "?"} (${targetVersion?.versionName ?? "最新"}) | 规则总数: ${targetVersion?.rulesCount ?? rulesList.length} 条\n` +
|
||||
`🔄 规则映射已归档: 共 ${rulesList.length} 条规则已与测试环境对齐\n` +
|
||||
`👉 下一步模拟测试建议: seal-use simulation create --document-sn <单号> --corp ${testCorp.id} --extract-expenses`
|
||||
);
|
||||
printJson(result, outputOptions(args.options));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -66,6 +66,26 @@ export async function handleSimulationCommand(
|
||||
const wait = booleanOption(args.options.wait) === true;
|
||||
const noWait = booleanOption(args.options.noWait) ?? booleanOption(args.options["no-wait"]) ?? (wait ? false : true);
|
||||
|
||||
const extractExpenses =
|
||||
booleanOption(args.options.extract) ??
|
||||
booleanOption(args.options["extract-expenses"]) ??
|
||||
booleanOption(args.options.extractExpenses) ??
|
||||
booleanOption(args.options["with-expense-extraction"]) ??
|
||||
booleanOption(args.options.withExpenseExtraction);
|
||||
const skipExpenseOption =
|
||||
booleanOption(args.options["skip-extract"]) ??
|
||||
booleanOption(args.options.skipExtract) ??
|
||||
booleanOption(args.options.skipExpenseExtraction) ??
|
||||
booleanOption(args.options["skip-expense-extraction"]);
|
||||
const skipExpenseExtraction =
|
||||
extractExpenses !== undefined ? !extractExpenses : skipExpenseOption;
|
||||
|
||||
if (extractExpenses === true) {
|
||||
console.error(
|
||||
"💡 [simulation] 已开启后台费用明细提取入库 (--extract)。此批次明细将写入费用库,供后续跨单防重报检索。"
|
||||
);
|
||||
}
|
||||
|
||||
const result = await runCapabilityResult(
|
||||
"sealSimulationBatchCreate",
|
||||
client,
|
||||
@@ -78,7 +98,7 @@ export async function handleSimulationCommand(
|
||||
rejectNodeName: stringOption(args.options.rejectNode) ?? stringOption(args.options["reject-node"]) ?? null,
|
||||
thinkingDepthOverride: stringOption(args.options.thinkingDepth) ?? stringOption(args.options["thinking-depth"]),
|
||||
skipInvoiceGeneration: booleanOption(args.options.skipInvoiceGeneration) ?? booleanOption(args.options["skip-invoice-generation"]),
|
||||
skipExpenseExtraction: booleanOption(args.options.skipExpenseExtraction) ?? booleanOption(args.options["skip-expense-extraction"]),
|
||||
skipExpenseExtraction,
|
||||
disableAttachmentCache: booleanOption(args.options.disableAttachmentCache) ?? booleanOption(args.options["disable-attachment-cache"]),
|
||||
signKey,
|
||||
packageIds,
|
||||
|
||||
+2
-2
@@ -654,9 +654,9 @@ export const HELP_REGISTRY: AreaHelp[] = [
|
||||
},
|
||||
{
|
||||
name: "create",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window)",
|
||||
summary: "Trigger a simulation batch (reuses an identical batch within the reuse window; defaults to skipping background expense DB extraction)",
|
||||
usage: [
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-invoice-generation|--skip-invoice-generation false] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode hosecloud --flow-ids \"B26017701,B26022501\" [--wait] [--timeout 10m] [--poll-interval 2s] [--reject-node 财务] [--thinking-depth default|medium|high] [--skip-extract|--extract] [--skip-invoice-generation] [--no-wait] [--force] [--reuse-window 5m] [--corp <corpId>]",
|
||||
"seal-use simulation create --mode material_pack --package-ids <materialPackageId> [--template-id conference_reimbursement_v1] [--schema-config file.json] [--corp <corpId>]",
|
||||
"seal-use simulation create --source-system weaver --request-ids \"req-01,req-02\" [--corp <corpId>]"
|
||||
]
|
||||
|
||||
+7
-7
@@ -26,14 +26,14 @@ export const BOOLEAN_FLAGS = new Set([
|
||||
"auto-login", "autoLogin", "bg-save", "changelog", "check", "check-only",
|
||||
"completed-only", "completedOnly", "confirm", "count", "disable-attachment-cache", "disableAttachmentCache",
|
||||
"download", "downloads", "dry-run", "dryRun", "elevate-hose", "enabled",
|
||||
"exclude-deleted", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||
"exclude-deleted", "extract", "extract-expenses", "extractExpenses", "fail-on-flips", "flow", "force", "full", "has-input", "has-output", "help",
|
||||
"hose", "hose-sso", "hoseSso", "include-deleted", "include-io-preview", "include-simulation", "include-unchanged",
|
||||
"includeBridge", "includeSimulation", "includeUnchanged", "local", "no-attachments", "no-flow",
|
||||
"no-wait", "noWait", "overwrite", "plain", "publish", "quiet",
|
||||
"r", "recode", "refresh", "refresh-if-missing", "reveal", "rotate-secret", "rotateSecret",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-flow",
|
||||
"save", "silent", "silent-save", "simulation", "skip-expense-extraction", "skip-extract", "skip-invoice-generation",
|
||||
"skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration", "snippet-only", "snippetOnly", "sso", "strict",
|
||||
"summary", "to-downloads", "toDownloads", "v", "wait", "with-expense-extraction", "withExpenseExtraction", "with-flow",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
@@ -98,7 +98,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"documentId", "documentLimit", "documentSn", "documentType", "domain", "download",
|
||||
"downloads", "dry-run", "dryRun", "elevate-hose", "enable", "enabled",
|
||||
"end", "end-date", "end-time", "endDate", "endTime", "env",
|
||||
"environment", "exclude-deleted", "expire", "expiresIn", "f", "fail-on-flips",
|
||||
"environment", "exclude-deleted", "extract", "extract-expenses", "extractExpenses", "expire", "expiresIn", "f", "fail-on-flips",
|
||||
"fields", "file", "file-id", "file-name", "flow", "flow-concurrency", "flow-ids", "flow-status-list",
|
||||
"flowIds", "flowStatusList", "force", "format", "from", "from-link",
|
||||
"full", "h", "has-input", "has-output", "help", "hose", "hose-sso", "hoseSso",
|
||||
@@ -124,7 +124,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"ruleVersion", "runtime-id", "runtimeId", "samples", "save", "scenarios",
|
||||
"schema-config", "schemaConfig", "scope", "sealUrl", "search", "secret",
|
||||
"selector", "session-id", "sign-key", "signKey", "silent", "silent-save", "simulation",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-invoice-generation", "skipExpenseExtraction", "skipInvoiceGeneration",
|
||||
"simulationBatchId", "since", "skip-expense-extraction", "skip-extract", "skip-invoice-generation", "skipExpenseExtraction", "skipExtract", "skipInvoiceGeneration",
|
||||
"sn", "sn-prefix", "sn-suffix", "snPrefix", "snSuffix", "snippet-only",
|
||||
"snippetOnly", "sns", "source-corp", "source-system", "sourceCorp", "sourceDocumentId",
|
||||
"sourceDocumentSN", "sourceSystem", "sso", "staff-id", "staff-name", "staff-phone",
|
||||
@@ -137,7 +137,7 @@ export const KNOWN_FLAGS = new Set([
|
||||
"to", "to-downloads", "toDownloads", "token", "tokenId", "trace-id", "trace-limit", "type",
|
||||
"until", "url", "userId", "v", "version", "version-name",
|
||||
"verdict",
|
||||
"versionName", "wait", "webhook", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"versionName", "wait", "webhook", "with-expense-extraction", "withExpenseExtraction", "with-flow", "workflow-type-id", "workflowTypeId",
|
||||
"workspace", "yes"
|
||||
]);
|
||||
|
||||
|
||||
@@ -60,6 +60,13 @@ export class LangfuseClient {
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new CliError(detail, 11, "检查注入的 Langfuse 密钥是否仍然有效");
|
||||
}
|
||||
if (response.status === 404) {
|
||||
const isProjectMismatch = body.includes("authorized project") || body.includes("not found");
|
||||
const suggestion = isProjectMismatch
|
||||
? "当前使用内置生产 Langfuse 凭据。若单据来自测试或 Staging 环境(如 staging.sealai.cc),其 Trace 属于 Staging 项目,无法通过内置生产凭据查询。可设置 LANGFUSE_BASE_URL、LANGFUSE_PUBLIC_KEY、LANGFUSE_SECRET_KEY 环境变量临时覆盖凭据。"
|
||||
: "确认 Trace ID / Session ID 是否正确,或已过生命周期保留期";
|
||||
throw new CliError(detail, 1, suggestion);
|
||||
}
|
||||
throw new CliError(detail, 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -735,6 +735,53 @@ describe("sealCapabilities", () => {
|
||||
});
|
||||
});
|
||||
|
||||
test("approval run cited rules attaches mappedProdCode when test snapshot exists", async () => {
|
||||
const mappingDir = mkdtempSync(join(tmpdir(), "seal-mapping-cited-"));
|
||||
process.env.SEAL_USE_MAPPINGS_DIR = mappingDir;
|
||||
try {
|
||||
saveRuleMappingSnapshot({
|
||||
syncedAt: "2026-10-10T10:00:00+08:00",
|
||||
source: { id: "corp-prod", name: "Prod Corp" },
|
||||
target: { id: "corp-test", name: "Test Corp", publishedVersionNumber: 16, rulesCount: 1 },
|
||||
versionMapping: {
|
||||
sourceProdVersionNumber: 22,
|
||||
sourceProdVersionName: "Prod v22",
|
||||
targetTestVersionNumber: 16,
|
||||
targetTestVersionName: "Test v16"
|
||||
},
|
||||
ruleMapping: [{
|
||||
index: 0,
|
||||
sourceRuleId: "prod-rule-17",
|
||||
sourceRuleCode: 17,
|
||||
targetRuleId: "test-rule-38",
|
||||
targetRuleCode: "0038",
|
||||
description: "Prod rule 17",
|
||||
scope: "travel",
|
||||
strictness: "MUST_FOLLOW"
|
||||
}]
|
||||
});
|
||||
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunCitedRulesGet");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
const handler = tool!.handler as CapabilityHandler;
|
||||
const context = { corp: { ...fakeContext().corp, id: "corp-test", environment: "test" as const } };
|
||||
const result = await handler(
|
||||
fakeApprovalRunsClient(),
|
||||
{ recordId: "run-1" },
|
||||
context
|
||||
) as { count: number; rules: Array<Record<string, unknown>> };
|
||||
|
||||
expect(result.rules[0]).toMatchObject({
|
||||
code: "0038",
|
||||
mappedProdCode: "0017",
|
||||
mappedProdRuleId: "prod-rule-17"
|
||||
});
|
||||
} finally {
|
||||
delete process.env.SEAL_USE_MAPPINGS_DIR;
|
||||
}
|
||||
});
|
||||
|
||||
test("approval run document summary returns key fields without raw payload", async () => {
|
||||
const tool = sealCapabilities.find((item) => item.name === "sealApprovalRunDocumentSummaryGet");
|
||||
expect(tool).toBeDefined();
|
||||
|
||||
@@ -377,10 +377,11 @@ export const approvalRunsCapabilities = [
|
||||
}),
|
||||
handler: async (
|
||||
client: KyInstance,
|
||||
params: { recordId: string }
|
||||
params: { recordId: string },
|
||||
context: CapabilityContext
|
||||
) => {
|
||||
const record = await api.getApprovalRun(client, params.recordId);
|
||||
return extractCitedRules(record);
|
||||
return extractCitedRules(record, context.corp);
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -654,7 +655,7 @@ export const approvalRunsCapabilities = [
|
||||
|
||||
const documentSummary = summarizeApprovalRunDocument(detail);
|
||||
const resultSummary = summarizeApprovalRunResult(detail);
|
||||
const citedRules = extractCitedRules(detail);
|
||||
const citedRules = extractCitedRules(detail, context.corp);
|
||||
|
||||
let ruleVersion: {
|
||||
version: ReturnType<typeof summarizeRuleVersion>;
|
||||
|
||||
@@ -635,10 +635,30 @@ export function summarizeApprovalRunResult(record: ApprovalRun) {
|
||||
};
|
||||
}
|
||||
|
||||
export function prioritizeKeyFields(fields: Array<Record<string, unknown>>, maxCount = 60) {
|
||||
const priorityKeywords = ["金额", "费用", "报销", "申请", "借款", "付款", "部门", "事由", "收款", "公司", "抬头", "税", "类别", "项目", "说明", "币种"];
|
||||
const prioritized: Array<Record<string, unknown>> = [];
|
||||
const others: Array<Record<string, unknown>> = [];
|
||||
|
||||
for (const field of fields) {
|
||||
const label = stringFromUnknown(field.label) ?? "";
|
||||
const path = stringFromUnknown(field.path) ?? "";
|
||||
const isPriority = priorityKeywords.some((k) => label.includes(k) || path.toLowerCase().includes(k.toLowerCase()));
|
||||
if (isPriority) {
|
||||
prioritized.push(field);
|
||||
} else {
|
||||
others.push(field);
|
||||
}
|
||||
}
|
||||
|
||||
return [...prioritized, ...others].slice(0, maxCount);
|
||||
}
|
||||
|
||||
export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
const document = asRecord(record.document);
|
||||
const fields = flattenDocumentFields(record.document);
|
||||
const fieldText = fields.map((field) => `${field.label ?? field.path ?? ""}:${field.value ?? ""}`).join("\n");
|
||||
const prioritizedFields = prioritizeKeyFields(fields, 60);
|
||||
return {
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
@@ -648,11 +668,44 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
sn: document?.sn ?? document?.sourceDocumentSN ?? record.sourceDocumentSN,
|
||||
title: document?.title ?? document?.name,
|
||||
template: firstPath(document, ["template.name", "templateName", "form.name", "formName", "formTitle"]),
|
||||
amount: firstByLabel(fields, ["金额", "报销金额", "付款金额", "合计", "价税合计"]) ?? firstPath(document, ["amount", "totalAmount", "expenseAmount"]),
|
||||
expenseType: firstByLabel(fields, ["费用类型", "费用类别", "报销类型"]),
|
||||
amount:
|
||||
firstByLabel(fields, [
|
||||
"金额",
|
||||
"报销金额",
|
||||
"付款金额",
|
||||
"申请金额",
|
||||
"借款金额",
|
||||
"实报金额",
|
||||
"总金额",
|
||||
"费用金额",
|
||||
"单据金额",
|
||||
"合计",
|
||||
"价税合计",
|
||||
"明细合计",
|
||||
"总计"
|
||||
]) ??
|
||||
firstPath(document, ["amount", "totalAmount", "expenseAmount", "applyAmount", "paymentAmount"]) ??
|
||||
fields.find((f) => {
|
||||
const path = stringFromUnknown(f.path)?.toLowerCase() ?? "";
|
||||
return path.endsWith(".amount") || path.endsWith(".totalamount");
|
||||
})?.value,
|
||||
expenseType:
|
||||
firstByLabel(fields, [
|
||||
"费用类型",
|
||||
"费用类别",
|
||||
"报销类型",
|
||||
"报销类别",
|
||||
"支出类别",
|
||||
"费用科目",
|
||||
"单据类型",
|
||||
"业务类型"
|
||||
]) ??
|
||||
firstPath(document, ["expenseType", "expenseCategory", "categoryName", "businessType"]),
|
||||
costCompany: firstByLabel(fields, ["费用承担公司", "承担公司", "成本中心", "费用归属"]),
|
||||
payee: firstByLabel(fields, ["收款方", "收款账户", "收款信息", "开户名", "银行账号"]),
|
||||
keyFields: fields.slice(0, 30)
|
||||
keyFields: prioritizedFields,
|
||||
totalFieldsCount: fields.length,
|
||||
fieldsTruncated: fields.length > prioritizedFields.length
|
||||
}),
|
||||
invoices: collectInvoiceSummary(record),
|
||||
attachments: extractApprovalRunAttachments(record, { summary: true }).attachments,
|
||||
@@ -665,7 +718,7 @@ export function summarizeApprovalRunDocument(record: ApprovalRun) {
|
||||
};
|
||||
}
|
||||
|
||||
export function extractCitedRules(record: ApprovalRun) {
|
||||
export function extractCitedRules(record: ApprovalRun, corp?: CorpConfig | string) {
|
||||
const candidates: Array<[string, unknown]> = [
|
||||
["result.rulesResult", getPath(record, "result.rulesResult")],
|
||||
["result.hitRules", getPath(record, "result.hitRules")],
|
||||
@@ -740,6 +793,35 @@ export function extractCitedRules(record: ApprovalRun) {
|
||||
});
|
||||
}
|
||||
|
||||
const corpId = typeof corp === "string" ? corp : corp?.id;
|
||||
if (corpId) {
|
||||
try {
|
||||
const snapshot = loadRuleMappingSnapshot(corpId, record.ruleSetVersionNumber ?? "latest");
|
||||
if (snapshot && snapshot.ruleMapping) {
|
||||
for (const rule of rules) {
|
||||
const ruleCode = stringFromUnknown(rule.code);
|
||||
const runtimeRuleId = stringFromUnknown(rule.runtimeRuleId);
|
||||
const codeNum = parseRuleCodeNumber(ruleCode ?? runtimeRuleId);
|
||||
const matchedItem = snapshot.ruleMapping.find((m) => {
|
||||
if (ruleCode && (String(m.targetRuleCode) === ruleCode || m.targetRuleCode === ruleCode)) return true;
|
||||
if (runtimeRuleId && (m.targetRuleId === runtimeRuleId || `rule-${m.targetRuleCode}` === runtimeRuleId)) return true;
|
||||
if (codeNum !== undefined) {
|
||||
const targetNum = parseRuleCodeNumber(m.targetRuleCode);
|
||||
if (targetNum !== undefined && targetNum === codeNum) return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
if (matchedItem) {
|
||||
const mappedCodeNum = parseRuleCodeNumber(matchedItem.sourceRuleCode);
|
||||
rule.mappedProdCode = mappedCodeNum !== undefined ? formatRuleCode(mappedCodeNum) : String(matchedItem.sourceRuleCode);
|
||||
rule.mappedProdRuleId = matchedItem.sourceRuleId;
|
||||
rule.mappingNote = `测试规则 ${ruleCode ?? runtimeRuleId} 对应生产规则 ${rule.mappedProdCode}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
}
|
||||
|
||||
return {
|
||||
recordId: record.id,
|
||||
sourceDocumentSN: record.sourceDocumentSN,
|
||||
|
||||
@@ -61,7 +61,7 @@ export const simulationCapabilities = [
|
||||
rejectNodeName: z.string().nullable().optional().describe("仅关注特定节点: 节点名称, 不设为 null 表示不限制"),
|
||||
thinkingDepthOverride: z.enum(["default", "medium", "high"]).optional().describe("思考深度: default=按偏好设置, medium=标准, high=深度推理"),
|
||||
skipInvoiceGeneration: z.boolean().optional().describe("跳过发票生成, 默认 true"),
|
||||
skipExpenseExtraction: z.boolean().optional().describe("跳过费用提取, 默认 true"),
|
||||
skipExpenseExtraction: z.boolean().optional().describe("跳过后台历史费用明细库提取(防重报检索用), 默认 true"),
|
||||
disableAttachmentCache: z.boolean().optional().describe("不使用附件缓存, 默认 false"),
|
||||
signKey: z.string().optional().describe("合思集成标识; 缺省时自动取第一个合思集成"),
|
||||
packageIds: z.array(z.string()).optional().describe("材料包模式: 材料包 id 列表(来自 material-packages upload 响应)"),
|
||||
@@ -317,8 +317,30 @@ export const simulationCapabilities = [
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 正在轮询等待结果(单据及附件解析预计耗时 1~3 分钟;若命令转入后台可等待完成通知,或随时执行 seal-use simulation status ${params.batchId} 查看进度)...`
|
||||
);
|
||||
let retryCount = 0;
|
||||
while (true) {
|
||||
const batch = await api.getSimulationBatch(client, params.batchId);
|
||||
let batch;
|
||||
try {
|
||||
batch = await api.getSimulationBatch(client, params.batchId);
|
||||
} catch (err: unknown) {
|
||||
const isInitialPhase = Date.now() - startedAt < 15000;
|
||||
const statusStr = String(
|
||||
(err && typeof err === "object" && "status" in err ? (err as { status: unknown }).status : "") ??
|
||||
(err instanceof Error ? err.message : "")
|
||||
);
|
||||
const isNotFoundOrForbidden =
|
||||
statusStr.includes("403") || statusStr.includes("404") || statusStr.toLowerCase().includes("not found");
|
||||
if (isInitialPhase && isNotFoundOrForbidden && retryCount < 4) {
|
||||
retryCount++;
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 刚创建,等待服务端落库就绪 (重试 ${retryCount}/4)...`
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 2000));
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
const status = (batch.status ?? "").toLowerCase();
|
||||
if (["completed", "failed", "cancelled", "canceled"].includes(status)) {
|
||||
return {
|
||||
@@ -332,7 +354,22 @@ export const simulationCapabilities = [
|
||||
};
|
||||
}
|
||||
if (Date.now() - startedAt >= timeoutMs) {
|
||||
throw new Error(`等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。可稍后执行 seal-use simulation get ${params.batchId} 查看状态`);
|
||||
console.error(
|
||||
`⏳ [Simulation] 批次 ${params.batchId} 等待超时(已等待 ${(Date.now() - startedAt) / 1000}s)。批次仍在服务端执行中。`
|
||||
);
|
||||
return {
|
||||
batchId: params.batchId,
|
||||
completed: false,
|
||||
timedOut: true,
|
||||
status: status || "running",
|
||||
elapsedMs: Date.now() - startedAt,
|
||||
message: `等待模拟批次 ${params.batchId} 超时(已等待 ${(Date.now() - startedAt) / 1000}s)。任务仍在后台执行。`,
|
||||
next: {
|
||||
status: `seal-use simulation status ${params.batchId}`,
|
||||
getRecords: `seal-use simulation batch-records ${params.batchId}`,
|
||||
wait: `seal-use simulation wait ${params.batchId}`
|
||||
}
|
||||
};
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user