feat(platform): Agent 与媒体能力 - 完善角色卡、音频协议与任务恢复链路
This commit is contained in:
1 parent
a8f83fedd5
commit
5650da6d31
91 files changed
+3438
-380
No files matched your search
@@ -58,9 +58,14 @@ func (s *Service) UserAssetsPage(userID string, page int, pageSize int, filter U
|
||||
}
|
||||
rawAssets := make([]json.RawMessage, 0, len(assets))
|
||||
for _, asset := range assets {
|
||||
if payload := clientAssetListPayload(asset); len(payload) > 0 {
|
||||
rawAssets = append(rawAssets, payload)
|
||||
payload := clientAssetListPayload(asset)
|
||||
if len(payload) == 0 {
|
||||
continue
|
||||
}
|
||||
if asset.Kind == "entity" && asset.Category == model.AssetCategoryCharacter {
|
||||
payload = s.characterAssetListPayload(userID, asset, payload)
|
||||
}
|
||||
rawAssets = append(rawAssets, payload)
|
||||
}
|
||||
kindRows, categoryRows, folderRows, err := s.repo.UserAssetFacets(userID, filter.Status)
|
||||
if err != nil {
|
||||
@@ -72,6 +77,53 @@ func (s *Service) UserAssetsPage(userID string, page int, pageSize int, filter U
|
||||
}, nil
|
||||
}
|
||||
|
||||
// characterAssetListPayload 给素材库里的角色卡补上当前版本的形象与声音。
|
||||
// 角色资产的 payload 只存设定,形象/声音在版本表里;不补的话列表卡片和档案只能显示空图标。
|
||||
// 只下发 resource: 存储键,展示时由前端换取授权地址,不经后端中转字节。
|
||||
func (s *Service) characterAssetListPayload(userID string, asset model.Asset, raw json.RawMessage) json.RawMessage {
|
||||
card, err := s.characterCard(userID, &asset)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal(raw, &payload); err != nil || payload == nil {
|
||||
return raw
|
||||
}
|
||||
data, _ := payload["data"].(map[string]any)
|
||||
if data == nil {
|
||||
data = map[string]any{}
|
||||
}
|
||||
data["definition"] = card.Definition
|
||||
data["version"] = card.Version
|
||||
data["visualStatus"], data["voiceStatus"] = card.VisualStatus, card.VoiceStatus
|
||||
if cover := characterCoverResourceID(card); cover != "" {
|
||||
data["coverStorageKey"] = "resource:" + cover
|
||||
}
|
||||
if card.Voice != nil {
|
||||
data["voiceName"] = card.Voice.Profile.Name
|
||||
if card.Voice.Profile.SampleResourceID != "" {
|
||||
data["voiceSampleStorageKey"] = "resource:" + card.Voice.Profile.SampleResourceID
|
||||
}
|
||||
}
|
||||
payload["data"] = data
|
||||
encoded, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return raw
|
||||
}
|
||||
return encoded
|
||||
}
|
||||
|
||||
func characterCoverResourceID(card CharacterCardSummary) string {
|
||||
for _, role := range []string{"turnaround_sheet", "primary", "front"} {
|
||||
for _, representation := range card.Representations {
|
||||
if representation.Role == role && representation.ResourceID != "" {
|
||||
return representation.ResourceID
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func assetFacetMap(rows []repository.UserAssetFacetRow) map[string]int64 {
|
||||
result := make(map[string]int64, len(rows))
|
||||
for _, row := range rows {
|
||||
|
||||
@@ -218,8 +218,8 @@ func validateChannelModelTierPricing(capability string, protocol model.ChannelIn
|
||||
if billingMode != "fixed_request" && billingMode != "per_second" && billingMode != "token" {
|
||||
return BadAuthRequest("模型计费方式仅支持按次、按秒或 Token")
|
||||
}
|
||||
if billingMode == "per_second" && capability != "video" {
|
||||
return BadAuthRequest("只有视频模型可以按秒计费")
|
||||
if billingMode == "per_second" && capability != "video" && capability != "audio" {
|
||||
return BadAuthRequest("只有视频或音频模型可以按秒计费")
|
||||
}
|
||||
if billingMode == "token" && !supportsTokenBilling(capability, protocol) {
|
||||
return BadAuthRequest("Token 计费仅支持文本和视频模型")
|
||||
|
||||
@@ -696,7 +696,7 @@ func cloudAgentCanvasSummary(canvas *model.CanvasProject, focusNodeIDs ...string
|
||||
if node.Type == "text" && node.Metadata.WorkflowKind == "character" {
|
||||
item["kind"] = "character"
|
||||
}
|
||||
if _, known := cloudAgentNodeCapabilityForType(node.Type); !known {
|
||||
if _, known := canvasCapabilityRegistry.ResolveNode(node.Type, node.Metadata.WorkflowKind); !known {
|
||||
item["agentSupported"] = false
|
||||
}
|
||||
nodes = append(nodes, item)
|
||||
|
||||
@@ -50,7 +50,7 @@ func cloudAgentCreativeAnchorForCanvas(repo *repository.Repository, userID strin
|
||||
|
||||
ids := make([]string, 0, 16)
|
||||
for _, node := range nodes {
|
||||
descriptor, known := cloudAgentNodeCapabilityForType(stringValue(node["type"]))
|
||||
descriptor, known := cloudAgentNodeCapabilityForNode(node)
|
||||
if known && descriptor.Connection.CanReference {
|
||||
ids = append(ids, stringValue(node["id"]))
|
||||
}
|
||||
@@ -63,13 +63,13 @@ func cloudAgentCreativeAnchorForCanvas(repo *repository.Repository, userID strin
|
||||
continue
|
||||
}
|
||||
node := byID[id]
|
||||
descriptor, known := cloudAgentNodeCapabilityForType(stringValue(node["type"]))
|
||||
descriptor, known := cloudAgentNodeCapabilityForNode(node)
|
||||
if !known || !descriptor.Connection.CanReference {
|
||||
continue
|
||||
}
|
||||
meta, _ := node["metadata"].(map[string]any)
|
||||
item := cloudAgentReferenceAnchor{
|
||||
NodeID: stringValue(node["id"]), Type: stringValue(node["type"]),
|
||||
NodeID: stringValue(node["id"]), Type: descriptor.Type,
|
||||
Title: truncateRunes(stringValue(node["title"]), 300),
|
||||
Prompt: truncateRunes(firstNonEmpty(stringValue(meta["prompt"]), stringValue(meta["composerContent"])), 1000),
|
||||
VisualIdentity: "unknown", RequiresVisualInspection: true,
|
||||
@@ -82,7 +82,8 @@ func cloudAgentCreativeAnchorForCanvas(repo *repository.Repository, userID strin
|
||||
}
|
||||
}
|
||||
if repo != nil {
|
||||
ref, _, refErr := cloudAgentReference(repo, userID, node)
|
||||
// 角色卡按三视图判定是否可作参考;普通媒体按节点资源判定。
|
||||
ref, _, refErr := cloudAgentMediaReference(repo, userID, "", node)
|
||||
if refErr == nil {
|
||||
item.ReferenceReady = true
|
||||
item.Width, item.Height = ref["width"], ref["height"]
|
||||
|
||||
@@ -167,8 +167,8 @@ func applyCloudAgentCanvasPlan(doc map[string]any, ops []agentCanvasOp) ([]cloud
|
||||
return nil, BadAuthRequest("连线重复")
|
||||
}
|
||||
}
|
||||
fromCapability, _ := cloudAgentNodeCapabilityForType(stringValue(nodes[fromIndex]["type"]))
|
||||
toCapability, _ := cloudAgentNodeCapabilityForType(stringValue(nodes[toIndex]["type"]))
|
||||
fromCapability, _ := cloudAgentNodeCapabilityForNode(nodes[fromIndex])
|
||||
toCapability, _ := cloudAgentNodeCapabilityForNode(nodes[toIndex])
|
||||
fromTitle := cloudAgentApprovalNodeTitle(nodes[fromIndex], fromCapability.Label)
|
||||
toTitle := cloudAgentApprovalNodeTitle(nodes[toIndex], toCapability.Label)
|
||||
edges = append(edges, map[string]any{"id": op.ID, "fromNodeId": op.FromNodeID, "toNodeId": op.ToNodeID})
|
||||
@@ -188,7 +188,7 @@ func applyCloudAgentCanvasPlan(doc map[string]any, ops []agentCanvasOp) ([]cloud
|
||||
if index < 0 {
|
||||
return nil, BadAuthRequest("只能更新现有且受 Agent 支持的节点")
|
||||
}
|
||||
capability, ok := cloudAgentNodeCapabilityForType(stringValue(nodes[index]["type"]))
|
||||
capability, ok := cloudAgentNodeCapabilityForNode(nodes[index])
|
||||
if !ok || !capability.CanUpdate {
|
||||
return nil, BadAuthRequest("该节点类型不支持 Agent 更新")
|
||||
}
|
||||
|
||||
@@ -138,7 +138,7 @@ func emitCloudAgentCanvasChange(repo *repository.Repository, runID string, state
|
||||
if old, _ := change["before"].(map[string]any); old == nil {
|
||||
action = "created"
|
||||
}
|
||||
entry := map[string]any{"action": action, "nodeId": node["id"], "title": node["title"], "nodeType": node["type"]}
|
||||
entry := map[string]any{"action": action, "nodeId": node["id"], "title": node["title"], "nodeType": cloudAgentEventNodeType(node)}
|
||||
previewOperation := "update_node"
|
||||
if action == "created" {
|
||||
previewOperation = "add_node"
|
||||
@@ -166,9 +166,9 @@ func emitCloudAgentCanvasChange(repo *repository.Repository, runID string, state
|
||||
for _, change := range edges {
|
||||
edge := change["after"].(map[string]any)
|
||||
if node := byID[stringValue(edge["fromNodeId"])]; node != nil {
|
||||
entry := map[string]any{"action": "referenced", "nodeId": node["id"], "title": node["title"], "nodeType": node["type"], "targetNodeId": edge["toNodeId"]}
|
||||
entry := map[string]any{"action": "referenced", "nodeId": node["id"], "title": node["title"], "nodeType": cloudAgentEventNodeType(node), "targetNodeId": edge["toNodeId"]}
|
||||
if target := byID[stringValue(edge["toNodeId"])]; target != nil {
|
||||
entry["targetTitle"], entry["targetNodeType"] = target["title"], target["type"]
|
||||
entry["targetTitle"], entry["targetNodeType"] = target["title"], cloudAgentEventNodeType(target)
|
||||
}
|
||||
if preview, ok := findPreview("connect_nodes", stringValue(edge["fromNodeId"])); ok && preview.TargetNodeTitle != "" {
|
||||
entry["targetTitle"], entry["targetNodeType"] = preview.TargetNodeTitle, preview.TargetNodeType
|
||||
@@ -194,6 +194,15 @@ func emitCloudAgentCanvasChange(repo *repository.Repository, runID string, state
|
||||
return nil
|
||||
}
|
||||
|
||||
// cloudAgentEventNodeType 给回执用的节点类型:角色卡等变体底层是 text,
|
||||
// 必须按 workflowKind 解析成能力类型,否则前端会把角色卡报成"文本节点"。
|
||||
func cloudAgentEventNodeType(node map[string]any) any {
|
||||
if descriptor, ok := cloudAgentNodeCapabilityForNode(node); ok && descriptor.Type != "" {
|
||||
return descriptor.Type
|
||||
}
|
||||
return node["type"]
|
||||
}
|
||||
|
||||
func cloudAgentPatchCoversDocument(before, after map[string]any) bool {
|
||||
for _, key := range []string{"nodes", "connections"} {
|
||||
old, next := creationMaps(before[key]), creationMaps(after[key])
|
||||
|
||||
@@ -248,7 +248,7 @@ func cloudAgentCanvasStateSelected(repo *repository.Repository, userID, canvasID
|
||||
if status, ok := meta["status"].(string); ok {
|
||||
item["status"] = truncateRunes(status, 40)
|
||||
}
|
||||
capability, known := cloudAgentNodeCapabilityForType(stringValue(node["type"]))
|
||||
capability, known := cloudAgentNodeCapabilityForNode(node)
|
||||
if !known {
|
||||
// Read visibility is not permission to mutate or use a node as a media reference.
|
||||
item["agentSupported"] = false
|
||||
@@ -263,6 +263,10 @@ func cloudAgentCanvasStateSelected(repo *repository.Repository, userID, canvasID
|
||||
included[id] = true
|
||||
continue
|
||||
}
|
||||
if capability.Variant != nil {
|
||||
// 变体节点(如角色卡)底层 type 仍是 text,用 kind 标明真实能力,避免当普通文本处理。
|
||||
item["kind"] = capability.Type
|
||||
}
|
||||
fields := capability.SummaryFields
|
||||
if precise {
|
||||
fields = capability.DetailFields
|
||||
@@ -333,7 +337,8 @@ func cloudAgentCanvasStateSelected(repo *repository.Repository, userID, canvasID
|
||||
}
|
||||
item["generationDraft"] = draft
|
||||
}
|
||||
if capability.Connection.CanReference {
|
||||
// 角色卡的引用可用性在 character.imageReference/audioReference 中给出。
|
||||
if capability.Connection.CanReference && !cloudAgentCharacterNode(node) {
|
||||
ref, _, err := cloudAgentReference(repo, userID, node)
|
||||
outputReference := map[string]any{"ready": err == nil}
|
||||
item["outputReference"] = outputReference
|
||||
|
||||
@@ -23,12 +23,13 @@ func cloudAgentCharacterNode(node map[string]any) bool {
|
||||
func cloudAgentResolveCharacter(repo *repository.Repository, userID, projectID string, node map[string]any) (*cloudAgentCharacter, error) {
|
||||
meta, _ := node["metadata"].(map[string]any)
|
||||
assetID := stringValue(meta["characterAssetId"])
|
||||
if projectID == "" || assetID == "" {
|
||||
return nil, BadAuthRequest("角色卡未关联当前项目的角色资产")
|
||||
if assetID == "" {
|
||||
return nil, BadAuthRequest("角色卡未关联角色资产")
|
||||
}
|
||||
asset, err := repo.ProjectCharacterAsset(userID, projectID, assetID)
|
||||
_ = projectID
|
||||
asset, err := repo.UserCharacterAsset(userID, assetID)
|
||||
if err != nil {
|
||||
return nil, BadAuthRequest("角色卡对应的项目角色资产不存在或不可访问")
|
||||
return nil, BadAuthRequest("角色卡不存在或不可访问")
|
||||
}
|
||||
policy := stringValue(meta["characterVersionPolicy"])
|
||||
versionID := asset.PrimaryVersionID
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"infinite-canvas/backend/internal/canvas/layout"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
)
|
||||
|
||||
const (
|
||||
cloudAgentCharacterNodeWidth = 264.0
|
||||
cloudAgentCharacterNodeHeight = 352.0
|
||||
)
|
||||
|
||||
// cloudAgentCharacterDefinitionArgs 是 Agent 可写的角色设定字段;未声明的字段会被拒绝。
|
||||
type cloudAgentCharacterDefinitionArgs struct {
|
||||
Role string `json:"role"`
|
||||
Aliases []string `json:"aliases"`
|
||||
Appearance string `json:"appearance"`
|
||||
Physique string `json:"physique"`
|
||||
Clothing string `json:"clothing"`
|
||||
Personality string `json:"personality"`
|
||||
Props string `json:"props"`
|
||||
ConsistencyPrompt string `json:"consistencyPrompt"`
|
||||
MultiViewPrompt string `json:"multiViewPrompt"`
|
||||
VoiceLanguage string `json:"voiceLanguage"`
|
||||
VoiceAge string `json:"voiceAge"`
|
||||
VoiceTimbre string `json:"voiceTimbre"`
|
||||
}
|
||||
|
||||
type cloudAgentCharacterCreateArgs struct {
|
||||
NodeID string `json:"nodeId"`
|
||||
Name string `json:"name"`
|
||||
ImageNodeID string `json:"imageNodeId"`
|
||||
AudioNodeID string `json:"audioNodeId"`
|
||||
Definition cloudAgentCharacterDefinitionArgs `json:"definition"`
|
||||
X *float64 `json:"x"`
|
||||
Y *float64 `json:"y"`
|
||||
}
|
||||
|
||||
type cloudAgentCharacterCreatePlan struct {
|
||||
Args cloudAgentCharacterCreateArgs
|
||||
Definition map[string]any
|
||||
ImageResourceID string
|
||||
AudioResourceID string
|
||||
VoiceName string
|
||||
Position layout.Position
|
||||
Preview cloudAgentApprovalPreview
|
||||
}
|
||||
|
||||
// 设定字段只在描述里列出键名以控制工具 schema 体积;解码时 DisallowUnknownFields 会拒绝未声明的键。
|
||||
func cloudAgentCharacterCreateSchema() map[string]any {
|
||||
str := func(description string) map[string]any {
|
||||
return map[string]any{"type": "string", "description": description}
|
||||
}
|
||||
return map[string]any{
|
||||
"nodeId": str("新节点ID"), "name": str("角色名"), "imageNodeId": str("就绪的形象图片节点ID"), "audioNodeId": str("可选,就绪的声音音频节点ID"),
|
||||
"definition": map[string]any{"type": "object", "description": "可选设定:role/appearance/physique/clothing/personality/props/consistencyPrompt/multiViewPrompt/voiceLanguage/voiceAge/voiceTimbre 为字符串,aliases 为字符串数组"},
|
||||
"x": map[string]any{"type": "number"}, "y": map[string]any{"type": "number"},
|
||||
}
|
||||
}
|
||||
|
||||
func cloudAgentCharacterText(value string, limit int) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if utf8.RuneCountInString(value) > limit {
|
||||
return "", BadAuthRequest(fmt.Sprintf("角色设定单项不能超过 %d 字", limit))
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (d cloudAgentCharacterDefinitionArgs) normalized() (map[string]any, error) {
|
||||
result := map[string]any{}
|
||||
for key, value := range map[string]string{
|
||||
"role": d.Role, "appearance": d.Appearance, "physique": d.Physique, "clothing": d.Clothing,
|
||||
"personality": d.Personality, "props": d.Props, "consistencyPrompt": d.ConsistencyPrompt,
|
||||
"multiViewPrompt": d.MultiViewPrompt, "voiceLanguage": d.VoiceLanguage, "voiceAge": d.VoiceAge, "voiceTimbre": d.VoiceTimbre,
|
||||
} {
|
||||
text, err := cloudAgentCharacterText(value, 4000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if text != "" {
|
||||
result[key] = text
|
||||
}
|
||||
}
|
||||
if len(d.Aliases) > 16 {
|
||||
return nil, BadAuthRequest("角色别名最多 16 个")
|
||||
}
|
||||
aliases := []string{}
|
||||
for _, alias := range d.Aliases {
|
||||
text, err := cloudAgentCharacterText(alias, 100)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if text != "" {
|
||||
aliases = append(aliases, text)
|
||||
}
|
||||
}
|
||||
result["aliases"] = aliases
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// cloudAgentCharacterMediaResource 从画布节点取已上传且就绪的账号资源;只接受真实节点,不接受 URL。
|
||||
func cloudAgentCharacterMediaResource(repo *repository.Repository, userID string, nodes map[string]map[string]any, nodeID, kind, label string) (string, map[string]any, error) {
|
||||
node := nodes[nodeID]
|
||||
if node == nil || stringValue(node["type"]) != kind {
|
||||
return "", nil, BadAuthRequest(label + "节点不在当前画布或类型不对")
|
||||
}
|
||||
meta, _ := node["metadata"].(map[string]any)
|
||||
key := stringValue(meta["storageKey"])
|
||||
if !strings.HasPrefix(key, "resource:") {
|
||||
return "", nil, BadAuthRequest(label + "尚未保存到账号资源库,不能用于角色卡")
|
||||
}
|
||||
resource, err := repo.ResourceForUser(userID, strings.TrimPrefix(key, "resource:"))
|
||||
if err != nil || resource == nil || resource.Kind != kind || resource.Status != "ready" {
|
||||
return "", nil, BadAuthRequest(label + "资源不存在、未就绪或类型不匹配")
|
||||
}
|
||||
if kind == "audio" && !isSupportedVoiceSampleMimeType(resource.MimeType) {
|
||||
return "", nil, BadAuthRequest("声音音频格式不支持:请使用 MP3、WAV、M4A/AAC、FLAC、OGG/Opus 或 WebM")
|
||||
}
|
||||
return resource.ID, node, nil
|
||||
}
|
||||
|
||||
func prepareCloudAgentCharacterCreate(repo *repository.Repository, userID, canvasID string, call cloudAgentCall) (*cloudAgentCharacterCreatePlan, error) {
|
||||
var args cloudAgentCharacterCreateArgs
|
||||
if err := decodeCloudAgentJSONObject(call.Function.Arguments, &args); err != nil {
|
||||
return nil, &cloudAgentArgumentError{BadAuthRequest("创建角色卡参数无效:仅允许 nodeId、name、imageNodeId、audioNodeId、definition、x、y")}
|
||||
}
|
||||
if err := validateCloudAgentID(args.NodeID, "角色卡节点ID", 80); err != nil {
|
||||
return nil, &cloudAgentArgumentError{err}
|
||||
}
|
||||
name, err := cloudAgentCharacterText(args.Name, 80)
|
||||
if err != nil || name == "" {
|
||||
return nil, &cloudAgentArgumentError{BadAuthRequest("角色名不能为空且不超过 80 字")}
|
||||
}
|
||||
if args.ImageNodeID == "" {
|
||||
return nil, &cloudAgentArgumentError{BadAuthRequest("创建角色卡需要 imageNodeId:先有一张已就绪的形象/三视图图片节点")}
|
||||
}
|
||||
definition, err := args.Definition.normalized()
|
||||
if err != nil {
|
||||
return nil, &cloudAgentArgumentError{err}
|
||||
}
|
||||
canvas, err := repo.CanvasProjectForUser(userID, canvasID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc, err := creationDocument(canvas.PayloadJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := creationObjects(doc["nodes"])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if nodes[args.NodeID] != nil {
|
||||
return nil, &cloudAgentArgumentError{BadAuthRequest("角色卡节点ID已存在,请换一个新ID")}
|
||||
}
|
||||
plan := &cloudAgentCharacterCreatePlan{Args: args, Definition: definition}
|
||||
plan.Args.Name = name
|
||||
imageID, imageNode, err := cloudAgentCharacterMediaResource(repo, userID, nodes, args.ImageNodeID, "image", "形象图片")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan.ImageResourceID = imageID
|
||||
details := []string{"形象:《" + cloudAgentApprovalNodeTitle(imageNode, "图片") + "》"}
|
||||
if args.AudioNodeID != "" {
|
||||
audioID, audioNode, err := cloudAgentCharacterMediaResource(repo, userID, nodes, args.AudioNodeID, "audio", "声音音频")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plan.AudioResourceID = audioID
|
||||
plan.VoiceName = truncateRunes(strings.TrimSpace(stringValue(audioNode["title"])), 160)
|
||||
details = append(details, "声音:《"+cloudAgentApprovalNodeTitle(audioNode, "音频")+"》")
|
||||
}
|
||||
if len(definition) > 1 {
|
||||
details = append(details, fmt.Sprintf("设定 %d 项", len(definition)-1))
|
||||
}
|
||||
// 显式坐标按原样使用;否则落在形象图片右侧的空位,不叠在已有节点上。
|
||||
if args.X != nil && args.Y != nil {
|
||||
plan.Position = layout.Position{X: *args.X, Y: *args.Y}
|
||||
} else {
|
||||
occupied := cloudAgentLayoutNodes(doc)
|
||||
var preferred *layout.Position
|
||||
if image, ok := findLayoutNode(occupied, args.ImageNodeID); ok {
|
||||
preferred = &layout.Position{X: image.X + image.Width + layout.PlacementGap, Y: image.Y}
|
||||
}
|
||||
plan.Position = layout.FreeSlot(cloudAgentCharacterNodeWidth, cloudAgentCharacterNodeHeight, "text", occupied, preferred, layout.PlacementGap)
|
||||
}
|
||||
withAudio := ""
|
||||
if plan.AudioResourceID != "" {
|
||||
withAudio = "和音频"
|
||||
}
|
||||
plan.Preview = cloudAgentApprovalPreview{
|
||||
Kind: "canvas_mutation", Title: "确认创建角色卡",
|
||||
Description: fmt.Sprintf("Agent 准备把画布上的图片%s打包为角色卡《%s》:写入账号角色库并在画布放置角色卡节点。批准后才会执行。", withAudio, name),
|
||||
Items: []cloudAgentApprovalPreviewItem{{Operation: "create_character", NodeID: args.NodeID, NodeTitle: name, NodeType: "character", NodeTypeLabel: "角色卡", Details: details, Summary: fmt.Sprintf("创建角色卡《%s》", name)}},
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
func cloudAgentCharacterReferencePrompt(name string, definition map[string]any) string {
|
||||
parts := []string{"【角色卡:" + name + "】"}
|
||||
for _, key := range []string{"role", "appearance", "physique", "clothing", "personality", "props", "consistencyPrompt"} {
|
||||
if value := strings.TrimSpace(stringValue(definition[key])); value != "" {
|
||||
parts = append(parts, value)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n")
|
||||
}
|
||||
|
||||
// applyCloudAgentCharacterCreate 在 Agent 检查点事务里建角色资产并放置角色卡节点;任一步失败整体回滚。
|
||||
func applyCloudAgentCharacterCreate(repo *repository.Repository, userID, canvasID string, call cloudAgentCall, policy RuntimePolicySetting, recorder ...cloudAgentMutationRecorder) (any, error) {
|
||||
plan, err := prepareCloudAgentCharacterCreate(repo, userID, canvasID, call)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
created, err := (&Service{repo: repo}).CreateCharacter(userID, CreateCharacterRequest{
|
||||
Name: plan.Args.Name, Definition: plan.Definition, ImageResourceID: plan.ImageResourceID,
|
||||
AudioResourceID: plan.AudioResourceID, VoiceName: plan.VoiceName,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
canvas, err := repo.CanvasProjectForUser(userID, canvasID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
doc, err := creationDocument(canvas.PayloadJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
beforeJSON, beforeHash := canvas.PayloadJSON, cloudAgentCanvasHash(doc)
|
||||
card := created.Character
|
||||
meta := map[string]any{
|
||||
"workflowKind": "character", "characterAssetId": created.Asset.ID, "assetId": created.Asset.ID,
|
||||
"characterVersionId": card.VersionID, "characterVersionPolicy": "current",
|
||||
"characterName": plan.Args.Name, "characterPrompt": cloudAgentCharacterReferencePrompt(plan.Args.Name, plan.Definition),
|
||||
"characterAliases": plan.Definition["aliases"], "characterDefinition": plan.Definition,
|
||||
"characterVisualStatus": card.VisualStatus, "characterVoiceStatus": card.VoiceStatus,
|
||||
"status": "success", "fontSize": float64(14),
|
||||
}
|
||||
if card.Voice != nil {
|
||||
meta["characterVoiceName"] = card.Voice.Profile.Name
|
||||
}
|
||||
node := map[string]any{
|
||||
"id": plan.Args.NodeID, "type": "text", "title": plan.Args.Name,
|
||||
"position": map[string]any{"x": plan.Position.X, "y": plan.Position.Y},
|
||||
"width": cloudAgentCharacterNodeWidth, "height": cloudAgentCharacterNodeHeight, "metadata": meta,
|
||||
}
|
||||
doc["nodes"] = append(creationMaps(doc["nodes"]), node)
|
||||
if err := saveCloudAgentDocument(repo, canvas, doc, policy); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(recorder) > 0 && recorder[0] != nil {
|
||||
if err := recorder[0](repo, cloudAgentMutationInput{UserID: userID, CanvasID: canvasID, StepID: call.ID, Operation: call.Function.Name, BeforeSnapshotHash: beforeHash, AfterSnapshotHash: cloudAgentCanvasHash(doc), BeforeJSON: beforeJSON, Preview: &plan.Preview}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return map[string]any{
|
||||
"canvasId": canvasID, "nodeId": plan.Args.NodeID, "characterAssetId": created.Asset.ID, "versionId": card.VersionID,
|
||||
"visualStatus": card.VisualStatus, "voiceStatus": card.VoiceStatus, "snapshotHash": cloudAgentCanvasHash(doc),
|
||||
"summary": plan.Preview.Items[0].Summary,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestCloudAgentCreatesCharacterCardFromCanvasMedia(t *testing.T) {
|
||||
s, db, _, _ := creationTestService(t)
|
||||
doc := map[string]any{"nodes": []any{
|
||||
map[string]any{"id": "portrait", "type": "image", "title": "李莫愁·定妆", "position": map[string]any{"x": 0.0, "y": 0.0}, "width": 300.0, "height": 400.0, "metadata": map[string]any{"storageKey": "resource:portrait-res"}},
|
||||
map[string]any{"id": "voice", "type": "audio", "title": "李莫愁·音色", "position": map[string]any{"x": 0.0, "y": 500.0}, "width": 340.0, "height": 120.0, "metadata": map[string]any{"storageKey": "resource:voice-res"}},
|
||||
map[string]any{"id": "pending", "type": "image", "title": "未上传", "metadata": map[string]any{"content": "blob:local"}},
|
||||
}, "connections": []any{}}
|
||||
raw, _ := json.Marshal(doc)
|
||||
for _, item := range []any{
|
||||
&model.CanvasProject{ID: "agent-canvas", UserID: "user", Title: "赤练劫", PayloadJSON: string(raw)},
|
||||
&model.Resource{ID: "portrait-res", UserID: "user", Kind: "image", Status: model.ResourceStatusReady, MimeType: "image/png", Size: 10, Width: 720, Height: 960},
|
||||
&model.Resource{ID: "voice-res", UserID: "user", Kind: "audio", Status: model.ResourceStatusReady, MimeType: "audio/mpeg", Size: 10},
|
||||
} {
|
||||
if err := db.Create(item).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
policy, err := s.RuntimePolicy()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args := map[string]any{"nodeId": "lmc-card", "name": "李莫愁", "imageNodeId": "portrait", "audioNodeId": "voice", "definition": map[string]any{"role": "赤练仙子", "appearance": "素纱襌衣", "aliases": []string{"赤练仙子"}}}
|
||||
|
||||
plan, err := prepareCloudAgentCharacterCreate(s.repo, "user", "agent-canvas", cloudAgentStoryboardCall(t, "canvas_create_character", "preview", args))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if plan.Preview.Items[0].Operation != "create_character" || !strings.Contains(strings.Join(plan.Preview.Items[0].Details, "\n"), "李莫愁·音色") {
|
||||
t.Fatalf("approval preview does not describe the card: %#v", plan.Preview)
|
||||
}
|
||||
// 审批预览不能提前写入角色库。
|
||||
var count int64
|
||||
db.Model(&model.Asset{}).Where("category = ?", model.AssetCategoryCharacter).Count(&count)
|
||||
if count != 0 {
|
||||
t.Fatal("preparing the approval created a character asset")
|
||||
}
|
||||
|
||||
result, err := applyCloudAgentCharacterCreate(s.repo, "user", "agent-canvas", cloudAgentStoryboardCall(t, "canvas_create_character", "apply", args), policy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
summary := result.(map[string]any)
|
||||
if summary["visualStatus"] != "ready" || summary["voiceStatus"] != "ready" {
|
||||
t.Fatalf("card media not bound: %#v", summary)
|
||||
}
|
||||
assetID := stringValue(summary["characterAssetId"])
|
||||
detail, err := s.Character("user", assetID)
|
||||
if err != nil || detail.Asset.Title != "李莫愁" || detail.Character.Voice == nil || detail.Character.Voice.Profile.Name != "李莫愁·音色" || detail.Character.Definition["role"] != "赤练仙子" {
|
||||
t.Fatalf("character asset = %#v, %v", detail, err)
|
||||
}
|
||||
canvas, _ := s.repo.CanvasProjectForUser("user", "agent-canvas")
|
||||
stored, _ := creationDocument(canvas.PayloadJSON)
|
||||
nodes, _ := creationObjects(stored["nodes"])
|
||||
card := nodes["lmc-card"]
|
||||
if card == nil {
|
||||
t.Fatal("character card node was not placed on canvas")
|
||||
}
|
||||
descriptor, ok := cloudAgentNodeCapabilityForNode(card)
|
||||
meta := card["metadata"].(map[string]any)
|
||||
if !ok || descriptor.Type != "character" || meta["characterAssetId"] != assetID || meta["characterVersionPolicy"] != "current" {
|
||||
t.Fatalf("placed node is not a usable character card: %#v", card)
|
||||
}
|
||||
// 未指定坐标时不能叠在形象图片上。
|
||||
if position := card["position"].(map[string]any); position["x"].(float64) < 300 {
|
||||
t.Fatalf("card overlaps the portrait: %#v", position)
|
||||
}
|
||||
if _, err := cloudAgentResolveCharacter(s.repo, "user", "", card); err != nil {
|
||||
t.Fatalf("placed card cannot be resolved for generation: %v", err)
|
||||
}
|
||||
|
||||
for name, bad := range map[string]map[string]any{
|
||||
"duplicate node": {"nodeId": "lmc-card", "name": "李莫愁", "imageNodeId": "portrait"},
|
||||
"missing image": {"nodeId": "x1", "name": "李莫愁"},
|
||||
"unsaved image": {"nodeId": "x2", "name": "李莫愁", "imageNodeId": "pending"},
|
||||
"audio as image": {"nodeId": "x3", "name": "李莫愁", "imageNodeId": "voice"},
|
||||
"unknown field": {"nodeId": "x4", "name": "李莫愁", "imageNodeId": "portrait", "definition": map[string]any{"secret": "x"}},
|
||||
"url instead node": {"nodeId": "x5", "name": "李莫愁", "imageNodeId": "https://example.com/a.png"},
|
||||
} {
|
||||
if _, err := prepareCloudAgentCharacterCreate(s.repo, "user", "agent-canvas", cloudAgentStoryboardCall(t, "canvas_create_character", name, bad)); err == nil {
|
||||
t.Fatalf("%s accepted", name)
|
||||
}
|
||||
}
|
||||
if !cloudAgentWrite("canvas_create_character") {
|
||||
t.Fatal("character creation must go through the write approval path")
|
||||
}
|
||||
}
|
||||
@@ -196,3 +196,50 @@ func TestCloudAgentCharacterReferenceUsesDefinitionAndTurnaround(t *testing.T) {
|
||||
t.Fatalf("approved character version drift not rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudAgentCharacterCardIsRegisteredCapability(t *testing.T) {
|
||||
node := map[string]any{"id": "hero", "type": "text", "title": "扶颦", "metadata": map[string]any{"workflowKind": "character", "characterAssetId": "character-asset"}}
|
||||
descriptor, ok := cloudAgentNodeCapabilityForNode(node)
|
||||
if !ok || descriptor.Type != "character" || descriptor.InputKind != "character" || !descriptor.Connection.CanReference {
|
||||
t.Fatalf("character node did not resolve to character capability: %#v, %v", descriptor, ok)
|
||||
}
|
||||
if plain, _ := cloudAgentNodeCapabilityForNode(map[string]any{"id": "note", "type": "text"}); plain.Type != "text" {
|
||||
t.Fatalf("plain text node resolved to %q", plain.Type)
|
||||
}
|
||||
if _, creatable := cloudAgentNodeCapabilityForType("character"); creatable {
|
||||
t.Fatal("character variant must not be resolvable as a creatable node type")
|
||||
}
|
||||
if err := validateCreationOps([]CreationCanvasOp{{Type: "add_node", ID: "new", NodeType: "character"}}); err == nil {
|
||||
t.Fatal("agent must not create character cards from nothing")
|
||||
}
|
||||
|
||||
nodes := []map[string]any{node, {"id": "video", "type": "video"}, {"id": "image", "type": "image"}, {"id": "audio", "type": "audio"}, {"id": "note", "type": "text"}}
|
||||
for _, target := range []string{"video", "image", "audio"} {
|
||||
if err := validateCloudAgentConnection(nodes, "hero", target); err != nil {
|
||||
t.Fatalf("character card cannot feed %s: %v", target, err)
|
||||
}
|
||||
}
|
||||
if err := validateCloudAgentConnection(nodes, "hero", "note"); err == nil {
|
||||
t.Fatal("character card connected to a non-generation text node")
|
||||
}
|
||||
// 角色卡设定只随角色资产版本变化,Agent 不能把节点正文或标题当成角色设定改写。
|
||||
if err := descriptor.ValidatePatch(map[string]any{"content": "改写设定"}); err == nil {
|
||||
t.Fatal("character card accepted content patch")
|
||||
}
|
||||
if err := descriptor.ValidatePatch(map[string]any{"x": 10.0, "y": 20.0}); err != nil {
|
||||
t.Fatalf("character card cannot move: %v", err)
|
||||
}
|
||||
|
||||
guide := cloudAgentCapabilityGuide()
|
||||
if !strings.Contains(guide, "角色卡(character)") || !strings.Contains(guide, "workflowKind=character") {
|
||||
t.Fatalf("capability guide does not introduce character cards: %s", guide)
|
||||
}
|
||||
view, err := cloudAgentCanvasState(nil, "user", "agent-canvas", map[string]any{"nodes": []any{node}, "connections": []any{}}, 0, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
item := view.(map[string]any)["nodes"].([]any)[0].(map[string]any)
|
||||
if item["kind"] != "character" || item["agentSupported"] == false {
|
||||
t.Fatalf("canvas read does not expose character kind: %#v", item)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package app
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloudAgentEventNodeTypeResolvesCharacterVariant(t *testing.T) {
|
||||
character := map[string]any{"type": "text", "metadata": map[string]any{"workflowKind": "character"}}
|
||||
if got := cloudAgentEventNodeType(character); got != "character" {
|
||||
t.Fatalf("character card node type = %v, want character", got)
|
||||
}
|
||||
if got := cloudAgentEventNodeType(map[string]any{"type": "text"}); got != "text" {
|
||||
t.Fatalf("plain text node type = %v, want text", got)
|
||||
}
|
||||
}
|
||||
@@ -465,7 +465,7 @@ func cloudAgentLayoutTitles(doc map[string]any) map[string]string {
|
||||
}
|
||||
title := strings.TrimSpace(stringValue(node["title"]))
|
||||
if title == "" {
|
||||
if capability, ok := cloudAgentNodeCapabilityForType(stringValue(node["type"])); ok {
|
||||
if capability, ok := cloudAgentNodeCapabilityForNode(node); ok {
|
||||
title = capability.Label
|
||||
}
|
||||
}
|
||||
|
||||
@@ -194,7 +194,7 @@ func (s *Service) cloudAgentMediaModelName(a cloudAgentMediaArgs) (string, error
|
||||
}
|
||||
|
||||
func cloudAgentReferenceDescriptor(node map[string]any) (cloudAgentNodeCapability, cloudAgentReferenceAdapter, error) {
|
||||
descriptor, known := cloudAgentNodeCapabilityForType(stringValue(node["type"]))
|
||||
descriptor, known := cloudAgentNodeCapabilityForNode(node)
|
||||
if !known || !descriptor.Connection.CanReference || descriptor.InputKind == "" {
|
||||
return cloudAgentNodeCapability{}, cloudAgentReferenceAdapter{}, BadAuthRequest("该节点不能作为媒体参考资产")
|
||||
}
|
||||
@@ -343,8 +343,9 @@ func cloudAgentMediaDocument(repo *repository.Repository, userID, canvasID strin
|
||||
return nil, nil, nil, BadAuthRequest("来源镜头节点不在当前画布")
|
||||
}
|
||||
if source := nodes[args.SourceNodeID]; source != nil {
|
||||
descriptor, known := cloudAgentNodeCapabilityForType(stringValue(source["type"]))
|
||||
if !known || !descriptor.Connection.CanSource || descriptor.InputKind != "text" {
|
||||
descriptor, known := cloudAgentNodeCapabilityForNode(source)
|
||||
// 角色卡作为文本来源时只取其角色设定(由 cloudAgentMediaCharacters 校验非空)。
|
||||
if !known || !descriptor.Connection.CanSource || (descriptor.InputKind != "text" && descriptor.InputKind != "character") {
|
||||
return nil, nil, nil, BadAuthRequest("sourceNodeId 仅接受可作为文本输入的节点;媒体资产请放入 referenceNodeIds,并将 sourceNodeId 留空,不要重复传入")
|
||||
}
|
||||
}
|
||||
@@ -519,8 +520,17 @@ func validateCloudAgentMediaReferences(mode string, refs map[string]any) error {
|
||||
return BadAuthRequest("图片生成仅支持图片参考资产")
|
||||
}
|
||||
case "audio":
|
||||
if imageCount > 0 || videoCount > 0 || audioCount > 0 {
|
||||
return BadAuthRequest("当前音频生成只支持文本输入,暂不支持媒体参考资产")
|
||||
if videoCount > 0 {
|
||||
return BadAuthRequest("音频生成不能使用参考视频")
|
||||
}
|
||||
if imageCount > 0 && audioCount > 0 {
|
||||
return BadAuthRequest("参考图片和参考音频不能同时使用")
|
||||
}
|
||||
if imageCount > 1 {
|
||||
return BadAuthRequest("音频生成最多使用 1 张参考图片")
|
||||
}
|
||||
if audioCount > 3 {
|
||||
return BadAuthRequest("音频生成最多使用 3 段参考音频")
|
||||
}
|
||||
case "video":
|
||||
// Video reference admission is completed against the selected model's
|
||||
|
||||
@@ -483,7 +483,7 @@ func TestCloudAgentModelListFiltersActualReferences(t *testing.T) {
|
||||
t.Fatalf("intent = %+v", intent)
|
||||
}
|
||||
}
|
||||
for _, args := range []string{`{"mode":"video","referenceNodeIds":["hero","hero"]}`, `{"mode":"video","referenceNodeIds":["missing"]}`, `{"referenceNodeIds":["hero"]}`, `{"mode":"audio","referenceNodeIds":["hero"]}`} {
|
||||
for _, args := range []string{`{"mode":"video","referenceNodeIds":["hero","hero"]}`, `{"mode":"video","referenceNodeIds":["missing"]}`, `{"referenceNodeIds":["hero"]}`, `{"mode":"audio","referenceNodeIds":["hero","cat"]}`} {
|
||||
if _, err := s.cloudAgentModelIntent("user", "agent-canvas", args); err == nil {
|
||||
t.Fatalf("accepted %s", args)
|
||||
}
|
||||
|
||||
@@ -21,6 +21,14 @@ func cloudAgentNodeCapabilityForType(nodeType string) (cloudAgentNodeCapability,
|
||||
return canvasCapabilityRegistry.Resolve(nodeType)
|
||||
}
|
||||
|
||||
// cloudAgentNodeCapabilityForNode 按画布节点本身解析能力:角色卡等 workflowKind 变体
|
||||
// 优先于底层类型。凡是手里有真实节点(读取、连线、引用、更新)的调用方都应使用它;
|
||||
// 只有 add_node 这类按类型名创建的入口才使用 cloudAgentNodeCapabilityForType。
|
||||
func cloudAgentNodeCapabilityForNode(node map[string]any) (cloudAgentNodeCapability, bool) {
|
||||
meta, _ := node["metadata"].(map[string]any)
|
||||
return canvasCapabilityRegistry.ResolveNode(stringValue(node["type"]), stringValue(meta["workflowKind"]))
|
||||
}
|
||||
|
||||
func cloudAgentNodeTypeNames() []string { return canvasCapabilityRegistry.Types() }
|
||||
|
||||
func cloudAgentGenerationModeNames() []string {
|
||||
|
||||
@@ -14,8 +14,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
@@ -292,17 +291,25 @@ func (s *Service) runCloudAgentPiSession(ctx context.Context, userID, runID stri
|
||||
|
||||
// 4. 准备会话文件
|
||||
sessionJSONL, _ := input["piSessionJSONL"].(string)
|
||||
// ownSession 表示快照是本轮自己落库的,而不是续轮沿用的上一轮会话。
|
||||
ownSession := false
|
||||
if saved, sessionErr := s.repo.CloudAgentPiSession(userID, runID); sessionErr == nil && saved != nil && saved.SessionJSONL != "" {
|
||||
sessionJSONL = saved.SessionJSONL
|
||||
ownSession = true
|
||||
} else if sessionErr != nil && !errors.Is(sessionErr, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("load session: %w", sessionErr)
|
||||
}
|
||||
|
||||
sessionDir := filepath.Join(s.dataDir, "pi-sessions")
|
||||
if err := os.MkdirAll(sessionDir, 0o700); err != nil {
|
||||
return fmt.Errorf("create session dir: %w", err)
|
||||
// 崩溃恢复:最后答案已写进会话快照、运行却没来得及标记完成。这一回合已经结束,
|
||||
// 直接收尾;再启动运行时会对同一提示词再调用一次模型、多扣一次费。
|
||||
if ownSession && cloudAgentPiTurnSettled(sessionJSONL, &runtimeState) {
|
||||
if runtimeState.PiResumePrompt != "" {
|
||||
if err := s.saveCloudAgentPiResumePrompt(userID, runID, ""); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.completeCloudAgentPiRun(userID, runID)
|
||||
}
|
||||
sessionFile := filepath.Join(sessionDir, runID+".jsonl")
|
||||
|
||||
// 5. 构建完整的 Pi 请求(核心重构)
|
||||
request, err := s.buildEnhancedPiRequest(ctx, EnhancedPiRequestParams{
|
||||
@@ -315,9 +322,7 @@ func (s *Service) runCloudAgentPiSession(ctx context.Context, userID, runID stri
|
||||
ModelID: modelID,
|
||||
RuntimeState: &runtimeState,
|
||||
Canonical: &canonical,
|
||||
SessionFile: sessionFile,
|
||||
SessionJSONL: sessionJSONL,
|
||||
SessionDir: sessionDir,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("build request: %w", err)
|
||||
@@ -366,6 +371,49 @@ func (s *Service) runCloudAgentPiSession(ctx context.Context, userID, runID stri
|
||||
return s.completeCloudAgentPiRun(userID, runID)
|
||||
}
|
||||
|
||||
// cloudAgentPiTurnSettled 判断本轮是否已在会话里完整结束:本轮已有成功的助手回复,
|
||||
// 没有挂着的任务或审批,且会话最后一条消息是不带工具调用的正常结束回复。
|
||||
// 只能用于本轮自己落库的快照:运行时的事件按顺序提交,助手回复计数增长之前,
|
||||
// 含本轮用户提示的快照已经落库,所以最后一条完成回复一定属于本轮。
|
||||
// 续轮沿用的上一轮会话最后一条也是完成回复,不能据此收尾。
|
||||
func cloudAgentPiTurnSettled(sessionJSONL string, state *cloudAgentRuntime) bool {
|
||||
if sessionJSONL == "" || state == nil || state.PiAssistantResponses == 0 {
|
||||
return false
|
||||
}
|
||||
if state.ActiveTaskID != "" || state.MediaTaskID != "" || state.Approval != nil {
|
||||
return false
|
||||
}
|
||||
lines := strings.Split(strings.TrimRight(sessionJSONL, "\n"), "\n")
|
||||
for i := len(lines) - 1; i >= 0; i-- {
|
||||
var entry struct {
|
||||
Type string `json:"type"`
|
||||
Message struct {
|
||||
Role string `json:"role"`
|
||||
StopReason string `json:"stopReason"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"content"`
|
||||
} `json:"message"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(lines[i]), &entry); err != nil {
|
||||
return false
|
||||
}
|
||||
if entry.Type != "message" {
|
||||
continue
|
||||
}
|
||||
if entry.Message.Role != "assistant" || entry.Message.StopReason != "stop" {
|
||||
return false
|
||||
}
|
||||
for _, block := range entry.Message.Content {
|
||||
if block.Type == "toolCall" {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// completeCloudAgentPiRun 完成运行
|
||||
func (s *Service) completeCloudAgentPiRun(userID, runID string) error {
|
||||
for attempt := 0; attempt < 4; attempt++ {
|
||||
|
||||
@@ -11,19 +11,6 @@ import (
|
||||
|
||||
// Skills Configuration Builders
|
||||
|
||||
// buildSkillPaths 构建 Skills 路径列表
|
||||
func (s *Service) buildSkillPaths(skills []cloudAgentSkill) []string {
|
||||
if len(skills) == 0 {
|
||||
return []string{}
|
||||
}
|
||||
|
||||
paths := make([]string, 0, len(skills))
|
||||
for _, skill := range skills {
|
||||
paths = append(paths, cloudAgentSkillPaths(skill)...)
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
// buildSkillManifests 构建 Skills 清单(传递给 Pi)
|
||||
func (s *Service) buildSkillManifests(skills []cloudAgentSkill) []map[string]any {
|
||||
if len(skills) == 0 {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"infinite-canvas/backend/internal/model"
|
||||
"infinite-canvas/backend/internal/repository"
|
||||
)
|
||||
@@ -106,6 +107,21 @@ func (s *Service) runCloudAgentModelStep(ctx context.Context, userID, runID stri
|
||||
}
|
||||
continue
|
||||
}
|
||||
// 重启恢复:上一个运行时进程已为这一步建好模型任务(可能已经出结果),
|
||||
// 只是没来得及把结果交回就退出了。运行时对 /model 串行调用,此时仍挂着的
|
||||
// 步骤任务只可能是这种遗留任务:接手等待它的结果,不再建新任务和订单。
|
||||
if false {
|
||||
adopt, released, err := s.adoptCloudAgentPiModelStep(userID, runID, state.ActiveTaskID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if adopt {
|
||||
break
|
||||
}
|
||||
if released {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
canonical := canonicalFromRuntimeMessages(messages, state.Canonical.Tools, state.Canonical.SystemPrompt)
|
||||
// A continuation starts a fresh Pi process. If its session snapshot was
|
||||
@@ -198,6 +214,32 @@ func (s *Service) runCloudAgentModelStep(ctx context.Context, userID, runID stri
|
||||
return map[string]any{"text": result.Text, "reasoning": result.Reasoning, "toolCalls": runtimeToolCalls(result.ToolCalls)}, false, nil
|
||||
}
|
||||
|
||||
// adoptCloudAgentPiModelStep 判断挂着的活动任务能否作为本步结果直接接手。
|
||||
// 排队、运行中或已成功的模型步骤直接接手;失败或已取消的先释放,由调用方重新调度。
|
||||
// 其它活动任务(运行根任务、上下文压缩)保持原有流程。
|
||||
func (s *Service) adoptCloudAgentPiModelStep(userID, runID, taskID string) (adopt, released bool, err error) {
|
||||
task, err := s.repo.TaskForUser(userID, taskID)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return false, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
if task.Operation != cloudAgentStepOperation {
|
||||
return false, false, nil
|
||||
}
|
||||
switch task.Status {
|
||||
case model.TaskStatusQueued, model.TaskStatusRunning, model.TaskStatusSucceeded:
|
||||
return true, false, nil
|
||||
case model.TaskStatusFailed, model.TaskStatusCancelled:
|
||||
if err := s.finishCloudAgentPiModelStep(userID, runID, taskID, "", ""); err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
return false, true, nil
|
||||
}
|
||||
return false, false, nil
|
||||
}
|
||||
|
||||
// cloudAgentPiThinkingEnabled treats an omitted thinking level the same as Pi's
|
||||
// explicit "off" value. Pi omits the field when thinking is disabled, and the
|
||||
// Go JSON decoder represents that omitted field as an empty string.
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
// 重启恢复:上一个运行时进程已为这一步建好模型任务、任务也已成功,但结果没交回。
|
||||
// 新进程重新发起 /model 时必须直接接手这份结果,不能再建任务、再扣一次费。
|
||||
func TestCloudAgentModelStepAdoptsOrphanedStepTask(t *testing.T) {
|
||||
s, db, a := agentMediaFixture(t)
|
||||
s.disablePiRuntime = true
|
||||
run, _ := agentMediaRun(t, s, a, "auto")
|
||||
|
||||
// 第一个进程:调度这一步,但还没等到结果就"崩溃"。
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
messages := []map[string]any{{"role": "user", "content": "继续"}}
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
_, _, _ = s.runCloudAgentModelStep(ctx, "user", run.ID, messages, "off")
|
||||
close(done)
|
||||
}()
|
||||
var orphanID string
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for time.Now().Before(deadline) && orphanID == "" {
|
||||
latest, err := s.repo.CloudAgent("user", run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := cloudAgentDecode(latest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
orphanID = state.ActiveTaskID
|
||||
time.Sleep(20 * time.Millisecond)
|
||||
}
|
||||
cancel()
|
||||
<-done
|
||||
if orphanID == "" {
|
||||
t.Fatal("first process never scheduled a model step")
|
||||
}
|
||||
if err := db.Model(&model.Task{}).Where("id = ?", orphanID).Updates(map[string]any{"status": model.TaskStatusSucceeded, "result_json": `{"text":"已完成"}`}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var before int64
|
||||
if err := db.Model(&model.Task{}).Where("agent_run_id = ? AND operation = ?", run.ID, cloudAgentStepOperation).Count(&before).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 第二个进程:重新发起同一步。
|
||||
result, _, err := s.runCloudAgentModelStep(context.Background(), "user", run.ID, messages, "off")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if text, _ := result.(map[string]any)["text"].(string); text != "已完成" {
|
||||
t.Fatalf("adopted result = %#v", result)
|
||||
}
|
||||
var after int64
|
||||
if err := db.Model(&model.Task{}).Where("agent_run_id = ? AND operation = ?", run.ID, cloudAgentStepOperation).Count(&after).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after != before {
|
||||
t.Fatalf("recovery created %d new step task(s); want the orphaned task to be adopted", after-before)
|
||||
}
|
||||
latest, err := s.repo.CloudAgent("user", run.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state, err := cloudAgentDecode(latest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state.ActiveTaskID != "" {
|
||||
t.Fatalf("adopted step was not released: active=%s", state.ActiveTaskID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudAgentPiTurnSettled(t *testing.T) {
|
||||
header := `{"type":"session","id":"s"}`
|
||||
user := `{"type":"message","message":{"role":"user","content":[{"type":"text","text":"hi"}]}}`
|
||||
done := `{"type":"message","message":{"role":"assistant","stopReason":"stop","content":[{"type":"text","text":"ok"}]}}`
|
||||
tool := `{"type":"message","message":{"role":"assistant","stopReason":"toolUse","content":[{"type":"toolCall","id":"c"}]}}`
|
||||
meta := `{"type":"thinking_level_change","thinkingLevel":"off"}`
|
||||
settled := &cloudAgentRuntime{PiAssistantResponses: 1}
|
||||
cases := []struct {
|
||||
name string
|
||||
jsonl string
|
||||
state *cloudAgentRuntime
|
||||
want bool
|
||||
}{
|
||||
{"final answer", strings.Join([]string{header, user, done, meta}, "\n") + "\n", settled, true},
|
||||
{"pending user prompt", strings.Join([]string{header, done, user}, "\n"), settled, false},
|
||||
{"tool call pending", strings.Join([]string{header, user, tool}, "\n"), settled, false},
|
||||
{"no response this run", strings.Join([]string{header, user, done}, "\n"), &cloudAgentRuntime{}, false},
|
||||
{"active task", strings.Join([]string{header, user, done}, "\n"), &cloudAgentRuntime{PiAssistantResponses: 1, ActiveTaskID: "t"}, false},
|
||||
{"empty", "", settled, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := cloudAgentPiTurnSettled(tc.jsonl, tc.state); got != tc.want {
|
||||
t.Errorf("%s: settled = %v, want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -24,9 +24,7 @@ type EnhancedPiRequestParams struct {
|
||||
ModelID string
|
||||
RuntimeState *cloudAgentRuntime
|
||||
Canonical *canonicalAgentRequest
|
||||
SessionFile string
|
||||
SessionJSONL string
|
||||
SessionDir string
|
||||
}
|
||||
|
||||
// buildEnhancedPiRequest 构建增强的 Pi 请求(核心方法)
|
||||
@@ -36,8 +34,8 @@ func (s *Service) buildEnhancedPiRequest(ctx context.Context, params EnhancedPiR
|
||||
// 1. 构建工具列表(包括画布工具)
|
||||
tools := s.buildCompletePiTools(params.Canonical.Tools)
|
||||
|
||||
// 2. 构建 Skills 配置
|
||||
skillPaths := s.buildSkillPaths(params.RuntimeState.Skills)
|
||||
// 2. 构建 Skills 配置。技能内容只经服务端读取工具提供,不交给运行时按路径加载:
|
||||
// 技能路径是相对路径,运行时按自己的工作目录解析,会读到无关文件。
|
||||
enabledSkills := s.buildSkillManifests(params.RuntimeState.Skills)
|
||||
|
||||
slog.Debug("agent enabled skills", "count", len(enabledSkills))
|
||||
@@ -80,12 +78,9 @@ func (s *Service) buildEnhancedPiRequest(ctx context.Context, params EnhancedPiR
|
||||
|
||||
// 10. 组装完整请求
|
||||
request := cloudAgentPiProcessRequest{
|
||||
// 会话信息
|
||||
SessionFile: params.SessionFile,
|
||||
// 会话信息:只传数据库里的快照。会话文件与工作目录由运行时在自己的
|
||||
// 临时目录里创建,独立容器里没有服务端的数据目录。
|
||||
SessionJSONL: params.SessionJSONL,
|
||||
SessionDir: params.SessionDir,
|
||||
Cwd: s.dataDir,
|
||||
AgentDir: params.SessionDir,
|
||||
|
||||
// 标识信息
|
||||
SessionId: params.RunID,
|
||||
@@ -98,7 +93,6 @@ func (s *Service) buildEnhancedPiRequest(ctx context.Context, params EnhancedPiR
|
||||
SystemPrompt: params.SystemPrompt,
|
||||
|
||||
// 核心增强:完整的上下文传递
|
||||
SkillPaths: skillPaths,
|
||||
EnabledSkills: enabledSkills,
|
||||
Profile: profile,
|
||||
Memory: memory,
|
||||
|
||||
@@ -16,18 +16,13 @@ type cloudAgentPiBridge = agentruntime.Bridge
|
||||
type cloudAgentPiProcessRequest struct {
|
||||
BridgeURL string `json:"bridgeURL"`
|
||||
BridgeToken string `json:"bridgeToken"`
|
||||
SessionFile string `json:"sessionFile,omitempty"`
|
||||
SessionJSONL string `json:"sessionJSONL,omitempty"`
|
||||
SessionDir string `json:"sessionDir,omitempty"`
|
||||
SessionId string `json:"sessionId,omitempty"`
|
||||
UserId string `json:"userId,omitempty"`
|
||||
CanvasId string `json:"canvasId,omitempty"`
|
||||
RunId string `json:"runId,omitempty"`
|
||||
Cwd string `json:"cwd"`
|
||||
AgentDir string `json:"agentDir"`
|
||||
Prompt string `json:"prompt"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
SkillPaths []string `json:"skillPaths,omitempty"`
|
||||
EnabledSkills []map[string]any `json:"enabledSkills,omitempty"`
|
||||
Profile map[string]any `json:"profile,omitempty"`
|
||||
Memory map[string]any `json:"memory,omitempty"`
|
||||
@@ -42,10 +37,10 @@ type cloudAgentPiProcessRequest struct {
|
||||
func runCloudAgentPi(ctx context.Context, request cloudAgentPiProcessRequest, bridge cloudAgentPiBridge) error {
|
||||
runtimeRequest := agentruntime.ProcessRequest{
|
||||
BridgeURL: request.BridgeURL, BridgeToken: request.BridgeToken,
|
||||
SessionFile: request.SessionFile, SessionJSONL: request.SessionJSONL, SessionDir: request.SessionDir,
|
||||
SessionID: request.SessionId, UserID: request.UserId, CanvasID: request.CanvasId, RunID: request.RunId,
|
||||
CWD: request.Cwd, AgentDir: request.AgentDir, Prompt: request.Prompt, SystemPrompt: request.SystemPrompt,
|
||||
SkillPaths: request.SkillPaths, EnabledSkills: request.EnabledSkills, Profile: request.Profile,
|
||||
SessionJSONL: request.SessionJSONL,
|
||||
SessionID: request.SessionId, UserID: request.UserId, CanvasID: request.CanvasId, RunID: request.RunId,
|
||||
Prompt: request.Prompt, SystemPrompt: request.SystemPrompt,
|
||||
EnabledSkills: request.EnabledSkills, Profile: request.Profile,
|
||||
Memory: request.Memory, Canvas: request.Canvas, Features: request.Features, Tools: request.Tools,
|
||||
Compaction: request.Compaction, Permissions: request.Permissions, Model: request.Model,
|
||||
}
|
||||
|
||||
@@ -101,6 +101,9 @@ func cloudAgentCapabilityGuide() string {
|
||||
b.WriteString(descriptor.Type)
|
||||
b.WriteString("):")
|
||||
b.WriteString(descriptor.Purpose)
|
||||
if variant := descriptor.Variant; variant != nil {
|
||||
fmt.Fprintf(&b, " 画布识别:type=%s 且 workflowKind=%s,读取结果 kind=%s;不能用 add_node 新建。", variant.BaseType, variant.WorkflowKind, descriptor.Type)
|
||||
}
|
||||
if len(descriptor.GoodFor) > 0 {
|
||||
b.WriteString(" 适合:")
|
||||
b.WriteString(strings.Join(descriptor.GoodFor, "、"))
|
||||
|
||||
@@ -456,6 +456,12 @@ func (s *Service) advanceCloudAgentTool(run *model.CloudAgentExecution, state *c
|
||||
if err == nil {
|
||||
preview = storyboardPlan.Preview
|
||||
}
|
||||
case "canvas_create_character":
|
||||
characterPlan, err := prepareCloudAgentCharacterCreate(repo, run.UserID, state.Request.CanvasID, call)
|
||||
mutationErr = err
|
||||
if err == nil {
|
||||
preview = characterPlan.Preview
|
||||
}
|
||||
case "canvas_edit_batch_table":
|
||||
batchPlan, err := prepareCloudAgentBatchTableEdit(repo, run.UserID, state.Request.CanvasID, call)
|
||||
mutationErr = err
|
||||
@@ -561,6 +567,8 @@ func (s *Service) advanceCloudAgentTool(run *model.CloudAgentExecution, state *c
|
||||
result, toolErr = applyCloudAgentArrangeNodes(repo, run.UserID, state.Request.CanvasID, call, policy, cloudAgentCanvasEventRecorder(run.ID, state))
|
||||
case call.Function.Name == "canvas_create_storyboard", call.Function.Name == "canvas_edit_storyboard":
|
||||
result, toolErr = applyCloudAgentStoryboardMutation(repo, run.UserID, state.Request.CanvasID, call, policy, cloudAgentCanvasEventRecorder(run.ID, state))
|
||||
case call.Function.Name == "canvas_create_character":
|
||||
result, toolErr = applyCloudAgentCharacterCreate(repo, run.UserID, state.Request.CanvasID, call, policy, cloudAgentCanvasEventRecorder(run.ID, state))
|
||||
case call.Function.Name == "canvas_edit_batch_table":
|
||||
result, toolErr = applyCloudAgentBatchTableMutation(repo, run.UserID, state.Request.CanvasID, call, policy, cloudAgentCanvasEventRecorder(run.ID, state))
|
||||
case call.Function.Name == "canvas_inspect_image":
|
||||
|
||||
@@ -620,13 +620,26 @@ func TestCloudAgentToolLoopPersistsApprovalAndAppliesCanvasWrite(t *testing.T) {
|
||||
func TestCloudAgentNodeTypesExposeExecutableAllowList(t *testing.T) {
|
||||
result := cloudAgentNodeTypes()
|
||||
nodes, ok := result["nodes"].([]map[string]any)
|
||||
if !ok || len(nodes) != 8 {
|
||||
if !ok || len(nodes) != 9 {
|
||||
t.Fatalf("unexpected node registry: %#v", result)
|
||||
}
|
||||
var character map[string]any
|
||||
for _, node := range nodes {
|
||||
if node["type"] == "panorama" {
|
||||
t.Fatal("UI-only node must not be exposed")
|
||||
}
|
||||
if node["type"] == "character" {
|
||||
character = node
|
||||
}
|
||||
}
|
||||
// 角色卡必须被 Agent 发现,但只是 text 节点的变体:不能出现在 add_node 的 nodeType 枚举里。
|
||||
if character == nil || character["creatable"] != false || character["canvasNodeType"] != "text" || character["workflowKind"] != "character" || character["canReference"] != true {
|
||||
t.Fatalf("character capability is not discoverable as a non-creatable variant: %#v", character)
|
||||
}
|
||||
for _, nodeType := range cloudAgentNodeTypeNames() {
|
||||
if nodeType == "character" {
|
||||
t.Fatal("character variant must not be creatable through add_node")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -52,11 +52,12 @@ func TestCloudAgentToolSchemaStaysCompact(t *testing.T) {
|
||||
t.Fatal("canvas_apply_ops 未暴露")
|
||||
}
|
||||
|
||||
// 体积预算:导演台、技能检索和上下文读取工具合入后,当前平台工具为 24 个,实测
|
||||
// 27,812 字节,因此把预算显式上调到 29,000(约 4.3% 余量)。新增工具或字段时请
|
||||
// 重新测量并有意识地调整这个数字,而不是让 schema 悄悄膨胀(它每一步都要发、还在
|
||||
// 前缀最前面)。
|
||||
if len(raw) > 29000 {
|
||||
t.Fatalf("平台工具 schema 体积 %d 字节超出预算 29000:请压缩描述或显式调整预算", len(raw))
|
||||
// 体积预算:导演台、技能检索和上下文读取工具合入后为 24 个工具、27,812 字节,预算 29,000。
|
||||
// 之后能力注册表加入角色卡(图片/视频/音频接受 character 输入)到 28,979 字节;再新增
|
||||
// canvas_create_character(角色卡打包创建,设定字段已压成一行描述)后为 25 个工具、实测
|
||||
// 29,938 字节,因此显式上调到 30,500(约 1.9% 余量)。新增工具或字段时请重新测量并
|
||||
// 有意识地调整这个数字,而不是让 schema 悄悄膨胀(它每一步都要发、还在前缀最前面)。
|
||||
if len(raw) > 30500 {
|
||||
t.Fatalf("平台工具 schema 体积 %d 字节超出预算 30500:请压缩描述或显式调整预算", len(raw))
|
||||
}
|
||||
}
|
||||
@@ -220,6 +220,7 @@ func compileCloudAgentTools(req CloudAgentRequest, includeProfileTool bool) []ma
|
||||
"rowId": str("update/remove 使用 canvas_read_storyboard 返回的真实 rowId;append 留空"),
|
||||
"patch": cloudAgentStoryboardPatchSchema(),
|
||||
}, "snapshotHash", "nodeId", "action")
|
||||
add("canvas_create_character", "把画布上就绪的形象图片(可加声音音频)打包成角色卡:写入角色库并在画布放置角色卡节点,按权限审批。已有同名角色卡先复用;definition 只填有依据的设定。", cloudAgentCharacterCreateSchema(), "nodeId", "name", "imageNodeId")
|
||||
add("canvas_edit_batch_table", "操作批量创作表组件:追加、修改或删除任务行,切换批量换装/创意生图,设置1/5/10并发,新增或减少参考图列,或设置覆盖各任务的全局提示词。必须先用 canvas_read_batch_table 获取最新 snapshotHash 和真实 rowId。行 patch 仅允许 enabled、inputNodeIds、prompt;prompt 可使用读取结果中的 @参考图1、@参考图2 等 mentionToken 指代本行对应位置的图片。append 未传 inputNodeIds 时会继承上一行参考图;图片ID必须来自当前画布。不能写 outputNodeId、任务状态、URL、storageKey 或任意 metadata。本工具只编辑计划,不提交收费生成。", map[string]any{
|
||||
"snapshotHash": str("最近一次 canvas_read_batch_table 返回的 snapshotHash(这个表节点的版本;其它节点的改动不影响它)"),
|
||||
"nodeId": str("真实批量创作表节点ID"),
|
||||
|
||||
@@ -106,8 +106,8 @@ func validateCloudAgentConnection(nodes []map[string]any, fromID, toID string, e
|
||||
if from == nil || to == nil {
|
||||
return BadAuthRequest("连线端点不存在")
|
||||
}
|
||||
fromCapability, fromKnown := cloudAgentNodeCapabilityForType(stringValue(from["type"]))
|
||||
toCapability, toKnown := cloudAgentNodeCapabilityForType(stringValue(to["type"]))
|
||||
fromCapability, fromKnown := cloudAgentNodeCapabilityForNode(from)
|
||||
toCapability, toKnown := cloudAgentNodeCapabilityForNode(to)
|
||||
if !fromKnown || !toKnown {
|
||||
return BadAuthRequest("连线包含当前 Agent 不支持的节点类型")
|
||||
}
|
||||
@@ -185,6 +185,10 @@ func cloudAgentNodeTypes() map[string]any {
|
||||
"defaultSize": map[string]any{"width": capability.DefaultWidth, "height": capability.DefaultHeight},
|
||||
"canUpdate": capability.CanUpdate,
|
||||
}
|
||||
if variant := capability.Variant; variant != nil {
|
||||
// 变体不能 add_node;画布里按 type+metadata.workflowKind 识别,读取结果以 kind 标出。
|
||||
item["canvasNodeType"], item["workflowKind"], item["creatable"] = variant.BaseType, variant.WorkflowKind, false
|
||||
}
|
||||
if len(capability.GoodFor) > 0 {
|
||||
item["goodFor"] = capability.GoodFor
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import (
|
||||
)
|
||||
|
||||
func cloudAgentWrite(name string) bool {
|
||||
return name == "canvas_apply_ops" || name == "canvas_arrange_nodes" || name == "generate_media" || name == "image_layer_split" || name == "canvas_create_storyboard" || name == "canvas_edit_storyboard" || name == "canvas_edit_batch_table"
|
||||
return name == "canvas_apply_ops" || name == "canvas_arrange_nodes" || name == "generate_media" || name == "image_layer_split" || name == "canvas_create_storyboard" || name == "canvas_edit_storyboard" || name == "canvas_edit_batch_table" || name == "canvas_create_character"
|
||||
}
|
||||
|
||||
// 同参缓存只能拦住“原样重复”的读取。模型也可能不断修改 offset、nodeIds 或
|
||||
|
||||
@@ -144,7 +144,8 @@ func (s *Service) prepareCloudAgentImageInspection(userID, canvasID string, stat
|
||||
if node == nil {
|
||||
return nil, BadAuthRequest("指定节点不在当前画布")
|
||||
}
|
||||
reference, _, err := cloudAgentReference(s.repo, userID, node)
|
||||
// 角色卡查看的是其绑定的三视图/形象图;普通节点查看自身图片资源。
|
||||
reference, _, err := cloudAgentMediaReference(s.repo, userID, canvas.ProjectID, node)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -457,7 +457,7 @@ func (s *Service) taskBillingOrder(userID string, task *model.Task, input map[st
|
||||
scene := firstNonEmpty(strings.TrimSpace(task.Operation), task.Type)
|
||||
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
|
||||
priceTierID, _ := config["priceTierId"].(string)
|
||||
return s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelID, modelKey, capability, scene, billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||
return s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelID, modelKey, capability, scene, requestedBillingQuantity(capability, config), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||
}
|
||||
|
||||
func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, input map[string]any) (*model.BillingOrder, error) {
|
||||
@@ -481,7 +481,7 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
|
||||
if logicalModel.PricePolicy == "channel" {
|
||||
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
|
||||
priceTierID, _ := config["priceTierId"].(string)
|
||||
order, priceErr := s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelModel.ChannelID, channelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||
order, priceErr := s.newBillingOrderWithPriceTier(userID, task.ID, "task:"+task.ID+":"+newID(), channelModel.ChannelID, channelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), requestedBillingQuantity(capability, config), estimateTaskBillingTokens(input, capability), strings.TrimSpace(priceTierID), intent)
|
||||
if priceErr != nil {
|
||||
return nil, priceErr
|
||||
}
|
||||
@@ -499,8 +499,8 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
|
||||
case "fixed_request":
|
||||
amount = logicalModel.UnitPriceMicrocredits
|
||||
case "per_second":
|
||||
quantity = billingQuantity(capability, config["videoSeconds"])
|
||||
if capability != "video" || quantity <= 0 {
|
||||
quantity = requestedBillingQuantity(capability, config)
|
||||
if (capability != "video" && capability != "audio") || quantity <= 0 {
|
||||
return nil, BadAuthRequest("当前模型按时长计费,但请求未提供有效时长")
|
||||
}
|
||||
amount, err = creditAmount(logicalModel.UnitPriceMicrocredits, quantity, 10_000)
|
||||
@@ -543,7 +543,7 @@ func (s *Service) newLogicalModelBillingOrder(userID string, task *model.Task, i
|
||||
}
|
||||
intent := ModelRequestIntentFromTaskInput(input, task.Type, task.Operation)
|
||||
priceTierID, _ := config["priceTierId"].(string)
|
||||
snapshotCreditCost(order, channelModelPriceTierForBilling(*channelModel, priceTierID, capability, intent), billingQuantity(capability, config["videoSeconds"]), tokenEstimate)
|
||||
snapshotCreditCost(order, channelModelPriceTierForBilling(*channelModel, priceTierID, capability, intent), requestedBillingQuantity(capability, config), tokenEstimate)
|
||||
return order, nil
|
||||
}
|
||||
|
||||
@@ -596,11 +596,11 @@ func (s *Service) newBillingOrderWithPriceTier(userID string, taskID string, ide
|
||||
switch tier.BillingMode {
|
||||
case "fixed_request":
|
||||
case "per_second":
|
||||
if item.Capability != "video" || capability != "video" {
|
||||
return nil, BadAuthRequest("按秒计费仅适用于视频生成")
|
||||
if (item.Capability != "video" && item.Capability != "audio") || capability != item.Capability {
|
||||
return nil, BadAuthRequest("按秒计费仅适用于视频或音频生成")
|
||||
}
|
||||
if requestedQuantity <= 0 {
|
||||
return nil, BadAuthRequest("视频生成时长无效,无法按秒计费")
|
||||
return nil, BadAuthRequest("生成时长无效,无法按秒计费")
|
||||
}
|
||||
quantity = requestedQuantity
|
||||
case "token":
|
||||
@@ -741,7 +741,7 @@ func tokenEstimateAmount(item *model.ChannelModel, estimate tokenBillingEstimate
|
||||
}
|
||||
|
||||
func billingQuantity(capability string, value any) int64 {
|
||||
if capability != "video" {
|
||||
if capability != "video" && capability != "audio" {
|
||||
return 1
|
||||
}
|
||||
quantity, err := strconv.ParseInt(strings.TrimSpace(fmt.Sprint(value)), 10, 64)
|
||||
@@ -751,6 +751,28 @@ func billingQuantity(capability string, value any) int64 {
|
||||
return quantity
|
||||
}
|
||||
|
||||
// requestedBillingQuantity is the quantity reserved before a provider has
|
||||
// returned the generated media. Audio output length is not known at request
|
||||
// time, so an audio per-second order uses one second as the minimum
|
||||
// preauthorization unless the caller explicitly supplied audioSeconds.
|
||||
// Settlement must replace this estimate with the measured output duration.
|
||||
func requestedBillingQuantity(capability string, config map[string]any) int64 {
|
||||
if capability == "audio" {
|
||||
if config == nil {
|
||||
return 1
|
||||
}
|
||||
value, present := config["audioSeconds"]
|
||||
if !present || strings.TrimSpace(fmt.Sprint(value)) == "" {
|
||||
return 1
|
||||
}
|
||||
return billingQuantity(capability, value)
|
||||
}
|
||||
if config == nil {
|
||||
return billingQuantity(capability, nil)
|
||||
}
|
||||
return billingQuantity(capability, config["videoSeconds"])
|
||||
}
|
||||
|
||||
func (s *Service) MarkBillingRunning(orderID string) error {
|
||||
return s.taskBilling().MarkBillingRunning(orderID)
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ func (s *Service) QuoteChannelModel(req ChannelModelQuoteRequest) (*LogicalModel
|
||||
config = input["config"].(map[string]any)
|
||||
estimate := estimateTaskBillingTokens(input, req.Intent.Capability)
|
||||
intent := ModelRequestIntentFromTaskInput(input, "canvas_"+req.Intent.Capability, req.Intent.Operation)
|
||||
order, err := s.newBillingOrderWithPriceTier("", "", "quote", req.ChannelID, req.ModelKey, req.Intent.Capability, "model_quote", billingQuantity(req.Intent.Capability, config["videoSeconds"]), estimate, stringValue(config["priceTierId"]), intent)
|
||||
order, err := s.newBillingOrderWithPriceTier("", "", "quote", req.ChannelID, req.ModelKey, req.Intent.Capability, "model_quote", requestedBillingQuantity(req.Intent.Capability, config), estimate, stringValue(config["priceTierId"]), intent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -89,8 +89,9 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
|
||||
providerModelKey = firstNonEmpty(routed.PriceTier.ProviderModelKey, providerModelKey)
|
||||
}
|
||||
input["config"].(map[string]any)["providerModelKey"] = providerModelKey
|
||||
quantity := billingQuantity(capability, inputConfigValue(input, "videoSeconds"))
|
||||
if capability != "video" {
|
||||
config, _ := input["config"].(map[string]any)
|
||||
quantity := requestedBillingQuantity(capability, config)
|
||||
if capability != "video" && capability != "audio" {
|
||||
quantity = 1
|
||||
}
|
||||
tokenEstimate := estimateTaskBillingTokens(input, capability)
|
||||
@@ -116,7 +117,7 @@ func (s *Service) QuoteLogicalModel(logicalModelID string, intent ModelRequestIn
|
||||
quantity = 1
|
||||
amount = routed.LogicalModel.UnitPriceMicrocredits
|
||||
case "per_second":
|
||||
if capability != "video" || quantity <= 0 {
|
||||
if (capability != "video" && capability != "audio") || quantity <= 0 {
|
||||
return nil, BadAuthRequest("当前模型按时长计费,但请求未提供有效时长")
|
||||
}
|
||||
amount, err = creditAmount(routed.LogicalModel.UnitPriceMicrocredits, quantity, 10_000)
|
||||
|
||||
@@ -429,8 +429,8 @@ func (s *Service) logicalModelBundle(actor *model.User, id string, req LogicalMo
|
||||
} else if billingMode != "fixed_request" && billingMode != "per_second" && billingMode != "token" {
|
||||
return nil, nil, nil, false, BadAuthRequest("前台模型计费方式仅支持按次、按秒或 Token")
|
||||
}
|
||||
if pricePolicy == "unified" && billingMode == "per_second" && capability != "video" {
|
||||
return nil, nil, nil, false, BadAuthRequest("只有视频前台模型可以按秒计费")
|
||||
if pricePolicy == "unified" && billingMode == "per_second" && capability != "video" && capability != "audio" {
|
||||
return nil, nil, nil, false, BadAuthRequest("只有视频或音频前台模型可以按秒计费")
|
||||
}
|
||||
if pricePolicy == "unified" && billingMode == "token" {
|
||||
if err := validateTokenPrices(capability, req.InputPriceMicrocredits, req.OutputPriceMicrocredits, req.CachedPriceMicrocredits); err != nil {
|
||||
|
||||
@@ -274,7 +274,7 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
|
||||
capability = capabilityFromTaskType(task.Type)
|
||||
}
|
||||
priceTierID, _ := config["priceTierId"].(string)
|
||||
replacement, err = s.newBillingOrderWithPriceTier(task.UserID, task.ID, "route-switch:"+task.ID+":"+selected.Route.ID, selected.ChannelModel.ChannelID, selected.ChannelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(nextInput, capability), strings.TrimSpace(priceTierID), intent)
|
||||
replacement, err = s.newBillingOrderWithPriceTier(task.UserID, task.ID, "route-switch:"+task.ID+":"+selected.Route.ID, selected.ChannelModel.ChannelID, selected.ChannelModel.ModelKey, capability, firstNonEmpty(strings.TrimSpace(task.Operation), task.Type), requestedBillingQuantity(capability, config), estimateTaskBillingTokens(nextInput, capability), strings.TrimSpace(priceTierID), intent)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -287,7 +287,7 @@ func (s *Service) switchTaskToNextRoute(task *model.Task, attempts []model.Route
|
||||
} else if task.BillingOrderID != "" {
|
||||
config, _ := nextInput["config"].(map[string]any)
|
||||
capability := selected.ChannelModel.Capability
|
||||
snapshotCreditCost(&costOrder, channelModelPriceTierForIntent(selected.ChannelModel, intent), billingQuantity(capability, config["videoSeconds"]), estimateTaskBillingTokens(nextInput, capability))
|
||||
snapshotCreditCost(&costOrder, channelModelPriceTierForIntent(selected.ChannelModel, intent), requestedBillingQuantity(capability, config), estimateTaskBillingTokens(nextInput, capability))
|
||||
}
|
||||
if err := s.repo.SwitchTaskLogicalRoute(task.ID, previousRouteID, selected.Route.ID, string(encoded), task.BillingOrderID, selected.ChannelModel.ChannelID, selected.ChannelModel.ID, replacement, costOrder.BillingCostSnapshot); err != nil {
|
||||
if errors.Is(err, repository.ErrInsufficientCredits) {
|
||||
|
||||
@@ -83,21 +83,24 @@ func (s *Service) UpdateTopupProduct(actor *model.User, id string, request Topup
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
existing, err := s.repo.TopupProduct(id)
|
||||
id = strings.TrimSpace(id)
|
||||
var product *model.TopupProduct
|
||||
// 已售数量必须在锁住商品行之后计算,否则会覆盖并发下单扣减或关单退回的库存。
|
||||
err := s.repo.UpdateTopupProduct(id, func(existing *model.TopupProduct) (*model.TopupProduct, error) {
|
||||
consumed := existing.StockTotal - existing.StockRemaining
|
||||
if existing.SaleStrategy != model.TopupSaleStrategyInventory {
|
||||
consumed = 0
|
||||
}
|
||||
built, buildErr := topupProductFromRequest(id, actor.ID, request, existing.StockTotal, consumed)
|
||||
if buildErr != nil {
|
||||
return nil, buildErr
|
||||
}
|
||||
product = built
|
||||
return built, nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
consumed := existing.StockTotal - existing.StockRemaining
|
||||
if existing.SaleStrategy != model.TopupSaleStrategyInventory {
|
||||
consumed = 0
|
||||
}
|
||||
product, err := topupProductFromRequest(strings.TrimSpace(id), actor.ID, request, existing.StockTotal, consumed)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.repo.UpdateTopupProduct(product); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.appendAdminAudit(actor, "topup_product.update", "topup_product", product.ID, "更新积分充值商品", map[string]any{"enabled": product.Enabled, "saleStrategy": product.SaleStrategy}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -18,6 +18,20 @@ type CreateProjectCharacterRequest struct {
|
||||
Definition map[string]any `json:"definition"`
|
||||
}
|
||||
|
||||
type CreateCharacterRequest struct {
|
||||
Name string `json:"name"`
|
||||
Definition map[string]any `json:"definition"`
|
||||
ImageResourceID string `json:"imageResourceId"`
|
||||
AudioResourceID string `json:"audioResourceId"`
|
||||
VoiceName string `json:"voiceName"`
|
||||
Instructions string `json:"instructions"`
|
||||
}
|
||||
|
||||
type CharacterAssetSummary struct {
|
||||
Asset ProjectAssetSummary `json:"asset"`
|
||||
Character CharacterCardSummary `json:"character"`
|
||||
}
|
||||
|
||||
type UpdateProjectCharacterRequest struct {
|
||||
Name string `json:"name"`
|
||||
Definition map[string]any `json:"definition"`
|
||||
@@ -117,6 +131,164 @@ func (s *Service) ListVoiceProfiles(userID string) ([]VoiceProfileSummary, error
|
||||
return result, nil
|
||||
}
|
||||
|
||||
type CharacterListPage struct {
|
||||
Characters []CharacterAssetSummary `json:"characters"`
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"hasMore"`
|
||||
}
|
||||
|
||||
func (s *Service) ListCharacters(userID string, query string, page int, pageSize int, ids []string) (CharacterListPage, error) {
|
||||
var assets []model.Asset
|
||||
var total int64
|
||||
var err error
|
||||
if len(ids) > 0 {
|
||||
assets, err = s.repo.UserCharacterAssetsByIDs(userID, ids)
|
||||
total = int64(len(assets))
|
||||
page, pageSize = 1, len(assets)
|
||||
} else {
|
||||
assets, total, err = s.repo.UserCharacterAssetsPage(userID, query, page, pageSize)
|
||||
pageSize = normalizeCharacterPageSize(pageSize)
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return CharacterListPage{}, err
|
||||
}
|
||||
result := make([]CharacterAssetSummary, 0, len(assets))
|
||||
for index := range assets {
|
||||
detail, detailErr := s.characterAssetDetail(userID, &assets[index])
|
||||
if detailErr != nil {
|
||||
return CharacterListPage{}, detailErr
|
||||
}
|
||||
result = append(result, detail)
|
||||
}
|
||||
if pageSize < 1 {
|
||||
pageSize = len(result)
|
||||
}
|
||||
return CharacterListPage{Characters: result, Page: page, PageSize: pageSize, Total: total, HasMore: int64(page*pageSize) < total}, nil
|
||||
}
|
||||
|
||||
func normalizeCharacterPageSize(pageSize int) int {
|
||||
if pageSize < 1 || pageSize > 48 {
|
||||
return 12
|
||||
}
|
||||
return pageSize
|
||||
}
|
||||
|
||||
func (s *Service) Character(userID string, assetID string) (CharacterAssetSummary, error) {
|
||||
asset, err := s.repo.UserCharacterAsset(userID, strings.TrimSpace(assetID))
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.characterAssetDetail(userID, asset)
|
||||
}
|
||||
|
||||
func (s *Service) CreateCharacter(userID string, req CreateCharacterRequest) (CharacterAssetSummary, error) {
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if name == "" {
|
||||
return CharacterAssetSummary{}, BadAuthRequest("角色名称不能为空")
|
||||
}
|
||||
definition, err := normalizedCharacterDefinition(req.Definition)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
now := time.Now()
|
||||
assetID, versionID := newID(), newID()
|
||||
payload, err := characterAssetPayload(assetID, versionID, name, definition, now, now)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
asset := model.Asset{ID: assetID, UserID: userID, Kind: "entity", Category: model.AssetCategoryCharacter, Status: model.AssetVersionStatusConfirmed, PrimaryVersionID: versionID, Title: name, PayloadJSON: payload, CreatedAt: now, UpdatedAt: now}
|
||||
version := model.AssetVersion{ID: versionID, AssetID: assetID, Version: 1, Status: model.AssetVersionStatusConfirmed, DefinitionJSON: string(definition), CreatedAt: now, UpdatedAt: now}
|
||||
representations, err := s.characterRepresentationsForResources(userID, newID(), req.ImageResourceID, now)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
voice, err := s.characterVoiceForResource(userID, req.AudioResourceID, req.VoiceName, req.Instructions, now)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
// 形象与声音绑定挂在首个版本上;漏设版本 ID 会让新卡读回来显示"形象缺失 / 声音未绑定"。
|
||||
for index := range representations {
|
||||
representations[index].AssetVersionID = versionID
|
||||
}
|
||||
if voice != nil {
|
||||
voice.AssetVersionID = versionID
|
||||
}
|
||||
if err := s.repo.CreateUserCharacter(&asset, &version, representations, voice); err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.characterAssetDetail(userID, &asset)
|
||||
}
|
||||
|
||||
func (s *Service) UpdateCharacter(userID string, assetID string, req UpdateProjectCharacterRequest) (CharacterAssetSummary, error) {
|
||||
asset, err := s.repo.UserCharacterAsset(userID, strings.TrimSpace(assetID))
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
name := strings.TrimSpace(req.Name)
|
||||
if name == "" {
|
||||
return CharacterAssetSummary{}, BadAuthRequest("角色名称不能为空")
|
||||
}
|
||||
definition, err := normalizedCharacterDefinition(req.Definition)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
if _, err := s.createNextCharacterVersion("", asset, name, string(definition), nil, nil, false); err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.Character(userID, asset.ID)
|
||||
}
|
||||
|
||||
func (s *Service) ReplaceCharacterRepresentations(userID string, assetID string, req ReplaceCharacterRepresentationsRequest) (CharacterAssetSummary, error) {
|
||||
asset, err := s.repo.UserCharacterAsset(userID, strings.TrimSpace(assetID))
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
representations, err := s.characterRepresentationsForInputs(userID, req.Representations, newID(), time.Now())
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
if _, err := s.createNextCharacterVersion("", asset, asset.Title, "", representations, nil, false); err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.Character(userID, asset.ID)
|
||||
}
|
||||
|
||||
func (s *Service) BindCharacterVoice(userID string, assetID string, req BindCharacterVoiceRequest) (CharacterAssetSummary, error) {
|
||||
asset, err := s.repo.UserCharacterAsset(userID, strings.TrimSpace(assetID))
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
voice, err := s.characterVoiceForResource(userID, req.SampleResourceID, req.VoiceName, req.Instructions, time.Now())
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
if voice == nil {
|
||||
voice, err = s.characterVoiceForProfile(userID, req.VoiceProfileID, req.Instructions, time.Now())
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
}
|
||||
if _, err := s.createNextCharacterVersion("", asset, asset.Title, "", nil, voice, false); err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.Character(userID, asset.ID)
|
||||
}
|
||||
|
||||
func (s *Service) UnbindCharacterVoice(userID string, assetID string) (CharacterAssetSummary, error) {
|
||||
asset, err := s.repo.UserCharacterAsset(userID, strings.TrimSpace(assetID))
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
if _, err := s.createNextCharacterVersion("", asset, asset.Title, "", nil, nil, true); err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
return s.Character(userID, asset.ID)
|
||||
}
|
||||
func (s *Service) CreateProjectCharacter(userID string, projectID string, req CreateProjectCharacterRequest) (ProjectCharacterDetail, error) {
|
||||
if _, err := s.repo.ProjectForUser(userID, projectID); err != nil {
|
||||
return ProjectCharacterDetail{}, err
|
||||
@@ -350,6 +522,11 @@ func (s *Service) BindProjectCharacterVoice(userID string, projectID string, ass
|
||||
}
|
||||
var profileErr error
|
||||
profile, profileErr = s.repo.VoiceProfileBySampleResource(userID, sampleResourceID)
|
||||
if profileErr == nil {
|
||||
if err := s.renameSampleVoiceProfile(userID, profile, req.VoiceName); err != nil {
|
||||
return ProjectCharacterDetail{}, err
|
||||
}
|
||||
}
|
||||
if profileErr != nil {
|
||||
if !errors.Is(profileErr, gorm.ErrRecordNotFound) {
|
||||
return ProjectCharacterDetail{}, profileErr
|
||||
@@ -549,6 +726,119 @@ func (s *Service) characterCardVersion(userID string, version *model.AssetVersio
|
||||
return CharacterCardSummary{VersionID: version.ID, Version: version.Version, Definition: definition, Representations: representations, Voice: voice, VisualStatus: visualStatus, VoiceStatus: voiceStatus}, nil
|
||||
}
|
||||
|
||||
func (s *Service) characterAssetDetail(userID string, asset *model.Asset) (CharacterAssetSummary, error) {
|
||||
if asset == nil || asset.Category != model.AssetCategoryCharacter || asset.Kind != "entity" {
|
||||
return CharacterAssetSummary{}, BadAuthRequest("角色资产不可用")
|
||||
}
|
||||
versions, err := s.repo.AssetVersions(asset.ID)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
card, err := s.characterCard(userID, asset)
|
||||
if err != nil {
|
||||
return CharacterAssetSummary{}, err
|
||||
}
|
||||
storageKey, previewText, source, durationMs := projectAssetPreview(asset.PayloadJSON)
|
||||
return CharacterAssetSummary{Asset: ProjectAssetSummary{ID: asset.ID, Title: asset.Title, MediaType: asset.Kind, Category: asset.Category, Status: asset.Status, PrimaryVersionID: asset.PrimaryVersionID, VersionCount: len(versions), Usages: []string{}, StorageKey: storageKey, PreviewText: previewText, DurationMs: durationMs, UpdatedAt: asset.UpdatedAt, Source: source, Character: &card}, Character: card}, nil
|
||||
}
|
||||
|
||||
func (s *Service) characterRepresentationsForResources(userID, taskID, imageResourceID string, now time.Time) ([]model.AssetRepresentation, error) {
|
||||
imageResourceID = strings.TrimSpace(imageResourceID)
|
||||
if imageResourceID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
resource, err := s.repo.ResourceForUser(userID, imageResourceID)
|
||||
if err != nil || resource == nil || resource.Kind != "image" || resource.Status != model.ResourceStatusReady {
|
||||
return nil, BadAuthRequest("角色形象资源不可用")
|
||||
}
|
||||
metadata, _ := json.Marshal(map[string]any{"source": "character_image"})
|
||||
return []model.AssetRepresentation{
|
||||
{ID: newID(), TaskID: taskID, ResourceID: imageResourceID, MediaType: "image", Role: "turnaround_sheet", MetadataJSON: string(metadata), CreatedAt: now},
|
||||
{ID: newID(), TaskID: taskID, ResourceID: imageResourceID, MediaType: "image", Role: "primary", MetadataJSON: string(metadata), CreatedAt: now},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) characterRepresentationsForInputs(userID string, inputs []CharacterRepresentationInput, taskID string, now time.Time) ([]model.AssetRepresentation, error) {
|
||||
if len(inputs) == 0 || len(inputs) > 8 {
|
||||
return nil, BadAuthRequest("角色形象数量必须在 1 到 8 之间")
|
||||
}
|
||||
roles := make(map[string]struct{}, len(inputs))
|
||||
result := make([]model.AssetRepresentation, 0, len(inputs))
|
||||
for _, input := range inputs {
|
||||
role := strings.TrimSpace(input.Role)
|
||||
if !validCharacterRepresentationRole(role) {
|
||||
return nil, BadAuthRequest("不支持的角色形象视角")
|
||||
}
|
||||
if _, exists := roles[role]; exists {
|
||||
return nil, BadAuthRequest("同一角色形象视角不能重复")
|
||||
}
|
||||
roles[role] = struct{}{}
|
||||
resourceID := strings.TrimSpace(input.ResourceID)
|
||||
resource, err := s.repo.ResourceForUser(userID, resourceID)
|
||||
if err != nil || resource == nil || resource.Kind != "image" || resource.Status != model.ResourceStatusReady {
|
||||
return nil, BadAuthRequest("角色形象资源不可用")
|
||||
}
|
||||
metadata, marshalErr := json.Marshal(input.Metadata)
|
||||
if marshalErr != nil {
|
||||
return nil, BadAuthRequest("角色形象元数据格式无效")
|
||||
}
|
||||
result = append(result, model.AssetRepresentation{ID: newID(), TaskID: taskID, ResourceID: resourceID, MediaType: "image", Role: role, MetadataJSON: string(metadata), CreatedAt: now})
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) characterVoiceForResource(userID, resourceID, voiceName, instructions string, now time.Time) (*model.CharacterVoiceBinding, error) {
|
||||
resourceID = strings.TrimSpace(resourceID)
|
||||
if resourceID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
resource, err := s.repo.ResourceForUser(userID, resourceID)
|
||||
if err != nil || resource == nil || resource.Kind != "audio" || resource.Status != model.ResourceStatusReady || !isSupportedVoiceSampleMimeType(resource.MimeType) {
|
||||
return nil, BadAuthRequest("请选择已上传完成的支持格式音频:MP3、WAV、M4A/AAC、FLAC、OGG/Opus 或 WebM")
|
||||
}
|
||||
profile, profileErr := s.repo.VoiceProfileBySampleResource(userID, resourceID)
|
||||
if profileErr == nil {
|
||||
if err := s.renameSampleVoiceProfile(userID, profile, voiceName); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if profileErr != nil {
|
||||
if !errors.Is(profileErr, gorm.ErrRecordNotFound) {
|
||||
return nil, profileErr
|
||||
}
|
||||
voiceName = strings.TrimSpace(voiceName)
|
||||
if voiceName == "" {
|
||||
voiceName = "上传声音 · " + resourceID[:min(8, len(resourceID))]
|
||||
}
|
||||
profile = &model.VoiceProfile{ID: newID(), UserID: userID, Name: voiceName, Provider: "user_upload", VoiceKey: "sample:" + resourceID, Language: "按样本使用", Timbre: "用户上传样本", SampleResourceID: resourceID, CompatibleModelsJSON: "[]", Status: "active", CreatedAt: now, UpdatedAt: now}
|
||||
if err := s.repo.CreateVoiceProfile(profile); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return &model.CharacterVoiceBinding{ID: newID(), VoiceProfileID: profile.ID, Instructions: strings.TrimSpace(instructions), CreatedAt: now, UpdatedAt: now}, nil
|
||||
}
|
||||
|
||||
// renameSampleVoiceProfile 让同一段样本复用的声音档案跟随用户最新给的名字
|
||||
// (例如画布上把「生成音频」改名为「杨过·声音」后重新绑定)。
|
||||
func (s *Service) renameSampleVoiceProfile(userID string, profile *model.VoiceProfile, voiceName string) error {
|
||||
voiceName = truncateRunes(strings.TrimSpace(voiceName), 160)
|
||||
if profile == nil || profile.Provider != "user_upload" || voiceName == "" || voiceName == profile.Name {
|
||||
return nil
|
||||
}
|
||||
if err := s.repo.RenameVoiceProfile(userID, profile.ID, voiceName); err != nil {
|
||||
return err
|
||||
}
|
||||
profile.Name = voiceName
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) characterVoiceForProfile(userID, profileID, instructions string, now time.Time) (*model.CharacterVoiceBinding, error) {
|
||||
profile, err := s.repo.VoiceProfileForUser(userID, strings.TrimSpace(profileID))
|
||||
if err != nil || profile == nil || profile.Status != "active" {
|
||||
return nil, BadAuthRequest("选择的声音素材不可用")
|
||||
}
|
||||
return &model.CharacterVoiceBinding{ID: newID(), VoiceProfileID: profile.ID, Instructions: strings.TrimSpace(instructions), CreatedAt: now, UpdatedAt: now}, nil
|
||||
}
|
||||
func normalizedCharacterDefinition(value map[string]any) (json.RawMessage, error) {
|
||||
if value == nil {
|
||||
value = map[string]any{}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestCharacterVoiceRebindUsesLatestSampleName(t *testing.T) {
|
||||
service, db, _, _ := creationTestService(t)
|
||||
now := time.Now()
|
||||
for _, item := range []any{
|
||||
&model.Resource{ID: "voice-sample", UserID: "user", Kind: "audio", Status: model.ResourceStatusReady, MimeType: "audio/mpeg", Size: 10},
|
||||
&model.VoiceProfile{ID: "sample-profile", UserID: "user", Name: "生成音频", Provider: "user_upload", VoiceKey: "sample:voice-sample", SampleResourceID: "voice-sample", CompatibleModelsJSON: "[]", Status: "active", CreatedAt: now, UpdatedAt: now},
|
||||
} {
|
||||
if err := db.Create(item).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
binding, err := service.characterVoiceForResource("user", "voice-sample", "杨过·声音", "", now)
|
||||
if err != nil || binding.VoiceProfileID != "sample-profile" {
|
||||
t.Fatalf("binding = %#v, %v", binding, err)
|
||||
}
|
||||
var renamed model.VoiceProfile
|
||||
if err := db.First(&renamed, "id = ?", "sample-profile").Error; err != nil || renamed.Name != "杨过·声音" {
|
||||
t.Fatalf("sample voice kept stale name: %q, %v", renamed.Name, err)
|
||||
}
|
||||
// 空名字不能把已有名字清掉。
|
||||
if _, err := service.characterVoiceForResource("user", "voice-sample", " ", "", now); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.First(&renamed, "id = ?", "sample-profile").Error; err != nil || renamed.Name != "杨过·声音" {
|
||||
t.Fatalf("empty name overwrote voice name: %q, %v", renamed.Name, err)
|
||||
}
|
||||
// 内置音色名称由系统维护,不跟随用户输入改名。
|
||||
builtin := model.VoiceProfile{ID: "builtin-profile", Provider: "openai", Name: "alloy"}
|
||||
if err := service.renameSampleVoiceProfile("user", &builtin, "改名"); err != nil || builtin.Name != "alloy" {
|
||||
t.Fatalf("builtin voice renamed: %q, %v", builtin.Name, err)
|
||||
}
|
||||
}
|
||||
@@ -86,6 +86,8 @@ type providerConfig struct {
|
||||
AudioFormat string `json:"audioFormat"`
|
||||
AudioSpeed string `json:"audioSpeed"`
|
||||
AudioInstructions string `json:"audioInstructions"`
|
||||
AudioLanguage string `json:"audioLanguage"`
|
||||
AudioDialect string `json:"audioDialect"`
|
||||
SystemPrompt string `json:"systemPrompt"`
|
||||
CapabilityConfig *ModelCapabilityConfig `json:"capabilityConfig"`
|
||||
WorkflowID string `json:"workflowId"`
|
||||
@@ -308,7 +310,8 @@ func providerPrefersMediaURLs(interfaceType string, input canvasGenerationInput)
|
||||
string(model.ChannelInterfaceXAIVideo), string(model.ChannelInterfaceNovitaVideo),
|
||||
string(model.ChannelInterfaceMiniMaxVideo), string(model.ChannelInterfaceNewAPIVideo),
|
||||
string(model.ChannelInterfaceNewAPIChannel1), string(model.ChannelInterfaceNewAPIChannel2),
|
||||
string(model.ChannelInterfaceVolcengineArkVideo), string(model.ChannelInterfaceVolcengineArkAgentPlanVideo):
|
||||
string(model.ChannelInterfaceVolcengineArkVideo), string(model.ChannelInterfaceVolcengineArkAgentPlanVideo),
|
||||
string(model.ChannelInterfaceDoubaoStreamingTTS):
|
||||
return true
|
||||
}
|
||||
if isGrokVideoConfig(input.Config) || isSeedanceVideoConfig(input.Config) || isArkPlanVideoConfig(input.Config) {
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -40,14 +43,44 @@ func providerResponseBusinessFailure(responseBody []byte) (string, string, bool)
|
||||
if len(responseBody) == 0 {
|
||||
return "", "", false
|
||||
}
|
||||
var payload map[string]any
|
||||
if json.Unmarshal(responseBody, &payload) != nil {
|
||||
return "", "", false
|
||||
// 火山单向语音合成把多帧 JSON 直接拼在同一个 HTTP 200 里。只解析第一帧会把后面的业务失败当成成功。
|
||||
decoder := json.NewDecoder(bytes.NewReader(responseBody))
|
||||
decoder.UseNumber()
|
||||
decoded := false
|
||||
for {
|
||||
var payload map[string]any
|
||||
err := decoder.Decode(&payload)
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
if !decoded {
|
||||
return "", "", false
|
||||
}
|
||||
break
|
||||
}
|
||||
decoded = true
|
||||
if payload == nil {
|
||||
continue
|
||||
}
|
||||
if code, message, failed := providerPayloadBusinessFailure(payload); failed {
|
||||
return code, message, true
|
||||
}
|
||||
}
|
||||
return providerPayloadBusinessFailure(payload)
|
||||
return "", "", false
|
||||
}
|
||||
|
||||
func providerPayloadBusinessFailure(payload map[string]any) (string, string, bool) {
|
||||
if header, ok := payload["header"].(map[string]any); ok {
|
||||
// 只认火山语音合成这种明确的资源拒绝。header.code 在别的协议里可能是 HTTP 状态,不能一律当成业务失败。
|
||||
rawMessage := strings.TrimSpace(stringField(header, "message"))
|
||||
if speechResourceDeniedUserMessage(rawMessage) != "" {
|
||||
if code, message, failed := providerBusinessFailure(header); failed {
|
||||
return code, message, true
|
||||
}
|
||||
return "resource_not_granted", rawMessage, true
|
||||
}
|
||||
}
|
||||
if code, message, failed := providerBusinessFailure(payload); failed {
|
||||
return code, message, true
|
||||
}
|
||||
|
||||
@@ -81,6 +81,26 @@ func TestProviderPayloadBusinessFailureReadsNestedOutputFailure(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderResponseBusinessFailureExplainsDoubaoSpeechDenial(t *testing.T) {
|
||||
body := []byte(`{"code":0,"data":"AAAA"}{"header":{"code":45000030,"message":"[resource_id=volc.seedtts.default] requested resource not granted"}}`)
|
||||
code, message, failed := providerResponseBusinessFailure(body)
|
||||
if !failed || !strings.Contains(message, "requested resource not granted") {
|
||||
t.Fatalf("business failure = (%q, %q, %v)", code, message, failed)
|
||||
}
|
||||
if code != "45000030" && code != "4.500003e+07" {
|
||||
t.Fatalf("unexpected code %q", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderPayloadBusinessFailureIgnoresOrdinaryHeader(t *testing.T) {
|
||||
if _, _, failed := providerPayloadBusinessFailure(map[string]any{
|
||||
"header": map[string]any{"code": float64(200), "message": "ok"},
|
||||
"data": map[string]any{"audio": "AAAA"},
|
||||
}); failed {
|
||||
t.Fatal("ordinary header code was treated as a business failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderPayloadBusinessFailureIgnoresPendingOutput(t *testing.T) {
|
||||
if code, message, failed := providerPayloadBusinessFailure(map[string]any{
|
||||
"output": map[string]any{"task_id": "task-1", "task_status": "PENDING"},
|
||||
|
||||
@@ -129,9 +129,21 @@ func (e providerHTTPError) Error() string {
|
||||
if e.StatusCode == http.StatusBadRequest || e.StatusCode == http.StatusUnprocessableEntity {
|
||||
return providerErrorWithDetail(e.summary(), e.Body)
|
||||
}
|
||||
if message := speechResourceDeniedUserMessage(e.Body); (e.StatusCode == http.StatusUnauthorized || e.StatusCode == http.StatusForbidden) && message != "" {
|
||||
return message
|
||||
}
|
||||
return appendProviderErrorDetail(e.summary(), e.Body)
|
||||
}
|
||||
|
||||
const volcengineSpeechResourceDeniedMessage = "语音合成服务未开通,或音色与模型版本不匹配。请在火山引擎控制台开通语音合成 1.0,并确认当前音色属于这一版本"
|
||||
|
||||
func speechResourceDeniedUserMessage(raw string) string {
|
||||
if strings.Contains(strings.ToLower(raw), "requested resource not granted") {
|
||||
return volcengineSpeechResourceDeniedMessage
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (e providerHTTPError) summary() string {
|
||||
switch e.StatusCode {
|
||||
case 524:
|
||||
|
||||
@@ -263,16 +263,22 @@ func doBinaryWithConsumer(req *http.Request, onChunk func(string, []byte)) ([]by
|
||||
channelID = metadata.ChannelID
|
||||
policy, err := metadata.Service.RuntimePolicy()
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取生成资源限制失败:%w", err)
|
||||
err = fmt.Errorf("读取生成资源限制失败:%w", err)
|
||||
recordProviderRequest(req, startedAt, 0, nil, err)
|
||||
return nil, "", err
|
||||
}
|
||||
responseLimit = megabytes(policy.Resource.GeneratedFileMB)
|
||||
if !cacheManagementRequest {
|
||||
open, err := coordinator.CircuitOpen(req.Context(), channelID)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("读取渠道熔断状态失败:%w", err)
|
||||
err = fmt.Errorf("读取渠道熔断状态失败:%w", err)
|
||||
recordProviderRequest(req, startedAt, 0, nil, err)
|
||||
return nil, "", err
|
||||
}
|
||||
if open {
|
||||
return nil, "", providerCircuitOpenError{}
|
||||
err = providerCircuitOpenError{}
|
||||
recordProviderRequest(req, startedAt, 0, nil, err)
|
||||
return nil, "", err
|
||||
}
|
||||
slotID := channelID
|
||||
if slotID == "" {
|
||||
@@ -445,6 +451,7 @@ func recordProviderRequest(req *http.Request, startedAt time.Time, statusCode in
|
||||
}
|
||||
}
|
||||
metadata.Service.EnrichAPICallLog(&callLog, responseBody)
|
||||
callLog.Error = withUserVisibleLogError(requestErr, callLog.Error)
|
||||
if err := metadata.Service.LogAPICall(callLog); err != nil {
|
||||
if !channelSlotFailure && metadata.Billing != nil {
|
||||
if uncertainErr := metadata.Billing.MarkBillingUncertain(metadata.BillingOrderID, "上游调用日志写入失败,费用状态待核对"); uncertainErr != nil {
|
||||
@@ -480,6 +487,43 @@ func providerRequestErrorDetails(err error) (string, string) {
|
||||
return "", safeProviderLogError(err)
|
||||
}
|
||||
|
||||
// withUserVisibleLogError 把画布上实际展示的失败原因写进请求日志,同时保留原始诊断。
|
||||
// 语音合成权限/音色不匹配和网络异常都会被前端改写成固定中文;只存上游原文时,后台按用户看到的文案检索不到。
|
||||
func withUserVisibleLogError(requestErr error, stored string) string {
|
||||
stored = strings.TrimSpace(stored)
|
||||
visible := userVisibleFailureLabel(requestErr, stored)
|
||||
if visible == "" || strings.Contains(stored, visible) {
|
||||
return truncateRunes(stored, 2_000)
|
||||
}
|
||||
if stored == "" {
|
||||
return visible
|
||||
}
|
||||
return truncateRunes(visible+" "+stored, 2_000)
|
||||
}
|
||||
|
||||
func userVisibleFailureLabel(requestErr error, stored string) string {
|
||||
texts := make([]string, 0, 3)
|
||||
if requestErr != nil {
|
||||
texts = append(texts, taskFailureMessage(requestErr), requestErr.Error())
|
||||
}
|
||||
if stored != "" {
|
||||
texts = append(texts, stored)
|
||||
}
|
||||
network := false
|
||||
for _, text := range texts {
|
||||
if speechResourceDeniedUserMessage(text) != "" {
|
||||
return volcengineSpeechResourceDeniedMessage
|
||||
}
|
||||
if userFacingTaskError(text) == taskErrorNetworkMessage {
|
||||
network = true
|
||||
}
|
||||
}
|
||||
if network {
|
||||
return taskErrorNetworkMessage
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func safeProviderLogError(err error) string {
|
||||
var httpErr providerHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
|
||||
@@ -66,7 +66,11 @@ func runProtocolAdapterTaskWithPolicy(ctx context.Context, input canvasGeneratio
|
||||
if streamedResult != nil {
|
||||
created = protocol.CreateResult{Status: protocol.StatusSucceeded, Result: streamedResult}
|
||||
} else {
|
||||
created, err = adapter.ParseCreate(ctx, body)
|
||||
if parser, ok := adapter.(protocol.RequestAwareCreateParser); ok {
|
||||
created, err = parser.ParseCreateWithRequest(ctx, request, body)
|
||||
} else {
|
||||
created, err = adapter.ParseCreate(ctx, body)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -46,10 +46,14 @@ func protocolRequestFromInput(input canvasGenerationInput) protocol.GenerationRe
|
||||
Watermark: parseBool(input.Config.VideoWatermark, false),
|
||||
Operation: firstNonEmpty(metadataString(input.Metadata, "videoEditOperation"), metadataString(input.Metadata, "videoOperation")),
|
||||
Extra: map[string]any{
|
||||
"videoSeconds": input.Config.VideoSeconds,
|
||||
"audioVoice": input.Config.AudioVoice,
|
||||
"audioFormat": input.Config.AudioFormat,
|
||||
"count": input.Config.Count,
|
||||
"videoSeconds": input.Config.VideoSeconds,
|
||||
"audioVoice": input.Config.AudioVoice,
|
||||
"audioFormat": input.Config.AudioFormat,
|
||||
"audioSpeed": input.Config.AudioSpeed,
|
||||
"audioInstructions": input.Config.AudioInstructions,
|
||||
"audioLanguage": input.Config.AudioLanguage,
|
||||
"audioDialect": input.Config.AudioDialect,
|
||||
"count": input.Config.Count,
|
||||
},
|
||||
}
|
||||
for _, message := range input.TextHistory {
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
@@ -19,6 +21,21 @@ type ProviderTaskQueryResult struct {
|
||||
ProviderStatus string `json:"providerStatus"`
|
||||
Recovered bool `json:"recovered"`
|
||||
BillingSettled bool `json:"billingSettled"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type ProviderTaskRecoveryItem struct {
|
||||
LogID string `json:"logId"`
|
||||
Recovered bool `json:"recovered"`
|
||||
ProviderStatus string `json:"providerStatus,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type ProviderTaskRecoveryBatchResult struct {
|
||||
Items []ProviderTaskRecoveryItem `json:"items"`
|
||||
Success int `json:"success"`
|
||||
Failed int `json:"failed"`
|
||||
Skipped int `json:"skipped"`
|
||||
}
|
||||
|
||||
func (s *Service) QueryFailedVideoTask(ctx context.Context, userID string, taskID string) (*ProviderTaskQueryResult, error) {
|
||||
@@ -29,7 +46,7 @@ func (s *Service) QueryFailedVideoTask(ctx context.Context, userID string, taskI
|
||||
return s.queryFailedVideoTask(ctx, task, strings.TrimSpace(userID))
|
||||
}
|
||||
|
||||
func (s *Service) AdminQueryFailedVideoTask(ctx context.Context, actor *model.User, logID string) (*ProviderTaskQueryResult, error) {
|
||||
func (s *Service) AdminQueryFailedVideoTask(ctx context.Context, actor *model.User, logID string, requestedProviderID string) (result *ProviderTaskQueryResult, returnErr error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -37,31 +54,262 @@ func (s *Service) AdminQueryFailedVideoTask(ctx context.Context, actor *model.Us
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var task *model.Task
|
||||
defer func() {
|
||||
metadata := map[string]any{
|
||||
"apiCallLogId": log.ID,
|
||||
"taskId": log.TaskID,
|
||||
"suppliedProviderRequestId": strings.TrimSpace(requestedProviderID),
|
||||
"providerRequestId": "",
|
||||
"providerStatus": "",
|
||||
"recovered": result != nil && result.Recovered,
|
||||
"outcome": "failed",
|
||||
"error": errorString(returnErr),
|
||||
}
|
||||
if task != nil {
|
||||
metadata["providerRequestId"] = task.ProviderRequestID
|
||||
}
|
||||
if result != nil {
|
||||
metadata["providerStatus"] = result.ProviderStatus
|
||||
if result.Recovered {
|
||||
metadata["outcome"] = "recovered"
|
||||
} else {
|
||||
metadata["outcome"] = "provider_processing"
|
||||
}
|
||||
}
|
||||
_ = s.appendAdminAudit(actor, "api_log.query_provider_task", "api_call_log", log.ID, "人工查询失败视频任务", metadata)
|
||||
}()
|
||||
if log.Capability != "video" || strings.TrimSpace(log.TaskID) == "" {
|
||||
return nil, BadAuthRequest("该请求没有可查询的视频任务")
|
||||
}
|
||||
task, err := s.repo.Task(log.TaskID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
task, returnErr = s.repo.Task(log.TaskID)
|
||||
if returnErr != nil {
|
||||
return nil, returnErr
|
||||
}
|
||||
if task.UserID != log.UserID {
|
||||
return nil, BadAuthRequest("请求与任务归属不一致")
|
||||
}
|
||||
if task.Status == model.TaskStatusSucceeded {
|
||||
result = &ProviderTaskQueryResult{Task: taskForOutput(*task), ProviderStatus: "succeeded", Recovered: true, BillingSettled: s.billingSettled(task)}
|
||||
return result, nil
|
||||
}
|
||||
if strings.TrimSpace(requestedProviderID) != "" {
|
||||
task.ProviderRequestID = strings.TrimSpace(requestedProviderID)
|
||||
}
|
||||
if task.ProviderRequestID == "" {
|
||||
task.ProviderRequestID = strings.TrimSpace(log.ProviderRequestID)
|
||||
}
|
||||
result, err := s.queryFailedVideoTask(ctx, task, "")
|
||||
result, returnErr = s.queryFailedVideoTask(ctx, task, "")
|
||||
return result, returnErr
|
||||
}
|
||||
|
||||
func (s *Service) AdminRecoverVideoByURL(ctx context.Context, actor *model.User, logID string, rawURL string, providerRequestID string) (result *ProviderTaskQueryResult, returnErr error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log, task, err := s.adminRecoveryTask(logID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.appendAdminAudit(actor, "api_log.query_provider_task", "task", task.ID, "人工查询失败视频任务", map[string]any{
|
||||
"apiCallLogId": log.ID, "providerRequestId": task.ProviderRequestID, "providerStatus": result.ProviderStatus, "recovered": result.Recovered,
|
||||
}); err != nil {
|
||||
parsedURL := ""
|
||||
defer func() {
|
||||
metadata := map[string]any{
|
||||
"apiCallLogId": log.ID,
|
||||
"taskId": task.ID,
|
||||
"suppliedProviderRequestId": strings.TrimSpace(providerRequestID),
|
||||
"providerRequestId": task.ProviderRequestID,
|
||||
"url": parsedURL,
|
||||
"recovered": result != nil && result.Recovered,
|
||||
"outcome": "failed",
|
||||
"error": errorString(returnErr),
|
||||
}
|
||||
if result != nil {
|
||||
metadata["providerStatus"] = result.ProviderStatus
|
||||
if result.Recovered {
|
||||
metadata["outcome"] = "recovered"
|
||||
}
|
||||
}
|
||||
_ = s.appendAdminAudit(actor, "api_log.recover_video_url", "api_call_log", log.ID, "人工转存上游视频并回写", metadata)
|
||||
}()
|
||||
if task.Status == model.TaskStatusSucceeded {
|
||||
result = &ProviderTaskQueryResult{Task: taskForOutput(*task), ProviderStatus: "succeeded", Recovered: true, BillingSettled: s.billingSettled(task)}
|
||||
return result, nil
|
||||
}
|
||||
if task.Status != model.TaskStatusFailed {
|
||||
return nil, BadAuthRequest("只能恢复失败的视频任务")
|
||||
}
|
||||
if strings.TrimSpace(providerRequestID) != "" {
|
||||
task.ProviderRequestID = strings.TrimSpace(providerRequestID)
|
||||
}
|
||||
if task.ProviderRequestID == "" {
|
||||
task.ProviderRequestID = strings.TrimSpace(log.ProviderRequestID)
|
||||
}
|
||||
parsed, err := url.Parse(strings.TrimSpace(rawURL))
|
||||
if err != nil || parsed.Hostname() == "" || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return nil, BadAuthRequest("视频 URL 只支持有效的 http/https 地址")
|
||||
}
|
||||
parsedURL = recoveryURLForAudit(parsed)
|
||||
owner := "manual-recovery:" + newID()
|
||||
if err := s.repo.ClaimFailedTaskProviderRecovery(task.ID, "", owner, providerTaskRecoveryLeaseDuration); err != nil {
|
||||
if errors.Is(err, repository.ErrTaskProviderRecoveryConflict) {
|
||||
return nil, &AuthError{Status: 409, Message: "该任务正在恢复中,请稍后再试"}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
task.LeaseOwner = owner
|
||||
defer func() { _ = s.repo.ReleaseTaskProviderRecovery(task.ID, owner) }()
|
||||
policy, err := s.RuntimePolicy()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
payload, err := downloadRemoteResource(parsed.String(), megabytes(policy.Resource.GeneratedFileMB)+1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !strings.HasPrefix(strings.ToLower(payload.mimeType), "video/") {
|
||||
return nil, BadAuthRequest("上游地址返回的不是视频文件")
|
||||
}
|
||||
resultPayload := map[string]interface{}{"mode": "video", "video": map[string]interface{}{"dataUrl": dataURL(payload.mimeType, payload.data), "mimeType": payload.mimeType}}
|
||||
resultPayload, err = s.persistGeneratedMediaResult(task.UserID, resultPayload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resultJSON, err := json.Marshal(resultPayload)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
task.Error = ""
|
||||
task.PollStage = "succeeded"
|
||||
task.NextPollAt = nil
|
||||
if err := s.saveTaskCompletionWithinStorageQuota(task, resultJSON, nil, false); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.settleRecoveredBilling(task, task.ProviderRequestID); err != nil {
|
||||
uncertainErr := s.taskBilling().MarkBillingUncertain(task.BillingOrderID, "人工转存视频已成功,但积分结算失败:"+err.Error())
|
||||
if uncertainErr != nil {
|
||||
return nil, errors.Join(err, uncertainErr)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
if err := s.RegisterTaskOutputFromTask(*task); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = &ProviderTaskQueryResult{Task: taskForOutput(*task), ProviderStatus: "succeeded", Recovered: true, BillingSettled: true}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) AdminBatchQueryFailedVideoTasks(ctx context.Context, actor *model.User, logIDs []string) (*ProviderTaskRecoveryBatchResult, error) {
|
||||
if err := s.RequireAdmin(actor); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids := uniqueNonEmpty(logIDs)
|
||||
result := &ProviderTaskRecoveryBatchResult{Items: make([]ProviderTaskRecoveryItem, len(ids))}
|
||||
sem := make(chan struct{}, 4)
|
||||
var wg sync.WaitGroup
|
||||
for index, id := range ids {
|
||||
index, id := index, id
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
sem <- struct{}{}
|
||||
defer func() { <-sem }()
|
||||
item := ProviderTaskRecoveryItem{LogID: id}
|
||||
log, logErr := s.repo.APICallLog(id)
|
||||
if logErr != nil {
|
||||
item.Error = logErr.Error()
|
||||
_ = s.appendAdminAudit(actor, "api_log.query_provider_task", "api_call_log", id, "批量查询视频任务失败", map[string]any{"apiCallLogId": id, "outcome": "failed", "error": item.Error})
|
||||
result.Items[index] = item
|
||||
return
|
||||
}
|
||||
if log.Capability != "video" {
|
||||
item.Error = "跳过:不是视频请求明细"
|
||||
_ = s.appendAdminAudit(actor, "api_log.query_provider_task", "api_call_log", id, "批量查询跳过非视频请求", map[string]any{"apiCallLogId": id, "outcome": "skipped", "error": item.Error})
|
||||
result.Items[index] = item
|
||||
return
|
||||
}
|
||||
queryResult, queryErr := s.AdminQueryFailedVideoTask(ctx, actor, id, "")
|
||||
if queryErr != nil {
|
||||
item.Error = queryErr.Error()
|
||||
} else {
|
||||
item.Recovered, item.ProviderStatus = queryResult.Recovered, queryResult.ProviderStatus
|
||||
}
|
||||
result.Items[index] = item
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
for _, item := range result.Items {
|
||||
if strings.HasPrefix(item.Error, "跳过:") {
|
||||
result.Skipped++
|
||||
} else if item.Error != "" || !item.Recovered {
|
||||
result.Failed++
|
||||
} else {
|
||||
result.Success++
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (s *Service) adminRecoveryTask(logID string) (*model.ApiCallLog, *model.Task, error) {
|
||||
log, err := s.repo.APICallLog(strings.TrimSpace(logID))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if log.Capability != "video" || strings.TrimSpace(log.TaskID) == "" {
|
||||
return nil, nil, BadAuthRequest("该请求没有可恢复的视频任务")
|
||||
}
|
||||
task, err := s.repo.Task(log.TaskID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if task.UserID != log.UserID {
|
||||
return nil, nil, BadAuthRequest("请求与任务归属不一致")
|
||||
}
|
||||
return log, task, nil
|
||||
}
|
||||
|
||||
func (s *Service) billingSettled(task *model.Task) bool {
|
||||
if task == nil || task.BillingOrderID == "" {
|
||||
return true
|
||||
}
|
||||
order, err := s.repo.BillingOrder(task.BillingOrderID)
|
||||
return err == nil && order.Status == model.BillingStatusSettled
|
||||
}
|
||||
|
||||
func (s *Service) settleRecoveredBilling(task *model.Task, providerRequestID string) error {
|
||||
if task == nil || task.BillingOrderID == "" {
|
||||
return nil
|
||||
}
|
||||
billing := s.taskBilling()
|
||||
order, err := billing.BillingOrder(task.BillingOrderID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if order == nil {
|
||||
return fmt.Errorf("任务计费订单不存在:%s", task.BillingOrderID)
|
||||
}
|
||||
if order.Status == model.BillingStatusSettled {
|
||||
return nil
|
||||
}
|
||||
if order.Status == model.BillingStatusRefunded {
|
||||
return billing.RestoreRefundedBilling(task.BillingOrderID, providerRequestID)
|
||||
}
|
||||
return billing.SettleBilling(task.BillingOrderID, providerRequestID)
|
||||
}
|
||||
|
||||
func errorString(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
return err.Error()
|
||||
}
|
||||
|
||||
func recoveryURLForAudit(value *url.URL) string {
|
||||
if value == nil {
|
||||
return ""
|
||||
}
|
||||
return value.Scheme + "://" + value.Host + value.Path
|
||||
}
|
||||
|
||||
func (s *Service) queryFailedVideoTask(ctx context.Context, task *model.Task, claimUserID string) (*ProviderTaskQueryResult, error) {
|
||||
billing := s.taskBilling()
|
||||
ctx = withProtocolRegistry(ctx, s.protocolRegistry())
|
||||
@@ -83,7 +331,6 @@ func (s *Service) queryFailedVideoTask(ctx context.Context, task *model.Task, cl
|
||||
if providerRequestID == "" {
|
||||
return nil, BadAuthRequest("该任务没有可恢复的上游任务 ID")
|
||||
}
|
||||
wasRefunded := false
|
||||
if task.BillingOrderID != "" {
|
||||
order, err := s.repo.BillingOrder(task.BillingOrderID)
|
||||
if err != nil {
|
||||
@@ -92,7 +339,6 @@ func (s *Service) queryFailedVideoTask(ctx context.Context, task *model.Task, cl
|
||||
if order.UserID != task.UserID || order.TaskID != task.ID {
|
||||
return nil, BadAuthRequest("任务与计费订单归属不一致")
|
||||
}
|
||||
wasRefunded = order.Status == model.BillingStatusRefunded
|
||||
}
|
||||
|
||||
decryptedInput, err := s.decryptTaskInputJSON(task.InputJSON)
|
||||
@@ -115,9 +361,6 @@ func (s *Service) queryFailedVideoTask(ctx context.Context, task *model.Task, cl
|
||||
input.Config = config
|
||||
task.InputJSON = decryptedInput
|
||||
task.ProviderRequestID = providerRequestID
|
||||
if err := s.repo.UpdateTaskProviderState(task.ID, providerRequestID, task.PollStage, task.NextPollAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
owner := "manual-recovery:" + newID()
|
||||
if err := s.repo.ClaimFailedTaskProviderRecovery(task.ID, claimUserID, owner, providerTaskRecoveryLeaseDuration); err != nil {
|
||||
@@ -173,11 +416,7 @@ func (s *Service) queryFailedVideoTask(ctx context.Context, task *model.Task, cl
|
||||
}
|
||||
billingSettled := true
|
||||
var billingErr error
|
||||
if wasRefunded {
|
||||
billingErr = billing.RestoreRefundedBilling(task.BillingOrderID, providerRequestID)
|
||||
} else {
|
||||
billingErr = billing.SettleBilling(task.BillingOrderID, providerRequestID)
|
||||
}
|
||||
billingErr = s.settleRecoveredBilling(task, providerRequestID)
|
||||
if billingErr != nil {
|
||||
billingSettled = false
|
||||
uncertainErr := billing.MarkBillingUncertain(task.BillingOrderID, "人工查询确认生成成功,但积分结算失败:"+billingErr.Error())
|
||||
|
||||
@@ -3,7 +3,12 @@ package app
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestProviderTaskRecoveryContextSurvivesClientCancellation(t *testing.T) {
|
||||
@@ -24,6 +29,96 @@ func TestProviderTaskRecoveryContextSurvivesClientCancellation(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSettleRecoveredBillingIsIdempotent(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status model.BillingStatus
|
||||
wantSettle int
|
||||
wantRestore int
|
||||
}{
|
||||
{name: "settled", status: model.BillingStatusSettled},
|
||||
{name: "running", status: model.BillingStatusRunning, wantSettle: 1},
|
||||
{name: "refunded", status: model.BillingStatusRefunded, wantRestore: 1},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
repo := &taskBillingRepositoryStub{order: &model.BillingOrder{Status: tt.status}}
|
||||
svc := &Service{taskBillingCoordinator: newTaskBillingCoordinator(repo)}
|
||||
if err := svc.settleRecoveredBilling(&model.Task{BillingOrderID: "order-1"}, "provider-1"); err != nil {
|
||||
t.Fatalf("settleRecoveredBilling() error = %v", err)
|
||||
}
|
||||
if got := len(repo.settleCalls); got != tt.wantSettle {
|
||||
t.Fatalf("settle calls = %d, want %d", got, tt.wantSettle)
|
||||
}
|
||||
if got := len(repo.restoreCalls); got != tt.wantRestore {
|
||||
t.Fatalf("restore calls = %d, want %d", got, tt.wantRestore)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDownloadRemoteResourceEnforcesVideoImportBounds(t *testing.T) {
|
||||
t.Setenv("CANVAS_ALLOW_PRIVATE_UPSTREAMS", "true")
|
||||
t.Setenv("HTTP_PROXY", "")
|
||||
t.Setenv("HTTPS_PROXY", "")
|
||||
t.Setenv("ALL_PROXY", "")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/large" {
|
||||
w.Header().Set("Content-Type", "video/mp4")
|
||||
_, _ = w.Write([]byte("12345"))
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "video/mp4; charset=binary")
|
||||
_, _ = w.Write([]byte("video"))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
payload, err := downloadRemoteResource(server.URL+"/video.mp4", 16)
|
||||
if err != nil {
|
||||
t.Fatalf("downloadRemoteResource() error = %v", err)
|
||||
}
|
||||
if payload.mimeType != "video/mp4" || string(payload.data) != "video" {
|
||||
t.Fatalf("payload = %#v, want video/mp4 body", payload)
|
||||
}
|
||||
if _, err := downloadRemoteResource(server.URL+"/large", 5); err == nil || !strings.Contains(err.Error(), "远程资源必须小于") {
|
||||
t.Fatalf("oversized download error = %v", err)
|
||||
}
|
||||
if _, err := downloadRemoteResource("file:///tmp/video.mp4", 16); err == nil {
|
||||
t.Fatal("downloadRemoteResource() accepted a non-http URL")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdminVideoRecoveryRequiresAdmin(t *testing.T) {
|
||||
service := &Service{}
|
||||
methods := map[string]func(*model.User) error{
|
||||
"query": func(actor *model.User) error {
|
||||
_, err := service.AdminQueryFailedVideoTask(context.Background(), actor, "log-1", "provider-1")
|
||||
return err
|
||||
},
|
||||
"url": func(actor *model.User) error {
|
||||
_, err := service.AdminRecoverVideoByURL(context.Background(), actor, "log-1", "https://example.com/video.mp4", "provider-1")
|
||||
return err
|
||||
},
|
||||
"batch": func(actor *model.User) error {
|
||||
_, err := service.AdminBatchQueryFailedVideoTasks(context.Background(), actor, []string{"log-1"})
|
||||
return err
|
||||
},
|
||||
}
|
||||
actors := map[string]*model.User{
|
||||
"anonymous": nil,
|
||||
"ordinary user": {Role: model.UserRoleUser},
|
||||
}
|
||||
for actorName, actor := range actors {
|
||||
for methodName, invoke := range methods {
|
||||
t.Run(actorName+"/"+methodName, func(t *testing.T) {
|
||||
if err := invoke(actor); err == nil {
|
||||
t.Fatalf("recovery method %q accepted %s actor", methodName, actorName)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRetryableProtocolMediaDownload(t *testing.T) {
|
||||
for _, err := range []error{
|
||||
errors.New("net/http: TLS handshake timeout"),
|
||||
|
||||
@@ -968,6 +968,19 @@ func TestProviderUserFacingErrorMessageClassifiesRejectedRequestBodies(t *testin
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderUserFacingErrorMessageExplainsDoubaoResourceDenial(t *testing.T) {
|
||||
message := providerUserFacingErrorMessage(providerHTTPError{
|
||||
StatusCode: http.StatusForbidden,
|
||||
Body: `{"header":{"code":45000030,"message":"[resource_id=volc.seedtts.default] requested resource not granted"}}`,
|
||||
})
|
||||
if !strings.Contains(message, "语音合成服务未开通") {
|
||||
t.Fatalf("providerUserFacingErrorMessage() = %q", message)
|
||||
}
|
||||
if strings.Contains(message, "API Key") {
|
||||
t.Fatalf("resource denial was reported as an API key failure: %q", message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProviderUserFacingErrorMessageOnlyClassifiesValidationStatuses(t *testing.T) {
|
||||
// 鉴权失败与网关错误的正文可能是密钥诊断或代理 HTML,不参与归类。
|
||||
for _, statusCode := range []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, http.StatusBadGateway} {
|
||||
|
||||
@@ -17,12 +17,14 @@ func (s *Service) ensureFailedProviderAttemptLogged(task model.Task, taskErr err
|
||||
if s == nil || s.repo == nil || strings.TrimSpace(task.ID) == "" || taskErr == nil {
|
||||
return
|
||||
}
|
||||
hasLog, err := s.repo.HasAPICallLogForTask(task.ID)
|
||||
hasVisibleFailure, err := s.repo.HasVisibleFailedAPICallLogForTask(task.ID)
|
||||
if err != nil {
|
||||
log.Printf("provider attempt log lookup failed: task_id=%s error=%v", task.ID, err)
|
||||
return
|
||||
}
|
||||
if hasLog {
|
||||
// 已有一条管理端默认可看到的失败日志时不再补写。只存在成功日志或被列表隐藏的轮询/下载日志时,
|
||||
// 用户看到的失败原因仍然不在请求明细里,需要补一条失败记录。
|
||||
if hasVisibleFailure {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -83,7 +85,7 @@ func (s *Service) ensureFailedProviderAttemptLogged(task model.Task, taskErr err
|
||||
DurationMs: now.Sub(startedAt).Milliseconds(),
|
||||
ProviderRequestID: metadata.ProviderRequestID,
|
||||
ErrorCode: errorCode,
|
||||
Error: truncateRunes(s.UserFacingErrorMessage(taskErr), 2_000),
|
||||
Error: truncateRunes(withUserVisibleLogError(taskErr, s.UserFacingErrorMessage(taskErr)), 2_000),
|
||||
StartedAt: startedAt,
|
||||
CreatedAt: now,
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -132,3 +134,82 @@ func TestEnsureFailedProviderAttemptLoggedDoesNotDuplicateHTTPLog(t *testing.T)
|
||||
t.Fatalf("api call log count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRecordProviderRequestKeepsUserVisibleSpeechAndNetworkErrors(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:provider-visible-error-log?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.SystemSetting{}, &model.Asset{}, &model.CanvasProject{}, &model.Task{}, &model.TaskLog{}, &model.Result{}, &model.ApiCallLog{}, &model.TaskTextDelta{}, &model.ModelPricing{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := &Service{repo: repository.New(db)}
|
||||
speechBody := []byte(`{"code":0,"data":"AAAA"}{"header":{"code":45000030,"message":"[resource_id=volc.seedtts.default] requested resource not granted"}}`)
|
||||
recordLoggedProviderRequest(t, service, "task-speech", http.StatusOK, speechBody, nil)
|
||||
recordLoggedProviderRequest(t, service, "task-network", 0, nil, errors.New(`dial tcp 10.0.0.1:443: connect: connection refused`))
|
||||
recordLoggedProviderRequest(t, service, "task-gateway", http.StatusBadGateway, []byte(`<html>Bad Gateway</html>`), providerHTTPError{StatusCode: http.StatusBadGateway, Status: "502 Bad Gateway", Body: "<html>Bad Gateway</html>"})
|
||||
|
||||
assertLoggedTaskError(t, db, "task-speech", "语音合成服务未开通")
|
||||
assertLoggedTaskError(t, db, "task-network", "网络异常。", "connection refused")
|
||||
assertLoggedTaskError(t, db, "task-gateway", "网络异常。", "502")
|
||||
}
|
||||
|
||||
func assertLoggedTaskError(t *testing.T, db *gorm.DB, taskID string, parts ...string) {
|
||||
t.Helper()
|
||||
var log model.ApiCallLog
|
||||
if err := db.Where("task_id = ?", taskID).First(&log).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if log.Status != model.ApiCallStatusFailed {
|
||||
t.Fatalf("%s status = %q, want failed; error %q", taskID, log.Status, log.Error)
|
||||
}
|
||||
for _, part := range parts {
|
||||
if !strings.Contains(log.Error, part) {
|
||||
t.Fatalf("%s error %q does not contain %q", taskID, log.Error, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureFailedProviderAttemptLoggedRecordsFailureHiddenBySuccessLog(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open("file:provider-success-hides-failure?mode=memory&cache=shared"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.SystemSetting{}, &model.Asset{}, &model.CanvasProject{}, &model.Task{}, &model.TaskLog{}, &model.Result{}, &model.ApiCallLog{}, &model.TaskTextDelta{}, &model.ModelPricing{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
success := model.ApiCallLog{ID: "api-log-success", TaskID: "task-1", Status: model.ApiCallStatusSucceeded, RequestKind: "create"}
|
||||
hidden := model.ApiCallLog{ID: "api-log-poll", TaskID: "task-1", Status: model.ApiCallStatusFailed, RequestKind: "poll", Error: "poll failed"}
|
||||
if err := db.Create(&success).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&hidden).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := &Service{repo: repository.New(db)}
|
||||
service.ensureFailedProviderAttemptLogged(model.Task{ID: "task-1", UserID: "user-1", Type: "canvas_audio", Model: "seed-tts-2.0"}, errors.New("流式音频合成失败(code 45000030):[resource_id=volc.seedtts.default] requested resource not granted"))
|
||||
service.ensureFailedProviderAttemptLogged(model.Task{ID: "task-1", UserID: "user-1", Type: "canvas_audio", Model: "seed-tts-2.0"}, errors.New("流式音频合成失败(code 45000030):[resource_id=volc.seedtts.default] requested resource not granted"))
|
||||
|
||||
var logs []model.ApiCallLog
|
||||
if err := db.Where("request_kind <> ?", "poll").Order("created_at asc").Find(&logs).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(logs) != 2 {
|
||||
t.Fatalf("visible log count = %d, want success plus one failure", len(logs))
|
||||
}
|
||||
if logs[1].Status != model.ApiCallStatusFailed || !strings.Contains(logs[1].Error, "语音合成服务未开通") {
|
||||
t.Fatalf("visible failure = status %q error %q", logs[1].Status, logs[1].Error)
|
||||
}
|
||||
}
|
||||
|
||||
func recordLoggedProviderRequest(t *testing.T, service *Service, taskID string, statusCode int, body []byte, requestErr error) {
|
||||
t.Helper()
|
||||
request, err := http.NewRequest(http.MethodPost, "https://openspeech.bytedance.com/api/v3/tts/unidirectional", strings.NewReader(`{"text":"你好"}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request = request.WithContext(context.WithValue(request.Context(), providerAnalyticsKey{}, providerAnalyticsContext{
|
||||
Service: service, UserID: "user-1", TaskID: taskID, ChannelID: "channel-1", Capability: "audio", Model: "seed-tts-2.0", RequestKind: "create",
|
||||
}))
|
||||
recordProviderRequest(request, time.Now(), statusCode, body, requestErr)
|
||||
}
|
||||
@@ -50,6 +50,25 @@ func (c *taskBillingCoordinator) SettleBilling(orderID string, providerRequestID
|
||||
return c.repo.SettleBillingOrder(orderID, providerRequestID)
|
||||
}
|
||||
|
||||
func (c *taskBillingCoordinator) BillingOrder(orderID string) (*model.BillingOrder, error) {
|
||||
if orderID == "" {
|
||||
return nil, nil
|
||||
}
|
||||
return c.repo.BillingOrder(orderID)
|
||||
}
|
||||
|
||||
func (c *taskBillingCoordinator) SettleBillingWithAudioDuration(orderID string, providerRequestID string, durationMs int64) error {
|
||||
if orderID == "" {
|
||||
return nil
|
||||
}
|
||||
if repo, ok := c.repo.(interface {
|
||||
SettleBillingOrderWithAudioDuration(string, string, int64) error
|
||||
}); ok {
|
||||
return repo.SettleBillingOrderWithAudioDuration(orderID, providerRequestID, durationMs)
|
||||
}
|
||||
return c.repo.SettleBillingOrder(orderID, providerRequestID)
|
||||
}
|
||||
|
||||
func (c *taskBillingCoordinator) RestoreRefundedBilling(orderID string, providerRequestID string) error {
|
||||
if orderID == "" {
|
||||
return nil
|
||||
|
||||
@@ -40,6 +40,27 @@ func (s *Service) mediaTaskProject(task *model.Task) (string, error) {
|
||||
return project.ID, nil
|
||||
}
|
||||
|
||||
// AudioOutputDurationMs returns the measured duration of the first persisted
|
||||
// audio output. A missing or unmeasured duration is returned as an error so
|
||||
// per-second billing can enter review instead of silently undercharging.
|
||||
func (s *Service) AudioOutputDurationMs(task model.Task) (int64, error) {
|
||||
if capabilityFromTaskType(task.Type) != "audio" {
|
||||
return 0, nil
|
||||
}
|
||||
resourceID, _ := taskOutputResource(task.ResultJSON, task.Type)
|
||||
if resourceID == "" {
|
||||
return 0, errors.New("音频结果缺少已保存的资源")
|
||||
}
|
||||
resource, err := s.repo.ResourceForUser(task.UserID, resourceID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if resource.DurationMs <= 0 {
|
||||
return 0, errors.New("音频结果缺少有效时长")
|
||||
}
|
||||
return resource.DurationMs, nil
|
||||
}
|
||||
|
||||
// Uses the same effect key and ID as browser materialization, so reconnecting
|
||||
// the canvas cannot create a second asset for a server-delivered output.
|
||||
func (s *Service) registerRecoveredMediaAssets(task model.Task) error {
|
||||
|
||||
@@ -8,9 +8,12 @@ import (
|
||||
"fmt"
|
||||
"image"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -215,6 +218,7 @@ func (s *Service) storeTaskMediaFile(task *model.Task, index int, path, mimeType
|
||||
return nil, errors.New("暂存作品不是普通文件")
|
||||
}
|
||||
width, height := 0, 0
|
||||
durationMs := int64(0)
|
||||
if kind == "image" {
|
||||
config, _, err := image.DecodeConfig(file)
|
||||
if err != nil {
|
||||
@@ -233,6 +237,11 @@ func (s *Service) storeTaskMediaFile(task *model.Task, index int, path, mimeType
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else if kind == "audio" {
|
||||
// Audio duration is the source of truth for per-second settlement. The
|
||||
// media can still be saved when ffprobe is unavailable; settlement then
|
||||
// moves the order to review instead of silently charging a fake length.
|
||||
durationMs = probeMediaDurationMs(path)
|
||||
}
|
||||
day, err := s.reserveGeneratedResourceQuota(task.UserID, info.Size())
|
||||
if err != nil {
|
||||
@@ -246,13 +255,14 @@ func (s *Service) storeTaskMediaFile(task *model.Task, index int, path, mimeType
|
||||
}()
|
||||
var resource *model.Resource
|
||||
if existing == nil {
|
||||
resource, _, err = s.storeResourceWithWriter(task.UserID, kind, "generated."+extensionFromMimeType(mimeType), mimeType, info.Size(), width, height, 0, file, mediaUploadKey(task.ID, index), false, s.storeTaskMediaObject)
|
||||
resource, _, err = s.storeResourceWithWriter(task.UserID, kind, "generated."+extensionFromMimeType(mimeType), mimeType, info.Size(), width, height, durationMs, file, mediaUploadKey(task.ID, index), false, s.storeTaskMediaObject)
|
||||
} else {
|
||||
// Reuse the same object key after a failed upload; no orphan per retry.
|
||||
resource = existing
|
||||
if resource.UserID != task.UserID || resource.Size != info.Size() || resource.MimeType != mimeType {
|
||||
return nil, errors.New("恢复文件与原始资源不一致")
|
||||
}
|
||||
resource.DurationMs = durationMs
|
||||
resource.ETag, err = s.storeTaskMediaObject(resource, "generated."+extensionFromMimeType(mimeType), file)
|
||||
if err == nil {
|
||||
resource.Status, resource.Error, resource.UpdatedAt = model.ResourceStatusReady, "", time.Now()
|
||||
@@ -271,6 +281,24 @@ func (s *Service) storeTaskMediaFile(task *model.Task, index int, path, mimeType
|
||||
return resource, nil
|
||||
}
|
||||
|
||||
func probeMediaDurationMs(path string) int64 {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return 0
|
||||
}
|
||||
if _, err := exec.LookPath("ffprobe"); err != nil {
|
||||
return 0
|
||||
}
|
||||
output, err := exec.Command("ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", path).Output()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
seconds, err := strconv.ParseFloat(strings.TrimSpace(string(output)), 64)
|
||||
if err != nil || seconds <= 0 || math.IsNaN(seconds) || math.IsInf(seconds, 0) {
|
||||
return 0
|
||||
}
|
||||
return int64(math.Ceil(seconds * 1000))
|
||||
}
|
||||
|
||||
// Unlike ordinary uploads, generated output preserves an OSS failure for
|
||||
// explicit recovery instead of silently changing the storage destination.
|
||||
func (s *Service) storeTaskMediaObject(resource *model.Resource, _ string, body io.Reader) (string, error) {
|
||||
|
||||
@@ -48,6 +48,18 @@ type taskOutputLifecycle interface {
|
||||
RegisterTaskOutputFromTask(task model.Task) error
|
||||
}
|
||||
|
||||
type audioDurationTaskBilling interface {
|
||||
SettleBillingWithAudioDuration(orderID string, providerRequestID string, durationMs int64) error
|
||||
}
|
||||
|
||||
type billingOrderReader interface {
|
||||
BillingOrder(orderID string) (*model.BillingOrder, error)
|
||||
}
|
||||
|
||||
type audioDurationTaskOutput interface {
|
||||
AudioOutputDurationMs(task model.Task) (int64, error)
|
||||
}
|
||||
|
||||
func newTaskTerminalCoordinator(s *Service) *taskTerminalCoordinator {
|
||||
return &taskTerminalCoordinator{
|
||||
repo: s.repo,
|
||||
@@ -225,7 +237,36 @@ func (c *taskTerminalCoordinator) handleSuccess(task *model.Task) error {
|
||||
completionErr = fmt.Errorf("任务成功后的项目产物登记失败:%w", registerErr)
|
||||
}
|
||||
}
|
||||
if err := c.billing.SettleBilling(task.BillingOrderID, ""); err != nil {
|
||||
settleBilling := func() error {
|
||||
if audioBilling, ok := c.billing.(audioDurationTaskBilling); ok && capabilityFromTaskType(task.Type) == "audio" {
|
||||
orderReader, readerOK := c.billing.(billingOrderReader)
|
||||
if readerOK {
|
||||
order, err := orderReader.BillingOrder(task.BillingOrderID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Only audio orders priced per second need measured output duration.
|
||||
// Fixed-request audio must retain the ordinary settlement path even
|
||||
// when the stored resource has no duration metadata.
|
||||
if order == nil || order.Capability != "audio" || order.BillingMode != "per_second" {
|
||||
return c.billing.SettleBilling(task.BillingOrderID, "")
|
||||
}
|
||||
}
|
||||
output, outputOK := c.outputs.(audioDurationTaskOutput)
|
||||
if outputOK {
|
||||
if completedTask == nil {
|
||||
return errors.New("任务成功后无法读取音频产物")
|
||||
}
|
||||
durationMs, err := output.AudioOutputDurationMs(*completedTask)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return audioBilling.SettleBillingWithAudioDuration(task.BillingOrderID, "", durationMs)
|
||||
}
|
||||
}
|
||||
return c.billing.SettleBilling(task.BillingOrderID, "")
|
||||
}
|
||||
if err := settleBilling(); err != nil {
|
||||
uncertainErr := c.billing.MarkBillingUncertain(task.BillingOrderID, "生成成功但积分结算失败:"+err.Error())
|
||||
_ = c.logger.log(task.UserID, task.ID, "error", "积分结算失败,已进入待核对", err.Error())
|
||||
completionErr = errors.Join(completionErr, fmt.Errorf("积分结算失败:%w", err))
|
||||
|
||||
@@ -317,7 +317,11 @@ func taskFailureMessage(err error) string {
|
||||
if err == nil {
|
||||
return "任务处理失败"
|
||||
}
|
||||
return truncateRunes(err.Error(), 2_000)
|
||||
message := err.Error()
|
||||
if denied := speechResourceDeniedUserMessage(message); denied != "" {
|
||||
return denied
|
||||
}
|
||||
return truncateRunes(message, 2_000)
|
||||
}
|
||||
|
||||
// taskLeaseRenewContext 给续租单独一份"不继承父 context 取消/时限"的上下文(仅 5 秒上限)。
|
||||
|
||||
Reference in new issue
Block a user