diff --git a/src/cli/commands/test.test.ts b/src/cli/commands/test.test.ts index 1e0191c..1681afe 100644 --- a/src/cli/commands/test.test.ts +++ b/src/cli/commands/test.test.ts @@ -144,7 +144,7 @@ function setupTestEnv() { return { root, enterprises, prodCorp, testCorp, unpairedCorp }; } -function mockApiFetch() { +function mockApiFetch(options: { integrations?: unknown[] } = {}) { globalThis.fetch = (async (input: RequestInfo | URL) => { const url = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; @@ -177,6 +177,34 @@ function mockApiFetch() { ); } + // Approval-style preferences: the webhook channel catalog regression reads + // through ensureTestWebhookIntegration. Default to one channel so the + // existing dry-run tests keep resolving without a selector. + if (url.includes("ai-approval/config")) { + const integrations = options.integrations ?? [ + { + type: "webhook", + id: "wh-default", + name: "默认通道", + mode: "assisted", + incomingDocumentWebhook: { + id: "in-default", + url: "https://test.sealai.cc/api/v1/integrations/webhook/wh-default/document" + }, + outgoingResultWebhook: "https://test.sealai.cc/out", + incomingManualResultWebhook: { + id: "in-default", + url: "https://test.sealai.cc/man" + }, + secret: "default-secret" + } + ]; + return new Response(JSON.stringify({ data: { integrations } }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); + } + return new Response("Not found", { status: 404 }); }) as any; } @@ -250,4 +278,83 @@ describe("seal-use test regression CLI", () => { expect(payload.verdict).toBe("DRY_RUN"); expect(payload.targetCorp.id).toBe("corp-test"); }); + + test("regression without --webhook and with several target channels fails with guidance instead of picking one (P0 regression)", async () => { + setupTestEnv(); + // Target tenant exposes TWO channels and neither is replay-named, so the + // selector must refuse rather than silently choose. The original bug + // repeated this same error even when --webhook WAS supplied, so pair this + // with the passing `--webhook` case above: guidance now matches behavior. + mockApiFetch({ + integrations: [ + { + type: "webhook", + id: "wh-1", + name: "通道甲", + mode: "assisted", + incomingDocumentWebhook: { + id: "in_1", + url: "https://test.sealai.cc/api/v1/integrations/webhook/wh-1/document" + }, + outgoingResultWebhook: "https://test.sealai.cc/out", + incomingManualResultWebhook: { + id: "in_1", + url: "https://test.sealai.cc/man" + }, + secret: "s1" + }, + { + type: "webhook", + id: "wh-2", + name: "通道乙", + mode: "assisted", + incomingDocumentWebhook: { + id: "in_2", + url: "https://test.sealai.cc/api/v1/integrations/webhook/wh-2/document" + }, + outgoingResultWebhook: "https://test.sealai.cc/out", + incomingManualResultWebhook: { + id: "in_2", + url: "https://test.sealai.cc/man" + }, + secret: "s2" + } + ] + }); + + // Live run (no --dry-run): the selector is consulted on the live path, + // which is where the P0 bug reproduced — guidance demanded --webhook but + // supplying it did not help. + const result = await runCli([ + "test", + "regression", + "--corp", + "corp-test", + "--samples", + "1" + ]); + // 13: local config/input validation — the caller must name a channel. + expect(result.exitCode).toBe(13); + expect(result.stderr).toContain("请通过 --webhook 指定目标通道"); + + // Supplying the selector resolves THAT channel instead of repeating the + // error (the exact P0 scenario). The run then proceeds past channel + // resolution; a later upstream failure in the minimal mock is fine as long + // as the selector error is gone. + const withSelector = await runCli([ + "test", + "regression", + "--corp", + "corp-test", + "--samples", + "1", + "--webhook", + "通道乙" + ]); + expect(withSelector.stderr).not.toContain("请通过 --webhook 指定目标通道"); + expect(withSelector.stderr).not.toContain("未找到匹配 \"通道乙\""); + // It must have resolved channel 乙: any failure after that point is + // mock-surface, not selector logic. + expect(withSelector.exitCode).not.toBe(13); + }); }); diff --git a/src/cli/commands/webhook-replay.test.ts b/src/cli/commands/webhook-replay.test.ts index df5b85c..ee35bcf 100644 --- a/src/cli/commands/webhook-replay.test.ts +++ b/src/cli/commands/webhook-replay.test.ts @@ -167,6 +167,91 @@ describe("seal-use webhook replay CLI", () => { expect(refField.type).toBe("TEXT"); }); + test("--sn replays exactly the requested record, not the newest one (regression for --sn being ignored)", async () => { + setupMockEnv(); + + // Two historical records; the requested one is the OLDER of the pair. + // The original P0 bug ignored --sn and replayed the newest record. + const oldRecord = { ...mockApprovalRun, id: "run-old", sourceDocumentSN: "BX9990001", createdAt: 1789000000000 }; + const newRecord = { + ...mockApprovalRun, + id: "run-new", + sourceDocumentSN: "BX9990002", + sourceDocumentId: "DOC-NEW", + createdAt: 1789999999000, + document: { ...mockApprovalRun.document, id: "DOC-NEW", sn: "BX9990002" } + }; + + const requestedSn = "BX9990001"; + let approvalsSearchUrl = ""; + + globalThis.fetch = (async (input: RequestInfo | URL) => { + const requestUrl = + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + + if (requestUrl.includes("api/v1/approvals") && !requestUrl.includes("api/v1/approvals/")) { + approvalsSearchUrl = requestUrl; + // Newest first, as the API returns them: the bug picked records[0]. + return new Response(JSON.stringify({ data: { records: [newRecord, oldRecord] } }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); + } + if (requestUrl.includes("api/v1/system/preferences/approval-style")) { + return new Response(JSON.stringify({ data: { integrations: mockWebhookIntegrations } }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const result = await runCli(["webhook", "replay", "--sn", requestedSn, "--dry-run"]); + + expect(result.isError).toBe(false); + expect(result.exitCode).toBe(0); + + // The search itself must target the requested SN. + expect(approvalsSearchUrl).toContain(`sourceDocumentSN=${requestedSn}`); + + const parsed = JSON.parse(result.stdout); + expect(parsed.dryRun).toBe(true); + expect(parsed.totalCount).toBe(1); + expect(parsed.originalRecord.id).toBe("run-old"); + expect(parsed.originalRecord.sourceDocumentSN).toBe(requestedSn); + expect(parsed.document.documentSN).toBe(requestedSn); + // The newer record must NOT be the one replayed. + expect(JSON.stringify(parsed)).not.toContain("run-new"); + expect(JSON.stringify(parsed)).not.toContain("BX9990002"); + }); + + test("--sn with a document that does not exist fails with a lookup error instead of falling back to the newest", async () => { + setupMockEnv(); + + globalThis.fetch = (async (input: RequestInfo | URL) => { + const requestUrl = + typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; + if (requestUrl.includes("api/v1/approvals")) { + return new Response(JSON.stringify({ data: { records: [mockApprovalRun] } }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); + } + if (requestUrl.includes("api/v1/system/preferences/approval-style")) { + return new Response(JSON.stringify({ data: { integrations: mockWebhookIntegrations } }), { + status: 200, + headers: { "Content-Type": "application/json" } + }); + } + return new Response("Not found", { status: 404 }); + }) as any; + + const result = await runCli(["webhook", "replay", "--sn", "DOES-NOT-EXIST", "--dry-run"]); + + expect(result.isError).toBe(true); + expect(result.stderr).toContain("未找到单据编号为「DOES-NOT-EXIST」的审批记录"); + }); + test("executes live webhook replay with successful response", async () => { setupMockEnv(); let pushedBody: any = null; diff --git a/src/domains/seal/webhook-replay.test.ts b/src/domains/seal/webhook-replay.test.ts index 5bc2644..6e0fe3b 100644 --- a/src/domains/seal/webhook-replay.test.ts +++ b/src/domains/seal/webhook-replay.test.ts @@ -359,6 +359,72 @@ describe("webhook-replay domain", () => { expect(savedIntegration).toBeDefined(); expect(savedIntegration.name).toBe("(Seal测-回放通道)"); }); + + test("selector resolves the named channel when the tenant has several (regression for --webhook being ignored)", async () => { + // P0 regression: with two channels and no replay-named one, running without + // a selector must fail with guidance, and passing --webhook must + // resolve exactly that channel instead of repeating the error. + const testCorp = { + id: "corp-test", + name: "测试企业", + environment: "test", + sourceType: "seal", + seal: { + url: "https://test.sealai.cc", + tenantSlug: "test", + endpoints: { approvalStylePreferences: "api/pref" } + }, + source: { + type: "seal", + token: "tok", + sealUrl: "https://test.sealai.cc", + expiresIn: 3600, + staffId: "seal" + } + } as unknown as CorpConfig; + + const channel = (id: string, name: string): WebhookIntegration => ({ + ...mockWebhookIntegration, + id, + name, + incomingDocumentWebhook: { + ...mockWebhookIntegration.incomingDocumentWebhook, + id: `hook_${id}` + } + }); + const alpha = channel("wh-a", "通道甲"); + const beta = channel("wh-b", "通道乙"); + + const mockClient: any = { + get: () => ({ + json: async () => ({ + data: { integrations: [alpha, beta] } + }) + }), + post: () => { + throw new Error("selector resolution must not create anything"); + } + }; + + // Named selector resolves the exact channel. + const picked = await ensureTestWebhookIntegration(mockClient, testCorp, "通道乙"); + expect(picked.id).toBe("wh-b"); + + // Selector also matches by integration id. + const pickedById = await ensureTestWebhookIntegration(mockClient, testCorp, "wh-a"); + expect(pickedById.id).toBe("wh-a"); + + // Without a selector the ambiguous set must be refused (exit-13 wording) + // rather than silently picking the first channel. + await expect(ensureTestWebhookIntegration(mockClient, testCorp)).rejects.toThrow( + /请通过 --webhook 指定目标通道/ + ); + + // An unknown selector names the available channels instead of failing obscurely. + await expect(ensureTestWebhookIntegration(mockClient, testCorp, "不存在的通道")).rejects.toThrow( + /未找到匹配 "不存在的通道" 的 Webhook 集成通道/ + ); + }); }); describe("executeApprovalRunsReplay sn matching", () => {