1183 lines
40 KiB
TypeScript
1183 lines
40 KiB
TypeScript
import { afterEach, describe, expect, test } from "bun:test";
|
|
import { KyInstance } from "ky";
|
|
import { z } from "zod";
|
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
import { CorpConfig } from "../../core/config/types.js";
|
|
import { buildRulePushPlan, findSealTool, sealTools } from "./tools.js";
|
|
|
|
type ToolHandler = (
|
|
client: KyInstance,
|
|
params: Record<string, unknown>,
|
|
context: { corp: CorpConfig }
|
|
) => Promise<unknown>;
|
|
|
|
const ORIGINAL_TOKEN_STORE = process.env.SEAL_HOME_TOKEN_STORE;
|
|
const tempDirs: string[] = [];
|
|
|
|
afterEach(() => {
|
|
if (ORIGINAL_TOKEN_STORE === undefined) {
|
|
delete process.env.SEAL_HOME_TOKEN_STORE;
|
|
} else {
|
|
process.env.SEAL_HOME_TOKEN_STORE = ORIGINAL_TOKEN_STORE;
|
|
}
|
|
|
|
for (const dir of tempDirs.splice(0)) {
|
|
rmSync(dir, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
describe("sealTools", () => {
|
|
test("exposes concrete JSON schemas for parameterized tools", () => {
|
|
const createRule = sealTools.find((tool) => tool.name === "seal_approval_rule_create");
|
|
expect(createRule).toBeDefined();
|
|
|
|
const schema = z.toJSONSchema(createRule!.parameters) as {
|
|
properties?: Record<string, unknown>;
|
|
required?: string[];
|
|
};
|
|
|
|
expect(Object.keys(schema.properties ?? {})).toEqual([
|
|
"description",
|
|
"scope",
|
|
"strictness"
|
|
]);
|
|
expect(schema.required).toEqual(["description", "scope", "strictness"]);
|
|
});
|
|
|
|
test("includes the approval context aggregation tool", () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_context_get");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("includes the session diagnostic tool", () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_session_get");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("includes the delegation management tools", () => {
|
|
const listTool = sealTools.find((item) => item.name === "seal_delegation_list");
|
|
const createTool = sealTools.find((item) => item.name === "seal_delegation_create");
|
|
const revokeTool = sealTools.find((item) => item.name === "seal_delegation_revoke");
|
|
|
|
expect(listTool).toBeDefined();
|
|
expect(createTool).toBeDefined();
|
|
expect(revokeTool).toBeDefined();
|
|
});
|
|
|
|
test("includes user management tools", () => {
|
|
const createTool = sealTools.find((item) => item.name === "seal_user_create");
|
|
const resetTool = sealTools.find((item) => item.name === "seal_user_reset_password");
|
|
const getTool = sealTools.find((item) => item.name === "seal_user_get");
|
|
const searchTool = sealTools.find((item) => item.name === "seal_user_search");
|
|
const deleteTool = sealTools.find((item) => item.name === "seal_user_delete");
|
|
const activateTool = sealTools.find((item) => item.name === "seal_user_activate");
|
|
const userDelegationTool = sealTools.find((item) => item.name === "seal_user_delegation_create");
|
|
|
|
expect(createTool).toBeDefined();
|
|
expect(resetTool).toBeDefined();
|
|
expect(getTool).toBeDefined();
|
|
expect(searchTool).toBeDefined();
|
|
expect(deleteTool).toBeDefined();
|
|
expect(activateTool).toBeDefined();
|
|
expect(userDelegationTool).toBeDefined();
|
|
});
|
|
|
|
test("includes read-only contacts directory tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_contacts_departments_root_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_contacts_department_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_contacts_department_children_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_contacts_department_users_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_contacts_last_sync_time_get")).toBeDefined();
|
|
});
|
|
|
|
test("includes the read-only insight stats tool", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_insight_stats_get")).toBeDefined();
|
|
});
|
|
|
|
test("includes read-only financial data tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_expenses_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_invoices_list")).toBeDefined();
|
|
});
|
|
|
|
test("includes the Feishu simulation approval definition tool", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_simulation_feishu_approval_definitions_list")).toBeDefined();
|
|
});
|
|
|
|
test("includes system configuration tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_llm_config_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_llm_providers_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_permissions_available_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_permissions_configs_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_billing_status_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_billing_plans_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_billing_features_list")).toBeDefined();
|
|
});
|
|
|
|
test("includes Webhook management tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_webhook_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_webhook_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_webhook_add")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_webhook_update")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_webhook_delete")).toBeDefined();
|
|
});
|
|
|
|
test("includes deploy hosecloud tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_requirements")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_status")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_configure")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_deploy_hosecloud_sync")).toBeDefined();
|
|
});
|
|
|
|
test("includes preference and thinking-depth tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_preference_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_preference_decision_update")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_preference_thinking_depth_set")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_preference_thinking_depth_policies_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_preference_thinking_depth_policies_upsert")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_preference_thinking_depth_policies_remove")).toBeDefined();
|
|
});
|
|
|
|
test("includes simulation wait, clean, specifications tools and approval run stats/count", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_simulation_batch_wait")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_simulation_batch_clean")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_simulation_specifications_list")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_approval_runs_stats")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_approval_runs_count")).toBeDefined();
|
|
});
|
|
|
|
test("includes the approval search tool", () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_search");
|
|
expect(tool).toBeDefined();
|
|
});
|
|
|
|
test("approval rules list can return count only", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rules_list");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(fakeRulesClient(), { countOnly: true }, fakeContext());
|
|
|
|
expect(result).toEqual({ count: 2 });
|
|
});
|
|
|
|
test("approval rules list treats limit zero as count only", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rules_list");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(fakeRulesClient(), { fields: ["id"], limit: 0 }, fakeContext());
|
|
|
|
expect(result).toEqual({ count: 2 });
|
|
});
|
|
|
|
test("approval rules list can project lightweight fields", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rules_list");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeRulesClient(),
|
|
{ fields: ["id", "code", "status", "strictness", "scope"], limit: 1 },
|
|
fakeContext()
|
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(2);
|
|
expect(result.rules).toEqual([
|
|
{
|
|
id: "rule-1",
|
|
code: 29,
|
|
status: "active",
|
|
strictness: "MUST_FOLLOW",
|
|
scope: "travel"
|
|
}
|
|
]);
|
|
expect(result.rules[0]).not.toHaveProperty("description");
|
|
});
|
|
|
|
test("approval rules clear can dry run without deleting", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear");
|
|
expect(tool).toBeDefined();
|
|
|
|
const client = fakeClearRulesClient();
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(client, { dryRun: true }, fakeContext()) as {
|
|
dryRun: boolean;
|
|
beforeCount: number;
|
|
deleted: number;
|
|
afterCount: number;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
dryRun: true,
|
|
beforeCount: 2,
|
|
deleted: 0,
|
|
afterCount: 2
|
|
});
|
|
expect(await countFakeRules(client)).toBe(2);
|
|
});
|
|
|
|
test("approval rules clear deletes all draft rules", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rules_clear");
|
|
expect(tool).toBeDefined();
|
|
|
|
const client = fakeClearRulesClient();
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(client, {}, fakeContext()) as {
|
|
dryRun: boolean;
|
|
beforeCount: number;
|
|
deleted: number;
|
|
afterCount: number;
|
|
failed: unknown[];
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
dryRun: false,
|
|
beforeCount: 2,
|
|
deleted: 2,
|
|
afterCount: 0,
|
|
failed: []
|
|
});
|
|
expect(await countFakeRules(client)).toBe(0);
|
|
});
|
|
|
|
test("preference dry run reads config without patching it", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_preference_decision_update");
|
|
expect(tool).toBeDefined();
|
|
let patched = false;
|
|
const client = {
|
|
get: () => ({
|
|
json: async () => ({
|
|
data: {
|
|
decisionPreferences: {
|
|
explicitApprove: "old",
|
|
explicitReject: "reject",
|
|
exemptApprove: "exempt",
|
|
review: "review"
|
|
},
|
|
integrations: []
|
|
}
|
|
})
|
|
}),
|
|
patch: () => {
|
|
patched = true;
|
|
throw new Error("preview must not patch");
|
|
}
|
|
} as unknown as KyInstance;
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(client, { explicitApprove: "new", dryRun: true }, fakeContext()) as {
|
|
preview: boolean;
|
|
targetUrl: string;
|
|
changesDiff: { after: { decisionPreferences: { explicitApprove: string } } };
|
|
};
|
|
|
|
expect(result.preview).toBe(true);
|
|
expect(result.targetUrl).toBe("https://seal.test/api/v1/agent/ai-approval/config");
|
|
expect(result.changesDiff.after.decisionPreferences.explicitApprove).toBe("new");
|
|
expect(patched).toBe(false);
|
|
});
|
|
|
|
test("plans incremental rule updates without rebuilding matched rules", () => {
|
|
const plan = buildRulePushPlan(
|
|
[
|
|
{
|
|
id: "rule-1",
|
|
code: 1,
|
|
description: "Keep receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
},
|
|
{
|
|
id: "rule-2",
|
|
code: 2,
|
|
description: "Keep attendee names",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW"
|
|
}
|
|
],
|
|
[
|
|
{
|
|
id: "rule-1",
|
|
description: "Keep complete receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
},
|
|
{
|
|
description: "Require cost center",
|
|
scope: "all",
|
|
strictness: "SUGGESTION"
|
|
}
|
|
]
|
|
);
|
|
|
|
expect(plan.updated).toMatchObject([
|
|
{ id: "rule-1", changedFields: ["description"] }
|
|
]);
|
|
expect(plan.created).toMatchObject([
|
|
{ description: "Require cost center" }
|
|
]);
|
|
expect(plan.deleted).toMatchObject([{ id: "rule-2", code: 2 }]);
|
|
expect(plan.unchanged).toEqual([]);
|
|
});
|
|
|
|
test("matches legacy local rules by unique content when no id is present", () => {
|
|
const plan = buildRulePushPlan(
|
|
[{
|
|
id: "rule-1",
|
|
description: "Keep receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}],
|
|
[{
|
|
description: "Keep receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}]
|
|
);
|
|
|
|
expect(plan.created).toEqual([]);
|
|
expect(plan.updated).toEqual([]);
|
|
expect(plan.deleted).toEqual([]);
|
|
expect(plan.unchanged).toEqual([{ id: "rule-1" }]);
|
|
});
|
|
|
|
test("rejects local rule ids that are absent from the current draft", () => {
|
|
expect(() => buildRulePushPlan(
|
|
[{
|
|
id: "rule-1",
|
|
description: "Keep receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}],
|
|
[{
|
|
id: "stale-rule",
|
|
description: "Keep receipts",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
}]
|
|
)).toThrow("stale-rule");
|
|
});
|
|
|
|
test("includes approval run Langfuse bridge tools", () => {
|
|
expect(sealTools.find((item) => item.name === "seal_approval_runs_search")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_approval_runs_summary")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_simulation_batch_records_get")).toBeDefined();
|
|
expect(sealTools.find((item) => item.name === "seal_approval_run_langfuse_bridge_get")).toBeDefined();
|
|
});
|
|
|
|
test("can find tools by name in sealTools", () => {
|
|
expect(findSealTool("seal_approval_rule_create")).toBeDefined();
|
|
expect(findSealTool("non_existent_tool")).toBeUndefined();
|
|
});
|
|
|
|
test("approval run search omits bridge unless requested", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_runs_search");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(fakeApprovalRunsClient(), { limit: 1 }, fakeContext());
|
|
|
|
expect(result).not.toHaveProperty("bridge");
|
|
expect(result).toHaveProperty("records");
|
|
});
|
|
|
|
test("approval run search can filter by extracted human result", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_runs_search");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ humanResult: "驳回", limit: 10 },
|
|
fakeContext()
|
|
) as {
|
|
records: Array<{
|
|
sourceDocumentSN?: string;
|
|
humanResult?: string;
|
|
humanResultPath?: string;
|
|
}>;
|
|
};
|
|
|
|
expect(result.records).toHaveLength(1);
|
|
expect(result.records[0]).toMatchObject({
|
|
sourceDocumentSN: "B26001965",
|
|
humanResult: "驳回",
|
|
humanResultPath: "result.manualApproval.result"
|
|
});
|
|
});
|
|
|
|
test("approval run search maps rejected human result to manual approval status", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_runs_search");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as ToolHandler;
|
|
await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{
|
|
humanResult: "驳回",
|
|
startDate: "1774972800000",
|
|
endDate: "1781020799999",
|
|
limit: 50
|
|
},
|
|
fakeContext()
|
|
);
|
|
|
|
expect(requests[0]).toContain("startDate=1774972800000");
|
|
expect(requests[0]).toContain("endDate=1781020799999");
|
|
expect(requests[0]).toContain("manualApprovalStatus%5B0%5D=TERMINATED");
|
|
});
|
|
|
|
test("approval run search forwards query as API search parameter", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_runs_search");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as ToolHandler;
|
|
await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{
|
|
query: "B26001965",
|
|
startDate: "1774972800000",
|
|
endDate: "1781020799999",
|
|
limit: 50
|
|
},
|
|
fakeContext()
|
|
);
|
|
|
|
expect(requests[0]).toContain("search=B26001965");
|
|
expect(requests[0]).toContain("startDate=1774972800000");
|
|
expect(requests[0]).toContain("endDate=1781020799999");
|
|
});
|
|
|
|
test("approval run get returns stable aliases for document concepts", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as {
|
|
aliases?: {
|
|
originalDocumentData?: { path?: string; frontendLabel?: string };
|
|
aiDocumentFields?: { path?: string; frontendLabel?: string };
|
|
aiDocument?: { path?: string; aliasOf?: string };
|
|
sourceDocument?: { path?: string };
|
|
aiResult?: { path?: string };
|
|
aiAuditLog?: { path?: string };
|
|
manualApproval?: { path?: string };
|
|
};
|
|
};
|
|
|
|
expect(result.aliases).toMatchObject({
|
|
originalDocumentData: { path: "document", frontendLabel: "单据原始数据" },
|
|
aiDocumentFields: { path: "document.fields", frontendLabel: "AI 看的单据" },
|
|
aiDocument: { path: "document.fields", aliasOf: "aiDocumentFields" },
|
|
sourceDocument: { path: "sourceExtendData.hosecloudViewUrl" },
|
|
aiResult: { path: "result" },
|
|
aiAuditLog: { path: "pipelineData.logs" },
|
|
manualApproval: { path: "manualApprovalRecord" }
|
|
});
|
|
});
|
|
|
|
test("approval run get can return selected fields only", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", fields: "metadata,document.fields,result.summary" },
|
|
fakeContext()
|
|
) as {
|
|
metadata?: { recordId?: string };
|
|
document?: { fields?: unknown[] };
|
|
result?: { summary?: string; manualApproval?: unknown };
|
|
pipelineData?: unknown;
|
|
};
|
|
|
|
expect(result.metadata?.recordId).toBe("run-1");
|
|
expect(result.document?.fields).toHaveLength(3);
|
|
expect(result.result?.summary).toBe("费用存在风险");
|
|
expect(result.result?.manualApproval).toBeUndefined();
|
|
expect(result.pipelineData).toBeUndefined();
|
|
});
|
|
|
|
test("approval run get can return summary preset", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", summary: true },
|
|
fakeContext()
|
|
) as { aiResult?: { decision?: string }; manualResult?: string; document?: { title?: string } };
|
|
|
|
expect(result.aiResult?.decision).toBe("驳回");
|
|
expect(result.manualResult).toBe("驳回");
|
|
expect(result.document?.title).toBe("差旅报销单");
|
|
});
|
|
|
|
test("approval run pick supports sn latest and compact candidate fields", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_pick");
|
|
expect(tool).toBeDefined();
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{ sn: "B26001965", latest: true },
|
|
fakeContext()
|
|
) as { matched: number; records: Array<{ recordId?: string; aiDecision?: string; aiSummary?: string }> };
|
|
|
|
expect(requests[0]).toContain("sourceDocumentSN=B26001965");
|
|
expect(result.matched).toBe(1);
|
|
expect(result.records[0]).toMatchObject({
|
|
recordId: "run-1",
|
|
aiDecision: "驳回",
|
|
aiSummary: "费用存在风险"
|
|
});
|
|
});
|
|
|
|
test("approval run attachments extracts compact attachment metadata", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_attachments_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { count: number; attachments: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(2);
|
|
expect(result.attachments).toContainEqual(expect.objectContaining({
|
|
kind: "attachment",
|
|
fileName: "receipt.pdf",
|
|
fileId: "file-1",
|
|
mimeType: "application/pdf",
|
|
ossPath: "oss://bucket/receipt.pdf"
|
|
}));
|
|
expect(result.attachments).toContainEqual(expect.objectContaining({
|
|
kind: "invoice",
|
|
fileName: "invoice.png",
|
|
url: "https://signed.example/invoice.png"
|
|
}));
|
|
});
|
|
|
|
test("approval run cited rules extracts rule application details", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_cited_rules_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { count: number; rules: Array<Record<string, unknown>> };
|
|
|
|
expect(result.count).toBe(1);
|
|
expect(result.rules[0]).toMatchObject({
|
|
runtimeRuleId: "rule-38",
|
|
ruleCode: "#0038",
|
|
versionNumber: 16,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
checkResult: "failed"
|
|
});
|
|
});
|
|
|
|
test("approval run document summary returns key fields without raw payload", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_document_summary_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeContext()
|
|
) as { document?: { amount?: unknown; expenseType?: unknown }; invoices?: Array<Record<string, unknown>> };
|
|
|
|
expect(result.document?.amount).toBe("100.00");
|
|
expect(result.document?.expenseType).toBe("差旅费");
|
|
expect(result.invoices?.[0]).toMatchObject({
|
|
buyer: "甲方公司",
|
|
seller: "乙方公司",
|
|
amount: 100
|
|
});
|
|
});
|
|
|
|
test("approval run result can return summary only", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_result_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", summary: true },
|
|
fakeContext()
|
|
) as {
|
|
decision?: string;
|
|
summary?: string;
|
|
riskPointCount?: number;
|
|
matchedRuleCount?: number;
|
|
traceId?: string;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
decision: "驳回",
|
|
summary: "费用存在风险",
|
|
riskPointCount: 2,
|
|
matchedRuleCount: 1,
|
|
traceId: "trace-1"
|
|
});
|
|
});
|
|
|
|
test("approval run url returns Hose enterprise and document links by recordId", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1" },
|
|
fakeHoseContext()
|
|
) as {
|
|
enterpriseAssistUrl?: string;
|
|
enterpriseUrl?: string;
|
|
hoseDomain?: string;
|
|
documentUrl?: string;
|
|
recordId?: string;
|
|
sourceDocumentSN?: string;
|
|
};
|
|
|
|
expect(result).toMatchObject({
|
|
url: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
|
sealResultUrl: "https://hose-corp-a.sealai.cc/approval-result/run-1",
|
|
type: "deep_link",
|
|
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
|
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
|
hoseDomain: "https://app.ekuaibao.com",
|
|
documentUrl: "https://app.ekuaibao.com/web/thirdparty.html",
|
|
recordId: "run-1",
|
|
sourceDocumentSN: "B26001965"
|
|
});
|
|
});
|
|
|
|
test("approval run url returns enterprise assist link without a document lookup", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{},
|
|
fakeHoseContext()
|
|
) as {
|
|
enterpriseAssistUrl?: string;
|
|
enterpriseUrl?: string;
|
|
documentUrl?: string;
|
|
};
|
|
|
|
expect(requests).toEqual([]);
|
|
expect(result).toMatchObject({
|
|
enterpriseAssistUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token",
|
|
enterpriseUrl: "https://app.ekuaibao.com/web/home.html?accessToken=close-token"
|
|
});
|
|
expect(result.documentUrl).toBeUndefined();
|
|
});
|
|
|
|
test("approval run url can resolve by sourceDocumentSN", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const requests: string[] = [];
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(requests),
|
|
{ sourceDocumentSN: "B26001965" },
|
|
fakeHoseContext()
|
|
) as { documentUrl?: string; url?: string; type?: string };
|
|
|
|
expect(requests[0]).toContain("search=B26001965");
|
|
expect(requests[1]).toBe("api/v1/approvals/run-1");
|
|
expect(result.documentUrl).toBe("https://app.ekuaibao.com/web/thirdparty.html");
|
|
expect(result.type).toBe("deep_link");
|
|
expect(result.url).toBe("https://hose-corp-a.sealai.cc/approval-result/run-1");
|
|
});
|
|
|
|
test("approval run url returns SSO link with identity, expiration, and warning when sso=true", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
|
expect(tool).toBeDefined();
|
|
primeHoseEnterpriseUrl("corp-a", "https://app.ekuaibao.com/web/home.html?accessToken=close-token");
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = (await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", sso: true, expiresIn: 3600 },
|
|
fakeHoseContext()
|
|
)) as {
|
|
url?: string;
|
|
ssoUrl?: string;
|
|
type?: string;
|
|
expiresIn?: number;
|
|
warning?: string;
|
|
identity?: { staffId?: string };
|
|
};
|
|
|
|
expect(result.type).toBe("sso_link");
|
|
expect(result.expiresIn).toBe(3600);
|
|
expect(result.url).toContain("/api/auth/oauth2/session/oem-hosecloud?token=close-token");
|
|
expect(result.url).toContain("path=%2Fapproval-result%2Frun-1");
|
|
expect(result.warning).toContain("安全警示");
|
|
expect(result.identity?.staffId).toBe("staff-a");
|
|
});
|
|
|
|
test("approval run url throws clear error when sso=true is used on non-hose enterprise", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_run_url_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
await expect(
|
|
handler(
|
|
fakeApprovalRunsClient(),
|
|
{ recordId: "run-1", sso: true },
|
|
fakeContext()
|
|
)
|
|
).rejects.toThrow("SSO direct links currently support Hose-integrated enterprises");
|
|
});
|
|
|
|
test("approval run summary filters by local date and returns compact aggregates", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_runs_summary");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeApprovalRunsClient(),
|
|
{ date: "2026-06-08", timezone: "Asia/Shanghai", limit: 100 },
|
|
fakeContext()
|
|
) as {
|
|
matched: number;
|
|
statusCounts: Record<string, number>;
|
|
taskModeCounts: Record<string, number>;
|
|
records: Array<{ sourceDocumentSN?: string; createdAt?: string }>;
|
|
};
|
|
|
|
expect(result.matched).toBe(2);
|
|
expect(result.statusCounts).toEqual({ completed: 1, failed: 1 });
|
|
expect(result.taskModeCounts).toEqual({ assisted: 1, simulation: 1 });
|
|
expect(result.records.map((record) => record.sourceDocumentSN)).toEqual([
|
|
"B26001965",
|
|
"B26001808"
|
|
]);
|
|
expect(result.records[0]?.createdAt).toBe("2026-06-08 13:56:04");
|
|
});
|
|
|
|
test("approval rule get resolves one rule by version and code", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_approval_rule_get");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const result = await handler(
|
|
fakeRulesClient(),
|
|
{ versionNumber: 16, code: "#0044" },
|
|
fakeContext()
|
|
) as { ruleCode?: string; description?: string; versionNumber?: number };
|
|
|
|
expect(result).toMatchObject({
|
|
ruleCode: "#0044",
|
|
description: "Second published rule",
|
|
versionNumber: 16
|
|
});
|
|
});
|
|
|
|
test("deploy hosecloud configure saves integration and rejects missing customApiUrl", async () => {
|
|
const tool = sealTools.find((item) => item.name === "seal_deploy_hosecloud_configure");
|
|
expect(tool).toBeDefined();
|
|
|
|
const handler = tool!.handler as ToolHandler;
|
|
const client = fakeDeployClient();
|
|
|
|
// 1. Rejects custom environment without customApiUrl
|
|
await expect(
|
|
handler(
|
|
client,
|
|
{
|
|
apiKey: "test-ak",
|
|
apiSecret: "test-sk",
|
|
apiOrigin: "custom"
|
|
},
|
|
fakeContext()
|
|
)
|
|
).rejects.toThrow("自定义合思环境必须提供 customApiUrl");
|
|
|
|
// 2. Saves successfully with customApiUrl
|
|
const result = await handler(
|
|
client,
|
|
{
|
|
apiKey: "test-ak",
|
|
apiSecret: "test-sk",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://dd2.hosecloud.com",
|
|
outboundName: "DingTalk AI Audit"
|
|
},
|
|
fakeContext()
|
|
) as { integration: { corporationId: string; apiOrigin: string; customApiUrl: string; outboundName: string } };
|
|
|
|
expect(result.integration).toMatchObject({
|
|
corporationId: "mock-hose-corp",
|
|
apiOrigin: "custom",
|
|
customApiUrl: "https://dd2.hosecloud.com",
|
|
outboundName: "DingTalk AI Audit"
|
|
});
|
|
});
|
|
});
|
|
|
|
function fakeApprovalRunsClient(requests: string[] = []): KyInstance {
|
|
return {
|
|
get: (url: string, options?: { searchParams?: URLSearchParams }) => ({
|
|
json: async () => ({
|
|
...(requests.push(`${url}${options?.searchParams ? `?${options.searchParams}` : ""}`) ? {} : {}),
|
|
data: url === "api/v1/approvals/run-1"
|
|
? {
|
|
id: "run-1",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
documentId: "normalized-doc-1",
|
|
ruleSetVersionNumber: 16,
|
|
document: {
|
|
id: "normalized-doc-1",
|
|
title: "差旅报销单",
|
|
templateName: "费用报销",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
fields: [
|
|
{ label: "金额", value: "100.00" },
|
|
{ label: "费用类型", value: "差旅费" },
|
|
{
|
|
label: "附件",
|
|
attachments: [
|
|
{
|
|
fileName: "receipt.pdf",
|
|
fileId: "file-1",
|
|
mimeType: "application/pdf",
|
|
ossPath: "oss://bucket/receipt.pdf"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
},
|
|
result: {
|
|
decision: "驳回",
|
|
summary: "费用存在风险",
|
|
riskPoints: ["金额异常", "附件缺失"],
|
|
matchedRules: [{
|
|
runtimeRuleId: "rule-38",
|
|
ruleCode: "#0038",
|
|
versionNumber: 16,
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
appliedAnalysis: "发票信息与报销说明不一致",
|
|
checkResult: "failed",
|
|
findings: ["金额异常"]
|
|
}],
|
|
manualApproval: {
|
|
result: "驳回"
|
|
},
|
|
invoices: [
|
|
{
|
|
fileName: "invoice.png",
|
|
mimeType: "image/png",
|
|
signedUrl: "https://signed.example/invoice.png",
|
|
buyer: "甲方公司",
|
|
seller: "乙方公司",
|
|
amount: 100,
|
|
taxRate: "6%",
|
|
category: "增值税普通发票"
|
|
}
|
|
]
|
|
},
|
|
pipelineData: {
|
|
logs: "audit logs"
|
|
},
|
|
sourceExtendData: {
|
|
_langfuseTraceId: "trace-1",
|
|
original_document_id: "B26001965",
|
|
hosecloudViewUrl: "https://app.ekuaibao.com/web/thirdparty.html"
|
|
},
|
|
createdAt: 1780898164536
|
|
}
|
|
: {
|
|
total: 3,
|
|
records: [
|
|
{
|
|
id: "run-1",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001965",
|
|
sourceDocumentId: "doc-source-1",
|
|
ruleSetVersionNumber: 16,
|
|
sourceExtendData: { _langfuseTraceId: "trace-1" },
|
|
createdAt: 1780898164536
|
|
},
|
|
{
|
|
id: "run-2",
|
|
status: "failed",
|
|
taskMode: "simulation",
|
|
sourceDocumentSN: "B26001808",
|
|
sourceDocumentId: "doc-source-2",
|
|
pipelineData: {
|
|
humanReview: {
|
|
decision: "通过"
|
|
}
|
|
},
|
|
createdAt: 1780887698055
|
|
},
|
|
{
|
|
id: "run-3",
|
|
status: "completed",
|
|
taskMode: "assisted",
|
|
sourceDocumentSN: "B26001762",
|
|
sourceDocumentId: "doc-source-3",
|
|
createdAt: 1780742324888
|
|
}
|
|
]
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
function fakeRulesClient(): KyInstance {
|
|
return {
|
|
get: (url: string) => ({
|
|
json: async () => ({
|
|
data: url === "api/v1/rule-set-versions"
|
|
? [
|
|
{
|
|
id: "version-16",
|
|
versionNumber: 16,
|
|
versionName: "v16",
|
|
publishedByName: "Tester",
|
|
rules: [
|
|
{
|
|
code: "rule-29",
|
|
description: "First published rule",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW"
|
|
},
|
|
{
|
|
code: "rule-44",
|
|
description: "Second published rule",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW"
|
|
}
|
|
]
|
|
}
|
|
]
|
|
: {
|
|
hasPendingDeletes: false,
|
|
rules: [
|
|
{
|
|
id: "rule-1",
|
|
tenantId: "tenant-1",
|
|
code: 29,
|
|
description: "Must include full invoice detail",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
status: "active",
|
|
createdAt: 1780898164536,
|
|
updatedAt: 1780898164536
|
|
},
|
|
{
|
|
id: "rule-2",
|
|
tenantId: "tenant-1",
|
|
code: 44,
|
|
description: "Prefer matching attendee names",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW",
|
|
status: "draft",
|
|
createdAt: 1780898164537,
|
|
updatedAt: 1780898164537
|
|
}
|
|
]
|
|
}
|
|
})
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
function fakeClearRulesClient(): KyInstance {
|
|
const rules = [
|
|
{
|
|
id: "rule-1",
|
|
tenantId: "tenant-1",
|
|
code: 29,
|
|
description: "Must include full invoice detail",
|
|
scope: "travel",
|
|
strictness: "MUST_FOLLOW",
|
|
status: "active"
|
|
},
|
|
{
|
|
id: "rule-2",
|
|
tenantId: "tenant-1",
|
|
code: 44,
|
|
description: "Prefer matching attendee names",
|
|
scope: "meal",
|
|
strictness: "SHOULD_FOLLOW",
|
|
status: "draft"
|
|
}
|
|
];
|
|
|
|
return {
|
|
get: () => ({
|
|
json: async () => ({
|
|
data: {
|
|
hasPendingDeletes: false,
|
|
rules: [...rules]
|
|
}
|
|
})
|
|
}),
|
|
delete: (url: string) => {
|
|
const ruleId = url.split("/").pop();
|
|
const index = rules.findIndex((rule) => rule.id === ruleId);
|
|
if (index >= 0) rules.splice(index, 1);
|
|
return Promise.resolve({});
|
|
},
|
|
post: () => Promise.resolve({
|
|
ok: true,
|
|
status: 200,
|
|
json: async () => ({ activeRules: rules.length, pendingDeleteRules: 0, nextCode: 1 })
|
|
})
|
|
} as unknown as KyInstance;
|
|
}
|
|
|
|
async function countFakeRules(client: KyInstance): Promise<number> {
|
|
const response = await client.get("api/v1/rules").json() as {
|
|
data: { rules: unknown[] };
|
|
};
|
|
return response.data.rules.length;
|
|
}
|
|
|
|
function fakeContext(): { corp: CorpConfig } {
|
|
return {
|
|
corp: {
|
|
id: "corp-a",
|
|
name: "Corp A",
|
|
environment: "production",
|
|
seal: {
|
|
endpoints: {
|
|
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
|
}
|
|
},
|
|
source: {
|
|
type: "direct",
|
|
token: "token",
|
|
sealUrl: "https://seal.test",
|
|
expiresIn: 3600,
|
|
staffId: "direct"
|
|
},
|
|
auth: {
|
|
refreshTtl: 300
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function fakeHoseContext(): { corp: CorpConfig } {
|
|
return {
|
|
corp: {
|
|
id: "corp-a",
|
|
name: "Corp A",
|
|
environment: "production",
|
|
seal: {
|
|
endpoints: {
|
|
approvalStylePreferences: "api/v1/agent/ai-approval/config"
|
|
}
|
|
},
|
|
source: {
|
|
type: "hose",
|
|
domain: "https://app.ekuaibao.com/",
|
|
appKey: "app-key",
|
|
appSecurity: "app-secret",
|
|
staffId: "staff-a",
|
|
corpId: "hose-corp-a"
|
|
},
|
|
auth: {
|
|
refreshTtl: 300
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function primeHoseEnterpriseUrl(corpId: string, url: string) {
|
|
const dir = mkdtempSync(join(tmpdir(), "seal-home-tools-"));
|
|
tempDirs.push(dir);
|
|
const storePath = join(dir, "tokens.json");
|
|
process.env.SEAL_HOME_TOKEN_STORE = storePath;
|
|
writeFileSync(storePath, JSON.stringify({
|
|
[corpId]: {
|
|
hose: {
|
|
closeapi: {
|
|
token: "close-token",
|
|
url,
|
|
expiresAt: Date.now() + 3600 * 1000
|
|
}
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
|
|
function fakeDeployClient(): KyInstance {
|
|
let config: Record<string, unknown> = {
|
|
integrationSystem: "hosecloud",
|
|
integrations: []
|
|
};
|
|
|
|
return {
|
|
get: (_url: string) => ({
|
|
json: async () => config
|
|
}),
|
|
patch: (url: string, options?: { json?: any }) => {
|
|
if (url === "api/v1/agent/ai-approval/config") {
|
|
config = options?.json ?? config;
|
|
return {
|
|
json: async () => config
|
|
};
|
|
}
|
|
return {
|
|
json: async () => ({})
|
|
};
|
|
},
|
|
post: (url: string, options?: { json?: any }) => {
|
|
if (url === "api/hosecloud/corporation") {
|
|
return {
|
|
json: async () => ({ corporationId: "mock-hose-corp" })
|
|
};
|
|
}
|
|
if (url === "api/v1/agent/ai-approval/config") {
|
|
config = options?.json ?? config;
|
|
return {
|
|
json: async () => config
|
|
};
|
|
}
|
|
return {
|
|
json: async () => ({})
|
|
};
|
|
}
|
|
} as unknown as KyInstance;
|
|
}
|