feat(agent): Agent 生成审批 - 支持改模型参数、忽略位置漂移并取消 8 轮硬限制
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
f394cd7385
commit
fc5548836f
21 files changed
+930
-66
No files matched your search
@@ -373,9 +373,6 @@ func (s *Service) CreateCloudAgentRun(userID string, req CloudAgentRequest, pare
|
||||
history = append(history, providerTextMessage{Role: "user", Content: parent.Prompt}, providerTextMessage{Role: "assistant", Content: text})
|
||||
}
|
||||
// Bound prompt growth without silently injecting a huge canvas or transcript.
|
||||
if len(history) > 16 {
|
||||
return nil, BadAuthRequest("对话已达到 8 轮上下文上限,请新建对话")
|
||||
}
|
||||
encodedHistory, err := json.Marshal(history)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
func TestCloudAgentMediaReadHashSurvivesMoveBeforeDraft(t *testing.T) {
|
||||
s, db, args := agentMediaFixture(t)
|
||||
canvas, _ := s.repo.CanvasProjectForUser("user", "agent-canvas")
|
||||
doc, _ := creationDocument(canvas.PayloadJSON)
|
||||
view, err := cloudAgentCanvasState(s.repo, "user", doc, 0, nil, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
args.SnapshotHash = view.(map[string]any)["mediaSnapshotHash"].(string)
|
||||
nodes, _ := creationObjects(doc["nodes"])
|
||||
nodes["cat"]["position"] = map[string]any{"x": 1600, "y": 500}
|
||||
raw, _ := json.Marshal(doc)
|
||||
if err := db.Model(canvas).Update("payload_json", string(raw)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ := agentMediaRun(t, s, args, "auto")
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, err := s.CloudAgentRun("user", run.ID)
|
||||
if err != nil || pending.Status != "waiting_approval" {
|
||||
t.Fatalf("movement prevented draft creation: %v %+v", err, pending)
|
||||
}
|
||||
approveAgentMediaDraft(t, s, run.ID)
|
||||
}
|
||||
|
||||
func TestCloudAgentMediaApprovalAllowsMovesButRejectsContentChanges(t *testing.T) {
|
||||
for _, change := range []string{"move", "prompt", "resource", "connection", "locked"} {
|
||||
t.Run(change, func(t *testing.T) {
|
||||
s, db, a := agentMediaFixture(t)
|
||||
run, _ := agentMediaRun(t, s, a, "auto")
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ = s.repo.CloudAgent("user", run.ID)
|
||||
state, err := cloudAgentDecode(run)
|
||||
if err != nil || state.Approval == nil {
|
||||
t.Fatalf("missing approval: %v", err)
|
||||
}
|
||||
canvas, _ := s.repo.CanvasProjectForUser("user", "agent-canvas")
|
||||
doc, _ := creationDocument(canvas.PayloadJSON)
|
||||
nodes, _ := creationObjects(doc["nodes"])
|
||||
fullHash := cloudAgentCanvasHash(doc)
|
||||
switch change {
|
||||
case "move":
|
||||
nodes["cat"]["position"] = map[string]any{"x": 1234, "y": 567}
|
||||
nodes[a.NodeID]["position"] = map[string]any{"x": 2000, "y": 900}
|
||||
case "prompt":
|
||||
nodes[a.NodeID]["metadata"].(map[string]any)["composerContent"] = "用户修改的提示词"
|
||||
case "resource":
|
||||
nodes["cat"]["metadata"].(map[string]any)["storageKey"] = "resource:ref-two"
|
||||
case "connection":
|
||||
doc["connections"] = []any{}
|
||||
case "locked":
|
||||
nodes[a.NodeID]["metadata"].(map[string]any)["locked"] = true
|
||||
}
|
||||
if fullHash == cloudAgentCanvasHash(doc) {
|
||||
t.Fatal("full mutation/undo hash must still detect changes")
|
||||
}
|
||||
raw, _ := json.Marshal(doc)
|
||||
if err := db.Model(canvas).Update("payload_json", string(raw)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.DecideCloudAgentApproval("user", run.ID, state.Approval.ID, "approve", ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var count int64
|
||||
db.Model(&model.Task{}).Where("type = ?", "canvas_video").Count(&count)
|
||||
if change != "move" {
|
||||
if count != 0 {
|
||||
t.Fatal("content change submitted generation")
|
||||
}
|
||||
return
|
||||
}
|
||||
if count != 1 {
|
||||
t.Fatal("layout-only change blocked generation")
|
||||
}
|
||||
canvas, _ = s.repo.CanvasProjectForUser("user", "agent-canvas")
|
||||
doc, _ = creationDocument(canvas.PayloadJSON)
|
||||
nodes, _ = creationObjects(doc["nodes"])
|
||||
if nodes["cat"]["position"].(map[string]any)["x"] != float64(1234) || nodes[a.NodeID]["position"].(map[string]any)["x"] != float64(2000) {
|
||||
t.Fatal("generation overwrote user's positions")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudAgentImageApprovalEditsAreValidatedAndIdempotent(t *testing.T) {
|
||||
s, db, a := agentMediaFixture(t)
|
||||
capability := DefaultModelCapabilityConfigForModel(string(model.ChannelInterfaceGrokImage), "grok-image")
|
||||
for _, key := range []string{"grok-image", "grok-image-alternative"} {
|
||||
for _, row := range []any{
|
||||
&model.ChannelModel{ID: key, ChannelID: "channel", ModelKey: key, DisplayName: key, Capability: "image", Protocol: model.ChannelInterfaceGrokImage, CapabilityConfigJSON: mustEncodeModelCapabilityConfig(t, capability), BillingMode: "fixed_request", PriceConfigured: true, Enabled: true},
|
||||
&model.ChannelModelPriceTier{ID: key + "-tier", ChannelModelID: key, SelectorKey: "{}", SelectorJSON: "{}", BillingMode: "fixed_request", UnitPriceMicrocredits: 1, PriceConfigured: true, Enabled: true},
|
||||
} {
|
||||
if err := db.Create(row).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
a.Mode, a.ChannelModelKey, a.Duration, a.VideoGenerateAudio = "image", "grok-image", 0, nil
|
||||
a.Size, a.Quality, a.NodeID = "1:1", "2k", "image-shot-1"
|
||||
a.ReferenceNodeIDs = []string{"cat"}
|
||||
run, _ := agentMediaRun(t, s, a, "auto")
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ = s.repo.CloudAgent("user", run.ID)
|
||||
state, err := cloudAgentDecode(run)
|
||||
if err != nil || state.Approval == nil {
|
||||
t.Fatalf("missing approval: %v", err)
|
||||
}
|
||||
id := state.Approval.ID
|
||||
settings := CloudAgentMediaSettings{ChannelID: "channel", ChannelModelKey: "grok-image-alternative", Size: "16:9", Quality: "1k"}
|
||||
for _, invalid := range []CloudAgentMediaSettings{
|
||||
{ChannelID: "channel", ChannelModelKey: "missing", Size: "16:9", Quality: "1k"},
|
||||
{ChannelID: "channel", ChannelModelKey: "text-test", Size: "16:9", Quality: "1k"},
|
||||
{LogicalModelID: "mixed", ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "16:9"},
|
||||
{ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "invalid-size", Quality: "1k"},
|
||||
{ChannelID: "channel", ChannelModelKey: settings.ChannelModelKey, Size: "16:9", Quality: "invalid-quality"},
|
||||
} {
|
||||
if err := s.DecideCloudAgentApproval("user", run.ID, id, "approve", "", &invalid); err == nil {
|
||||
t.Fatalf("invalid settings accepted: %+v", invalid)
|
||||
}
|
||||
}
|
||||
if err := s.DecideCloudAgentApproval("other", run.ID, id, "approve", "", &settings); err == nil {
|
||||
t.Fatal("cross-user approval accepted")
|
||||
}
|
||||
pending, _ := s.CloudAgentRun("user", run.ID)
|
||||
if pending.Status != "waiting_approval" {
|
||||
t.Fatal("invalid settings consumed approval")
|
||||
}
|
||||
var before int64
|
||||
db.Model(&model.BillingOrder{}).Count(&before)
|
||||
for range 2 {
|
||||
if err := s.DecideCloudAgentApproval("user", run.ID, id, "approve", "", &settings); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var orders int64
|
||||
db.Model(&model.BillingOrder{}).Count(&orders)
|
||||
if orders != before {
|
||||
t.Fatal("editing approval charged before task submission")
|
||||
}
|
||||
changed := settings
|
||||
changed.Size = "1:1"
|
||||
if err := s.DecideCloudAgentApproval("user", run.ID, id, "approve", "", &changed); err == nil {
|
||||
t.Fatal("conflicting retry accepted")
|
||||
}
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
run, _ = s.repo.CloudAgent("user", run.ID)
|
||||
state, err = cloudAgentDecode(run)
|
||||
if err != nil || state.MediaTaskID == "" {
|
||||
t.Fatalf("edited approval did not submit: %v %+v", err, state.Events)
|
||||
}
|
||||
task, err := s.repo.TaskForUser("user", state.MediaTaskID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var input canvasGenerationInput
|
||||
if err := json.Unmarshal([]byte(task.InputJSON), &input); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if input.Config.Model != settings.ChannelModelKey || input.Config.Size != settings.Size || input.Config.Quality != settings.Quality || task.Prompt != a.Prompt || len(input.ReferenceImages) != 1 {
|
||||
t.Fatalf("approved inputs were lost: %+v", input.Config)
|
||||
}
|
||||
var count int64
|
||||
db.Model(&model.Task{}).Where("type = ?", "canvas_image").Count(&count)
|
||||
if count != 1 {
|
||||
t.Fatalf("expected exactly one image task, got %d", count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloudAgentConversationContinuesBeyondEightRounds(t *testing.T) {
|
||||
s, db, _, _ := creationTestService(t)
|
||||
if err := db.Create(&model.CanvasProject{ID: "agent-canvas", UserID: "user", PayloadJSON: `{"nodes":[]}`}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent := ""
|
||||
for round := 0; round < 11; round++ {
|
||||
req := agentTestRequest()
|
||||
req.IdempotencyKey = fmt.Sprintf("long-conversation-%d", round)
|
||||
run, err := s.CreateCloudAgentRun("user", req, parent)
|
||||
if err != nil {
|
||||
t.Fatalf("round %d failed: %v", round+1, err)
|
||||
}
|
||||
execution, _ := s.repo.CloudAgent("user", run.ID)
|
||||
state, err := cloudAgentDecode(execution)
|
||||
if err != nil || len(state.TextHistory) != round*2 {
|
||||
t.Fatalf("history was lost at round %d: %v", round, err)
|
||||
}
|
||||
if err := db.Model(&model.Task{}).Where("id = ?", run.ID).Updates(map[string]any{"status": model.TaskStatusSucceeded, "result_json": `{"text":"继续创作"}`}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.advanceCloudAgentByID("user", run.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parent = run.ID
|
||||
}
|
||||
// Removing the turn cap must not remove the existing context-size bound.
|
||||
run, _ := s.repo.CloudAgent("user", parent)
|
||||
state, _ := cloudAgentDecode(run)
|
||||
for i := range state.TextHistory {
|
||||
state.TextHistory[i].Content = strings.Repeat("x", 4000)
|
||||
}
|
||||
raw, _ := json.Marshal(state)
|
||||
if err := db.Model(run).Update("state_json", string(raw)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req := agentTestRequest()
|
||||
req.IdempotencyKey = "long-conversation-byte-bound"
|
||||
if _, err := s.CreateCloudAgentRun("user", req, parent); err == nil || !strings.Contains(err.Error(), "64KB") {
|
||||
t.Fatalf("context byte bound removed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,28 @@ func cloudAgentCanvasHash(doc map[string]any) string {
|
||||
return creationHash(content)
|
||||
}
|
||||
|
||||
// Generation does not depend on node positions. Keep the full canvas hash for
|
||||
// mutations and undo, which must still detect layout edits before restoring data.
|
||||
func cloudAgentMediaContentHash(doc map[string]any) string {
|
||||
content := make(map[string]any, len(doc))
|
||||
for key, value := range doc {
|
||||
content[key] = value
|
||||
}
|
||||
nodes := creationMaps(doc["nodes"])
|
||||
projected := make([]map[string]any, 0, len(nodes))
|
||||
for _, node := range nodes {
|
||||
item := make(map[string]any, len(node))
|
||||
for key, value := range node {
|
||||
if key != "position" {
|
||||
item[key] = value
|
||||
}
|
||||
}
|
||||
projected = append(projected, item)
|
||||
}
|
||||
content["nodes"] = projected
|
||||
return cloudAgentCanvasHash(content)
|
||||
}
|
||||
|
||||
func cloudAgentCanvasState(repo *repository.Repository, userID string, doc map[string]any, offset int, ids []string, storyboardOffset int) (any, error) {
|
||||
if offset < 0 || storyboardOffset < 0 || len(ids) > 8 {
|
||||
return nil, BadAuthRequest("画布读取分页参数无效")
|
||||
@@ -152,7 +174,7 @@ func cloudAgentCanvasState(repo *repository.Repository, userID string, doc map[s
|
||||
edges = append(edges, map[string]any{"id": edge["id"], "fromNodeId": edge["fromNodeId"], "toNodeId": edge["toNodeId"]})
|
||||
}
|
||||
}
|
||||
return map[string]any{"snapshotHash": cloudAgentCanvasHash(doc), "nodes": nodes, "connections": edges, "totalNodes": len(all), "nextOffset": next, "hasMore": next > 0}, nil
|
||||
return map[string]any{"snapshotHash": cloudAgentCanvasHash(doc), "mediaSnapshotHash": cloudAgentMediaContentHash(doc), "nodes": nodes, "connections": edges, "totalNodes": len(all), "nextOffset": next, "hasMore": next > 0}, nil
|
||||
}
|
||||
|
||||
func cloudAgentSafeNumber(value any) (any, bool) {
|
||||
|
||||
@@ -213,7 +213,8 @@ func cloudAgentMediaDocument(repo *repository.Repository, userID, canvasID strin
|
||||
if err != nil {
|
||||
return nil, nil, nil, err
|
||||
}
|
||||
if args.SnapshotHash == "" || cloudAgentCanvasHash(doc) != args.SnapshotHash {
|
||||
unchanged := args.SnapshotHash != "" && (cloudAgentCanvasHash(doc) == args.SnapshotHash || cloudAgentMediaContentHash(doc) == args.SnapshotHash)
|
||||
if !unchanged {
|
||||
return nil, nil, nil, creationConflict("画布已变化,请重新读取画布并重新审批;未提交生成任务")
|
||||
}
|
||||
nodes, err := creationObjects(doc["nodes"])
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
)
|
||||
|
||||
// Only user-editable image options cross the approval boundary. Targets,
|
||||
// references, prompt, snapshot and generation mode remain server-authored.
|
||||
type CloudAgentMediaSettings struct {
|
||||
LogicalModelID string `json:"logicalModelId,omitempty"`
|
||||
ChannelID string `json:"channelId,omitempty"`
|
||||
ChannelModelKey string `json:"channelModelKey,omitempty"`
|
||||
Size string `json:"size"`
|
||||
Quality string `json:"quality"`
|
||||
}
|
||||
|
||||
func (s *Service) updateCloudAgentMediaApproval(run *model.CloudAgentExecution, state *cloudAgentRuntime, settings CloudAgentMediaSettings) error {
|
||||
call := state.Approval.Call
|
||||
if call.Function.Name != "generate_media" {
|
||||
return BadAuthRequest("当前审批不是图片生成,不能修改生成参数")
|
||||
}
|
||||
var args cloudAgentMediaArgs
|
||||
if err := decodeCloudAgentJSONObject(call.Function.Arguments, &args); err != nil {
|
||||
return err
|
||||
}
|
||||
if args.Mode != "image" {
|
||||
return BadAuthRequest("仅图片生成审批支持修改模型、画幅和质量")
|
||||
}
|
||||
args.LogicalModelID, args.ChannelID, args.ChannelModelKey = settings.LogicalModelID, settings.ChannelID, settings.ChannelModelKey
|
||||
args.Size, args.Quality = settings.Size, settings.Quality
|
||||
raw, err := json.Marshal(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
call.Function.Arguments = string(raw)
|
||||
req, plan, err := s.prepareCloudAgentMedia(run, state, call)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Dry admission uses the same model, ownership and option checks as task
|
||||
// submission, without reserving credits or creating a generation task.
|
||||
req.creationPrepare = &creationTaskPreparation{}
|
||||
task, err := s.CreateTask(run.UserID, req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var resolved struct {
|
||||
Config map[string]any `json:"config"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(task.InputJSON), &resolved); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateCloudAgentResolvedMediaOptions(req.Input["config"].(map[string]any), resolved.Config); err != nil {
|
||||
return err
|
||||
}
|
||||
name, err := s.cloudAgentMediaModelName(args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state.Calls[state.CallIndex] = call
|
||||
state.Approval.Call = call
|
||||
state.Approval.CallHash = cloudAgentApprovalCallHash(call)
|
||||
state.Approval.ModelName = name
|
||||
state.Approval.Preview = cloudAgentMediaApprovalPreview(plan, name)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateCloudAgentResolvedMediaOptions(requested, resolved map[string]any) error {
|
||||
for _, key := range []string{"size", "videoSeconds", "vquality", "quality", "count", "videoGenerateAudio"} {
|
||||
if value := stringValue(requested[key]); value != "" && !strings.EqualFold(value, stringValue(resolved[key])) {
|
||||
return creationConflict("模型解析后的生成规格与审批参数不同,请重新读取目录并审批")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -96,7 +96,7 @@ func compileCloudAgentPolicies(req CloudAgentRequest, skills []cloudAgentSkill,
|
||||
b.WriteString(media.Text)
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString("本轮执行上下文(仅供行为编排,不改变服务端权限):\n")
|
||||
b.WriteString("- 本轮最多 8 次模型调用,每次最多 8 个工具。\n")
|
||||
b.WriteString("- 模型调用不设固定轮数,由累计积分预算和运行状态控制;每次响应最多 8 个工具。生成任务数和视频秒数预算为 0 时表示该项不限。\n")
|
||||
b.WriteString("- 当前权限模式:")
|
||||
b.WriteString(req.PermissionMode)
|
||||
b.WriteString("。只读模式只能读取分析,不能修改或生成媒体。\n")
|
||||
|
||||
@@ -46,29 +46,30 @@ type cloudAgentApproval struct {
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
type cloudAgentRuntime struct {
|
||||
Request CloudAgentRequest `json:"request"`
|
||||
Policy cloudAgentPolicySnapshot `json:"policy"`
|
||||
ParentID string `json:"parentId,omitempty"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
CreativeAnchor cloudAgentCreativeAnchor `json:"creativeAnchor,omitempty"`
|
||||
TextHistory []providerTextMessage `json:"textHistory,omitempty"`
|
||||
Skills []cloudAgentSkill `json:"skills"`
|
||||
SkillReads map[string]bool `json:"skillReads,omitempty"`
|
||||
Profile cloudAgentProfileSnapshot `json:"profile"`
|
||||
ProfileReads map[string]bool `json:"profileReads,omitempty"`
|
||||
Canonical canonicalAgentRequest `json:"canonical"`
|
||||
ActiveTaskID string `json:"activeTaskId"`
|
||||
ActiveTextDraft string `json:"activeTextDraft,omitempty"`
|
||||
MediaTaskID string `json:"mediaTaskId,omitempty"`
|
||||
TaskIDs []string `json:"taskIds"`
|
||||
Step int `json:"step"`
|
||||
Generations int `json:"generations"`
|
||||
VideoSeconds int `json:"videoSeconds"`
|
||||
Calls []cloudAgentCall `json:"calls"`
|
||||
CallIndex int `json:"callIndex"`
|
||||
Approval *cloudAgentApproval `json:"approval,omitempty"`
|
||||
Decisions map[string]string `json:"decisions"`
|
||||
Events []CloudAgentEvent `json:"events"`
|
||||
Request CloudAgentRequest `json:"request"`
|
||||
Policy cloudAgentPolicySnapshot `json:"policy"`
|
||||
ParentID string `json:"parentId,omitempty"`
|
||||
Fingerprint string `json:"fingerprint,omitempty"`
|
||||
CreativeAnchor cloudAgentCreativeAnchor `json:"creativeAnchor,omitempty"`
|
||||
TextHistory []providerTextMessage `json:"textHistory,omitempty"`
|
||||
Skills []cloudAgentSkill `json:"skills"`
|
||||
SkillReads map[string]bool `json:"skillReads,omitempty"`
|
||||
Profile cloudAgentProfileSnapshot `json:"profile"`
|
||||
ProfileReads map[string]bool `json:"profileReads,omitempty"`
|
||||
Canonical canonicalAgentRequest `json:"canonical"`
|
||||
ActiveTaskID string `json:"activeTaskId"`
|
||||
ActiveTextDraft string `json:"activeTextDraft,omitempty"`
|
||||
MediaTaskID string `json:"mediaTaskId,omitempty"`
|
||||
TaskIDs []string `json:"taskIds"`
|
||||
Step int `json:"step"`
|
||||
Generations int `json:"generations"`
|
||||
VideoSeconds int `json:"videoSeconds"`
|
||||
Calls []cloudAgentCall `json:"calls"`
|
||||
CallIndex int `json:"callIndex"`
|
||||
Approval *cloudAgentApproval `json:"approval,omitempty"`
|
||||
Decisions map[string]string `json:"decisions"`
|
||||
DecisionSettings map[string]string `json:"decisionSettings,omitempty"`
|
||||
Events []CloudAgentEvent `json:"events"`
|
||||
}
|
||||
|
||||
func (s *Service) ensureCloudAgentExecution(task *model.Task, initial cloudAgentState) error {
|
||||
@@ -842,7 +843,7 @@ func (s *Service) advanceCloudAgentTool(run *model.CloudAgentExecution, state *c
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
plan.Args.SnapshotHash = cloudAgentCanvasHash(doc)
|
||||
plan.Args.SnapshotHash = cloudAgentMediaContentHash(doc)
|
||||
raw, err := json.Marshal(plan.Args)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -978,10 +979,8 @@ func (s *Service) enqueueCloudAgentTask(run *model.CloudAgentExecution, state *c
|
||||
if media != nil {
|
||||
requested, _ := req.Input["config"].(map[string]any)
|
||||
resolved, _ := input["config"].(map[string]any)
|
||||
for _, key := range []string{"size", "videoSeconds", "vquality", "quality", "count", "videoGenerateAudio"} {
|
||||
if value := stringValue(requested[key]); value != "" && !strings.EqualFold(value, stringValue(resolved[key])) {
|
||||
return s.cloudAgentMediaError(run, state, "admission", false, false, creationConflict("模型解析后的生成规格与审批参数不同,请重新读取目录并审批"))
|
||||
}
|
||||
if err := validateCloudAgentResolvedMediaOptions(requested, resolved); err != nil {
|
||||
return s.cloudAgentMediaError(run, state, "admission", false, false, err)
|
||||
}
|
||||
}
|
||||
if err = s.protectTaskSecrets(input); err != nil {
|
||||
@@ -1138,7 +1137,17 @@ func (s *Service) advanceCloudAgentMedia(run *model.CloudAgentExecution, state *
|
||||
return s.enqueueCloudAgentTask(run, state, req, plan)
|
||||
}
|
||||
|
||||
func (s *Service) DecideCloudAgentApproval(userID, id, approvalID, decision, reason string) error {
|
||||
func (s *Service) DecideCloudAgentApproval(userID, id, approvalID, decision, reason string, mediaSettings ...*CloudAgentMediaSettings) error {
|
||||
var settings *CloudAgentMediaSettings
|
||||
if len(mediaSettings) > 1 {
|
||||
return BadAuthRequest("只能提交一组生成参数")
|
||||
}
|
||||
if len(mediaSettings) == 1 {
|
||||
settings = mediaSettings[0]
|
||||
}
|
||||
if settings != nil && decision != "approve" {
|
||||
return BadAuthRequest("仅批准生成时可修改生成参数")
|
||||
}
|
||||
if decision != "approve" && decision != "reject" {
|
||||
return BadAuthRequest("无效审批决定")
|
||||
}
|
||||
@@ -1157,7 +1166,7 @@ func (s *Service) DecideCloudAgentApproval(userID, id, approvalID, decision, rea
|
||||
return err
|
||||
}
|
||||
if previous, ok := state.Decisions[approvalID]; ok {
|
||||
if previous == decision {
|
||||
if previous == decision && (settings == nil || state.DecisionSettings[approvalID] == creationHash(settings)) {
|
||||
return nil
|
||||
}
|
||||
return creationConflict("该审批已有不同决定")
|
||||
@@ -1165,10 +1174,21 @@ func (s *Service) DecideCloudAgentApproval(userID, id, approvalID, decision, rea
|
||||
if run.Status != "waiting_approval" || state.Approval == nil || state.Approval.ID != approvalID {
|
||||
return creationConflict("审批不存在或已过期")
|
||||
}
|
||||
if settings != nil {
|
||||
if err := s.updateCloudAgentMediaApproval(run, &state, *settings); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.repo.MutateCloudAgent(userID, id, run.Revision, func(current *model.CloudAgentExecution, _ *repository.Repository) error {
|
||||
state.Approval.Decision = decision
|
||||
state.Approval.Reason = reason
|
||||
state.Decisions[approvalID] = decision
|
||||
if settings != nil {
|
||||
if state.DecisionSettings == nil {
|
||||
state.DecisionSettings = map[string]string{}
|
||||
}
|
||||
state.DecisionSettings[approvalID] = creationHash(settings)
|
||||
}
|
||||
if decision == "reject" {
|
||||
// Rejection is a user control-plane decision, not a failed tool
|
||||
// invocation. Make it terminal before the scheduler can advance the
|
||||
@@ -1186,7 +1206,7 @@ func (s *Service) DecideCloudAgentApproval(userID, id, approvalID, decision, rea
|
||||
return cloudAgentSave(current, &state)
|
||||
}
|
||||
current.Status = "running"
|
||||
state.event(id, "approval_decided", map[string]any{"approvalId": approvalID, "decision": decision})
|
||||
state.event(id, "approval_decided", map[string]any{"approvalId": approvalID, "decision": decision, "arguments": json.RawMessage(state.Approval.Call.Function.Arguments), "preview": state.Approval.Preview, "modelName": state.Approval.ModelName})
|
||||
return cloudAgentSave(current, &state)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ func cloudAgentTools(req CloudAgentRequest) []map[string]any {
|
||||
"mode": map[string]any{"type": "string", "enum": cloudAgentGenerationModeNames()}, "prompt": str("完整生成提示词"),
|
||||
"logicalModelId": str("selection.logicalModelId;与channelId/channelModelKey互斥"), "channelId": str("selection.channelId"), "channelModelKey": str("selection.channelModelKey"),
|
||||
"durationSeconds": map[string]any{"type": "integer", "minimum": 0}, "size": str("模型支持的画幅,例如9:16"), "quality": str("目录支持的分辨率或质量"), "videoGenerateAudio": map[string]any{"type": "boolean", "description": "是否生成音频,仅视频可用"},
|
||||
"snapshotHash": str("最近canvas_get_state的snapshotHash"), "nodeId": str("可续用的未提交媒体草稿ID;无草稿时才使用新唯一ID"), "title": str("媒体节点名称"), "sourceNodeId": str("仅文本/镜头提示词节点ID;无文本来源则留空,绝不能填图片/视频/音频ID"), "referenceNodeIds": map[string]any{"type": "array", "maxItems": 16, "items": str("当前画布媒体参考节点ID;参考图只放此处,保持引用顺序")},
|
||||
"snapshotHash": str("使用最近 canvas_get_state 返回的 mediaSnapshotHash;媒体生成忽略纯节点移动,但仍校验内容与引用变化"), "nodeId": str("可续用的未提交媒体草稿ID;无草稿时才使用新唯一ID"), "title": str("媒体节点名称"), "sourceNodeId": str("仅文本/镜头提示词节点ID;无文本来源则留空,绝不能填图片/视频/音频ID"), "referenceNodeIds": map[string]any{"type": "array", "maxItems": 16, "items": str("当前画布媒体参考节点ID;参考图只放此处,保持引用顺序")},
|
||||
}, "mode", "prompt", "snapshotHash", "nodeId", "title", "referenceNodeIds")
|
||||
}
|
||||
return tools
|
||||
|
||||
@@ -22,7 +22,7 @@ func RegisterAgentRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
return
|
||||
}
|
||||
capabilities := service.CloudAgentCapabilitySetInfo()
|
||||
ok(c, gin.H{"version": 2, "permissionModes": []string{"read_only", "request_approval", "auto"}, "contextScopes": []string{"canvas"}, "skills": true, "writeTools": true, "billing": "fixed_request", "maxHistoryPairs": 8, "maxSteps": 8, "tools": service.CloudAgentSupportedToolNames(), "capabilitySetVersion": capabilities.Version, "capabilitySetHash": capabilities.Hash, "nodeTypes": capabilities.Nodes})
|
||||
ok(c, gin.H{"version": 2, "permissionModes": []string{"read_only", "request_approval", "auto"}, "contextScopes": []string{"canvas"}, "skills": true, "writeTools": true, "billing": "fixed_request", "maxHistoryPairs": 0, "maxHistoryBytes": 64000, "maxSteps": 0, "tools": service.CloudAgentSupportedToolNames(), "capabilitySetVersion": capabilities.Version, "capabilitySetHash": capabilities.Hash, "nodeTypes": capabilities.Nodes})
|
||||
})
|
||||
// Profiles are durable preference data, not an authorization surface. The
|
||||
// service validates scope ownership and the compiler injects the effective
|
||||
@@ -204,8 +204,9 @@ func RegisterAgentRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
}
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)
|
||||
var req struct {
|
||||
Decision string `json:"decision"`
|
||||
Reason string `json:"reason"`
|
||||
Decision string `json:"decision"`
|
||||
Reason string `json:"reason"`
|
||||
MediaSettings *service.CloudAgentMediaSettings `json:"mediaSettings,omitempty"`
|
||||
}
|
||||
decoder := json.NewDecoder(c.Request.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
@@ -225,7 +226,7 @@ func RegisterAgentRoutes(r *gin.RouterGroup, svc *service.Service) {
|
||||
fail(c, http.StatusBadRequest, errors.New("请求必须只包含一个 JSON 对象"))
|
||||
return
|
||||
}
|
||||
if err := svc.DecideCloudAgentApproval(user.ID, c.Param("id"), c.Param("approvalId"), req.Decision, req.Reason); err != nil {
|
||||
if err := svc.DecideCloudAgentApproval(user.ID, c.Param("id"), c.Param("approvalId"), req.Decision, req.Reason, req.MediaSettings); err != nil {
|
||||
failService(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -40,7 +40,7 @@ paths:
|
||||
summary: 读取云端 Agent 能力
|
||||
responses:
|
||||
"200":
|
||||
description: 信封 data 包含 version、permissionModes、contextScopes、skills、writeTools、billing、maxHistoryPairs、capabilitySetVersion、capabilitySetHash、nodeTypes、tools
|
||||
description: 信封 data 包含 version、permissionModes、contextScopes、skills、writeTools、billing、maxHistoryPairs、maxSteps、maxHistoryBytes、capabilitySetVersion、capabilitySetHash、nodeTypes、tools;maxHistoryPairs 和 maxSteps 为 0 表示无固定轮数上限,历史仍受 maxHistoryBytes 限制
|
||||
/agent/profile:
|
||||
get:
|
||||
tags: [agent]
|
||||
@@ -192,6 +192,22 @@ paths:
|
||||
reason:
|
||||
type: string
|
||||
maxLength: 2000
|
||||
mediaSettings:
|
||||
type: object
|
||||
additionalProperties: false
|
||||
description: 仅 approve 图片生成审批可传;替换本次模型、画幅和质量,重新强校验,不修改提示词、引用或目标。logicalModelId 与 channelId + channelModelKey 二选一。
|
||||
required: [size, quality]
|
||||
properties:
|
||||
logicalModelId:
|
||||
type: string
|
||||
channelId:
|
||||
type: string
|
||||
channelModelKey:
|
||||
type: string
|
||||
size:
|
||||
type: string
|
||||
quality:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
description: 信封 data.accepted
|
||||
|
||||
@@ -4,6 +4,7 @@ import "infinite-canvas/backend/internal/app"
|
||||
|
||||
type (
|
||||
CloudAgentRequest = app.CloudAgentRequest
|
||||
CloudAgentMediaSettings = app.CloudAgentMediaSettings
|
||||
CloudAgentCapabilitySet = app.CloudAgentCapabilitySet
|
||||
AgentProfileRequest = app.AgentProfileRequest
|
||||
AgentProfileView = app.AgentProfileView
|
||||
|
||||
Reference in new issue
Block a user