From c572cba842f59331f4052f43732c2c2bfb83c917 Mon Sep 17 00:00:00 2001 From: yunyingk <128617637+yunyingk@users.noreply.github.com> Date: Tue, 10 Nov 2026 19:25:50 +0800 Subject: [PATCH] =?UTF-8?q?fix(approval-runs):=20=E4=BC=A0=E8=BE=93?= =?UTF-8?q?=E5=B1=82=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D=E8=A2=AB=E8=AF=AF?= =?UTF-8?q?=E5=88=A4=E4=B8=BA=E4=B8=9A=E5=8A=A1=E7=BB=93=E8=AE=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `sealApprovalRunFlowGet` 用两次"请求被拒"充当路由信号:记录查询被拒,就 认为入参是单号;运行记录列表被拒,就认为该单据没有 AI 记录。两处都写成 裸 `catch {}`,于是所有失败都被吸收进这两个业务结论。 后果不是偶尔不准,而是以十足的语气给出错误答案:token 过期、连接重置、 网关 5xx 会被渲染成「单据已删除」或「AI 从未审核」,用户没有任何线索去 怀疑刚才那次请求其实失败了;退出码同时失去语义,本该由 classifyCliError 产出 11(认证/上游失败),实际退化成一次"成功的查询"。 现在只有标识符形态的拒绝才计为未命中:HTTP 400/404/422,或响应体确实 到达但不是一条审批记录。认证失败、5xx、限流、以及根本没有响应的传输 错误一律原样上抛。 - errors:导出既有的 `responseStatus` 结构读取器,让调用方能区分"没有 响应"与"收到了 400/404 响应"。 - approval-runs:新增 `isUpstreamLookupMiss`,替换两处裸 catch。 - test:新增四个回归用例(401/403/503/连接失败),断言原始错误对象抵达 调用方;另加一条非合思租户的守卫用例。 --- src/core/errors.ts | 8 +- .../capabilities/approval-runs-flow.test.ts | 95 +++++++++++++++++++ .../seal/capabilities/approval-runs.ts | 34 ++++++- 3 files changed, 131 insertions(+), 6 deletions(-) create mode 100644 src/domains/seal/capabilities/approval-runs-flow.test.ts diff --git a/src/core/errors.ts b/src/core/errors.ts index 5f83688..f6577a7 100644 --- a/src/core/errors.ts +++ b/src/core/errors.ts @@ -97,7 +97,13 @@ function isValidationIssueList(error: unknown): boolean { ); } -function responseStatus(error: unknown): number | undefined { +/** + * Read the HTTP status off an error thrown by the HTTP layer, structurally: + * ky's `HTTPError` is not a dependency of this module, and test doubles only + * carry `{ response: { status } }`. `undefined` means the request never got a + * response (DNS failure, connection reset, timeout). + */ +export function responseStatus(error: unknown): number | undefined { if (!error || typeof error !== "object") return undefined; const response = (error as { response?: unknown }).response; if (!response || typeof response !== "object") return undefined; diff --git a/src/domains/seal/capabilities/approval-runs-flow.test.ts b/src/domains/seal/capabilities/approval-runs-flow.test.ts new file mode 100644 index 0000000..d310233 --- /dev/null +++ b/src/domains/seal/capabilities/approval-runs-flow.test.ts @@ -0,0 +1,95 @@ +import { describe, expect, test } from "bun:test"; +import type { KyInstance } from "ky"; +import type { CorpConfig } from "../../../core/config/types.js"; +import { findSealCapability } from "../capabilities.js"; + +/** + * The flow lookup uses a rejected record query as a routing signal ("this was + * not a record ID, treat it as a document number") and a rejected run listing + * as "this document has no AI records". Both are fine for an identifier-shaped + * rejection and catastrophic for anything else: an expired token or a reset + * connection would be reported downstream as 「单据已删除」 or 「AI 从未审核」, + * which is a wrong answer delivered with full confidence. + * + * These cases stop before the Hose client is built, so no tenant is required. + */ + +const HOSE_CORP = { + id: "corp-hose", + name: "测试合思企业", + source: { type: "hose" } +} as unknown as CorpConfig; + +type Handler = ( + client: KyInstance, + params: Record, + context: { corp: CorpConfig } +) => Promise; + +function flowHandler(): Handler { + const capability = findSealCapability("sealApprovalRunFlowGet"); + expect(capability).toBeDefined(); + return capability!.handler as unknown as Handler; +} + +function failingClient(error: unknown): KyInstance { + return { + get: () => { + throw error; + } + } as unknown as KyInstance; +} + +function httpError(status: number): Error { + return Object.assign(new Error(`Request failed with status code ${status}`), { + response: { status } + }); +} + +async function captured(promise: Promise): Promise { + try { + await promise; + return undefined; + } catch (error) { + return error; + } +} + +const SURFACED = [ + ["expired credentials", httpError(401)], + ["forbidden credentials", httpError(403)], + ["upstream service failure", httpError(503)], + ["connection failure without a response", new TypeError("fetch failed")] +] as const; + +describe("sealApprovalRunFlowGet failure attribution", () => { + for (const [label, error] of SURFACED) { + test(`surfaces ${label} instead of absorbing it as a document number`, async () => { + const thrown = await captured( + flowHandler()(failingClient(error), { target: "B26001887" }, { corp: HOSE_CORP }) + ); + // Identity, not message: the original error must reach the CLI layer so + // classifyCliError can still produce exit code 11 for auth failures. + expect(thrown).toBe(error); + }); + } + + test("keeps rejecting non-Hose enterprises before any request", async () => { + let called = false; + const client = { + get: () => { + called = true; + throw new Error("must not be reached"); + } + } as unknown as KyInstance; + + const thrown = await captured( + flowHandler()(client, { target: "B26001887" }, { + corp: { id: "corp-seal", name: "Seal 企业", source: { type: "seal" } } as unknown as CorpConfig + }) + ); + + expect(String(thrown)).toContain("非合思"); + expect(called).toBe(false); + }); +}); diff --git a/src/domains/seal/capabilities/approval-runs.ts b/src/domains/seal/capabilities/approval-runs.ts index 4810e18..465b0b1 100644 --- a/src/domains/seal/capabilities/approval-runs.ts +++ b/src/domains/seal/capabilities/approval-runs.ts @@ -1,4 +1,4 @@ -import { usageError, validationError } from "../../../core/errors.js"; +import { classifyCliError, responseStatus, usageError, validationError } from "../../../core/errors.js"; import { z } from "zod"; import type { KyInstance } from "ky"; import * as api from "../api.js"; @@ -48,6 +48,28 @@ const { summarizeRuleVersion } = helpers; +/** + * Decide whether a failed lookup means "the caller's input was not an ID of + * that kind" or something worse. + * + * Distinguishing them matters because both call sites below use the failure as + * a routing signal: a rejected record lookup means "treat the input as a + * document number", and a rejected run listing means "this document has no AI + * records". Swallowing everything turns a transient failure into a confident + * business verdict — an expired token or a reset connection would surface as + * 「单据已删除」 or 「AI 从未审核」, which is worse than an error. + */ +function isUpstreamLookupMiss(error: unknown): boolean { + const status = responseStatus(error); + if (status !== undefined) { + // Malformed or unknown identifier: the answer we were hoping for. + return status === 400 || status === 404 || status === 422; + } + // No response at all (DNS, reset, timeout) is never a miss. Structural + // validation failures are: the body arrived, it just is not an approval run. + return classifyCliError(error).exitCode === 13; +} + export const approvalRunsCapabilities = [ { name: "sealApprovalRunsSearch", @@ -273,8 +295,9 @@ export const approvalRunsCapabilities = [ if (targetRecord?.sourceDocumentSN || targetRecord?.sourceDocumentId) { sn = (targetRecord.sourceDocumentSN || targetRecord.sourceDocumentId)!; } - } catch { - // Continue as SN + } catch (error) { + if (!isUpstreamLookupMiss(error)) throw error; + // Not a record ID: the caller passed a document number. Continue as SN. } let runs: ApprovalRun[] = []; @@ -287,8 +310,9 @@ export const approvalRunsCapabilities = [ runs = (runsData.records || []).filter( (r) => r.sourceDocumentSN === sn || r.sourceDocumentId === sn || r.id === input ); - } catch { - // ignore + } catch (error) { + if (!isUpstreamLookupMiss(error)) throw error; + // No AI records for this document is a legitimate outcome. } if (runs.length === 0 && targetRecord) {