fix: 表达工作流部分保存结果并校验认证重放

Piper 的 chooses 刷新与删除检查业务码,保留空成功响应。主保存成功后刷新失败抛出携带已保存版本的 WorkflowSavePartialError;统一 JSON 错误保留可选 EkbError.details。
workflow save 在部分成功时返回非零与恢复信息,--in-place 仍同步已保存版本;新增带写确认的 refresh-chooses,仅重试元数据刷新,不重发完整快照。主保存失败不改本地版本。
认证重放保留最终鉴权响应检查(含 HTTP 200 的错误头),最多重放一次,其他 HTTP 错误维持 Ky 语义。补充 SDK、CLI、恢复与重放回归,并更新文档。

验证:bun test 922 通过、0 失败;bun run check、git diff --check 通过。所有业务请求均为离线假接口。
This commit is contained in:
gitea committed 2026-10-29 18:21:30 +08:00
1 parent 51fb54dfe8
commit 55d31e27e6
19 files changed
+298 -23

No files matched your search

+1
View File
@@ -11,6 +11,7 @@
- `printer.ts`:输出渲染(`printJson` / `printHelp` / `redactSensitiveText` 敏感信息脱敏)。
完整 JSON 按值类型脱敏,保留 `keepItSecret` 等布尔业务标记和 null,凭据字符串及数值仍被遮蔽;紧凑 NDJSON 保持单行。普通诊断文本沿用 URL、Bearer 和键值脱敏。
- `errors.ts`:`classifyCliError` 按 `EkbError` 子类与状态码映射退出码与恢复建议。
带结构化元数据的 `EkbError.details` 会保留在 JSON 错误中,例如工作流主保存已完成但元数据刷新失败时的 `remoteSaved` 和服务端版本;普通错误输出不变。
- `mutation.ts`:写操作统一防护(确认/dry-run 语义),边界由 `mutation-boundaries.test.ts` 强制。
- `生产环境安全阻断 (Production Safeguard)`:对带副作用的敏感调试命令(如 `workflow test`),在正式生产企业 (`env === "prod"`) 执行时触发硬阻断,要求必须显式带上 `--force` 确认生产风险;自省命令(`corps list`、`corps current`、`context`、`probe`)显式输出环境标识,并提供 `corps tag` 标记与 `corps list --test/--prod` 筛选。
- `helpers.ts`:横切运行时助手(`initCorpRuntime` / `requireSelectedCorp` / `getSessionClientForRuntime`)。
+1
View File
@@ -214,6 +214,7 @@ export const COMMAND_METADATA: Record<string, CliCommandMetadata> = {
"save": "保存草稿到远端",
"toggle": "切换启停状态",
"publish": "发布并启用工作流",
"refresh-chooses": "只刷新工作流选择器元数据,用于主保存后的失败恢复",
"history": "查看版本历史",
"logs": "查看运行日志",
"check": "检查错误管道",
+1 -1
View File
@@ -1523,7 +1523,7 @@ describe("CLI - workflow job 执行详情与异常精准透视", () => {
},
put: (url: string, opts: any) => {
if (url.endsWith("/chooses")) {
return { json: async () => ({ code: 200, data: [] }) };
return Response.json({ code: 200, data: [] });
}
if (url.includes("api/easo/pipelines/pipe_node_test")) {
savedWorkflowPayload = opts.json;
+33 -4
View File
@@ -1,5 +1,7 @@
import { readFileSync, writeFileSync } from "node:fs";
import { getWorkflowDetail, listAllWorkflows, updateWorkflow } from "../../../domains/platform/services.js";
import { EkbError } from "../../../core/errors.js";
import { getWorkflowDetail, listAllWorkflows, refreshWorkflowChooses, updateWorkflow } from "../../../domains/platform/services.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js";
import { WorkflowDetailSchema } from "../../../domains/platform/types.js";
import {
applyWorkflowPathPatch,
@@ -137,8 +139,14 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
const payload = state.workflow.inputs?.length
? state.workflow
: { ...state.workflow, inputs: [{ key: "$platformId", value: platformId }] };
const saved = await updateWorkflow(piperClient, payload);
let partialError: WorkflowSavePartialError | undefined;
const saved = await updateWorkflow(piperClient, payload).catch((error: unknown) => {
if (!(error instanceof WorkflowSavePartialError)) throw error;
partialError = error;
return error.savedWorkflow;
});
state = commitWorkflowSave(state, saved);
if (partialError) state = { ...state, status: "partial", error: partialError.message };
let fileSynced = false;
let fileSyncWarning = "";
if (syncFile) {
@@ -155,8 +163,11 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
fileSyncWarning = `本地文件同步失败: ${error instanceof Error ? error.message : String(error)}`;
}
}
const quoteArg = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
const nextAction = `hose-use workflow refresh-chooses ${quoteArg(pipelineId)} --platform-id=${quoteArg(platformId)} --corp=${quoteArg(runtime.selectedCorp!.id)} --yes`;
const result = {
success: true,
success: !partialError,
...(partialError ? { remoteSaved: true, failedStep: "chooses", nextAction, message: partialError.message } : {}),
pipelineId,
status: state.status,
version: saved.version,
@@ -165,7 +176,12 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
fileSynced,
...(fileSyncWarning ? { fileSyncWarning } : {}),
};
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: 0 };
if (runtime.jsonMode) return { stdout: printJson(result, runtime.outputOptions), stderr: fileSyncWarning, exitCode: partialError ? 1 : 0 };
if (partialError) return {
stdout: `⚠️ ${partialError.message}\n${fileSynced ? "已同步本地文件版本。\n" : ""}恢复命令: ${nextAction}\n`,
stderr: fileSyncWarning,
exitCode: 1,
};
return {
stdout: `✅ 工作流 [${pipelineId}] 草稿保存成功:${formatWorkflowVersion(saved)}。${fileSynced ? "\n📝 已同步更新本地文件。" : ""}${fileSyncWarning ? `\n⚠️ ${fileSyncWarning}` : ""}\n`,
stderr: fileSyncWarning,
@@ -173,10 +189,23 @@ export async function handleSave(parsed: CliParsedArgs, runtime: CliRuntime): Pr
};
} catch (error) {
state = failWorkflowSave(state, error);
if (error instanceof EkbError) throw error;
throw new Error(`工作流保存失败(${state.status}): ${state.error}`);
}
}
export async function handleRefreshChooses(parsed: CliParsedArgs, runtime: CliRuntime): Promise<CliResult> {
const pipelineId = parsed.args[0] || stringOption(parsed.options, ["id", "pipelineId"]);
if (!pipelineId) throw new Error("请提供工作流 ID: hose-use workflow refresh-chooses <pipelineId> --yes");
requireMutationConfirmation(parsed, runtime, "刷新工作流元数据", `hose-use workflow refresh-chooses ${pipelineId} --yes`);
if (isDryRun(parsed, runtime)) return mutationPreview(parsed, runtime, "刷新工作流元数据", pipelineId, { retryStep: "chooses", saveWorkflow: false });
const clients = await createClientsForCorp(runtime.selectedCorp!);
const platformId = await resolveWorkflowPlatformId(parsed, clients, pipelineId);
const client = await createPiperClientForCorp(runtime.selectedCorp!, platformId);
await refreshWorkflowChooses(client, pipelineId);
return { stdout: runtime.jsonMode ? printJson({ success: true, pipelineId, metadataRefreshed: true }, runtime.outputOptions) : `工作流 [${pipelineId}] 元数据刷新成功,未重新提交快照。\n`, stderr: "", exitCode: 0 };
}
async function resolveWorkflowPlatformId(
parsed: CliParsedArgs,
clients: Awaited<ReturnType<typeof createClientsForCorp>>,
+4 -2
View File
@@ -1,7 +1,7 @@
import type { CliParsedArgs, CliResult, CliRuntime } from "../../types.js";
import { handleList, handleGet, handleFind } from "./list.js";
import { handleToggle, handlePublish } from "./lifecycle.js";
import { handlePatch, handleSave } from "./draft.js";
import { handlePatch, handleSave, handleRefreshChooses } from "./draft.js";
import { handleHistory, handleLogs } from "./history.js";
import { handleJob } from "./job.js";
import { handleCheck } from "./check.js";
@@ -52,6 +52,8 @@ export async function handleWorkflowCommand(
case "save":
case "update":
return handleSave(parsed, runtime);
case "refresh-chooses":
return handleRefreshChooses(parsed, runtime);
case "patch":
return handlePatch(parsed, runtime);
case "history":
@@ -122,7 +124,7 @@ export async function handleWorkflowCommand(
default:
return {
stdout: "",
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
stderr: `未知 workflow 子命令: ${action}。支持: list, get, find, analyze, toggle, publish, patch, save, refresh-chooses, history, logs, job, diff, diff-job, check, test, copy, create, delete, node, tail, lint-script, eval-script, enum, webhook\n`,
exitCode: 1,
};
}
@@ -0,0 +1,77 @@
import { afterEach, expect, spyOn, test } from "bun:test";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import ky from "ky";
import * as helpers from "../../helpers.js";
import { parseArgs } from "../../parser.js";
import { cliErrorResult } from "../../runner.js";
import { normalizeCliArgs, tokenizeCommand } from "../../../server.js";
import { handleWorkflowCommand } from "./index.js";
import { WorkflowDetailSchema } from "../../../domains/platform/types.js";
import { WorkflowSavePartialError } from "../../../domains/platform/workflow/save-error.js";
import type { CliRuntime } from "../../types.js";
const spies: Array<{ mockRestore(): void }> = [];
const directories: string[] = [];
afterEach(() => {
for (const spy of spies.splice(0)) spy.mockRestore();
for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true });
});
function fixture(mainFails = false) {
const dir = mkdtempSync(join(tmpdir(), "hose-save-partial-"));
directories.push(dir);
const file = join(dir, "workflow.json");
const workflow = WorkflowDetailSchema.parse({ id: "p", label: "本地名称", version: "v1", tasksVersion: 1, localNote: "keep" });
writeFileSync(file, JSON.stringify(workflow));
const requests: Array<{ method: string; path: string }> = [];
let failRefresh = true;
const client = ky.create({ prefix: "https://piper.invalid", retry: 0, fetch: async (input, init) => {
const req = input instanceof Request ? input : new Request(input.toString(), init);
const path = new URL(req.url).pathname;
requests.push({ method: req.method, path });
if (req.method === "GET") return Response.json({ code: 200, data: workflow });
if (path.endsWith("/chooses")) return Response.json(failRefresh ? { code: 500, msg: "刷新失败" } : { code: 200, data: [] });
return Response.json(mainFails ? { code: 500, msg: "保存失败" } : { code: 200, data: { ...workflow, label: "远端名称", version: "v2", tasksVersion: 2 } });
} });
const corp = { id: "corp", name: "测试企业", baseUrl: "https://tenant.invalid", source: "manual", credentials: { corpId: "corp", staffId: "staff", accessToken: "fake" } } as const;
const runtime = { selectedCorp: corp, corpContext: {}, jsonMode: true } as CliRuntime;
spies.push(spyOn(helpers, "createClientsForCorp").mockResolvedValue({ corp, sessionClient: client, ekbClient: client, unityClient: client, easoClient: client }));
spies.push(spyOn(helpers, "createPiperClientForCorp").mockResolvedValue(client));
return { file, workflow, runtime, requests, restoreRefresh: () => { failRefresh = false; } };
}
test("部分保存返回非零与新版本,同步本地版本后可只重试 chooses", async () => {
const f = fixture();
const result = await handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes", "--json"]), f.runtime);
expect(result.exitCode).toBe(1);
const partial = JSON.parse(result.stdout);
expect(partial).toMatchObject({ success: false, remoteSaved: true, failedStep: "chooses", status: "partial", version: "v2", tasksVersion: 2, fileSynced: true });
expect(JSON.parse(readFileSync(f.file, "utf8"))).toMatchObject({ label: "本地名称", localNote: "keep", version: "v2", tasksVersion: 2 });
f.restoreRefresh();
const retry = await handleWorkflowCommand(parseArgs(normalizeCliArgs(tokenizeCommand(partial.nextAction))), f.runtime);
expect(retry.exitCode).toBe(0);
expect(f.requests.filter(r => r.method === "PUT").map(r => r.path)).toEqual(["/api/easo/pipelines/p", "/api/easo/pipelines/p/chooses", "/api/easo/pipelines/p/chooses"]);
});
test("主保存失败不更新本地版本,也不发送 chooses", async () => {
const f = fixture(true);
await expect(handleWorkflowCommand(parseArgs(["workflow", "save", "p", "--file", f.file, "--platform-id", "app", "--in-place", "--yes"]), f.runtime)).rejects.toThrow("保存失败");
expect(JSON.parse(readFileSync(f.file, "utf8")).tasksVersion).toBe(1);
expect(f.requests.some(r => r.path.endsWith("/chooses"))).toBe(false);
});
test("定向刷新支持无网络预演,且仍要求写确认", async () => {
const f = fixture();
const preview = await handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p", "--dry-run", "--json"]), f.runtime);
expect(JSON.parse(preview.stdout)).toMatchObject({ dryRun: true, changes: { saveWorkflow: false } });
await expect(handleWorkflowCommand(parseArgs(["workflow", "refresh-chooses", "p"]), f.runtime)).rejects.toThrow("--yes");
expect(f.requests).toEqual([]);
});
test("其他保存入口的部分成功异常通过统一 JSON 错误边界保留元数据", () => {
const result = cliErrorResult(new WorkflowSavePartialError(WorkflowDetailSchema.parse({ id: "p", tasksVersion: 2 }), new Error("refresh failed")), true);
expect(result.exitCode).not.toBe(0);
expect(JSON.parse(result.stdout)).toMatchObject({ error: true, details: { remoteSaved: true, failedStep: "chooses", saved: { pipelineId: "p", tasksVersion: 2 } } });
});
+2 -1
View File
@@ -6,6 +6,7 @@ import { classifyCliError } from "./errors.js";
import { initCorpRuntime } from "./helpers.js";
import { findCommandByArea, isStandingCommand } from "./registry.js";
import type { CliParsedArgs, CliResult, CliRunOptions } from "./types.js";
import { EkbError } from "../core/errors.js";
let runQueue = Promise.resolve<any>(undefined);
@@ -109,7 +110,7 @@ export function cliErrorResult(error: unknown, jsonMode: boolean): CliResult {
const message = redactSensitiveText(error instanceof Error ? error.message : String(error));
const classification = classifyCliError(error);
return {
stdout: jsonMode ? JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}) }, null, 2) : "",
stdout: jsonMode ? redactSensitiveText(JSON.stringify({ error: true, message, exitCode: classification.exitCode, ...(classification.nextAction ? { nextAction: classification.nextAction } : {}), ...(error instanceof EkbError && error.details ? { details: error.details } : {}) }, null, 2)) : "",
stderr: jsonMode ? "" : `[ERROR] ${message}${classification.nextAction ? `\n下一步: ${classification.nextAction}` : ""}\n`,
exitCode: classification.exitCode,
};