Merge pull request #261 from yunyingk/mac15/simulation-local-search

Add local search for simulation batches
This commit is contained in:
yunyingk authored and GitHub committed 2026-10-23 16:43:50 +08:00
commit fed0a8464c
12 files changed
+606 -19

No files matched your search

+9 -2
View File
@@ -137,7 +137,9 @@ seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s] [--corp
seal-use simulation clean <batchId> --yes [--corp <corpId>]
seal-use simulation specifications [--integration <sign-key>] [--corp <corpId>]
seal-use simulation approval-definitions [--corp <corpId>]
seal-use simulation list [--limit 50] [--corp <corpId>]
seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]
seal-use simulation search "任务 fe1993e4" --since 2026-10-01 [--corp <corpId>]
seal-use simulation get <batchId> [--corp <corpId>]
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
@@ -420,7 +422,8 @@ Approval runs, simulations, and Langfuse bridge:
- `seal-use simulation approval-definitions --corp <corpId>` lists available Feishu approval definitions so an `approvalCode` can be selected before creating a batch.
- `seal-use simulation wait <batchId> --corp <corpId>`
- `seal-use simulation clean <batchId> --yes --corp <corpId>`
- `seal-use simulation list --corp <corpId>`
- `seal-use simulation list [--query <text>] [--since <time>] [--until <time>] [--all] --corp <corpId>` (过滤在本地完成,见下方“本地聚合”说明)
- `seal-use simulation search "<关键词>" [--since 7d] [--all] --corp <corpId>` (**本地聚合检索,非云端原生**;先按 limit/offset 拉取批次再过滤,响应 `retrieval.serverSideSearch: false`)
- `seal-use simulation get <batchId> --corp <corpId>`
- `seal-use simulation batch-records <batchId> --corp <corpId>`
- `seal-use simulation templates --corp <corpId>`
@@ -521,8 +524,12 @@ seal-use simulation get <batchId> --corp <corpId>
seal-use simulation batch-records <batchId> --corp <corpId>
seal-use simulation templates --corp <corpId>
seal-use simulation integrations --corp <corpId>
# 本地检索批次(服务端无原生 search): 界面「任务 fe1993e4」可直接粘贴
seal-use simulation search "任务 fe1993e4" --since 7d --all --corp <corpId>
```
> **本地聚合,不是云端原生检索**:`/api/v1/simulation/batches` 只有 `limit`/`offset`,没有名称或关键词检索,批次对象也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。`list --query/--since/--until` 与 `search` 都是 CLI 先把批次拉到本地再过滤,返回体固定带 `retrieval: { mode: "local_scan", serverSideSearch: false, scanned }`;命中范围以 `scanned` 为准,不覆盖未扫描的批次(`truncated: true` 时用 `--all` 或调大 `--max-scan`)。不要把它当作服务端能力向用户描述。
## Failure Handling
- If no run is found by `sourceDocumentSN`, retry with `sourceDocumentId` or a broader `query`.
@@ -170,6 +170,8 @@ flowchart TD
seal-use simulation create --corp <testCorpId> --mode hosecloud --flow-ids "<单号1>,<单号2>" --wait
```
> **打断/重发防重复扣费**:批次创建默认幂等——复用窗口(默认 5 分钟,`--reuse-window` 可调)内对同一组 `--flow-ids`/`--package-ids` 再次执行 `simulation create` 会直接返回既有批次(`reused: true`),不会重复扣费。若 `--wait` 挂起期间命令被用户消息打断或后台 task 被 kill,**先执行 `seal-use simulation list --limit 3` 查最近批次**(同单批次可能已在服务端跑完),拿到批次 ID 后用 `status`/`batch-records` 取结果;确认无在途同单批次再决定重发。确需立刻重跑同组单号时显式加 `--force`。
>
> **按界面名称找历史批次**:模拟测试服务端没有名称/关键词检索,批次也没有 `name` 字段(界面的「任务 fe1993e4」是 UUID 末 8 位)。用 `seal-use simulation search "任务 fe1993e4" --since 7d` 或 `seal-use simulation list --query <关键词> --since <时间>`;这是 **CLI 本地聚合检索**(先按 `limit`/`offset` 拉取再过滤,响应带 `retrieval.serverSideSearch: false`),命中范围以 `scanned` 为准,需要覆盖更早批次时加 `--all`(可用 `--max-scan` 控上限)。
- **方式 C:Webhook 原始报文重放 (Webhook Replay,仅限事件通知调测)**:
直接将正式企业的特定单据/不良案例表单抽取并推送到测试企业 Webhook 通道:
+79
View File
@@ -76,6 +76,85 @@ function trackMutationRequests() {
return mutations;
}
function mockSimulationBatches() {
const requested: string[] = [];
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;
requested.push(url);
const body = url.includes("/api/v1/simulation/batches")
? {
data: [
{
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-10T06:38:17.757Z"
},
{
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
createdAt: "2026-10-09T02:56:58.000Z"
}
]
}
: { data: {} };
return new Response(JSON.stringify(body), {
status: 200,
headers: { "Content-Type": "application/json" }
});
}) as typeof fetch;
return requested;
}
describe("simulation local search", () => {
test("search matches the console「任务 fe1993e4」label locally", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务 fe1993e4"]);
expect(result.isError).toBe(false);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as {
count: number;
scanned: number;
retrieval: { mode: string; serverSideSearch: boolean };
batches: Array<{ id: string }>;
};
expect(payload.count).toBe(1);
expect(payload.retrieval).toMatchObject({ mode: "local_scan", serverSideSearch: false });
expect(payload.batches[0]?.id).toBe("01a12488-a69d-74c4-88b1-118bfe1993e4");
expect(result.stderr).toContain("本地聚合检索");
expect(requested.every((url) => url.includes("/api/v1/simulation/batches"))).toBe(true);
});
test("search respects a local time window", async () => {
setupMockEnv();
mockSimulationBatches();
const result = await runCli(["simulation", "search", "任务", "--since", "2026-10-09", "--until", "2026-10-09"]);
expect(result.exitCode).toBe(0);
const payload = JSON.parse(result.stdout) as { count: number; batches: Array<{ id: string }> };
expect(payload.count).toBe(1);
expect(payload.batches[0]?.id).toBe("01a123be-0742-743a-ac16-87f7c4e121c7");
});
test("search without a keyword is a usage error", async () => {
setupMockEnv();
const requested = mockSimulationBatches();
const result = await runCli(["simulation", "search"]);
expect(result.isError).toBe(true);
expect(result.exitCode).toBe(2);
expect(requested).toEqual([]);
});
});
describe("simulation command confirmation gates", () => {
test("simulation clean refuses without --yes and never reaches the API", async () => {
setupMockEnv();
+21 -2
View File
@@ -205,13 +205,32 @@ export async function handleSimulationCommand(
return;
}
if (action === "list") {
if (action === "list" || action === "search") {
const query =
stringOption(args.options.query) ??
stringOption(args.options.q) ??
(action === "search" ? maybeName : undefined);
if (action === "search" && (!query || !query.trim())) {
throw usageError(
"Usage: seal-use simulation search <keyword> [--since 7d] [--until <time>] [--all]"
);
}
const limit = numberOption(args.options.limit);
// search 默认扫到底(受 --max-scan 保护), 避免只搜到最近 50 个;显式 --limit 时按用户范围
const all = booleanOption(args.options.all) ?? (action === "search" ? limit === undefined : false);
await runCapability(
"sealSimulationBatchesList",
client,
corp,
{
limit: numberOption(args.options.limit)
limit,
all,
maxScan: numberOption(args.options.maxScan) ?? numberOption(args.options["max-scan"]),
query,
since: stringOption(args.options.since) ?? stringOption(args.options["created-after"]),
until: stringOption(args.options.until) ?? stringOption(args.options["created-before"])
},
outputOptions(args.options)
);
+11 -3
View File
@@ -772,7 +772,7 @@ export const HELP_REGISTRY: AreaHelp[] = [
{
area: "simulation",
title: "Simulation testing engine",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules.",
description: "Execute and analyze offline or HoseCloud batch simulations against approval rules. Note: batch search is a local scan over the list API — the server exposes no name/keyword search.",
commands: [
{
name: "batch-records",
@@ -815,8 +815,16 @@ export const HELP_REGISTRY: AreaHelp[] = [
},
{
name: "list",
summary: "List recent simulation batches",
usage: ["seal-use simulation list [--limit 50] [--corp <corpId>]"]
summary: "List recent simulation batches (filtering is LOCAL only: batches are pulled by limit/offset, the server has no query API)",
usage: ["seal-use simulation list [--limit 50] [--all] [--query <text>] [--since <time>] [--until <time>] [--max-scan <n>] [--corp <corpId>]"]
},
{
name: "search",
summary: "Search simulation batches LOCALLY (not a server-side/native search): scans batches then filters by UI name fragment, document SN, package/template or time window",
usage: [
"seal-use simulation search <keyword> [--since 7d] [--until <time>] [--limit <n>] [--max-scan <n>] [--corp <corpId>]",
"seal-use simulation search \"任务 fe1993e4\" --since 2026-10-01 [--corp <corpId>]"
]
},
{
name: "get",
+1
View File
@@ -53,6 +53,7 @@ const READ_ONLY_COMMANDS: Record<string, string[]> = {
"specifications",
"approval-definitions",
"list",
"search",
"get",
"templates",
"integrations"
+4 -4
View File
@@ -780,12 +780,12 @@ export async function createMaterialPackBatch(
export async function listSimulationBatches(
client: KyInstance,
opts: { limit?: number } = {}
opts: { limit?: number; offset?: number } = {}
): Promise<SimulationBatch[]> {
const searchParams: Record<string, string> = { limit: String(opts.limit ?? 50) };
if (opts.offset !== undefined && opts.offset > 0) searchParams.offset = String(opts.offset);
const json = (await client
.get("api/v1/simulation/batches", {
searchParams: { limit: String(opts.limit ?? 50) }
})
.get("api/v1/simulation/batches", { searchParams })
.json()) as { data?: unknown };
const data = json.data ?? json;
return z.array(SimulationBatchSchema).parse(data);
@@ -745,6 +745,77 @@ describe("simulation tool handlers", () => {
}
});
});
test("list tool scans pages and filters locally by UI name and time window", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
expect(tool).toBeDefined();
const newer = {
...hosecloudBatchFixture,
id: "01a12488-a69d-74c4-88b1-118bfe1993e4",
createdAt: "2026-10-10T06:38:17.757Z"
};
const older = {
...hosecloudBatchFixture,
id: "01a123be-0742-743a-ac16-87f7c4e121c7",
createdAt: "2026-10-09T02:56:58.000Z"
};
const calls: string[] = [];
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push(`${limit}@${offset}`);
const all = [newer, older];
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as CapabilityHandler;
const result = await handler(
client,
{ query: "任务 fe1993e4", since: "2026-10-10", until: "2026-10-10" },
fakeContext()
) as Record<string, unknown>;
expect(calls).toEqual(["50@0"]);
expect(result).toMatchObject({
retrieval: { mode: "local_scan", serverSideSearch: false, scanned: 2 },
scanned: 2,
truncated: false,
count: 1,
filters: {
query: "任务 fe1993e4",
since: "2026-10-10T00:00:00+08:00",
until: "2026-10-10T23:59:59+08:00"
}
});
expect((result.batches as Array<{ id: string }>)[0]?.id).toBe(newer.id);
});
test("list tool paginates when all=true is requested", async () => {
const tool = sealCapabilities.find((item) => item.name === "sealSimulationBatchesList");
const calls: string[] = [];
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push(`${limit}@${offset}`);
// Every page comes back full so the scanner keeps advancing until maxScan.
const data = Array.from({ length: limit }, (_, index) => ({
...hosecloudBatchFixture,
id: `batch-${offset + index}`
}));
return { json: async () => ({ data }) };
}
} as unknown as KyInstance;
const handler = tool!.handler as CapabilityHandler;
const result = await handler(client, { all: true, maxScan: 250 }, fakeContext()) as Record<string, unknown>;
expect(calls).toEqual(["100@0", "100@100", "50@200"]);
expect(result).toMatchObject({ scanned: 250, scanLimit: 250, truncated: true, count: 250 });
});
});
describe("simulation response schemas", () => {
+78 -7
View File
@@ -2,12 +2,21 @@ import { validationError } from "../../../core/errors.js";
import { z } from "zod";
import type { KyInstance } from "ky";
import { readFileSync } from "node:fs";
import { formatBeijingIso } from "../../../core/config/timestamps.js";
import * as api from "../api.js";
import {
type SimulationBatch
} from "../types.js";
import * as helpers from "./helpers.js";
import { parseDurationMs } from "../../../core/duration.js";
import {
collectSimulationBatches,
DEFAULT_SIMULATION_MAX_SCAN,
DEFAULT_SIMULATION_SCAN_LIMIT,
filterSimulationBatches,
MAX_SIMULATION_SCAN,
parseSimulationTimeBound
} from "../simulation/batch-search.js";
const {
buildSimulationBatchParams,
@@ -187,18 +196,80 @@ export const simulationCapabilities = [
},
{
name: "sealSimulationBatchesList",
description: "列出 Seal 模拟测试批次摘要(含状态、统计计数与展示摘要)",
description: "【本地聚合检索, 非云端原生能力】列出或检索 Seal 模拟测试批次摘要。服务端 /simulation/batches 只支持 limit/offset, 没有名称/关键词检索, 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是 UUID 末 8 位)。CLI 先把批次拉到本地再按关键词与时间窗过滤, 结果完整度取决于 scanned 范围: 默认扫描最近 50 个批次, all=true 分页扫到底。返回体带 retrieval.mode=local_scan / serverSideSearch=false 标记, 不要把它当成服务端搜索。",
parameters: z.object({
limit: z.number().int().positive().max(100).optional().describe("最多返回批次数量, 默认 50")
limit: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
.describe(`本地扫描的最近批次数量(不是返回条数上限), 默认 ${DEFAULT_SIMULATION_SCAN_LIMIT}`),
all: z.boolean().optional()
.describe(`分页扫描到底(仍受 maxScan 保护), 用于检索较早批次`),
maxScan: z.number().int().positive().max(MAX_SIMULATION_SCAN).optional()
.describe(`all=true 时的扫描上限, 默认 ${DEFAULT_SIMULATION_MAX_SCAN}`),
query: z.string().optional()
.describe("本地关键词检索(CLI 端过滤, 非服务端): 空格/逗号分隔的多个关键词同时命中(AND); 匹配批次 ID(含无连字符形式)、界面「任务」后缀、单号、材料包/模板、条件摘要等"),
since: z.string().optional()
.describe("创建时间下界(含): ISO、YYYY-MM-DD、毫秒, 或相对时长如 7d"),
until: z.string().optional()
.describe("创建时间上界(含): 格式同 since")
}),
handler: async (client: KyInstance, params: { limit?: number }) => {
const batches = await api.listSimulationBatches(client, { limit: params.limit ?? 50 });
handler: async (
client: KyInstance,
params: {
limit?: number;
all?: boolean;
maxScan?: number;
query?: string;
since?: string;
until?: string;
}
) => {
const sinceMs = parseSimulationTimeBound(params.since, { endOfDay: false });
const untilMs = parseSimulationTimeBound(params.until, { endOfDay: true });
const scanLimit = params.all
? (params.maxScan ?? DEFAULT_SIMULATION_MAX_SCAN)
: (params.limit ?? DEFAULT_SIMULATION_SCAN_LIMIT);
const { batches, capped } = await collectSimulationBatches(client, scanLimit);
const matched = filterSimulationBatches(batches, {
query: params.query,
sinceMs,
untilMs
});
const searching = Boolean(params.query?.trim()) || sinceMs !== undefined || untilMs !== undefined;
if (searching) {
console.error(
`ℹ️ [Simulation] 本地聚合检索(非云端原生): 服务端无关键词/名称检索, 已拉取最近 ${batches.length} 个批次并在本地过滤。`
);
}
if (capped) {
console.error(
`🔎 [Simulation] 已扫描 ${batches.length} 个批次(达到扫描上限), 更早的批次未参与检索; 可用 --all 或调大 --max-scan。`
);
}
return {
count: batches.length,
batches: batches.map(summarizeSimulationBatch),
retrieval: {
mode: "local_scan",
serverSideSearch: false,
scanned: batches.length,
note: searching
? "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次结果是 CLI 本地拉取后过滤, 命中范围以 scanned 为准, 不代表服务端全量。"
: "模拟测试服务端只有 limit/offset 列表, 无名称/关键词检索; 本次仅列出最近 scanned 个批次, 不代表服务端全量。"
},
scanned: batches.length,
scanLimit,
truncated: capped,
filters: {
query: params.query ?? null,
since: sinceMs === undefined ? null : formatBeijingIso(sinceMs),
until: untilMs === undefined ? null : formatBeijingIso(untilMs)
},
count: matched.length,
batches: matched.map(summarizeSimulationBatch),
next: {
getBatch: "seal-use simulation get <batchId>",
getRecords: "seal-use simulation batch-records <batchId>"
getRecords: "seal-use simulation batch-records <batchId>",
search: "seal-use simulation search <关键词> [--since 7d] [--all] (本地检索)"
}
};
}
@@ -0,0 +1,155 @@
import { describe, expect, test } from "bun:test";
import { KyInstance } from "ky";
import { CliError } from "../../../core/errors.js";
import { SimulationBatch } from "../types.js";
import {
collectSimulationBatches,
filterSimulationBatches,
parseSimulationTimeBound,
simulationQueryTokens
} from "./batch-search.js";
function batch(id: string, createdAt: string, extra: Partial<SimulationBatch> = {}): SimulationBatch {
return {
id,
status: "completed",
approvalCode: "hosecloud",
sourceSystem: "hosecloud",
totalCount: 1,
processedCount: 1,
successCount: 1,
failedCount: 0,
createdCount: 1,
createFailedCount: 0,
createdAt,
...extra
};
}
const fe1993e4 = batch("01a12488-a69d-74c4-88b1-118bfe1993e4", "2026-10-10T06:38:17.757Z", {
params: {
approvalCode: "hosecloud",
flowIds: ["S26002992"],
packageLabel: "会议材料包.zip"
},
requestSummary: {
mode: "指定单号",
conditions: [{ label: "驳回节点", value: "出纳支付" }]
}
});
const older = batch("01a123be-0742-743a-ac16-87f7c4e121c7", "2026-10-09T02:56:58.000Z", {
params: { approvalCode: "hosecloud", flowIds: ["B26017701"] }
});
describe("simulationQueryTokens", () => {
test("strips the UI 任务 prefix and punctuation", () => {
expect(simulationQueryTokens("任务 fe1993e4")).toEqual(["fe1993e4"]);
expect(simulationQueryTokens("任务:fe1993e4")).toEqual(["fe1993e4"]);
expect(simulationQueryTokens("任务fe1993e4")).toEqual(["fe1993e4"]);
});
test("drops standalone noise words and splits on commas", () => {
expect(simulationQueryTokens("任务, fe1993e4, 出纳")).toEqual(["fe1993e4", "出纳"]);
expect(simulationQueryTokens("task")).toEqual([]);
expect(simulationQueryTokens(undefined)).toEqual([]);
});
});
describe("filterSimulationBatches", () => {
test("matches the last 8 hex chars shown in the console UI", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4" })).toEqual([fe1993e4]);
});
test("matches hyphen-less UUID fragments", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "01a12488a69d" })).toEqual([fe1993e4]);
});
test("matches document SN, package label and request summary values", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "S26002992" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "会议材料包" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "出纳支付" })).toEqual([fe1993e4]);
});
test("requires every keyword to match (AND semantics)", () => {
expect(filterSimulationBatches([fe1993e4, older], { query: "任务 fe1993e4 出纳" })).toEqual([fe1993e4]);
expect(filterSimulationBatches([fe1993e4, older], { query: "fe1993e4 B26017701" })).toEqual([]);
});
test("filters by createdAt window, inclusive", () => {
const since = Date.parse("2026-10-10T00:00:00+08:00");
const until = Date.parse("2026-10-10T23:59:59.999+08:00");
expect(filterSimulationBatches([fe1993e4, older], { sinceMs: since, untilMs: until })).toEqual([fe1993e4]);
});
test("returns everything without filters", () => {
expect(filterSimulationBatches([fe1993e4, older])).toEqual([fe1993e4, older]);
});
});
describe("parseSimulationTimeBound", () => {
test("reads Beijing-local dates, epoch millis and ISO timestamps", () => {
expect(parseSimulationTimeBound("2026-10-10")).toBe(Date.parse("2026-10-10T00:00:00+08:00"));
expect(parseSimulationTimeBound("2026-10-10", { endOfDay: true })).toBe(
Date.parse("2026-10-10T23:59:59.999+08:00")
);
expect(parseSimulationTimeBound("1759000000000")).toBe(1759000000000);
expect(parseSimulationTimeBound("2026-10-10T06:38:17.757Z")).toBe(Date.parse("2026-10-10T06:38:17.757Z"));
});
test("interprets relative durations as now minus the offset", () => {
const now = Date.parse("2026-10-23T16:00:00+08:00");
expect(parseSimulationTimeBound("7d", { nowMs: now })).toBe(now - 7 * 86400_000);
expect(parseSimulationTimeBound("90m", { nowMs: now })).toBe(now - 90 * 60_000);
});
test("rejects unparseable bounds with the validation exit code", () => {
let error: unknown;
try {
parseSimulationTimeBound("上周三");
} catch (caught) {
error = caught;
}
expect(error).toBeInstanceOf(CliError);
expect((error as CliError).exitCode).toBe(13);
});
});
describe("collectSimulationBatches", () => {
function pagedClient(total: number) {
const calls: Array<{ limit: number; offset: number }> = [];
const all = Array.from({ length: total }, (_, index) =>
batch(`batch-${index}`, new Date(Date.UTC(2026, 9, 10, 0, index)).toISOString())
);
const client = {
get: (_url: string, options: { searchParams: Record<string, string> }) => {
const limit = Number(options.searchParams.limit);
const offset = Number(options.searchParams.offset ?? 0);
calls.push({ limit, offset });
return { json: async () => ({ data: all.slice(offset, offset + limit) }) };
}
} as unknown as KyInstance;
return { client, calls };
}
test("paginates with offset until the scan limit is reached", async () => {
const { client, calls } = pagedClient(250);
const result = await collectSimulationBatches(client, 250);
expect(result.batches).toHaveLength(250);
expect(result.capped).toBe(true);
expect(calls.map((call) => [call.limit, call.offset])).toEqual([
[100, 0],
[100, 100],
[50, 200]
]);
});
test("stops when the server returns a short page", async () => {
const { client, calls } = pagedClient(30);
const result = await collectSimulationBatches(client, 500);
expect(result.batches).toHaveLength(30);
expect(result.capped).toBe(false);
expect(calls).toEqual([{ limit: 100, offset: 0 }]);
});
});
+173
View File
@@ -0,0 +1,173 @@
import type { KyInstance } from "ky";
import { durationSeconds, tokenizeDuration } from "../../../core/duration.js";
import { validationError } from "../../../core/errors.js";
import * as api from "../api.js";
import type { SimulationBatch } from "../types.js";
/**
* 原生模拟测试没有服务端检索: `/api/v1/simulation/batches` 只接受 limit/offset,
* 批次对象也没有 name 字段(界面上的「任务 fe1993e4」是前端取 UUID 末 8 位拼的)。
* 因此检索放在本地: 先按 limit/offset 把批次扫进内存, 再按关键词与时间窗过滤。
*/
export const SIMULATION_SCAN_PAGE_SIZE = 100;
export const DEFAULT_SIMULATION_SCAN_LIMIT = 50;
export const DEFAULT_SIMULATION_MAX_SCAN = 500;
export const MAX_SIMULATION_SCAN = 2000;
export type SimulationBatchFilter = {
query?: string;
sinceMs?: number;
untilMs?: number;
};
const STANDALONE_NOISE_TOKENS = new Set([
"任务",
"批次",
"模拟测试",
"测试",
"task",
"batch",
"test",
"simulation"
]);
// 界面名称形如「任务 fe1993e4」「任务:fe1993e4」, 直接粘贴时把中文前缀剥掉
const GLUED_NOISE_PREFIXES = ["模拟测试", "任务", "批次"];
function stripGluedNoise(token: string): string {
let value = token;
for (const prefix of GLUED_NOISE_PREFIXES) {
if (value.length > prefix.length && value.startsWith(prefix)) {
value = value.slice(prefix.length);
}
}
return value.replace(/^[\s::#\-_]+/, "");
}
export function simulationQueryTokens(query?: string): string[] {
if (!query) return [];
const raw = query
.split(/[\s,,;;、]+/)
.map((token) => token.trim())
.filter(Boolean)
.map((token) => token.toLowerCase())
.filter((token) => !STANDALONE_NOISE_TOKENS.has(token));
return raw
.map((token) => stripGluedNoise(token))
.filter(Boolean);
}
function batchHaystack(batch: SimulationBatch): string {
const params = batch.params;
const values: Array<string | number | null | undefined> = [
batch.id,
batch.id.replace(/-/g, ""),
batch.approvalCode,
batch.nodeId,
batch.sourceSystem,
batch.status,
batch.requestSummary?.mode,
batch.resultSummary?.message,
params?.packageLabel,
params?.templateId,
params?.signKey,
params?.rejectNodeName,
params?.dataCollectionMode,
...(params?.flowIds ?? []),
...(params?.packageIds ?? []),
...(batch.requestSummary?.conditions ?? []).flatMap((condition) => [
condition.label,
condition.value
])
];
return values
.filter((value): value is string | number => value !== undefined && value !== null && value !== "")
.map((value) => String(value).toLowerCase())
.join("\n");
}
function batchCreatedAtMs(batch: SimulationBatch): number | null {
if (batch.createdAt === undefined) return null;
const ms = typeof batch.createdAt === "number" ? batch.createdAt : Date.parse(batch.createdAt);
return Number.isFinite(ms) ? ms : null;
}
export function filterSimulationBatches(
batches: SimulationBatch[],
filter: SimulationBatchFilter = {}
): SimulationBatch[] {
const tokens = simulationQueryTokens(filter.query);
return batches.filter((batch) => {
if (filter.sinceMs !== undefined || filter.untilMs !== undefined) {
const createdAtMs = batchCreatedAtMs(batch);
if (createdAtMs === null) return false;
if (filter.sinceMs !== undefined && createdAtMs < filter.sinceMs) return false;
if (filter.untilMs !== undefined && createdAtMs > filter.untilMs) return false;
}
if (tokens.length === 0) return true;
const haystack = batchHaystack(batch);
return tokens.every((token) => haystack.includes(token));
});
}
/**
* 解析时间下界/上界: 支持 ISO、`YYYY-MM-DD`、10/13 位毫秒、以及相对时长(`7d` / `24h` / `90m`)。
* 相对时长按「现在往前推」解释, 便于 `--since 7d` 这类用法。
*/
export function parseSimulationTimeBound(
raw: string | undefined,
options: { endOfDay?: boolean; nowMs?: number } = {}
): number | undefined {
if (raw === undefined) return undefined;
const value = raw.trim();
if (!value) return undefined;
if (/^\d{10,13}$/.test(value)) {
return value.length === 10 ? Number(value) * 1000 : Number(value);
}
const relative = tokenizeDuration(value);
if (relative?.unit) {
const offsetMs = Math.round(durationSeconds(relative, "d") * 1000);
return (options.nowMs ?? Date.now()) - offsetMs;
}
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
const timeSuffix = options.endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
const parsed = new Date(`${value}${timeSuffix}`).getTime();
if (Number.isFinite(parsed)) return parsed;
}
const parsed = new Date(value).getTime();
if (Number.isFinite(parsed)) return parsed;
throw validationError(
`无法解析时间 "${raw}"。支持 ISO 时间、YYYY-MM-DD、10/13 位毫秒, 或相对时长(如 7d / 24h / 90m)。`
);
}
export async function collectSimulationBatches(
client: KyInstance,
scanLimit: number
): Promise<{ batches: SimulationBatch[]; capped: boolean }> {
const target = Math.max(1, Math.min(scanLimit, MAX_SIMULATION_SCAN));
const batches: SimulationBatch[] = [];
let offset = 0;
while (batches.length < target) {
const pageSize = Math.min(SIMULATION_SCAN_PAGE_SIZE, target - batches.length);
const page = await api.listSimulationBatches(client, { limit: pageSize, offset });
batches.push(...page);
// 服务端已无更多批次
if (page.length < pageSize) return { batches, capped: false };
offset += page.length;
}
// 达到扫描上限: 更早的批次未进入检索
return { batches, capped: true };
}
+2 -1
View File
@@ -463,7 +463,8 @@ export const SimulationBatchParamsSchema = z.object({
nodeId: z.string().optional(),
// 合思指定单号模式
flowIds: z.array(z.string()).max(100).optional(),
limit: z.number().int().positive().max(100).optional(),
// 历史批次存在 limit=0(取数模式不按条数限制)与超过 100 的回显值,读路径不能因此整页失败
limit: z.number().int().nonnegative().optional(),
dataCollectionMode: z.string().optional(),
signKey: z.string().optional(),
rejectNodeName: z.string().nullable().optional(),