From bd3379ff5dd550667eb6bb109c796de3db118b21 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=BE=99=E5=AE=89?= <297888591+wanglongan587@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:11:04 +0800 Subject: [PATCH 1/5] feat(v2-server): preflight workflow skills across whole graph on run start --- v2-server/README.md | 4 +- v2-server/internal/scheduler/workflow.go | 24 +- v2-server/internal/scheduler/workflow_test.go | 2 + .../server/schedule_workflow_target.go | 8 +- .../server/schedule_workflow_target_test.go | 84 ++++--- .../server/task_comment_workflow_test.go | 64 +++++ v2-server/internal/server/task_workflows.go | 3 +- .../internal/server/task_workflows_test.go | 28 +++ .../internal/server/workflow_run_lifecycle.go | 34 +++ .../server/workflow_run_lifecycle_test.go | 8 + v2-server/internal/store/workflow_skills.go | 39 ++- v2-server/internal/workflow/graph.go | 52 ++++ v2-server/internal/workflowhost/agents.go | 8 +- v2-server/internal/workflowhost/host.go | 51 +++- .../internal/workflowhost/skills_test.go | 230 ++++++++++++++++-- 15 files changed, 562 insertions(+), 77 deletions(-) diff --git a/v2-server/README.md b/v2-server/README.md index baa62c0ca..114ce39a9 100644 --- a/v2-server/README.md +++ b/v2-server/README.md @@ -220,7 +220,7 @@ Ora 实际创建的技能目录和市场技能链接会追加到该工作副本 **工作流目标** 在配置的 `projectId`(必填)里运行一个工作流。默认或 `versionPolicy: "fixed"` 保存 `{kind: "workflow", workflowId, snapshotId, input}`,校验项目属于当前用户、`snapshotId` 是这个工作流在本租户的非草稿版本;`schedule-resources` 列出已发布工作流及当前生效快照,固定模式保存此快照。`versionPolicy: "latest"` 不带 `snapshotId`,保存时只校验存在生效发布版本,每次触发在创建运行的事务内解析当前发布快照。两种模式的运行都保留实际使用的快照;发布不改写配置或历史。启动变量用快照里的默认值,`input` 作为开始节点的初始输入。进程没有执行桥时(`Options.WorkflowRuns` 为空)不列出工作流,写入返回 `503 schedule_target_unavailable`。旧的、没有这些字段的 workflow 引用照旧只读,按它写入返回 `400 invalid_target`。 -执行走页面同一个运行入口:`scheduler.WorkflowAdapter` 用任务创建者的 scope 创建运行(冻结快照、项目、输入,名称取任务名)并经执行桥启动,occurrence 的 `executionRef` 记 `{"workflowRunId"}`。运行的 `trigger_kind = 'schedule'`、`trigger_ref = `,唯一索引 `v2_workflow_runs_schedule_trigger` 保证一个触发只对应一个运行,重复派发和恢复都按这个身份找回原运行,不创建替代运行。执行桥拒绝启动(图里有还不能执行的节点、输入不满足开始节点)时记 `skipped / workflow_run_not_startable` 并取消那个未开始的运行。协调器每次 Tick 核对未释放的记录:运行结束后成功记 `succeeded`、失败记 `failed / workflow_run_failed`(重启恢复中失败的记 `interrupted`;boot sweep 吸收并恢复的 Iteration 运行仍在执行,记录回到 `running`,可从定时任务取消,之后按它自己的结果记)、取消记 `cancelled`,随即释放占位;运行结束后、结算之前被用户删除的,记 `failed / workflow_run_deleted` 并释放;节点会话由执行桥自己结束,定时侧没有会话要 End。还是 pending 的运行说明启动没有提交(进程重启过),取消它并记 `execution_not_started`。工作流 occurrence 的结果就是它的运行,`…/runs/{oid}/result` 返回 `404 execution_result_not_found`,页面按 `workflowRunId` 读运行详情。 +执行走页面同一个运行入口:`scheduler.WorkflowAdapter` 用任务创建者的 scope 创建运行(冻结快照、项目、输入,名称取任务名)并经执行桥启动,occurrence 的 `executionRef` 记 `{"workflowRunId"}`。运行的 `trigger_kind = 'schedule'`、`trigger_ref = `,唯一索引 `v2_workflow_runs_schedule_trigger` 保证一个触发只对应一个运行,重复派发和恢复都按这个身份找回原运行,不创建替代运行。执行桥拒绝启动时取消那个未开始的运行并记 `skipped`:缺工作区角色记 `workflow_role_not_found`,缺个人 Skill 或项目市场 Skill 记 `workflow_skill_not_found`,图里有还不能执行的节点或输入不满足开始节点记 `workflow_run_not_startable`。协调器每次 Tick 核对未释放的记录:运行结束后成功记 `succeeded`、失败记 `failed / workflow_run_failed`(重启恢复中失败的记 `interrupted`;boot sweep 吸收并恢复的 Iteration 运行仍在执行,记录回到 `running`,可从定时任务取消,之后按它自己的结果记)、取消记 `cancelled`,随即释放占位;运行结束后、结算之前被用户删除的,记 `failed / workflow_run_deleted` 并释放;节点会话由执行桥自己结束,定时侧没有会话要 End。还是 pending 的运行说明启动没有提交(进程重启过),取消它并记 `execution_not_started`。工作流 occurrence 的结果就是它的运行,`…/runs/{oid}/result` 返回 `404 execution_result_not_found`,页面按 `workflowRunId` 读运行详情。 之前已保存的引用仍按原 JSON 读取,可暂停/恢复计划;只读候选类型 `ScheduleLegacyTarget` 保留未知字段,不解释、改写或校验其中的提供方参数。没有删除数据库数据或迁移其字段,前端也不提供引用参数编辑/执行入口。 @@ -858,7 +858,7 @@ ConversationAdapter 按冻结配置分流:无项目文本对话用公共 Start - **Condition**:按 desktop 的 `condition.rs` 依次判断各个 case,第一个成立的 case 胜出,都不成立走 `else`(没有 `sourceHandle` 的出边就是 `else`);还没写规则的 case 直接跳过。16 个比较运算符同 desktop;只有 `exists`/`not_exists`/`empty`/`not_empty` 容忍未赋值,其余读到未赋值、未声明或类型不符的变量时节点以 `condition_evaluation` 失败,不猜分支。比较值只写一个 `{{#…#}}` 时保留变量的原类型,混排时按字符串渲染。选中的分支写进运行 payload 的 `conditionDecisions`,不写节点输出,也不进变量池;启动时拒绝重复的 case id(`workflow_run_duplicate_condition_case`)和指向不存在分支的出边(`workflow_run_unknown_condition_branch`)。没走的分支上的节点不建节点行(desktop 同样不落库分支激活),运行详情返回 `conditionDecisions`,由客户端投影为“未激活分支”。 - **Aggregator**:按 desktop 的 V1 契约,按声明顺序取第一个**已赋值**的候选原样传出(键存在即算,`null`、`false`、`0`、`""`、`[]`、`{}` 都命中),写入 `{node}.output`;全部未赋值时以 `aggregator_no_match` 失败,读到未声明的候选直接失败。它不读分支决策,只看变量池。 - **Agent 结构化输出**:`outputContract.type` 为 `structured` 的 Agent,prompt 末尾追加 desktop 的输出约定(示例和 Schema);回答按 desktop 的顺序提取 JSON 对象(整段 → 代码块 → 文中第一个完整对象),再按 Schema 子集(`type`、`properties`、`required`、`additionalProperties`、`items`)校验。通过时原回答仍是 `{node}.output`,对象写入 `{node}.structured_output`;不通过时节点以 `structured_output` 失败并保留原回答。 -- **节点 Skill**:启用的个人 Skill 按启动运行的用户读取,在节点开始时冻结文档;插件 Skill 使用 `namespace/identifier`,必须有目标项目当前安装版本的成功回执。启动 Agent 前,仅将所选导入放到运行目录的 `.opencode/skills`、`.claude/skills`,并在 prompt 中要求读取。插件选择包含该包内全部 Skill;下一节点替换上一个节点的投影,未选择的导入不会自动继承。项目自带的技能保留,同名冲突、已修改的投影文档、缺失包或失效回执会让节点失败,不覆盖或静默略过。节点 payload 的 `skills` 记录所选标识,执行会话保留冻结的文档和插件版本。 +- **节点 Skill**:`StartRun` 在发起首次调度前按启动者身份与目标项目整图预检冻结图里所有可执行 Agent 节点(根图、Iteration 区域成员与全部 Loop 体;禁用绑定与备用节点不参与)已启用的 `skills`:个人 Skill 缺失或插件 Skill 尚未在目标项目生效时返回 `400 workflow_skill_not_found`(`params` 携带 `nodeId`、`nodeTitle`、`skillId`,节点标题为空白时回退 `nodeId`),运行保持 `pending`、不启动会话,补齐后同一运行可直接启动;底层存储故障按服务端错误处理,不误报为技能缺失。节点开始时再读一次并冻结文档:启用的个人 Skill 按启动运行的用户读取,插件 Skill 使用 `namespace/identifier`,必须有目标项目当前安装版本的成功回执;启动后技能被删除或移除时,该节点失败(可「从失败处继续」)。启动 Agent 前,仅将所选导入放到运行目录的 `.opencode/skills`、`.claude/skills`,并在 prompt 中要求读取。插件选择包含该包内全部 Skill;下一节点替换上一个节点的投影,未选择的导入不会自动继承。项目自带的技能保留,同名冲突、已修改的投影文档、缺失包或失效回执会让节点失败,不覆盖或静默略过。节点 payload 的 `skills` 记录所选标识,执行会话保留冻结的文档和插件版本。 - **节点 MCP**:启用绑定从租户目录读取精确版本、配置 revision 和设置,最多 16 个服务、设置紧凑 JSON 合计最多 64 KiB。首轮向支持 `session_mcp_lifecycle` 的 Node 发送选中插件和设置。会话存储支持固定显式选择,并为每个成员保留无值目标。保存配置、移除或重装插件的事务同步推进受影响的活跃会话 generation。每轮准入与配置保存共用会话行锁,派发使用该轮提交时记录的 generation。禁用或空选择沿用普通执行路径。 - **角色、Skill、MCP 与重试已应用;Loop 内的交互模式不应用**:节点 payload 的 `unapplied` 只剩 `interactive`(只有 Loop 成员:v2 自动执行它;根图中的交互式 Agent 停下等发起人,见下一条)。角色从工作区的角色目录实时读取并注入提示词(见「工作区角色」),Skill 按节点选择物化,MCP 按上一条解析并派发,三者都不再列出;`retry` 不再列出:自动重试已按 desktop 覆盖根作用域、Loop 成员与 Iteration 成员(交互节点从不重试,`node_runtime.rs:373-379`@`ebd5b725`),`enabled: false` 或 `maxRetries: 0` 表示不会发生重试,也不算 v2 的缺口。是否自动重试由 `internal/workflow` 的 `retryApplies` 一处决定,`unappliedAgentSettings` 与运行时的重试判断都调用它。历史运行保存的 `skill`、`retry` 标记仍按原样展示。analyze 的 `unappliedSettings` 与运行调用同一个判断(`internal/workflow` 的 `unappliedAgentSettings`),两边都传入节点所在的 Iteration 或 Loop,备用节点按它所属的容器算;某项设置开始应用后从这份列表里去掉,编辑器的提示随之消失,前端不需要改。 - **交互式 Agent 节点(简化版)**:按 desktop 的旧版 `end_turn` 完成规则(desktop@ebd5b725 `docs/workflows/workflow-runs.md` “Interactive nodes”)。根作用域开了 `interactive` 的 Agent 首轮结束后不结束会话,节点行回到 `pending`(运行读作 `awaitingInput`),payload 的 `interactive` 记下已结束的轮数、会话是否已结束、能否完成、阻止完成的原因和完成时会采用的回答,以及发起人发过几条消息(`sent`)和其中最后一条是否没有送达(`last_turn_error`,见下文)。只有发起人可以发消息、停止本轮或完成,其他成员调用得到 `409 run_owned`,只能看。每轮消息立即在同一会话里执行,与运行里其他节点的轮次同时进行,执行期间节点为 `running`,结束后再回到等待输入。一轮怎么结束都不会让节点失败(desktop `workflow-runs.md:125-126, 152-155`):Agent 自己结束、但没有正常结束的一轮(拒绝、`max_tokens`、`max_turn_requests`、未知停止原因、v2 没有要求的取消、模型调用被时限截断),包括首轮,都让节点回到等待输入,会话保持打开(执行服务的 `LifetimeHeld`),可以继续对话。能不能完成由完成门禁决定(见下一条“交互节点的完成门禁”),被拒时节点保持等待输入。通过后先结束会话(结束没有得到确认时返回 `503`,节点留在等待完成,但会话不再接受消息,可以重试完成),再一次性写入输出和 `{node}.structured_output`、调度后继。“停止本轮”只停这一轮(见「停止一轮」):会话保留时节点回到等待输入、可以接着发消息;Node 没能保留会话时会话结束,节点继续等待完成、不再接受消息。被停的这一轮记 `turn_stopped`,要「仍然完成」(`force`)或接着对话。在提示送到 Agent 之前就被停的消息(Node 在准入前丢弃了它,或者它的提交被拒、还没重发)也算作一轮被停的轮次,不提示「未送达」,但它没有回答任何东西:节点保留上一次回答过的轮次,原来能完成的回答照样能直接完成,重启后重建的节点也一样。Agent 丢失(崩溃、事件流断开、历史读不全,执行服务报告 `AgentLost`,或结果读不到;Node 本身丢失除外,见「交互等待跨重启」)时会话结束,节点同样停在等待完成,`session_ended` 为 true,丢失的这一轮记 `turn_unknown`,同样要 `force`。同一运行的节点共用一个目录,目录里可以同时有多个活着的会话(和 desktop 一样):节点等待输入时,运行里其他分支的 Agent 照常开始、执行和结束自己的会话,等待中的会话不受影响,之后的消息仍进同一个会话。这依赖 Node 的 `shared_checkout_sessions` 能力(desktop `c5265072` 起,同一 checkout 最多 8 个未结束的会话),执行服务在握手时要求它;每个会话一次只执行一轮,运行里不同节点的会话同时执行,发给等待中节点的消息不用等其他节点的轮次。执行桥让同一运行的未结束会话不超过这个上限(等待输入的交互会话也占名额),多出的节点等到有会话结束再开始,所以一波节点多于空余名额时不会失败,只是排队;排队中的节点行仍是 `running`、没有会话,payload 带 `session_slot_wait`(`since` 开始等待的时刻、`limit` 上限),拿到名额(在 Start 之前)或因取消、Loop 关闭、续跑换代、关停而放弃时去掉,绑定会话的同一条语句也会去掉(那次清除失败时,执行中的节点也不会读作排队),页面据此对还没有会话的节点显示「等待会话名额」而不是运行中;进程在排队时退出留下的标记随 boot sweep 失败的行留着,页面不把终态运行下的行显示为等待;名额全被等待输入的会话占着时,要等其中一个完成或运行结束;重启不会让出这些名额,合法的交互等待跨重启保留(见「交互等待跨重启」)。Node 仍拒绝超出的会话(`checkout_session_limit`,例如上一个会话的结束还没被 Node 确认)时,只有它自己失败:普通节点按 `session` 失败并照常自动重试,交互节点首轮就被拒时没有会话可等,按 `interactive_session` 失败(可续跑)。会话已经结束的节点(停止时没能保留会话,或 Agent 丢失)再发消息得到 `409 workflow_node_session_ended`,不会先返回 200;兄弟节点让运行失败时,正在执行的消息照常执行完,之后节点不再回到等待输入,会话结束、随运行一起关闭;还没开始执行的消息不再执行。已接受的一轮在提交给会话时被执行服务拒绝的(例如服务不可用,或会话已在别处结束),这条消息没有执行,而发消息的接口此前已经返回 200:节点回到等待输入,`payload.interactive.last_turn_error` 记为 `not_delivered`,说的是第 `sent` 条消息,运行页面据此提示上一条消息未送达;发消息的接口在响应里返回这条消息的序号(`sent`),页面拿它和摘要里的 `sent` 比对,只对发出这条消息的页面提供重新填入;发起人的下一条消息被接受时清掉这个标记。会话还开着的可以重发。执行服务接受了、随后在 Agent 驱动里被拒绝、Agent 并没有收到的消息也一样处理(#1234),不算一轮:轮数、回答和完成条件都停在上一轮送达的样子,`sent` 照常占用这个序号,下一条消息用下一个序号。驱动确知没送到的情况有:发给 Node 之前就被拒绝(会话在 Node 上已经结束、已损坏或 Node 已经断开而没有新 Agent 接手,项目解析失败,或这一轮没能启动),以及 Node 不执行就拒收了这条命令(会话已结束,或等的 MCP 配置一直没到);执行服务把这样的结果标为 `NotDelivered`。拒绝同时结束了会话的(执行服务报 `AgentLost`),摘要里还有 `session_ended: true`,页面提示消息没送到、会话也已结束,并给出两条出路:用上一轮送达的回答完成这一步,或者停止运行后「从失败处继续」重新开始这一步(整次运行会被取消,这个节点从首轮重来,这段对话不再接续);会话没结束的可以重发。发送中途失败(写到一半 Node 断了)或已经交给 Node 之后会话才结束的,消息可能已经到了 Agent,仍按丢失的一轮计数、会话结束。重启后从会话轮次重建节点时,这样的记录同样不计入轮数;只认 `NotDelivered`,升级前写下的、只带 `NotStarted` 的追问记录当时算了一轮,重建后照旧算一轮(不会悄悄去掉这一轮和它的阻止原因)。共用目录里的 Skill 是各个活着会话所选 Skill 的并集:等待中节点的 Skill 留在目录里,同名时以后开始的节点为准,会话结束后在下一个节点开始时清掉。交互节点仍可能失败的只有会话没能建立(执行器清单不可用、执行服务拒绝启动、会话绑定被拒,或首轮在 Agent 启动之前就失败:项目、checkout、插件、Skill 没准备好,Agent 配置或模型授权在发给 Node 之前没通过,或被 Node 按 checkout 拒绝;Agent 启动之后才丢失的首轮仍停在等待完成),失败类型是 v2 自己的 `interactive_session`(可续跑,不自动重试;desktop 从不重试交互节点,`retry_tests.rs:636-644`);模型、Agent、提示词模板等配置错误照普通 Agent 的类型失败,这些类型本来就不自动重试。完成、发消息、停止在执行桥里按节点认领,同时到达时只有一个生效,其余得到 `400 workflow_node_not_awaiting_input` 或 `409 workflow_node_turn_not_running`。取消运行会先结束所有等待中的会话;行刚移到 `running` 而运行恰好被取消时,发消息返回 `400 workflow_node_not_awaiting_input`,不返回 200。兄弟节点让运行失败时,等待中的节点结束会话并记为 `cancelled`;完成请求此时已经在结束会话的,照样记下采用的回答(和运行失败后才结束的其他根节点一样,「从失败处继续」会沿用它),不启动后继,运行可以删除。不做:Agent 完成信号(`completionSignal: "agent"` 按 `end_turn` 执行,记进 `unapplied`,等 Node 协议能交给 Agent 宿主 MCP,circus#1242),以及人工轮次前缀的 ``;Loop 内的交互式 Agent 照普通节点执行并在 `unapplied` 记 `interactive`(desktop 会在 Loop 里停住,v2 不支持),Iteration 内的交互式成员和 desktop 一样在发布校验时被拒。 diff --git a/v2-server/internal/scheduler/workflow.go b/v2-server/internal/scheduler/workflow.go index 8962063ce..4432f11ed 100644 --- a/v2-server/internal/scheduler/workflow.go +++ b/v2-server/internal/scheduler/workflow.go @@ -42,6 +42,10 @@ var ( // ErrWorkflowNotStartable is the bridge refusing to start the run: the graph holds a node kind // v2 cannot execute yet, or the input does not satisfy the Start node. ErrWorkflowNotStartable = errors.New("workflow run cannot start") + // ErrWorkflowRoleNotFound is the bridge refusing start because a referenced workspace role is missing. + ErrWorkflowRoleNotFound = errors.New("workflow role not found") + // ErrWorkflowSkillNotFound is the bridge refusing start because an enabled Skill is unavailable. + ErrWorkflowSkillNotFound = errors.New("workflow skill not found") // ErrWorkflowStopUnconfirmed is a cancellation execution has not confirmed yet. ErrWorkflowStopUnconfirmed = errors.New("workflow run stop unconfirmed") ) @@ -177,13 +181,9 @@ func (a *WorkflowAdapter) Dispatch(ctx context.Context, scope execution.Scope, o } if run.Status == store.WorkflowStatusPending { if _, err = a.runs.Start(ctx, scope, run.ID); err != nil { - if errors.Is(err, ErrWorkflowNotStartable) || errors.Is(err, execution.ErrUnavailable) { + if reason := workflowStartRejected(err); reason != "" { // Nothing started: withdraw the pending run so no list keeps waiting on it. _, cancelErr := a.runs.Cancel(writeCtx, scope, run.ID) - reason := "workflow_run_not_startable" - if errors.Is(err, execution.ErrUnavailable) { - reason = "execution_unavailable" - } _, applyErr := a.apply(writeCtx, scope, o, "rejected", "", reason) return errors.Join(err, cancelErr, applyErr) } @@ -195,6 +195,20 @@ func (a *WorkflowAdapter) Dispatch(ctx context.Context, scope execution.Scope, o return err } +func workflowStartRejected(err error) string { + switch { + case errors.Is(err, execution.ErrUnavailable): + return "execution_unavailable" + case errors.Is(err, ErrWorkflowSkillNotFound): + return "workflow_skill_not_found" + case errors.Is(err, ErrWorkflowRoleNotFound): + return "workflow_role_not_found" + case errors.Is(err, ErrWorkflowNotStartable): + return "workflow_run_not_startable" + } + return "" +} + // workflowTargetUnavailable names a frozen target that can no longer be created: the workflow, // its snapshot or the project is gone. Creating nothing is then certain. func workflowTargetUnavailable(err error) string { diff --git a/v2-server/internal/scheduler/workflow_test.go b/v2-server/internal/scheduler/workflow_test.go index 25c9c7e31..436d56cc7 100644 --- a/v2-server/internal/scheduler/workflow_test.go +++ b/v2-server/internal/scheduler/workflow_test.go @@ -190,6 +190,8 @@ func TestWorkflowStartRefusalWithdrawsTheRun(t *testing.T) { reason string }{ {ErrWorkflowNotStartable, "workflow_run_not_startable"}, + {ErrWorkflowRoleNotFound, "workflow_role_not_found"}, + {ErrWorkflowSkillNotFound, "workflow_skill_not_found"}, {execution.ErrUnavailable, "execution_unavailable"}, } { t.Run(tc.reason, func(t *testing.T) { diff --git a/v2-server/internal/server/schedule_workflow_target.go b/v2-server/internal/server/schedule_workflow_target.go index e7a39cd12..49249d0c6 100644 --- a/v2-server/internal/server/schedule_workflow_target.go +++ b/v2-server/internal/server/schedule_workflow_target.go @@ -49,7 +49,13 @@ func (r scheduleWorkflowRuns) Find(ctx context.Context, scope execution.Scope, t func (r scheduleWorkflowRuns) Start(ctx context.Context, scope execution.Scope, runID string) (store.WorkflowRun, error) { run, err := r.host.StartRun(ctx, runScope(scope), runID) - if errors.Is(err, ErrWorkflowRunNotStartable) { + var invalidInput *WorkflowRunInputInvalid + switch { + case errors.Is(err, ErrWorkflowSkillNotFound): + return run, errors.Join(scheduler.ErrWorkflowSkillNotFound, err) + case errors.Is(err, ErrWorkflowRoleNotFound): + return run, errors.Join(scheduler.ErrWorkflowRoleNotFound, err) + case errors.Is(err, ErrWorkflowRunNotStartable), errors.As(err, &invalidInput): return run, errors.Join(scheduler.ErrWorkflowNotStartable, err) } return run, err diff --git a/v2-server/internal/server/schedule_workflow_target_test.go b/v2-server/internal/server/schedule_workflow_target_test.go index 45d8fa8fa..c7d6d9e09 100644 --- a/v2-server/internal/server/schedule_workflow_target_test.go +++ b/v2-server/internal/server/schedule_workflow_target_test.go @@ -23,18 +23,26 @@ import ( ) // storeRunHost starts and cancels runs in the store as the execution bridge would, executing -// nothing; refuse makes it decline to start, as the bridge does for a graph it cannot run. +// nothing; refuseErr (or refuse) makes it decline to start, as the bridge does for a graph it +// cannot run or a missing dependency. type storeRunHost struct { - db *store.Store - refuse bool - scopes []server.WorkflowRunScope + db *store.Store + refuse bool + refuseErr error + scopes []server.WorkflowRunScope } func (h *storeRunHost) StartRun(ctx context.Context, scope server.WorkflowRunScope, runID string) (store.WorkflowRun, error) { h.scopes = append(h.scopes, scope) + if h.refuseErr != nil { + return store.WorkflowRun{}, h.refuseErr + } if h.refuse { return store.WorkflowRun{}, server.ErrWorkflowRunNotStartable } + if err := h.db.SetWorkflowStarter(ctx, scope.TenantID, runID, scope.UserID); err != nil { + return store.WorkflowRun{}, err + } return h.db.StartWorkflowRun(ctx, scope.TenantID, runID) } @@ -260,6 +268,10 @@ func TestScheduledWorkflowRunsThroughTheRunEntry(t *testing.T) { if _, err := f.db.FinishWorkflowRun(ctx, f.scope.TenantID, run.ID, store.WorkflowStatusSucceeded, &output, nil); err != nil { t.Fatal(err) } + finishedRun, err := f.db.WorkflowRun(ctx, f.scope.TenantID, run.ID) + if err != nil || finishedRun.StartedBy != f.scope.UserID || finishedRun.StartedByName != "Owner" { + t.Fatalf("scheduled finished run starter = %+v %v", finishedRun, err) + } if err := c.Tick(ctx, f.scope); err != nil { t.Fatal(err) } @@ -280,31 +292,43 @@ func TestScheduledWorkflowRunsThroughTheRunEntry(t *testing.T) { } func TestScheduledWorkflowTheBridgeRefusesLeavesNoRunBehind(t *testing.T) { - f := newWorkflowTargetFixture(t) - f.host.refuse = true - ctx := context.Background() - input, _ := json.Marshal(f.target(nil)) - saved, err := f.db.CreateScheduleConfig(ctx, f.scope.TenantID, f.scope.UserID, store.ScheduleInput{Name: "拒绝", ProjectID: f.project.ID, Target: input, Rule: json.RawMessage(`{"kind":"hours","hours":1,"timezone":"UTC"}`)}) - if err != nil { - t.Fatal(err) - } - c, err := server.NewScheduleCoordinator(f.db, f.options(true), func() time.Time { return saved.CreatedAt.Add(time.Minute) }) - if err != nil { - t.Fatal(err) - } - if err = c.Recover(ctx, f.scope); err != nil { - t.Fatal(err) - } - occ, err := c.Manual(ctx, f.scope, saved.ID, "refused") - if !errors.Is(err, server.ErrWorkflowRunNotStartable) { - t.Fatalf("manual = %+v %v", occ, err) - } - occ, err = f.db.GetOccurrence(ctx, f.scope.TenantID, f.scope.UserID, occ.ID) - if err != nil || occ.Status != "skipped" || occ.Reason != "workflow_run_not_startable" || !occ.Released { - t.Fatalf("occurrence = %+v %v", occ, err) - } - run, err := f.db.ScheduledWorkflowRun(ctx, f.scope.TenantID, occ.ID) - if err != nil || run.Status != store.WorkflowStatusCancelled { - t.Fatalf("refused run = %+v %v", run, err) + for _, tc := range []struct { + name string + err error + wantReason string + }{ + {"not_startable", server.ErrWorkflowRunNotStartable, "workflow_run_not_startable"}, + {"role_missing", server.ErrWorkflowRoleNotFound, "workflow_role_not_found"}, + {"skill_missing", &server.WorkflowSkillNotFound{NodeID: "a", NodeTitle: "审查", SkillID: "review-checklist"}, "workflow_skill_not_found"}, + } { + t.Run(tc.name, func(t *testing.T) { + f := newWorkflowTargetFixture(t) + f.host.refuseErr = tc.err + ctx := context.Background() + input, _ := json.Marshal(f.target(nil)) + saved, err := f.db.CreateScheduleConfig(ctx, f.scope.TenantID, f.scope.UserID, store.ScheduleInput{Name: "拒绝", ProjectID: f.project.ID, Target: input, Rule: json.RawMessage(`{"kind":"hours","hours":1,"timezone":"UTC"}`)}) + if err != nil { + t.Fatal(err) + } + c, err := server.NewScheduleCoordinator(f.db, f.options(true), func() time.Time { return saved.CreatedAt.Add(time.Minute) }) + if err != nil { + t.Fatal(err) + } + if err = c.Recover(ctx, f.scope); err != nil { + t.Fatal(err) + } + occ, err := c.Manual(ctx, f.scope, saved.ID, "refused-"+tc.name) + if !errors.Is(err, tc.err) { + t.Fatalf("manual = %+v %v", occ, err) + } + occ, err = f.db.GetOccurrence(ctx, f.scope.TenantID, f.scope.UserID, occ.ID) + if err != nil || occ.Status != "skipped" || occ.Reason != tc.wantReason || !occ.Released { + t.Fatalf("occurrence = %+v %v, want reason %q", occ, err, tc.wantReason) + } + run, err := f.db.ScheduledWorkflowRun(ctx, f.scope.TenantID, occ.ID) + if err != nil || run.Status != store.WorkflowStatusCancelled { + t.Fatalf("refused run = %+v %v", run, err) + } + }) } } diff --git a/v2-server/internal/server/task_comment_workflow_test.go b/v2-server/internal/server/task_comment_workflow_test.go index 74606be19..16609d4ee 100644 --- a/v2-server/internal/server/task_comment_workflow_test.go +++ b/v2-server/internal/server/task_comment_workflow_test.go @@ -658,6 +658,70 @@ func TestTaskCommentWorkflowMissingRoleReturns400AndRecovers(t *testing.T) { waitForCommentWorkflowStatus(t, c, "/api/v2/tenants/"+tid+"/tasks/"+task["id"].(string)+"/timeline", runID, "succeeded") } +func TestTaskCommentWorkflowMissingSkillReturns400AndRecovers(t *testing.T) { + f := newSquadServer(t) + commentWorkflowServer(t, f) + c := f.taskClient() + c.login() + tid := f.tenant(t) + f.project(t) + + graph := `{"nodes":[{"id":"start","data":{"kind":"start"}},{"id":"a","data":{"kind":"agent","title":"代码检查","agentConfig":{"prompt":"Review","skills":[{"skillId":"review-checklist","enabled":true}]}}},{"id":"out","data":{"kind":"output","outputs":[{"name":"comment","variableSelector":["start","input"]}]}}],"edges":[{"source":"start","target":"a"},{"source":"a","target":"out"}]}` + wf, _, err := f.store.CreateWorkflow(f.ctx, tid, "MissingSkillWF", graph) + if err != nil { + t.Fatal(err) + } + if _, err := f.store.PublishWorkflow(f.ctx, tid, wf.ID, "v1", nil); err != nil { + t.Fatal(err) + } + _, task := c.do("POST", "/api/v2/tenants/"+tid+"/tasks", map[string]any{"title": "MissingSkillTask", "projectId": taskProjectID}) + path := "/api/v2/tenants/" + tid + "/tasks/" + task["id"].(string) + "/comments" + payload := map[string]any{ + "body": "@MissingSkillWF", + "mentions": []map[string]any{{"type": "workflow", "id": wf.ID}}, + "workflow": map[string]any{"workflowId": wf.ID, "values": map[string]any{}}, + } + key := map[string]string{"Idempotency-Key": "missing-skill-comment"} + status, got := c.doHeaders("POST", path, payload, key) + if status != 400 || got["code"] != "workflow_skill_not_found" { + t.Fatalf("missing skill comment = %d %v, want 400 workflow_skill_not_found", status, got) + } + params, _ := got["params"].(map[string]any) + if params["nodeId"] != "a" || params["nodeTitle"] != "代码检查" || params["skillId"] != "review-checklist" { + t.Fatalf("missing skill comment params = %v", params) + } + for _, table := range []string{"v2_task_comments", "v2_workflow_runs", "v2_workflow_scopes", "v2_workflow_run_roots"} { + var count int + if err := f.db.QueryRow(f.ctx, `SELECT COUNT(*) FROM `+table).Scan(&count); err != nil { + t.Fatal(err) + } + if count != 0 { + t.Fatalf("missing skill refusal left %d rows in %s", count, table) + } + } + + if _, err := f.store.CreateSkill(f.ctx, tid, task["createdBy"].(string), store.SkillInput{Name: "review-checklist", Description: "审查清单", Content: "# 清单"}); err != nil { + t.Fatal(err) + } + // Replace the graph with a no-agent output path while keeping an unreached Agent declaring the skill so preflight still runs. + readyGraph := `{"nodes":[{"id":"start","data":{"kind":"start"}},{"id":"cond","data":{"kind":"condition","cases":[{"id":"never","logic":"and","conditions":[{"variableSelector":["start","input"],"operator":"is","value":"__never__"}]}]}},{"id":"a","data":{"kind":"agent","title":"代码检查","agentConfig":{"prompt":"Review","skills":[{"skillId":"review-checklist","enabled":true}]}}},{"id":"out","data":{"kind":"output","outputs":[{"name":"comment","variableSelector":["start","input"]}]}}],"edges":[{"source":"start","target":"cond"},{"source":"cond","sourceHandle":"never","target":"a"},{"source":"cond","target":"out"}]}` + wfReady, _, err := f.store.CreateWorkflow(f.ctx, tid, "ReadySkillWF", readyGraph) + if err != nil { + t.Fatal(err) + } + if _, err := f.store.PublishWorkflow(f.ctx, tid, wfReady.ID, "v1", nil); err != nil { + t.Fatal(err) + } + payload["mentions"] = []map[string]any{{"type": "workflow", "id": wfReady.ID}} + payload["workflow"] = map[string]any{"workflowId": wfReady.ID, "values": map[string]any{}} + status, created := c.doHeaders("POST", path, payload, key) + if status != 201 { + t.Fatalf("retry after skill creation = %d %v", status, created) + } + runID := created["workflowRun"].(map[string]any)["id"].(string) + waitForCommentWorkflowStatus(t, c, "/api/v2/tenants/"+tid+"/tasks/"+task["id"].(string)+"/timeline", runID, "succeeded") +} + func TestTaskCommentWorkflowBootRecoverClearsPendingCrashWindow(t *testing.T) { f := newSquadServer(t) diff --git a/v2-server/internal/server/task_workflows.go b/v2-server/internal/server/task_workflows.go index 9fee9b050..3f9dae03a 100644 --- a/v2-server/internal/server/task_workflows.go +++ b/v2-server/internal/server/task_workflows.go @@ -37,7 +37,8 @@ func taskWorkflowFault(w http.ResponseWriter, err error) { fault(w, http.StatusConflict, "task_closed") case errors.Is(err, store.ErrNotFound): fault(w, http.StatusNotFound, "not_found") - case errors.Is(err, ErrWorkflowRunNotStartable), errors.Is(err, ErrWorkflowRunNotEditable), errors.Is(err, ErrWorkflowRoleNotFound): + case errors.Is(err, ErrWorkflowRunNotStartable), errors.Is(err, ErrWorkflowRunNotEditable), + errors.Is(err, ErrWorkflowRoleNotFound), errors.Is(err, ErrWorkflowSkillNotFound): workflowRunLifecycleFault(w, err, "task workflow") default: workflowRunFault(w, err, "task workflow") diff --git a/v2-server/internal/server/task_workflows_test.go b/v2-server/internal/server/task_workflows_test.go index 0efc4aef3..bd7db672c 100644 --- a/v2-server/internal/server/task_workflows_test.go +++ b/v2-server/internal/server/task_workflows_test.go @@ -230,6 +230,34 @@ func TestTaskWorkflowChoiceErrorsHTTP(t *testing.T) { if status, started := c.doHeaders("POST", path, map[string]any{"workflowId": roleWF.ID}, map[string]string{"Idempotency-Key": "role-ready"}); status != 201 || started["workflowRunId"] == "" { t.Fatalf("start after creating role = %d %v", status, started) } + + // Reset task back to pending to verify missing Skill preflight refusal and recovery. + c.routes = original + _, secondTask := c.do("POST", base, map[string]any{"title": "Skill handling", "projectId": taskProjectID, "assignee": map[string]any{"type": "human", "id": task["createdBy"]}}) + secondPath := base + "/" + secondTask["id"].(string) + "/workflow-runs" + c.routes = routes + skillGraph := `{"nodes":[{"id":"start","data":{"kind":"start"}},{"id":"reviewer","data":{"kind":"agent","title":"审查","agentConfig":{"prompt":"Review","skills":[{"skillId":"review-checklist","enabled":true}]}}}],"edges":[{"source":"start","target":"reviewer"}]}` + skillWF, _, err := f.store.CreateWorkflow(f.ctx, tid, "Needs skill", skillGraph) + if err != nil { + t.Fatal(err) + } + if _, err := f.store.PublishWorkflow(f.ctx, tid, skillWF.ID, "v1", nil); err != nil { + t.Fatal(err) + } + status, got = c.doHeaders("POST", secondPath, map[string]any{"workflowId": skillWF.ID}, map[string]string{"Idempotency-Key": "missing-skill"}) + if status != 400 || got["code"] != "workflow_skill_not_found" { + t.Fatalf("missing skill = %d %v, want 400 workflow_skill_not_found", status, got) + } + skillParams, _ := got["params"].(map[string]any) + if skillParams["nodeId"] != "reviewer" || skillParams["nodeTitle"] != "审查" || skillParams["skillId"] != "review-checklist" { + t.Fatalf("missing skill params = %v", skillParams) + } + if _, err := f.store.CreateSkill(f.ctx, tid, secondTask["createdBy"].(string), store.SkillInput{Name: "review-checklist", Description: "审查清单", Content: "# 清单"}); err != nil { + t.Fatal(err) + } + if status, started := c.doHeaders("POST", secondPath, map[string]any{"workflowId": skillWF.ID}, map[string]string{"Idempotency-Key": "skill-ready"}); status != 201 || started["workflowRunId"] == "" { + t.Fatalf("start after creating skill = %d %v", status, started) + } } func TestTaskWorkflowListHidesDeletedHandleFailureOnFirstSettlementHTTP(t *testing.T) { diff --git a/v2-server/internal/server/workflow_run_lifecycle.go b/v2-server/internal/server/workflow_run_lifecycle.go index e977bebf6..b4283002c 100644 --- a/v2-server/internal/server/workflow_run_lifecycle.go +++ b/v2-server/internal/server/workflow_run_lifecycle.go @@ -40,10 +40,31 @@ var ( // ErrWorkflowRoleNotFound reports a run whose frozen graph references a role the workspace's // role catalog does not have, so the start is refused before anything executes. ErrWorkflowRoleNotFound = errors.New("workflow role not found") + // ErrWorkflowSkillNotFound reports a run whose frozen graph enables a personal or marketplace + // Skill that is not available to the starter in the target project, refusing start before dispatch. + ErrWorkflowSkillNotFound = errors.New("workflow skill not found") // ErrWorkflowRunStopUnconfirmed reports a cancellation whose stop was not confirmed. ErrWorkflowRunStopUnconfirmed = errors.New("workflow run stop is unconfirmed") ) +// WorkflowSkillNotFound names the first enabled Skill binding a start preflight could not resolve, +// mirroring desktop's WorkflowSkillNotFoundParams (nodeId, nodeTitle, skillId). +type WorkflowSkillNotFound struct { + NodeID string + NodeTitle string + SkillID string + Reason string +} + +func (e *WorkflowSkillNotFound) Error() string { + if e.Reason != "" { + return fmt.Sprintf("%s: node %q (%s) skill %q: %s", ErrWorkflowSkillNotFound, e.NodeTitle, e.NodeID, e.SkillID, e.Reason) + } + return fmt.Sprintf("%s: node %q (%s) skill %q", ErrWorkflowSkillNotFound, e.NodeTitle, e.NodeID, e.SkillID) +} + +func (e *WorkflowSkillNotFound) Unwrap() error { return ErrWorkflowSkillNotFound } + // WorkflowRunInputInvalid names one rejected start variable, mirroring desktop's error params. type WorkflowRunInputInvalid struct { Variable string @@ -173,6 +194,7 @@ func (h *handler) completeWorkflowNode(w http.ResponseWriter, r *http.Request, a // stays a 500 so an implementation bug is not reported as a client mistake. func workflowRunLifecycleFault(w http.ResponseWriter, err error, op string) { var invalid *WorkflowRunInputInvalid + var missingSkill *WorkflowSkillNotFound if interactiveNodeFault(w, err) { return } @@ -185,6 +207,18 @@ func workflowRunLifecycleFault(w http.ResponseWriter, err error, op string) { fault(w, http.StatusBadRequest, "workflow_run_start_failed") case errors.Is(err, ErrWorkflowRoleNotFound): fault(w, http.StatusBadRequest, "workflow_role_not_found") + case errors.As(err, &missingSkill): + writeJSON(w, http.StatusBadRequest, map[string]any{ + "code": "workflow_skill_not_found", + "params": map[string]any{ + "nodeId": missingSkill.NodeID, + "nodeTitle": missingSkill.NodeTitle, + "skillId": missingSkill.SkillID, + }, + "requestId": requestID(), + }) + case errors.Is(err, ErrWorkflowSkillNotFound): + fault(w, http.StatusBadRequest, "workflow_skill_not_found") case errors.Is(err, ErrWorkflowRunNotEditable): fault(w, http.StatusConflict, "workflow_run_not_editable") case errors.Is(err, ErrWorkflowNodeNotAwaitingInput): diff --git a/v2-server/internal/server/workflow_run_lifecycle_test.go b/v2-server/internal/server/workflow_run_lifecycle_test.go index 54a8b0351..ea6f0bf03 100644 --- a/v2-server/internal/server/workflow_run_lifecycle_test.go +++ b/v2-server/internal/server/workflow_run_lifecycle_test.go @@ -147,6 +147,8 @@ func TestWorkflowRunLifecycleRefusals(t *testing.T) { {"run missing", store.ErrWorkflowRunNotFound, "workflow_run_not_found", 404, "POST", "/start", nil}, {"stop unconfirmed", server.ErrWorkflowRunStopUnconfirmed, "workflow_run_stop_unconfirmed", 503, "POST", "/cancel", nil}, {"state conflict", store.ErrWorkflowRunState, "workflow_run_state_conflict", 409, "POST", "/start", nil}, + {"role missing", server.ErrWorkflowRoleNotFound, "workflow_role_not_found", 400, "POST", "/start", nil}, + {"skill missing", &server.WorkflowSkillNotFound{NodeID: "reviewer", NodeTitle: "代码审查", SkillID: "code_review"}, "workflow_skill_not_found", 400, "POST", "/start", nil}, {"input invalid", &server.WorkflowRunInputInvalid{Variable: "count", Reason: "must be a number"}, "workflow_run_input_invalid", 400, "PATCH", "/input", map[string]any{"input": "x"}}, } { t.Run(tc.name, func(t *testing.T) { @@ -163,6 +165,12 @@ func TestWorkflowRunLifecycleRefusals(t *testing.T) { t.Fatalf("params = %v", params) } } + if tc.code == "workflow_skill_not_found" { + params := failure["params"].(map[string]any) + if params["nodeId"] != "reviewer" || params["nodeTitle"] != "代码审查" || params["skillId"] != "code_review" { + t.Fatalf("skill params = %v", params) + } + } }) } } diff --git a/v2-server/internal/store/workflow_skills.go b/v2-server/internal/store/workflow_skills.go index 66905ac30..2fb6fe74f 100644 --- a/v2-server/internal/store/workflow_skills.go +++ b/v2-server/internal/store/workflow_skills.go @@ -2,12 +2,27 @@ package store import ( "context" + "errors" "fmt" "strings" + "github.com/jackc/pgx/v5" + "github.com/wanglongan587/cloud/v2-server/internal/execution" ) +// MissingWorkflowSkillError reports one enabled Skill binding that is absent from the starter's +// personal catalog or not yet deployed to the target project. It unwraps to ErrSkillNotFound so +// callers can separate user-actionable missing dependencies from storage failures. +type MissingWorkflowSkillError struct { + SkillID string + Reason string +} + +func (e *MissingWorkflowSkillError) Error() string { return e.Reason } + +func (e *MissingWorkflowSkillError) Unwrap() error { return ErrSkillNotFound } + // projectName returns the display name of a tenant project, falling back to its id when the // row has no Name yet (projects are created from repository URLs). func (s *Store) projectName(ctx context.Context, tenant, id string) (string, error) { @@ -27,15 +42,15 @@ func (s *Store) ResolveWorkflowSkills(ctx context.Context, scope execution.Scope return result, nil } if _, err := s.GetProject(ctx, scope, project); err != nil { - return nil, fmt.Errorf("could not load the project for selected Skills") + return nil, fmt.Errorf("could not load the project for selected Skills: %w", err) } projectName, err := s.projectName(ctx, scope.TenantID, project) if err != nil { - return nil, fmt.Errorf("could not load the project for selected Skills") + return nil, fmt.Errorf("could not load the project for selected Skills: %w", err) } documents, err := s.ListSkills(ctx, scope.TenantID, scope.UserID) if err != nil { - return nil, fmt.Errorf("could not load your imported Skills") + return nil, fmt.Errorf("could not load your imported Skills: %w", err) } byName := make(map[string]Skill, len(documents)) for _, doc := range documents { @@ -50,7 +65,10 @@ func (s *Store) ResolveWorkflowSkills(ctx context.Context, scope execution.Scope if strings.Contains(name, "/") { namespace, identifier, ok := pluginIdentity(name) if !ok { - return nil, fmt.Errorf("invalid Skill plugin identity: %s", name) + return nil, &MissingWorkflowSkillError{ + SkillID: name, + Reason: fmt.Sprintf("invalid Skill plugin identity: %s", name), + } } var version string err := s.pool.QueryRow(ctx, `SELECT a.desired_version FROM v2_projects p @@ -60,14 +78,23 @@ func (s *Store) ResolveWorkflowSkills(ctx context.Context, scope execution.Scope AND a.kind='skill' AND a.desired_state='installed' AND a.status='active' AND r.revision=a.version AND r.state='installed' AND r.installed_version=a.desired_version`, project, scope.TenantID, namespace, identifier).Scan(&version) + if errors.Is(err, pgx.ErrNoRows) { + return nil, &MissingWorkflowSkillError{ + SkillID: name, + Reason: fmt.Sprintf("技能 %s 还没下发到项目「%s」:请先在技能页确认该技能已下发成功(或等下发中完成)后再重新运行工作流", name, projectName), + } + } if err != nil { - return nil, fmt.Errorf("技能 %s 还没下发到项目「%s」:请先在技能页确认该技能已下发成功(或等下发中完成)后再重新运行工作流", name, projectName) + return nil, fmt.Errorf("resolve project Skill %s: %w", name, err) } result.Plugins = append(result.Plugins, execution.SkillPlugin{ID: name, Version: version}) } else { doc, ok := byName[name] if !ok { - return nil, fmt.Errorf("Skill %s is missing from your imported skills", name) + return nil, &MissingWorkflowSkillError{ + SkillID: name, + Reason: fmt.Sprintf("Skill %s is missing from your imported skills", name), + } } result.Documents = append(result.Documents, execution.SkillDocument{Name: doc.Name, Description: doc.Description, Content: doc.Content}) } diff --git a/v2-server/internal/workflow/graph.go b/v2-server/internal/workflow/graph.go index 0bfaaf5bd..bd135c762 100644 --- a/v2-server/internal/workflow/graph.go +++ b/v2-server/internal/workflow/graph.go @@ -193,6 +193,58 @@ func (g *Graph) RoleReferences() []string { return result } +// SkillReference names one enabled Skill binding an executable Agent node declares. +type SkillReference struct { + NodeID string + NodeTitle string + SkillID string +} + +// SkillReferences lists the enabled Skill bindings every executable Agent node declares, in a +// stable order: the root graph, then each Loop body by id. As on desktop (collect_skills), every +// enabled Skill in the frozen graph is checked before the run starts, even on branches this run +// never reaches; disabled bindings and unpublished spare nodes are excluded, and a blank node +// title falls back to its id. +func (g *Graph) SkillReferences() []SkillReference { + type key struct { + nodeID string + skillID string + } + seen := map[key]bool{} + result := []SkillReference{} + collect := func(nodes []*node) { + for _, n := range nodes { + if n.kind != "agent" { + continue + } + view := g.view(n) + title := strings.TrimSpace(view.Title) + if title == "" { + title = view.ID + } + for _, skillID := range view.Agent().Skills { + k := key{nodeID: view.ID, skillID: skillID} + if skillID != "" && !seen[k] { + seen[k] = true + result = append(result, SkillReference{NodeID: view.ID, NodeTitle: title, SkillID: skillID}) + } + } + } + } + collect(g.root.order) + ids := make([]string, 0, len(g.scopes)) + for id := range g.scopes { + if id != "" { + ids = append(ids, id) + } + } + sort.Strings(ids) + for _, id := range ids { + collect(g.scopes[id].order) + } + return result +} + // StartVariable is one typed Start input declaration. type StartVariable struct { Name string diff --git a/v2-server/internal/workflowhost/agents.go b/v2-server/internal/workflowhost/agents.go index caab4f42d..16290f3ef 100644 --- a/v2-server/internal/workflowhost/agents.go +++ b/v2-server/internal/workflowhost/agents.go @@ -197,7 +197,13 @@ func (h *Host) runAgent(st *runState, d workflow.AgentDispatch, generation uint6 } skills, err := h.store.ResolveWorkflowSkills(h.ctx, st.scope, d.ProjectID, cfg.Skills) if err != nil { - fail(workflow.Failure{Kind: workflow.FailureMissingAgentConfig, Message: err.Error()}) + msg := "could not resolve selected Skills" + if errors.Is(err, store.ErrSkillNotFound) { + msg = err.Error() + } else if h.ctx.Err() == nil { + h.log.Warn("resolve workflow skills", "run", d.RunID, "node_run", d.NodeRunID, "error", publicReason(err), "error_type", fmt.Sprintf("%T", err)) + } + fail(workflow.Failure{Kind: workflow.FailureMissingAgentConfig, Message: msg}) return } mcp, err := h.store.ResolveWorkflowMCP(h.ctx, st.scope, d.ProjectID, cfg.MCPs) diff --git a/v2-server/internal/workflowhost/host.go b/v2-server/internal/workflowhost/host.go index a93875169..2f9308c49 100644 --- a/v2-server/internal/workflowhost/host.go +++ b/v2-server/internal/workflowhost/host.go @@ -442,12 +442,12 @@ func executionScope(s server.WorkflowRunScope) execution.Scope { return execution.Scope{TenantID: s.TenantID, UserID: s.UserID} } -// StartRun authorizes the run against the caller's tenant, then checks the roles its graph -// references, then starts it and its first wave. Roles are a start hard-dependency exactly as on -// desktop: the whole frozen graph is checked before anything runs, so a role missing from a node -// this run would not reach still refuses the start, and the run stays pending until the role -// exists again. A graph that does not parse is left to the engine, which reports it as it always -// has. +// StartRun authorizes the run against the caller's tenant, then checks the roles and Skills its +// graph references, then starts it and its first wave. Roles and Skills are start hard-dependencies +// exactly as on desktop: the whole frozen graph is checked before anything runs, so a dependency +// missing from a node this run would not reach still refuses the start, and the run stays pending +// until the dependency exists again. A graph that does not parse is left to the engine, which +// reports it as it always has. func (h *Host) StartRun(ctx context.Context, scope server.WorkflowRunScope, runID string) (store.WorkflowRun, error) { run, err := h.store.WorkflowRun(ctx, scope.TenantID, runID) if err != nil { @@ -456,10 +456,11 @@ func (h *Host) StartRun(ctx context.Context, scope server.WorkflowRunScope, runI if run.Status != store.WorkflowStatusPending { return store.WorkflowRun{}, server.ErrWorkflowRunNotStartable } - if err := h.checkRoles(ctx, scope.TenantID, runID); err != nil { + execScope := executionScope(scope) + if err := h.checkDependencies(ctx, execScope, run.ProjectID, runID); err != nil { return store.WorkflowRun{}, err } - st := h.register(runID, executionScope(scope)) + st := h.register(runID, execScope) // The run outlives the request once it starts; a disconnecting client must not abandon the // first scheduling pass halfway. err = h.engine.StartAs(context.WithoutCancel(ctx), runID, st.scope.UserID) @@ -473,9 +474,10 @@ func (h *Host) StartRun(ctx context.Context, scope server.WorkflowRunScope, runI return h.store.WorkflowRun(ctx, scope.TenantID, runID) } -// checkRoles resolves every role the frozen graph references in the caller's tenant. Roles are -// shared by the tenant, so the check reads the same catalog the settings page writes. -func (h *Host) checkRoles(ctx context.Context, tenant, runID string) error { +// checkDependencies resolves every role and enabled Skill the frozen graph references before the +// first scheduling pass: roles against the workspace catalog, personal Skills against the starter's +// catalog, and marketplace Skill plugins against the run's project. +func (h *Host) checkDependencies(ctx context.Context, scope execution.Scope, projectID, runID string) error { frozen, err := h.store.WorkflowEngineContext(ctx, runID) if err != nil { return err @@ -485,10 +487,35 @@ func (h *Host) checkRoles(ctx context.Context, tenant, runID string) error { return nil // the engine reports the parse failure on start } for _, reference := range graph.RoleReferences() { - if _, err := h.store.ResolveWorkflowRole(ctx, tenant, reference); err != nil { + if _, err := h.store.ResolveWorkflowRole(ctx, scope.TenantID, reference); err != nil { return roleCheckError(reference, err) } } + skillRefs := graph.SkillReferences() + if len(skillRefs) == 0 { + return nil + } + names := make([]string, 0, len(skillRefs)) + firstBySkill := make(map[string]workflow.SkillReference, len(skillRefs)) + for _, ref := range skillRefs { + if _, ok := firstBySkill[ref.SkillID]; !ok { + firstBySkill[ref.SkillID] = ref + names = append(names, ref.SkillID) + } + } + if _, err := h.store.ResolveWorkflowSkills(ctx, scope, projectID, names); err != nil { + var missing *store.MissingWorkflowSkillError + if errors.As(err, &missing) { + ref := firstBySkill[missing.SkillID] + return &server.WorkflowSkillNotFound{ + NodeID: ref.NodeID, + NodeTitle: ref.NodeTitle, + SkillID: ref.SkillID, + Reason: missing.Reason, + } + } + return err + } return nil } diff --git a/v2-server/internal/workflowhost/skills_test.go b/v2-server/internal/workflowhost/skills_test.go index ec04cffdd..14d131d18 100644 --- a/v2-server/internal/workflowhost/skills_test.go +++ b/v2-server/internal/workflowhost/skills_test.go @@ -3,12 +3,16 @@ package workflowhost import ( "context" "encoding/json" + "errors" "fmt" "slices" "strings" "testing" + "time" + "github.com/wanglongan587/cloud/v2-server/internal/server" "github.com/wanglongan587/cloud/v2-server/internal/store" + "github.com/wanglongan587/cloud/v2-server/internal/workflow" ) func TestWorkflowFreezesSelectedSkillAndClearsItForNextNode(t *testing.T) { @@ -40,26 +44,214 @@ func TestWorkflowFreezesSelectedSkillAndClearsItForNextNode(t *testing.T) { f.await(t, runID, terminal) } -func TestWorkflowRejectsMissingSkillBeforeExecution(t *testing.T) { - for _, config := range []string{`"skills":[{"skillId":"missing-skill","enabled":true}]`} { - t.Run(config, func(t *testing.T) { - f := newFixture(t) - graph := strings.Replace(twoAgents, `"roleId":"reviewer"`, config, 1) - runID := f.run(t, graph, str("check")) - if _, err := f.host.StartRun(context.Background(), f.scope, runID); err != nil { - t.Fatal(err) - } - run, nodes := f.await(t, runID, terminal) - if run.Status != store.WorkflowStatusFailed || errorKind(t, node(nodes, "a")) != "missing_agent_config" { - t.Fatalf("not refused: %+v", run) - } - f.exec.mu.Lock() - defer f.exec.mu.Unlock() - if len(f.exec.started) != 0 { - t.Fatal("started despite missing dependency") - } - }) +func TestStartRefusesASkillMissingFromAnyNodeOfTheGraph(t *testing.T) { + t.Run("unreached branch personal skill", func(t *testing.T) { + f := newFixture(t) + ctx := context.Background() + graph := strings.Replace( + reviewBranches, + `"prompt":"返工"`, + `"prompt":"返工","skills":[{"skillId":"ignored-disabled","enabled":false},{"skillId":"missing-rework","enabled":true}]`, + 1, + ) + runID := f.run(t, graph, str("支付重构")) + + _, err := f.host.StartRun(ctx, f.scope, runID) + if !errors.Is(err, server.ErrWorkflowSkillNotFound) { + t.Fatalf("start error = %v, want missing skill", err) + } + var missing *server.WorkflowSkillNotFound + if !errors.As(err, &missing) || missing.NodeID != "fix" || missing.NodeTitle != "返工" || missing.SkillID != "missing-rework" { + t.Fatalf("WorkflowSkillNotFound = %+v, want node fix (返工) skill missing-rework", missing) + } + f.exec.mu.Lock() + started := len(f.exec.started) + f.exec.mu.Unlock() + if started != 0 { + t.Fatalf("started %d Agents despite missing skill", started) + } + run, err := f.s.WorkflowRun(ctx, f.scope.TenantID, runID) + if err != nil { + t.Fatal(err) + } + if run.Status != store.WorkflowStatusPending { + t.Fatalf("run status = %s, want pending", run.Status) + } + + // Creating the skill in the starter's catalog makes the same pending run startable. + if _, err := f.s.CreateSkill(ctx, f.scope.TenantID, f.scope.UserID, store.SkillInput{ + Name: "missing-rework", Description: "返工清单", Content: "# 返工步骤", + }); err != nil { + t.Fatal(err) + } + if _, err := f.host.StartRun(ctx, f.scope, runID); err != nil { + t.Fatalf("start after creating skill = %v", err) + } + f.exec.finish(f.exec.awaitStart(t), completed(`{"approved":true}`)) + f.exec.finish(f.exec.awaitStart(t), completed("已发布")) + f.await(t, runID, terminal) + }) + + t.Run("loop body blank title and undeployed marketplace skill", func(t *testing.T) { + f := newFixture(t) + ctx := context.Background() + loopGraph := `{ + "schemaVersion": 2, + "nodes":[ + {"id":"start","data":{"kind":"start"}}, + {"id":"loop","data":{"kind":"loop","loopConfig":{ + "maxIterations":2, + "variables":[{"name":"draft","valueType":"string","initial":{"kind":"constant","value":""},"feedback":["worker","output"]}], + "until":{"logic":"and","conditions":[{"variableSelector":["worker","output"],"operator":"equals","value":"done"}]}, + "outputs":[{"name":"result","variableSelector":["worker","output"]}] + }}}, + {"id":"entry","parentId":"loop","data":{"kind":"start","containerId":"loop"}}, + {"id":"worker","data":{"kind":"agent","title":" ","containerId":"loop","agentConfig":{"executor":{"agentCli":"official/ora-space.opencode","modelId":"fixture"},"prompt":"工作","skills":[{"skillId":"official/mattpocock.skills","enabled":true}]}}}, + {"id":"out","data":{"kind":"output","outputs":[{"name":"res","variableSelector":["loop","result"]}]}} + ], + "edges":[ + {"source":"start","target":"loop"}, + {"source":"entry","target":"worker"}, + {"source":"loop","target":"out"} + ] + }` + runID := f.run(t, loopGraph, str("检查循环技能")) + _, err := f.host.StartRun(ctx, f.scope, runID) + var missing *server.WorkflowSkillNotFound + if !errors.Is(err, server.ErrWorkflowSkillNotFound) || !errors.As(err, &missing) { + t.Fatalf("start error = %v, want WorkflowSkillNotFound", err) + } + if missing.NodeID != "worker" || missing.NodeTitle != "worker" || missing.SkillID != "official/mattpocock.skills" { + t.Fatalf("missing = %+v, want worker/worker/official/mattpocock.skills", missing) + } + }) +} + +func TestSkillDeletedAfterStartFailsTheNodeResumably(t *testing.T) { + f := newFixture(t) + ctx := context.Background() + skill, err := f.s.CreateSkill(ctx, f.scope.TenantID, f.scope.UserID, store.SkillInput{ + Name: "review-checklist", Description: "审查", Content: "# 审查清单", + }) + if err != nil { + t.Fatal(err) + } + graph := strings.Replace(twoAgents, `"prompt":"审阅这段初稿:{{#a.output#}}"`, + `"prompt":"审阅这段初稿:{{#a.output#}}","skills":[{"skillId":"review-checklist","enabled":true}]`, 1) + runID := f.run(t, graph, str("支付重构")) + if _, err := f.host.StartRun(ctx, f.scope, runID); err != nil { + t.Fatal(err) } + a := f.exec.awaitStart(t) + if err := f.s.DeleteSkill(ctx, f.scope.TenantID, f.scope.UserID, skill.ID); err != nil { + t.Fatal(err) + } + f.exec.finish(a, completed("初稿")) + + run, nodes := f.await(t, runID, terminal) + if run.Status != store.WorkflowStatusFailed { + t.Fatalf("run = %+v, want failed", run) + } + b := node(nodes, "b") + if kind := errorKind(t, b); kind != "missing_agent_config" { + t.Fatalf("node b failure = %s, want missing_agent_config", kind) + } + var detail struct { + ErrorDetail struct { + Message string `json:"message"` + Resumable bool `json:"resumable"` + AutoRetryable bool `json:"auto_retryable"` + } `json:"error_detail"` + } + if err := json.Unmarshal(b.Payload, &detail); err != nil { + t.Fatal(err) + } + if !detail.ErrorDetail.Resumable || detail.ErrorDetail.AutoRetryable || !strings.Contains(detail.ErrorDetail.Message, "review-checklist") { + t.Fatalf("detail = %+v", detail.ErrorDetail) + } + + if _, err := f.s.CreateSkill(ctx, f.scope.TenantID, f.scope.UserID, store.SkillInput{ + Name: "review-checklist", Description: "审查", Content: "# 恢复后的审查清单", + }); err != nil { + t.Fatal(err) + } + if _, err := f.host.ResumeRun(ctx, f.scope, runID); err != nil { + t.Fatalf("resume after recreating skill = %v", err) + } + bSession := f.exec.awaitStart(t) + f.exec.finish(bSession, completed("已审阅")) + resumed, _ := f.await(t, runID, terminal) + if resumed.Status != store.WorkflowStatusSucceeded { + t.Fatalf("resumed run = %+v, want succeeded", resumed) + } +} + +func TestSkillLookupDatabaseErrorIsNotReportedAsMissingSkill(t *testing.T) { + t.Run("start preflight preserves database error", func(t *testing.T) { + f, admin := newFixtureWithAdmin(t) + ctx := context.Background() + graph := strings.Replace(twoAgents, `"roleId":"reviewer"`, `"skills":[{"skillId":"review-checklist","enabled":true}]`, 1) + runID := f.run(t, graph, str("技能库故障")) + if _, err := admin.Exec(ctx, `ALTER TABLE v2_skills RENAME COLUMN content TO broken_content`); err != nil { + t.Fatal(err) + } + _, err := f.host.StartRun(ctx, f.scope, runID) + if err == nil || errors.Is(err, server.ErrWorkflowSkillNotFound) { + t.Fatalf("start error = %v, want database error rather than ErrWorkflowSkillNotFound", err) + } + }) + + t.Run("interactive node mid-run database error stays non-retryable and hides SQL", func(t *testing.T) { + f, admin := newFixtureWithAdmin(t) + ctx := context.Background() + if _, err := f.s.CreateSkill(ctx, f.scope.TenantID, f.scope.UserID, store.SkillInput{ + Name: "review-checklist", Description: "审查", Content: "# 审查", + }); err != nil { + t.Fatal(err) + } + graph := strings.Replace( + interactiveChain, + `"prompt":"起草:{{#start.input#}}","interactive":true`, + `"prompt":"起草:{{#start.input#}}","interactive":true,"skills":[{"skillId":"review-checklist","enabled":true}],"retry":{"enabled":true,"maxRetries":2,"initialDelaySeconds":0}`, + 1, + ) + runID := f.run(t, graph, str("交互技能库故障")) + entered, release := f.holdDispatchOf(t, "a") + if _, err := f.host.StartRun(ctx, f.scope, runID); err != nil { + t.Fatal(err) + } + select { + case <-entered: + case <-time.After(5 * time.Second): + t.Fatal("interactive Agent dispatch never started") + } + if _, err := admin.Exec(ctx, `ALTER TABLE v2_skills RENAME COLUMN content TO broken_content`); err != nil { + t.Fatal(err) + } + release() + + run, nodes := f.await(t, runID, terminal) + if run.Status != store.WorkflowStatusFailed { + t.Fatalf("run = %+v, want failed", run) + } + var detail struct { + ErrorDetail struct { + Kind string `json:"kind"` + Message string `json:"message"` + Resumable bool `json:"resumable"` + AutoRetryable bool `json:"auto_retryable"` + } `json:"error_detail"` + } + if err := json.Unmarshal(node(nodes, "a").Payload, &detail); err != nil { + t.Fatal(err) + } + if detail.ErrorDetail.Kind != string(workflow.FailureMissingAgentConfig) || !detail.ErrorDetail.Resumable || detail.ErrorDetail.AutoRetryable { + t.Fatalf("error_detail = %+v, want missing_agent_config resumable=true auto_retryable=false", detail.ErrorDetail) + } + if strings.Contains(detail.ErrorDetail.Message, "broken_content") { + t.Fatalf("error_detail leaked SQL identifier: %q", detail.ErrorDetail.Message) + } + }) } func TestWorkflowRejectsMissingEnabledMCPAndIgnoresDisabledBindings(t *testing.T) { From 5a664cff76adde5b20f3afad1c744da5d776c31f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=BE=99=E5=AE=89?= <297888591+wanglongan587@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:11:05 +0800 Subject: [PATCH 2/5] test(v2-server): verify workflow starter persistence and retry failure injection --- .../internal/store/workflow_runs_test.go | 74 +++++++++ v2-server/internal/workflowhost/retry_test.go | 155 +++++++++++++++++- 2 files changed, 228 insertions(+), 1 deletion(-) diff --git a/v2-server/internal/store/workflow_runs_test.go b/v2-server/internal/store/workflow_runs_test.go index c9b7e3619..3d188f9ad 100644 --- a/v2-server/internal/store/workflow_runs_test.go +++ b/v2-server/internal/store/workflow_runs_test.go @@ -444,3 +444,77 @@ func TestWorkflowRunCreationAndVersionDeletionSerialize(t *testing.T) { } } } + +func TestWorkflowRunStarterPersistsAcrossFinishCancelAndSchedule(t *testing.T) { + s := storetest.Open(t) + user, tenant := storetest.Login(t, s, "starter-lifecycle-owner") + ctx := context.Background() + project := workflowProject(t, s, user, tenant, "project-starter-lifecycle") + w, _ := publishedWorkflow(t, s, tenant, "发起人追踪", "v1") + + startAs := func(in store.WorkflowRunInput) store.WorkflowRun { + t.Helper() + created, err := s.CreateWorkflowRun(ctx, tenant, w.ID, "", in) + if err != nil { + t.Fatal(err) + } + if err := s.SetWorkflowStarter(ctx, tenant, created.ID, user); err != nil { + t.Fatal(err) + } + if _, err := s.StartWorkflowRun(ctx, tenant, created.ID); err != nil { + t.Fatal(err) + } + return created + } + + // 1. Succeeded run keeps starter name in detail and list. + okRun := startAs(store.WorkflowRunInput{ProjectID: project.ID, Name: "成功运行"}) + out := `{"ok":true}` + finished, err := s.FinishWorkflowRun(ctx, tenant, okRun.ID, store.WorkflowStatusSucceeded, &out, nil) + if err != nil || finished.Status != store.WorkflowStatusSucceeded || finished.StartedBy != user || finished.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("finish succeeded = %+v %v", finished, err) + } + + // 2. Failed run keeps starter name. + failRun := startAs(store.WorkflowRunInput{ProjectID: project.ID, Name: "失败运行"}) + errMsg := "node failed" + failed, err := s.FinishWorkflowRun(ctx, tenant, failRun.ID, store.WorkflowStatusFailed, nil, &errMsg) + if err != nil || failed.Status != store.WorkflowStatusFailed || failed.StartedBy != user || failed.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("finish failed = %+v %v", failed, err) + } + + // 3. Cancelled run keeps starter name. + cancelRun := startAs(store.WorkflowRunInput{ProjectID: project.ID, Name: "取消运行"}) + cancelled, err := s.CancelWorkflowRun(ctx, tenant, cancelRun.ID) + if err != nil || cancelled.Status != store.WorkflowStatusCancelled || cancelled.StartedBy != user || cancelled.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("cancel = %+v %v", cancelled, err) + } + + // 4. Scheduled workflow run keeps starter name across ScheduledWorkflowRun, detail and lists. + schedRun := startAs(store.WorkflowRunInput{ + ProjectID: project.ID, + Name: "定时运行", + TriggerKind: "schedule", + TriggerRef: "occ-starter-1", + }) + foundSched, err := s.ScheduledWorkflowRun(ctx, tenant, "occ-starter-1") + if err != nil || foundSched.ID != schedRun.ID || foundSched.StartedBy != user || foundSched.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("scheduled run = %+v %v", foundSched, err) + } + + for _, id := range []string{okRun.ID, failRun.ID, cancelRun.ID, schedRun.ID} { + got, err := s.WorkflowRun(ctx, tenant, id) + if err != nil || got.StartedBy != user || got.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("WorkflowRun(%s) = %+v %v", id, got, err) + } + } + listed, err := s.WorkflowRuns(ctx, tenant, w.ID, project.ID) + if err != nil || len(listed) != 4 { + t.Fatalf("WorkflowRuns = %+v %v", listed, err) + } + for _, item := range listed { + if item.StartedBy != user || item.StartedByName != "starter-lifecycle-owner" { + t.Fatalf("listed run %s starter = (%q, %q), want (%q, starter-lifecycle-owner)", item.ID, item.StartedBy, item.StartedByName, user) + } + } +} diff --git a/v2-server/internal/workflowhost/retry_test.go b/v2-server/internal/workflowhost/retry_test.go index ed6020dd4..da4e00731 100644 --- a/v2-server/internal/workflowhost/retry_test.go +++ b/v2-server/internal/workflowhost/retry_test.go @@ -811,13 +811,15 @@ func TestRetryInjectsPreviousFailureAndRespectsSwitch(t *testing.T) { func TestPreviousFailureForInjectionFilteringAndEnglishFormatting(t *testing.T) { errMsg := "refused by policy" + refusalOutput := "REFUSAL_BODY_MUST_NOT_BE_INJECTED" refusal := &store.WorkflowNodeRun{ Error: &errMsg, + Output: &refusalOutput, Payload: []byte(`{"error_detail":{"kind":"agent_refusal","attempt":2,"message":""}}`), } prev := previousFailureForInjection(true, refusal) if prev == nil || prev.Attempt != 2 || prev.Message != errMsg || prev.Output != nil { - t.Fatalf("prev = %+v", prev) + t.Fatalf("prev = %+v (want Output=nil for agent_refusal)", prev) } rendered := renderPreviousFailure(*prev, workflow.LocaleEnUS) for _, want := range []string{ @@ -829,6 +831,20 @@ func TestPreviousFailureForInjectionFilteringAndEnglishFormatting(t *testing.T) t.Fatalf("rendered missing %q:\n%s", want, rendered) } } + if strings.Contains(rendered, refusalOutput) || strings.Contains(rendered, "Previous final output") { + t.Fatalf("refusal answer leaked into injected prompt:\n%s", rendered) + } + + structuredOutput := "STRUCTURED_BAD_JSON_BODY" + structured := &store.WorkflowNodeRun{ + Output: &structuredOutput, + Payload: []byte(`{"error_detail":{"kind":"structured_output","attempt":1,"message":"invalid json"}}`), + } + prevStructured := previousFailureForInjection(true, structured) + if prevStructured == nil || prevStructured.Output == nil || *prevStructured.Output != structuredOutput { + t.Fatalf("structured prev = %+v, want output kept", prevStructured) + } + sessionFail := &store.WorkflowNodeRun{ Payload: []byte(`{"error_detail":{"kind":"session","attempt":1,"message":"boom"}}`), } @@ -839,3 +855,140 @@ func TestPreviousFailureForInjectionFilteringAndEnglishFormatting(t *testing.T) t.Fatalf("disabled flag returned %+v", got) } } + +func TestAgentPromptBlockOrderWithPreviousFailure(t *testing.T) { + graphJSON := strings.Replace( + reviewBranches, + `"prompt":"评审:{{#start.input#}}"`, + `"prompt":"评审:{{#start.input#}}","roleId":"reviewer","skills":[{"skillId":"review-checklist","enabled":true}]`, + 1, + ) + g, err := workflow.ParseGraph(graphJSON) + if err != nil { + t.Fatal(err) + } + reviewNode, ok := g.Node("review") + if !ok { + t.Fatal("missing review node") + } + d := workflow.AgentDispatch{ + Node: reviewNode, + Graph: g, + Locale: workflow.LocaleZhCN, + RunInput: str("支付重构"), + } + prevText := renderPreviousFailure(previousFailureForPrompt{ + Attempt: 1, + Kind: workflow.FailureStructuredOutput, + Message: "missing approved", + Output: str(`{"ok":1}`), + }, workflow.LocaleZhCN) + + blockText := func(raw json.RawMessage) string { + t.Helper() + var block struct { + Text string `json:"text"` + } + if err := json.Unmarshal(raw, &block); err != nil { + t.Fatalf("unmarshal prompt block %s: %v", raw, err) + } + return block.Text + } + + prompt := agentPrompt(d, "评审:支付重构", "# 评审角色约束", prevText) + wantPrefixes := []string{ + "", + "", + "", + "", + "", + "## 上一次尝试(第 1 次)失败信息", + "", + } + if len(prompt) != len(wantPrefixes) { + t.Fatalf("prompt block count = %d, want %d\n%s", len(prompt), len(wantPrefixes), promptText(t, prompt)) + } + for i, prefix := range wantPrefixes { + got := blockText(prompt[i]) + if !strings.HasPrefix(got, prefix) { + t.Fatalf("block[%d] = %q, want prefix %q", i, got, prefix) + } + } + + // Without a structured contract, the previous failure block sits last. + plainGraph, err := workflow.ParseGraph(strings.Replace(twoAgents, `"roleId":"reviewer"`, `"roleId":"reviewer","skills":[{"skillId":"review-checklist","enabled":true}]`, 1)) + if err != nil { + t.Fatal(err) + } + aNode, _ := plainGraph.Node("a") + plainPrompt := agentPrompt(workflow.AgentDispatch{Node: aNode, Graph: plainGraph, Locale: workflow.LocaleZhCN, RunInput: str("支付重构")}, "起草:支付重构", "# 评审角色约束", prevText) + if len(plainPrompt) != 6 || !strings.HasPrefix(blockText(plainPrompt[5]), "## 上一次尝试(第 1 次)失败信息") { + t.Fatalf("plain prompt blocks = %d, last = %q", len(plainPrompt), blockText(plainPrompt[len(plainPrompt)-1])) + } +} + +func TestAgentRefusalKeepsNodeOutputButDropsAnswerWhenInjectingRetry(t *testing.T) { + f := newFixture(t) + clock := retryClock(t, f) + ctx := context.Background() + graph := retryGraph(`{"enabled":true,"maxRetries":1,"initialDelaySeconds":0}`) + runID := f.run(t, graph, str("检查安全策略")) + if _, err := f.host.StartRun(ctx, f.scope, runID); err != nil { + t.Fatal(err) + } + firstSession := f.exec.awaitStart(t) + const refusalAnswer = "I cannot process this request because of refusal-answer-marker" + f.exec.finish(firstSession, execution.Result{ + Status: execution.StatusCompleted, + Answer: refusalAnswer, + AnswerComplete: true, + StopReason: "refusal", + }) + + waitRow, p := awaitWait(t, f, runID, "a") + history, err := f.s.WorkflowRunFailedAttempts(ctx, f.scope.TenantID, runID) + if err != nil || len(history) != 1 { + t.Fatalf("failed history = %+v %v", history, err) + } + if history[0].Output == nil || *history[0].Output != refusalAnswer { + t.Fatalf("failed refusal attempt output = %v, want preserved %q", history[0].Output, refusalAnswer) + } + + clock.Store(p.Wait.Due) + if err := f.host.engine.WakeRetry(ctx, runID, waitRow.ID); err != nil { + t.Fatal(err) + } + retrySession := f.exec.awaitStart(t) + prompt := promptText(t, f.exec.request(retrySession).Prompt) + for _, want := range []string{ + "## 上一次尝试(第 1 次)失败信息", + "失败类型:智能体拒绝了请求", + "agent refused the request", + } { + if !strings.Contains(prompt, want) { + t.Fatalf("retry prompt missing %q:\n%s", want, prompt) + } + } + if strings.Contains(prompt, refusalAnswer) || strings.Contains(prompt, "上一次的最终输出") { + t.Fatalf("retry prompt must drop agent_refusal answer:\n%s", prompt) + } + nodes, err := f.s.WorkflowRunNodes(ctx, f.scope.TenantID, runID) + if err != nil { + t.Fatal(err) + } + var payload map[string]any + if err := json.Unmarshal(node(nodes, "a").Payload, &payload); err != nil { + t.Fatal(err) + } + injected, _ := payload["injected_failure_context"].(string) + if !strings.Contains(injected, "智能体拒绝了请求") || strings.Contains(injected, refusalAnswer) { + t.Fatalf("injected_failure_context = %q", injected) + } + + f.exec.finish(retrySession, completed("已合规完成")) + f.exec.finish(f.exec.awaitStart(t), completed("审阅通过")) + settled, _ := f.await(t, runID, terminal) + if settled.Status != store.WorkflowStatusSucceeded { + t.Fatalf("settled = %+v, want succeeded", settled) + } +} From b2940aa17f31e7a96ca321ad29492e8d6a26449f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=8B=E9=BE=99=E5=AE=89?= <297888591+wanglongan587@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:11:05 +0800 Subject: [PATCH 3/5] feat(frontend-v2): localize workflow skill preflight errors and personal skill visibility hints --- frontend-v2/README.md | 2 +- .../chat/workflow-run/run-flow.test.tsx | 55 +++++++++++++++ .../features/chat/workflow-run/run-pane.tsx | 2 + .../chat/workflow-run/run-sidebar.tsx | 6 ++ .../features/chat/workflow-run/server-runs.ts | 11 ++- .../chat/workflow-run/translations.ts | 9 ++- .../workflow-run-start-dialog.tsx | 11 +++ .../features/collaboration/task-composer.tsx | 3 + .../collaboration/task-decomposition.tsx | 3 + .../features/collaboration/task-model.test.ts | 9 +++ .../src/features/collaboration/task-model.ts | 14 ++++ .../features/collaboration/task-page.test.tsx | 65 +++++++++++++++++ .../collaboration/task-workflow-dialog.tsx | 3 + frontend-v2/src/features/schedules/runtime.ts | 2 +- .../features/schedules/schedule-form.test.tsx | 23 +++++- .../src/features/schedules/schedule-form.tsx | 3 + .../editor/workflow-inspector.test.tsx | 4 +- .../src/lib/workflows/editor/translations.ts | 4 +- .../lib/workflows/host/contract-error.test.ts | 54 ++++++++++++++ .../src/lib/workflows/host/contract-error.ts | 25 +++++-- .../src/lib/workflows/personal-skills.test.ts | 58 +++++++++++++++ .../src/lib/workflows/personal-skills.ts | 70 +++++++++++++++++++ 22 files changed, 422 insertions(+), 14 deletions(-) create mode 100644 frontend-v2/src/lib/workflows/host/contract-error.test.ts create mode 100644 frontend-v2/src/lib/workflows/personal-skills.test.ts create mode 100644 frontend-v2/src/lib/workflows/personal-skills.ts diff --git a/frontend-v2/README.md b/frontend-v2/README.md index 1550b6cd5..352c8d97b 100644 --- a/frontend-v2/README.md +++ b/frontend-v2/README.md @@ -143,7 +143,7 @@ v2 只做核心执行,有几项界面在、但不会出现或不可用:服 Agent 和模型清单读取与 Chat 相同的 `/chat/executors`,保存后端返回的 `agentId` / `modelId`,目录为空或读取失败时不提供演示选项。旧占位配置保留并提示重新选择。角色目录读取工作区服务端目录(与设置页同一份数据);Skill 清单合并当前用户的服务端技能库与租户各空间已确认安装的 Skill 插件,插件标识保留 `namespace/identifier`,运行时检查目标项目的安装回执。MCP 候选读取租户真实安装目录,展示配置是否完整。卸载后已有绑定保留并提示不可用。每个节点最多启用 16 个 MCP,配置使用团队共享设置。安装和选择可以保存,非空执行须待 Node 与服务端完整生命周期接入;当前明确报错,不会忽略已启用的 MCP 后继续运行。 -Agent 检查器在「必需 Skill」下方提示“运行的节点会话对团队可见,所选个人 Skill 的内容也会被看到”,并在交互模式旁标「暂不生效」和一句原因(`editor/workflow-unapplied-setting-hint.tsx`)。标哪几项只看 v2-server analyze 返回的 `unappliedSettings`,它和运行结果里的 `payload.unapplied` 出自同一段服务端代码;前端只知道每项放在哪个字段旁、原因怎么说,不自己判断。角色、Skill、MCP 与重试已经应用,新分析不再列出它们;历史运行 payload 里保存的 `role`、`skill`、`retry` 标记仍按原样显示。服务端列出某项时提示出现,不再列出时自动消失;列出前端还没有对应字段的项时,在 Agent 设置末尾统一说明。浏览器里的旧工作流库(`local-workflow-backend.ts`)不执行运行,这两项总是空的。工作流页本身不运行工作流,运行在对话页里(见"运行工作流")。 +Agent 检查器在「必需 Skill」下方提示“运行时读取发起人同名的个人 Skill,其内容在节点会话中对团队可见”(工作流创建/启动对话框、任务处理/拆分/评论 `@` 工作流和定时任务表单在所选工作流启用了个人 Skill 时同步提示),并在交互模式旁标「暂不生效」和一句原因(`editor/workflow-unapplied-setting-hint.tsx`)。标哪几项只看 v2-server analyze 返回的 `unappliedSettings`,它和运行结果里的 `payload.unapplied` 出自同一段服务端代码;前端只知道每项放在哪个字段旁、原因怎么说,不自己判断。角色、Skill、MCP 与重试已经应用,新分析不再列出它们;历史运行 payload 里保存的 `role`、`skill`、`retry` 标记仍按原样显示。服务端列出某项时提示出现,不再列出时自动消失;列出前端还没有对应字段的项时,在 Agent 设置末尾统一说明。浏览器里的旧工作流库(`local-workflow-backend.ts`)不执行运行,这两项总是空的。工作流页本身不运行工作流,运行在对话页里(见"运行工作流")。 ### Unapplied settings and start warnings (English) diff --git a/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx b/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx index e17466f90..2e781648e 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-flow.test.tsx @@ -762,4 +762,59 @@ describe('workflow runs in chat', () => { dialog = await openDialog() expect(within(dialog).getByRole('checkbox', { name: '节点重跑时把上次失败原因告诉智能体' })).toBeChecked() }) + + it('shows the personal Skill team visibility hint in create and start dialogs only when enabled', async () => { + const hint = '运行时读取发起人同名的个人 Skill,其内容在节点会话中对团队可见。' + const graphWithPersonalSkill = { + nodes: [ + { id: 'start', type: 'workflow', position: { x: 0, y: 100 }, data: { kind: 'start', title: '开始', description: '' } }, + { + id: 'agent-1', + type: 'workflow', + position: { x: 300, y: 100 }, + data: { + kind: 'agent', + title: '审查节点', + description: '', + agentConfig: { + skills: [{ skillId: 'my-personal-skill', enabled: true }], + }, + }, + }, + { id: 'output', type: 'workflow', position: { x: 600, y: 100 }, data: { kind: 'output', title: '输出', description: '', outputs: [] } }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'agent-1' }, + { id: 'e2', source: 'agent-1', target: 'output' }, + ], + } + const created = workflows.backend.create({ name: '带个人技能的工作流', graph: JSON.stringify(graphWithPersonalSkill) }) + workflows.backend.publish({ workflowId: created.workflow.id, version: 'v1' }) + + const user = userEvent.setup() + await renderPage() + + // Workflow without personal Skills does not show the hint. + await user.click(within(project()).getByRole('button', { name: '在 ora-space/cloud 新建对话' })) + await user.click(await screen.findByRole('menuitem', { name: '运行工作流' })) + fireEvent.click(await screen.findByRole('menuitem', { name: /示例:代码审查/ })) + const plainDialog = await screen.findByRole('dialog', { name: '运行工作流' }) + expect(within(plainDialog).queryByText(hint)).not.toBeInTheDocument() + await user.keyboard('{Escape}') + await waitFor(() => expect(screen.queryByRole('dialog', { name: '运行工作流' })).not.toBeInTheDocument()) + + // Workflow with an enabled personal Skill shows the hint in both create and start dialogs. + await user.click(within(project()).getByRole('button', { name: '在 ora-space/cloud 新建对话' })) + await user.click(await screen.findByRole('menuitem', { name: '运行工作流' })) + fireEvent.click(await screen.findByRole('menuitem', { name: /带个人技能的工作流/ })) + const createDialog = await screen.findByRole('dialog', { name: '运行工作流' }) + expect(within(createDialog).getByText(hint)).toBeInTheDocument() + await user.click(within(createDialog).getByRole('button', { name: '创建运行' })) + + const pane = await screen.findByRole('region', { name: '工作流运行' }) + await within(pane).findByRole('button', { name: '启动' }, { timeout: 10_000 }) + await user.click(within(pane).getByRole('button', { name: '启动' })) + const startDialog = await screen.findByRole('dialog') + expect(within(startDialog).getByText(hint)).toBeInTheDocument() + }, 20_000) }) diff --git a/frontend-v2/src/features/chat/workflow-run/run-pane.tsx b/frontend-v2/src/features/chat/workflow-run/run-pane.tsx index 757687d03..cac9007c4 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-pane.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-pane.tsx @@ -15,6 +15,7 @@ import { useDarkTheme } from '@/lib/workflows/host/theme' import { toast } from '@/lib/workflows/host/ui' import { ContractError } from '@/lib/workflows/contracts' import { localizeContractError } from '@/lib/workflows/host/contract-error' +import { hasEnabledPersonalSkills } from '@/lib/workflows/personal-skills' import { isTerminalRunStatus, type GraphWorkflowRun, type WorkflowArtifact, type WorkflowNodeConversationItem } from '@/lib/workflows/runtime' import { WorkspaceNavigationProvider } from '@/components/workspace-panel/navigation' import { useWorkspacePanel, type WorkspacePanelState } from '@/components/workspace-panel/use-panel' @@ -487,6 +488,7 @@ function RunWorkspace({ tenantId, run, readOnly, hostedWorkspace, leading, refre unsupportedNodes={unsupportedNodes} analyzing={preflight.analyzing} analysisFailed={preflight.failed} + hasPersonalSkills={hasEnabledPersonalSkills(run.definitionSnapshot.nodes)} busy={busy} onOpenChange={setStartOpen} onStart={async (prompt, variables) => { diff --git a/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx b/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx index 17a1f697a..5995a810d 100644 --- a/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx +++ b/frontend-v2/src/features/chat/workflow-run/run-sidebar.tsx @@ -21,6 +21,7 @@ import { createHttpWorkflowContracts } from '@/lib/workflows/data/contracts-clie import { ContractError } from '@/lib/workflows/contracts' import { localizeContractError } from '@/lib/workflows/host/contract-error' import { workflowI18n } from '@/lib/workflows/host/i18n' +import { WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT } from '@/lib/workflows/personal-skills' import { isTerminalRunStatus } from '@/lib/workflows/runtime' import { FadeText } from '../components/fade-text' import { useChatStore } from '../store' @@ -210,6 +211,11 @@ function RunWorkflowForm({ {workflowRunTranslations['zh-CN']['workflowRun.injectLastFailure']} + {workflow.hasPersonalSkills && ( +

+ {WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT} +

+ )} {error &&

{error}

} }>取消 diff --git a/frontend-v2/src/features/chat/workflow-run/server-runs.ts b/frontend-v2/src/features/chat/workflow-run/server-runs.ts index 60136efc8..f3efc124a 100644 --- a/frontend-v2/src/features/chat/workflow-run/server-runs.ts +++ b/frontend-v2/src/features/chat/workflow-run/server-runs.ts @@ -24,6 +24,7 @@ import { } from '@/lib/workflows/api/generated' import { ContractError } from '@/lib/workflows/contracts' import { contractError, type WorkflowContracts } from '@/lib/workflows/data/contracts-client' +import { graphHasEnabledPersonalSkills } from '@/lib/workflows/personal-skills' import { isTerminalRunStatus, normalizeWorkflowDefinition, @@ -45,6 +46,8 @@ export interface PublishedWorkflow { * version is deleted, so the run is checked against this, never against the name. */ snapshotId: string + /** True when any Agent node in the published snapshot enables a personal Skill. */ + hasPersonalSkills?: boolean } /** @@ -74,7 +77,13 @@ export async function listPublishedWorkflows(library: WorkflowContracts, signal? .map(async (w): Promise => { try { const { workflow, published } = await library.get({ workflowId: w.id }, { signal }) - return published && { id: workflow.id, name: workflow.name, version: published.version, snapshotId: published.id } + return published && { + id: workflow.id, + name: workflow.name, + version: published.version, + snapshotId: published.id, + hasPersonalSkills: graphHasEnabledPersonalSkills(published.graph), + } } catch (error) { if (error instanceof ContractError && error.code === 'workflow_not_found') return null throw error diff --git a/frontend-v2/src/features/chat/workflow-run/translations.ts b/frontend-v2/src/features/chat/workflow-run/translations.ts index 954d77aee..24e342689 100644 --- a/frontend-v2/src/features/chat/workflow-run/translations.ts +++ b/frontend-v2/src/features/chat/workflow-run/translations.ts @@ -40,7 +40,10 @@ export const workflowRunTranslations = { "errors.workflow_run_validation": "工作流运行校验失败。", "errors.workflow_run_input_invalid": "启动变量 {{variable}} 的输入无效:{{reason}}", - "errors.workflow_skill_not_found": "该工作流需要的技能不可用。", + "errors.workflow_skill_not_found": + "该工作流需要的技能不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后重试。", + "errors.workflow_skill_not_found_detail": + "节点「{{nodeTitle}}」需要的技能 {{skillId}} 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后重试。", "errors.workflow_role_not_found": "工作流引用的角色在工作区角色目录里不存在,请先在设置的角色页新建同名角色再启动。", "errors.workflow_run_start_failed": "启动工作流运行失败。", @@ -639,7 +642,9 @@ export const workflowRunTranslations = { "errors.workflow_run_input_invalid": "Invalid input for start variable '{{variable}}': {{reason}}", "errors.workflow_skill_not_found": - "A skill required by this workflow is unavailable.", + "A skill required by this workflow is unavailable. Import the personal skill or verify the marketplace skill is deployed to the project, then retry.", + "errors.workflow_skill_not_found_detail": + "The skill {{skillId}} required by node '{{nodeTitle}}' is unavailable. Import the personal skill or verify the marketplace skill is deployed to the project, then retry.", "errors.workflow_role_not_found": "The role this workflow references is missing from the workspace's role catalog. Create it on the Roles settings page, then start the run again.", "errors.workflow_run_start_failed": "Failed to start the workflow run.", diff --git a/frontend-v2/src/features/chat/workflow-run/workflow-run-start-dialog.tsx b/frontend-v2/src/features/chat/workflow-run/workflow-run-start-dialog.tsx index 709ab8b22..1c9fe65fe 100644 --- a/frontend-v2/src/features/chat/workflow-run/workflow-run-start-dialog.tsx +++ b/frontend-v2/src/features/chat/workflow-run/workflow-run-start-dialog.tsx @@ -15,6 +15,7 @@ import { import type { WorkflowInputVariable } from "@/lib/workflows/mock"; import { WorkflowStartVariableFields } from "@/lib/workflows/host/start-variable-fields"; import { workflowStartDrafts, parseWorkflowStartDrafts } from "@/lib/workflows/host/start-variable-drafts"; +import { WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT } from "@/lib/workflows/personal-skills"; /** A reachable node start will refuse, named as the author titled it. */ export interface WorkflowRunUnsupportedNode { @@ -38,6 +39,8 @@ interface WorkflowRunStartDialogProps { analyzing?: boolean; /** Keeps a failed preflight visible while server start remains the authority. */ analysisFailed?: boolean; + /** True when any Agent node in the frozen snapshot enables a personal Skill. */ + hasPersonalSkills?: boolean; busy: boolean; onOpenChange: (open: boolean) => void; onStart: ( @@ -55,6 +58,7 @@ export function WorkflowRunStartDialog({ unsupportedNodes = [], analyzing = false, analysisFailed = false, + hasPersonalSkills = false, busy, onOpenChange, onStart, @@ -69,6 +73,7 @@ export function WorkflowRunStartDialog({ unsupportedNodes={unsupportedNodes} analyzing={analyzing} analysisFailed={analysisFailed} + hasPersonalSkills={hasPersonalSkills} busy={busy} onCancel={() => onOpenChange(false)} onStart={onStart} @@ -86,6 +91,7 @@ function WorkflowRunStartDialogContent({ unsupportedNodes, analyzing, analysisFailed, + hasPersonalSkills, busy, onCancel, onStart, @@ -142,6 +148,11 @@ function WorkflowRunStartDialogContent({ {unsupportedNodes.length > 0 && ( )} + {hasPersonalSkills && ( +

+ {WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT} +

+ )}
diff --git a/frontend-v2/src/features/collaboration/task-composer.tsx b/frontend-v2/src/features/collaboration/task-composer.tsx index 349761cb9..9e792b32d 100644 --- a/frontend-v2/src/features/collaboration/task-composer.tsx +++ b/frontend-v2/src/features/collaboration/task-composer.tsx @@ -8,6 +8,7 @@ import { Input } from '@/components/ui/input' import { NativeSelect, NativeSelectOption } from '@/components/ui/native-select' import { Switch } from '@/components/ui/switch' import { Textarea } from '@/components/ui/textarea' +import { useWorkflowHasPersonalSkills, WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT } from '@/lib/workflows/personal-skills' import { extractWorkflowInputServerError, resolveFormDraftValues, @@ -186,6 +187,7 @@ export function TaskComposer({ tenantId, task, me, inSquad, sending, error, subm undefined, { query: { enabled: !!tenantId && !!stagedWorkflow?.formRef, staleTime: 60_000 } }, ) + const stagedWorkflowHasPersonalSkills = useWorkflowHasPersonalSkills(tenantId, stagedWorkflow?.workflowId) const reach = agentReach(task, me, inSquad) const taskFinished = isTaskFinished(task.status) const sendToAgent = !stagedWorkflow && reach.ok && (toAgent ?? true) @@ -346,6 +348,7 @@ export function TaskComposer({ tenantId, task, me, inSquad, sending, error, subm
} {formQuery.data && <> {formQuery.data.description &&

{formQuery.data.description}

} + {stagedWorkflowHasPersonalSkills &&

{WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT}

} {fields.length > 0 ?
{fields.map(field => { diff --git a/frontend-v2/src/features/collaboration/task-decomposition.tsx b/frontend-v2/src/features/collaboration/task-decomposition.tsx index d944e36cf..c82260dea 100644 --- a/frontend-v2/src/features/collaboration/task-decomposition.tsx +++ b/frontend-v2/src/features/collaboration/task-decomposition.tsx @@ -7,6 +7,7 @@ import { Field, FieldDescription, FieldGroup, FieldLabel } from '@/components/ui import { NativeSelect, NativeSelectOptGroup, NativeSelectOption } from '@/components/ui/native-select' import { listDecompositionWorkflows } from './decomposition-api/generated' import { PanelDialog } from '@/components/panel/panel-dialog' +import { useWorkflowHasPersonalSkills, WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT } from '@/lib/workflows/personal-skills' import { decompositionMessageFor, DEMO_DECOMPOSITION_WORKFLOW, taskStatusLabel } from './task-model' import { startTaskDecomposition, type Task, type TaskDecomposition } from './tasks-api/generated' import { useTaskList } from './workspace' @@ -38,6 +39,7 @@ export function DecomposeDialog({ tenantId, task, onClose, onStarted }: { for (const w of blocked) blockedByReason.set(w.decompositionBlockedReason, [...(blockedByReason.get(w.decompositionBlockedReason) ?? []), w.name]) const [picked, setPicked] = useState('') const workflowId = picked || (eligible.find(w => w.name === DEMO_DECOMPOSITION_WORKFLOW) ?? eligible[0])?.id || '' + const hasPersonalSkills = useWorkflowHasPersonalSkills(tenantId, workflowId) const [key] = useState(() => crypto.randomUUID()) const [error, setError] = useState('') const start = useMutation({ @@ -73,6 +75,7 @@ export function DecomposeDialog({ tenantId, task, onClose, onStarted }: { } {hint} + {hasPersonalSkills && {WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT}} {blocked.length > 0 &&
有 {blocked.length} 个已发布工作流不能用于拆分
diff --git a/frontend-v2/src/features/collaboration/task-model.test.ts b/frontend-v2/src/features/collaboration/task-model.test.ts index 067c19c6e..1ca49ede6 100644 --- a/frontend-v2/src/features/collaboration/task-model.test.ts +++ b/frontend-v2/src/features/collaboration/task-model.test.ts @@ -92,6 +92,15 @@ describe('task errors', () => { expect(boardMoveMessageFor(http(400, 'invalid_transition'))).toContain('待处理 → 进行中 → 待验收 → 已完成') expect(boardMoveMessageFor(http(403, 'forbidden'))).toBe('只有任务创建人或工作区管理员能确认完成、退回或取消任务。') expect(taskRunMessageFor(http(400, 'workflow_role_not_found'))).toBe('工作流引用的角色在工作区角色目录里不存在,请先在设置的角色页新建同名角色再启动。') + expect(taskRunMessageFor(http(400, 'workflow_skill_not_found'))).toBe('工作流引用的技能不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。') + expect(taskRunMessageFor({ + isAxiosError: true, + response: { status: 400, data: { code: 'workflow_skill_not_found', params: { nodeId: 'a1', nodeTitle: '代码审查', skillId: 'my-skill' } } }, + })).toBe('节点「代码审查」需要的技能 my-skill 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。') + expect(taskRunMessageFor({ + isAxiosError: true, + response: { status: 400, data: { code: 'workflow_skill_not_found', params: { nodeId: 'a1', nodeTitle: ' ', skillId: 'official/pack' } } }, + })).toBe('节点「a1」需要的技能 official/pack 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。') }) }) diff --git a/frontend-v2/src/features/collaboration/task-model.ts b/frontend-v2/src/features/collaboration/task-model.ts index 1ddbbe654..476d97553 100644 --- a/frontend-v2/src/features/collaboration/task-model.ts +++ b/frontend-v2/src/features/collaboration/task-model.ts @@ -123,6 +123,7 @@ export function taskRunMessageFor(error: unknown): string { case 'workflow_snapshot_not_found': return '所选工作流版本不存在,请重新选择。' case 'workflow_draft_snapshot': return '草稿版本不能直接运行,请选择已发布的工作流。' case 'workflow_role_not_found': return '工作流引用的角色在工作区角色目录里不存在,请先在设置的角色页新建同名角色再启动。' + case 'workflow_skill_not_found': return missingSkillMessageOf(error) case 'workflow_run_start_failed': return '工作流图定义不可执行,请检查工作流配置。' case 'workflow_run_host_unavailable': return '工作流执行服务不可用,请稍后重试。' case 'execution_unavailable': return '执行服务暂时不可用,请稍后重试。' @@ -167,6 +168,19 @@ function serverMessageOf(error: unknown): string | undefined { return typeof message === 'string' && message ? message : undefined } +function missingSkillMessageOf(error: unknown): string { + if (isAxiosError(error)) { + const params = (error.response?.data as { params?: { nodeId?: unknown; nodeTitle?: unknown; skillId?: unknown } } | undefined)?.params + const skillId = typeof params?.skillId === 'string' ? params.skillId.trim() : '' + const nodeTitle = (typeof params?.nodeTitle === 'string' && params.nodeTitle.trim()) || + (typeof params?.nodeId === 'string' && params.nodeId.trim()) || '' + if (skillId && nodeTitle) { + return `节点「${nodeTitle}」需要的技能 ${skillId} 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。` + } + } + return '工作流引用的技能不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。' +} + /** A user-facing reason for a refused decomposition. */ export function decompositionMessageFor(error: unknown): string { switch (codeOf(error)) { diff --git a/frontend-v2/src/features/collaboration/task-page.test.tsx b/frontend-v2/src/features/collaboration/task-page.test.tsx index 154acef28..a137efe53 100644 --- a/frontend-v2/src/features/collaboration/task-page.test.tsx +++ b/frontend-v2/src/features/collaboration/task-page.test.tsx @@ -1063,3 +1063,68 @@ it('shows workflow assignee guidance on not_assignee errors in TaskWorkflowDialo expect(await within(dialog).findByText('任务派给了别人,只有负责人本人或所属小队成员能用工作流处理。')).toBeInTheDocument() }) + +const personalSkillGraph = JSON.stringify({ + nodes: [ + { id: 'start', type: 'workflow', position: { x: 0, y: 0 }, data: { kind: 'start', title: '开始' } }, + { id: 'agent-1', type: 'workflow', position: { x: 200, y: 0 }, data: { kind: 'agent', title: '代码审查', agentConfig: { skills: [{ skillId: 'my-skill', enabled: true }] } } }, + ], + edges: [{ id: 'e1', source: 'start', target: 'agent-1' }], +}) + +it('shows the missing skill message and personal Skill hint when @ workflow comment uses a personal Skill', async () => { + targets.items.push(workflowTarget) + forms.byRef['wf-check'] = workflowForm + vi.mocked(workflowsApi.getWorkflow).mockResolvedValue({ + published: { id: 'snapshot-skill', workflowId: 'wf-check', version: 'v1', graph: personalSkillGraph, createdAt: 0, updatedAt: 0 }, + } as never) + vi.mocked(api.createTaskComment).mockRejectedValueOnce( + httpFault(400, 'workflow_skill_not_found', { nodeId: 'agent-1', nodeTitle: '代码审查', skillId: 'my-skill' }), + ) + + renderPage('?tab=discussion') + const box = await screen.findByLabelText('评论或给 Agent 的消息') + await userEvent.type(box, '@') + await userEvent.click(await screen.findByRole('option', { name: /发布检查/ })) + + expect(await screen.findByText('运行时读取发起人同名的个人 Skill,其内容在节点会话中对团队可见。')).toBeInTheDocument() + + await userEvent.type(screen.getByLabelText(/目标分支/), 'main') + await userEvent.click(screen.getByRole('button', { name: '发送并运行' })) + + expect(await screen.findByText('节点「代码审查」需要的技能 my-skill 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。')).toBeInTheDocument() + expect(screen.getByLabelText('评论或给 Agent 的消息')).toHaveValue('@发布检查 ') +}) + +it('shows the missing skill message and personal Skill hint in TaskWorkflowDialog and DecomposeDialog', async () => { + const user = userEvent.setup() + const human = { type: 'human' as const, id: 'user-me', displayName: '演示用户', identifier: '' } + vi.mocked(api.getTask).mockResolvedValue(task({ assignee: human })) + vi.mocked(workflowsApi.listWorkflows).mockResolvedValue({ + workflows: [{ id: 'wf-dev', namespace: 'team', name: '需求开发', publishedVersion: 'v1', createdAt: 1, updatedAt: 1 }], + }) + vi.mocked(decompositionApi.listDecompositionWorkflows).mockResolvedValue({ + items: [{ id: 'wf-split', name: '需求拆分', publishedVersion: 'v1', canDecompose: true, decompositionBlockedReason: '' }], + }) + vi.mocked(workflowsApi.getWorkflow).mockResolvedValue({ + published: { id: 'snapshot-skill', workflowId: 'wf-dev', version: 'v1', graph: personalSkillGraph, createdAt: 0, updatedAt: 0 }, + } as never) + vi.mocked(taskWorkflows.startTaskWorkflow).mockRejectedValueOnce( + httpFault(400, 'workflow_skill_not_found', { nodeId: 'agent-1', nodeTitle: '代码审查', skillId: 'my-skill' }), + ) + + renderPage() + await user.click(await screen.findByRole('button', { name: '用工作流处理' })) + const handleDialog = screen.getByRole('dialog') + await screen.findByRole('option', { name: '需求开发(v1)' }) + await user.selectOptions(within(handleDialog).getByLabelText('工作流'), 'wf-dev') + expect(await within(handleDialog).findByText('运行时读取发起人同名的个人 Skill,其内容在节点会话中对团队可见。')).toBeInTheDocument() + await user.click(await within(handleDialog).findByRole('button', { name: '启动工作流' })) + expect(await within(handleDialog).findByText('节点「代码审查」需要的技能 my-skill 不可用,请先在个人技能页导入同名技能或确认市场技能已下发到项目后再启动。')).toBeInTheDocument() + await user.click(within(handleDialog).getByRole('button', { name: '取消' })) + + await user.click(await screen.findByRole('button', { name: '拆分' })) + const splitDialog = screen.getByRole('dialog') + await waitFor(() => expect(within(splitDialog).getByLabelText('工作流')).toHaveValue('wf-split')) + expect(await within(splitDialog).findByText('运行时读取发起人同名的个人 Skill,其内容在节点会话中对团队可见。')).toBeInTheDocument() +}) diff --git a/frontend-v2/src/features/collaboration/task-workflow-dialog.tsx b/frontend-v2/src/features/collaboration/task-workflow-dialog.tsx index 2454c7f62..4d00aacd5 100644 --- a/frontend-v2/src/features/collaboration/task-workflow-dialog.tsx +++ b/frontend-v2/src/features/collaboration/task-workflow-dialog.tsx @@ -12,6 +12,7 @@ import { parseWorkflowGraph } from '@/lib/workflows/runtime' import { createWorkflowI18n } from '@/lib/workflows/host/i18n' import { WorkflowStartVariableFields } from '@/lib/workflows/host/start-variable-fields' import { workflowStartDrafts, parseWorkflowStartDrafts } from '@/lib/workflows/host/start-variable-drafts' +import { graphHasEnabledPersonalSkills, WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT } from '@/lib/workflows/personal-skills' import { workflowRunTranslations } from '@/features/chat/workflow-run/translations' import { codeOf } from '@/lib/api-client' import { taskRunMessageFor } from './task-model' @@ -46,6 +47,7 @@ export function TaskWorkflowDialog({ tenantId, task, onClose, onStarted }: { function HandlingForm({tenantId,task,snapshot,onClose,onStarted}:{tenantId:string;task:Task;snapshot:WorkflowSnapshot;onClose:()=>void;onStarted:(id:string)=>void}){ const client=useQueryClient() const [variables]=useState(()=>parseWorkflowGraph(snapshot.graph).nodes.find(n=>n.data.kind==='start' && !n.parentId)?.data.inputVariables ?? []) + const [hasPersonalSkills]=useState(()=>graphHasEnabledPersonalSkills(snapshot.graph)) const [drafts,setDrafts]=useState(()=>workflowStartDrafts(variables)) const [prompt,setPrompt]=useState(()=>[task.title,task.description].filter(Boolean).join('\n\n')) const [attempted,setAttempted]=useState(false) @@ -67,6 +69,7 @@ function HandlingForm({tenantId,task,snapshot,onClose,onStarted}:{tenantId:strin const submit=(event:FormEvent)=>{event.preventDefault();setAttempted(true);if(!invalid)start.mutate()} return
+ {hasPersonalSkills &&

{WORKFLOW_PERSONAL_SKILL_TEAM_VISIBILITY_HINT}

} {attempt.current=null;setDrafts(next)}} attemptedStart={attempted}/> 需求