diff --git a/AGENTS.md b/AGENTS.md index ba28010a5..74014dc69 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,6 +38,26 @@ - **动效优先纯 CSS**,不要为了视觉效果引入 Three.js。Three.js 只在 3D 导演台功能中按需引入。 - 协作跟随(follow mode)是低成本高感知功能,纳入后续迭代候选。 +## 开发前置:先查四个参考工程(强制) + +每次**新增或修改功能**前,必须先在下面四个工程里检索是否已有实现。有实现就移植或对齐,**不要凭想象另起炉灶**;页面布局、组件拆分、交互细节同样以它们为参照。 + +| 参考工程 | 本地路径 | +| --- | --- | +| `infinite-canvas` | `D:\TongTongStudio\ai\infinite-canvas` | +| `open-ai-canvas` | `D:\TongTongStudio\ai\open-ai-canvas` | +| `open-canvas` | `D:\TongTongStudio\ai\open-canvas` | +| `ttstd-3d-director` | `D:\TongTongStudio\ai\ttstd-3d-director` | + +执行顺序: + +1. **检索**:按功能关键词、组件名、路由、接口路径在四个工程中查找。检索时排除 `node_modules` / `dist` / `.next` / `build` 等构建产物,只读源码。 +2. **对齐**:找到实现就优先移植,或按其结构与布局落地;前端布局、组件划分、交互细节都以参考工程为准,不要自行发明。 +3. **自研**:确认四个工程都没有对应实现时,才自行设计,并在回复中说明「四个参考工程均无实现」。 +4. **守许可**:移植的代码必须保留版权声明,汇总到 `THIRD_PARTY_NOTICES.md`(见下文"许可与合规红线")。 + +汇报时用一句话给出参考结论即可,例如「参照 `open-ai-canvas` 的 `internal/service/task.go` 落地」或「四个参考工程均无实现,按本项目约定自行设计」,不要展开长篇调研过程。 + ## 技术栈(已锁定) ### 前端 `web/` diff --git a/backend/cmd/server/main.go b/backend/cmd/server/main.go index c95c8237f..e2a82d7ad 100644 --- a/backend/cmd/server/main.go +++ b/backend/cmd/server/main.go @@ -38,6 +38,8 @@ func main() { canvasRepo := repository.NewCanvasRepository(db) taskRepo := repository.NewTaskRepository(db) + preferenceRepo := repository.NewPreferenceRepository(db) + promptRepo := repository.NewPromptRepository(db) broker := sse.NewBroker() store, err := storage.NewLocal(cfg.FilesDir(), cfg.PublicBaseURL) @@ -58,11 +60,13 @@ func main() { taskService.SetController(pool) router := handler.NewRouter(handler.Deps{ - Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)), - Task: handler.NewTaskHandler(taskService), - Event: handler.NewEventHandler(broker), - Config: cfg, - FileDir: store.Root(), + Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)), + Task: handler.NewTaskHandler(taskService), + Event: handler.NewEventHandler(broker), + Preference: handler.NewPreferenceHandler(service.NewPreferenceService(preferenceRepo)), + Prompt: handler.NewPromptHandler(service.NewPromptService(promptRepo)), + Config: cfg, + FileDir: store.Root(), }) server := &http.Server{ diff --git a/backend/internal/database/database.go b/backend/internal/database/database.go index 916e67ede..ee4e20e1d 100644 --- a/backend/internal/database/database.go +++ b/backend/internal/database/database.go @@ -28,7 +28,12 @@ func Open(cfg config.Config) (*gorm.DB, error) { return nil, err } - if err := db.AutoMigrate(&model.Canvas{}, &model.Task{}); err != nil { + if err := db.AutoMigrate( + &model.Canvas{}, + &model.Task{}, + &model.Preference{}, + &model.PromptCustomization{}, + ); err != nil { return nil, err } diff --git a/backend/internal/handler/preference.go b/backend/internal/handler/preference.go new file mode 100644 index 000000000..5c93ea46e --- /dev/null +++ b/backend/internal/handler/preference.go @@ -0,0 +1,41 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/ttstd/infinite-canvas/backend/internal/service" +) + +type PreferenceHandler struct { + preferences *service.PreferenceService +} + +func NewPreferenceHandler(preferences *service.PreferenceService) *PreferenceHandler { + return &PreferenceHandler{preferences: preferences} +} + +func (h *PreferenceHandler) Get(c *gin.Context) { + view, err := h.preferences.Get() + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, view) +} + +func (h *PreferenceHandler) Update(c *gin.Context) { + var body service.UpdatePreferenceInput + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求体格式不正确"}) + return + } + + view, err := h.preferences.Update(body) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, view) +} diff --git a/backend/internal/handler/prompt.go b/backend/internal/handler/prompt.go new file mode 100644 index 000000000..1f8ca0214 --- /dev/null +++ b/backend/internal/handler/prompt.go @@ -0,0 +1,52 @@ +package handler + +import ( + "net/http" + + "github.com/gin-gonic/gin" + + "github.com/ttstd/infinite-canvas/backend/internal/service" +) + +type PromptHandler struct { + prompts *service.PromptService +} + +func NewPromptHandler(prompts *service.PromptService) *PromptHandler { + return &PromptHandler{prompts: prompts} +} + +func (h *PromptHandler) List(c *gin.Context) { + preferences, err := h.prompts.Preferences() + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"preferences": preferences}) +} + +func (h *PromptHandler) Customize(c *gin.Context) { + var body struct { + Mode string `json:"mode"` + Content string `json:"content"` + } + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "请求体格式不正确"}) + return + } + + preference, err := h.prompts.Customize(c.Param("operation"), body.Mode, body.Content) + if err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"preference": preference}) +} + +func (h *PromptHandler) Reset(c *gin.Context) { + if err := h.prompts.Reset(c.Param("operation")); err != nil { + respondError(c, err) + return + } + c.JSON(http.StatusOK, gin.H{"ok": true}) +} diff --git a/backend/internal/handler/router.go b/backend/internal/handler/router.go index 2ac0f8bf2..7c562005b 100644 --- a/backend/internal/handler/router.go +++ b/backend/internal/handler/router.go @@ -14,11 +14,13 @@ import ( ) type Deps struct { - Canvas *CanvasHandler - Task *TaskHandler - Event *EventHandler - Config config.Config - FileDir string + Canvas *CanvasHandler + Task *TaskHandler + Event *EventHandler + Preference *PreferenceHandler + Prompt *PromptHandler + Config config.Config + FileDir string } func NewRouter(deps Deps) *gin.Engine { @@ -42,6 +44,13 @@ func NewRouter(deps Deps) *gin.Engine { api.GET("/tasks", deps.Task.List) api.POST("/tasks", deps.Task.Create) api.POST("/tasks/:id/cancel", deps.Task.Cancel) + + api.GET("/preferences", deps.Preference.Get) + api.PUT("/preferences", deps.Preference.Update) + + api.GET("/prompts", deps.Prompt.List) + api.PATCH("/prompts/:operation", deps.Prompt.Customize) + api.DELETE("/prompts/:operation", deps.Prompt.Reset) } if deps.FileDir != "" { diff --git a/backend/internal/model/preference.go b/backend/internal/model/preference.go new file mode 100644 index 000000000..5d6216f63 --- /dev/null +++ b/backend/internal/model/preference.go @@ -0,0 +1,27 @@ +package model + +import "time" + +// PreferenceID 当前没有用户体系,配置与偏好固定为一条全局记录。 +const PreferenceID = "default" + +// APIKeyConfig 用户自带的模型渠道(BYOK)。 +// 密钥只落在本机数据库,对外输出时由 service 脱敏,不回传明文。 +type APIKeyConfig struct { + ID string `json:"id"` + Provider string `json:"provider"` + Label string `json:"label"` + BaseURL string `json:"baseUrl"` + APIKey string `json:"apiKey"` + Model string `json:"model"` + Enabled bool `json:"enabled"` +} + +// Preference 配置与用户偏好。 +// 提示词定制单独存放,见 model.PromptCustomization 与 internal/prompts。 +type Preference struct { + ID string `gorm:"primaryKey;size:32" json:"id"` + APIKeys []APIKeyConfig `gorm:"type:text;serializer:json" json:"apiKeys"` + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} diff --git a/backend/internal/model/prompt.go b/backend/internal/model/prompt.go new file mode 100644 index 000000000..45042f64a --- /dev/null +++ b/backend/internal/model/prompt.go @@ -0,0 +1,25 @@ +package model + +import "time" + +// 提示词定制模式:跟随平台模板 / 在模板后追加要求 / 完全改写。 +const ( + PromptModeInherit = "inherit" + PromptModeAppend = "append" + PromptModeRewrite = "rewrite" +) + +// PromptCustomization 用户对某个任务类型提示词的定制。 +// 平台模板本身内置在 internal/prompts,只有定制需要落库;一个任务类型最多一条。 +type PromptCustomization struct { + ID string `gorm:"primaryKey;size:64" json:"id"` + Operation string `gorm:"size:64;not null;uniqueIndex" json:"operation"` + Mode string `gorm:"size:16;not null" json:"mode"` + Content string `gorm:"type:text" json:"content"` + + // BaseTemplateVersion 定制时依据的平台模板版本,用于判断定制是否已落后于平台更新。 + BaseTemplateVersion int `json:"baseTemplateVersion"` + + CreatedAt time.Time `json:"createdAt"` + UpdatedAt time.Time `json:"updatedAt"` +} diff --git a/backend/internal/prompts/catalog.go b/backend/internal/prompts/catalog.go new file mode 100644 index 000000000..105b93a8f --- /dev/null +++ b/backend/internal/prompts/catalog.go @@ -0,0 +1,219 @@ +// Package prompts 维护平台内置的提示词模板目录。 +// +// 结构与 open-ai-canvas 的 internal/prompts 对齐: +// 任务类型(operation)+ 平台默认模板(DefaultContent)+ 用户定制模式(inherit / append / rewrite)。 +// 本项目暂不提供管理后台,平台模板直接内置在代码里,不落库;落库的只有用户定制。 +package prompts + +// 内置任务类型。新增或改名时同步维护 web/src/types/prompt.ts。 +const ( + OperationTextToImage = "text_to_image" + OperationReferenceImage = "reference_image" + OperationTextToVideo = "text_to_video" + OperationImageToVideo = "image_to_video" + OperationTextToAudio = "text_to_audio" + OperationPromptEnhance = "prompt_enhance" +) + +// TemplateVersion 平台模板版本。**修改任一 DefaultContent 后必须递增**, +// 基于旧版本做过定制的用户会在界面上看到「平台模板已更新」提示。 +const TemplateVersion = 1 + +// Variable 模板里可被替换的占位符,供前端提示可用变量。 +type Variable struct { + Label string `json:"label"` + Placeholder string `json:"placeholder"` +} + +// Definition 一个任务类型的元信息。 +type Definition struct { + Operation string `json:"operation"` + Label string `json:"label"` + Category string `json:"category"` + Description string `json:"description"` + OutputType string `json:"outputType"` + Variables []Variable `json:"variables"` + + // DefaultContent 平台默认模板,只用于后端组装响应,不随目录整体下发。 + DefaultContent string `json:"-"` +} + +// Definitions 返回全部内置任务类型,顺序即前端展示顺序。 +func Definitions() []Definition { + return []Definition{ + { + Operation: OperationTextToImage, + Label: "文生图", + Category: "图片", + Description: "把文本提示词整理成图片模型的执行提示词。", + OutputType: "text", + Variables: []Variable{ + {Label: "主体描述", Placeholder: "{{主体描述}}"}, + {Label: "画面风格", Placeholder: "{{画面风格}}"}, + {Label: "构图与镜头", Placeholder: "{{构图与镜头}}"}, + {Label: "光线与色调", Placeholder: "{{光线与色调}}"}, + {Label: "负面要求", Placeholder: "{{负面要求}}"}, + }, + DefaultContent: `生成一张单一、可执行的画面。只描述静止图像,不写后续运动。明确主体、环境与视觉焦点,写清前中后景关系、遮挡与材质表现,不添加未要求的人物、文字或水印。 + +【主体描述】 +{{主体描述}} + +【画面风格】 +{{画面风格}} + +【构图与镜头】 +{{构图与镜头}} + +【光线与色调】 +{{光线与色调}} + +【负面要求】 +{{负面要求}}`, + }, + { + Operation: OperationReferenceImage, + Label: "参考图生成", + Category: "图片", + Description: "在参考图基础上生成新画面,写清要改什么、要保留什么。", + OutputType: "text", + Variables: []Variable{ + {Label: "参考图说明", Placeholder: "{{参考图说明}}"}, + {Label: "目标修改", Placeholder: "{{目标修改}}"}, + {Label: "需要保持", Placeholder: "{{需要保持}}"}, + {Label: "负面要求", Placeholder: "{{负面要求}}"}, + }, + DefaultContent: `基于参考图生成新画面。先锁定必须保持不变的部分,再描述需要改变的部分;改动范围之外的构图、身份、服装与材质不要自行改写。 + +【参考图说明】 +{{参考图说明}} + +【目标修改】 +{{目标修改}} + +【需要保持】 +{{需要保持}} + +【负面要求】 +{{负面要求}}`, + }, + { + Operation: OperationTextToVideo, + Label: "文生视频", + Category: "视频", + Description: "把文本提示词整理成视频模型的执行提示词。", + OutputType: "text", + Variables: []Variable{ + {Label: "主体描述", Placeholder: "{{主体描述}}"}, + {Label: "镜头运动", Placeholder: "{{镜头运动}}"}, + {Label: "时间节拍", Placeholder: "{{时间节拍}}"}, + {Label: "氛围与光线", Placeholder: "{{氛围与光线}}"}, + {Label: "负面要求", Placeholder: "{{负面要求}}"}, + }, + DefaultContent: `生成单一连续镜头。一个镜头只保留一个叙事目标、一个主运镜和一条主要动作链;摄影机运动必须有起点、动机和停止点。优先保证主体身份、关键动作和连续性,次要环境效果可以简化。 + +【主体描述】 +{{主体描述}} + +【镜头运动】 +{{镜头运动}} + +【时间节拍】 +{{时间节拍}} + +【氛围与光线】 +{{氛围与光线}} + +【负面要求】 +{{负面要求}}`, + }, + { + Operation: OperationImageToVideo, + Label: "图生视频", + Category: "视频", + Description: "以首帧图片为起点驱动视频,专注运动与调度。", + OutputType: "text", + Variables: []Variable{ + {Label: "首帧说明", Placeholder: "{{首帧说明}}"}, + {Label: "运动与调度", Placeholder: "{{运动与调度}}"}, + {Label: "镜头运动", Placeholder: "{{镜头运动}}"}, + {Label: "时间节拍", Placeholder: "{{时间节拍}}"}, + {Label: "负面要求", Placeholder: "{{负面要求}}"}, + }, + DefaultContent: `以给定首帧为起点生成单一连续镜头。构图、主体身份、服装与光线严格继承首帧,只描述首帧之后的运动与调度,不重新设计画面。 + +【首帧说明】 +{{首帧说明}} + +【运动与调度】 +{{运动与调度}} + +【镜头运动】 +{{镜头运动}} + +【时间节拍】 +{{时间节拍}} + +【负面要求】 +{{负面要求}}`, + }, + { + Operation: OperationTextToAudio, + Label: "音频生成", + Category: "音频", + Description: "把文本整理成配音或音效的生成提示词。", + OutputType: "text", + Variables: []Variable{ + {Label: "内容与情绪", Placeholder: "{{内容与情绪}}"}, + {Label: "音色与语速", Placeholder: "{{音色与语速}}"}, + {Label: "时长与节奏", Placeholder: "{{时长与节奏}}"}, + {Label: "负面要求", Placeholder: "{{负面要求}}"}, + }, + DefaultContent: `生成一段可直接使用的音频。发音清晰、断句自然,情绪与内容一致,不添加未要求的背景音乐或旁白。 + +【内容与情绪】 +{{内容与情绪}} + +【音色与语速】 +{{音色与语速}} + +【时长与节奏】 +{{时长与节奏}} + +【负面要求】 +{{负面要求}}`, + }, + { + Operation: OperationPromptEnhance, + Label: "提示词扩写", + Category: "通用", + Description: "把简短想法扩写为可直接投喂模型的提示词。", + OutputType: "text", + Variables: []Variable{ + {Label: "用户原始想法", Placeholder: "{{用户原始想法}}"}, + {Label: "目标模型", Placeholder: "{{目标模型}}"}, + {Label: "补充约束", Placeholder: "{{补充约束}}"}, + }, + DefaultContent: `你是一位提示词工程师。把用户的简短想法扩写为可直接投喂模型的提示词:保留原意,补齐主体、环境、构图、光线与材质等可执行细节,不添加用户未要求的元素,不解释你的改写过程,只输出提示词本身。 + +【用户原始想法】 +{{用户原始想法}} + +【目标模型】 +{{目标模型}} + +【补充约束】 +{{补充约束}}`, + }, + } +} + +// Find 按任务类型查定义。 +func Find(operation string) (Definition, bool) { + for _, definition := range Definitions() { + if definition.Operation == operation { + return definition, true + } + } + return Definition{}, false +} diff --git a/backend/internal/repository/preference.go b/backend/internal/repository/preference.go new file mode 100644 index 000000000..858f630c0 --- /dev/null +++ b/backend/internal/repository/preference.go @@ -0,0 +1,35 @@ +package repository + +import ( + "errors" + + "gorm.io/gorm" + + "github.com/ttstd/infinite-canvas/backend/internal/model" +) + +type PreferenceRepository struct { + db *gorm.DB +} + +func NewPreferenceRepository(db *gorm.DB) *PreferenceRepository { + return &PreferenceRepository{db: db} +} + +// Get 读取全局偏好;尚未配置过时返回一个空骨架,不写入数据库。 +func (r *PreferenceRepository) Get() (*model.Preference, error) { + var preference model.Preference + if err := r.db.First(&preference, "id = ?", model.PreferenceID).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return &model.Preference{ID: model.PreferenceID}, nil + } + return nil, err + } + return &preference, nil +} + +// Save 整条覆盖写入,记录不存在时创建。 +// CreatedAt 由调用方从旧记录带入,避免更新时被零值覆盖。 +func (r *PreferenceRepository) Save(preference *model.Preference) error { + return r.db.Save(preference).Error +} diff --git a/backend/internal/repository/prompt.go b/backend/internal/repository/prompt.go new file mode 100644 index 000000000..7b0ceda67 --- /dev/null +++ b/backend/internal/repository/prompt.go @@ -0,0 +1,50 @@ +package repository + +import ( + "errors" + + "gorm.io/gorm" + + "github.com/ttstd/infinite-canvas/backend/internal/model" +) + +type PromptRepository struct { + db *gorm.DB +} + +func NewPromptRepository(db *gorm.DB) *PromptRepository { + return &PromptRepository{db: db} +} + +func (r *PromptRepository) List() ([]model.PromptCustomization, error) { + var rows []model.PromptCustomization + err := r.db.Order("created_at asc").Find(&rows).Error + return rows, err +} + +func (r *PromptRepository) Get(operation string) (*model.PromptCustomization, error) { + var customization model.PromptCustomization + if err := r.db.First(&customization, "operation = ?", operation).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, ErrNotFound + } + return nil, err + } + return &customization, nil +} + +// Save 覆盖写入一条定制。调用方需保证同 operation 复用已有 ID,否则会撞唯一索引。 +func (r *PromptRepository) Save(customization *model.PromptCustomization) error { + return r.db.Save(customization).Error +} + +func (r *PromptRepository) Delete(operation string) error { + result := r.db.Delete(&model.PromptCustomization{}, "operation = ?", operation) + if result.Error != nil { + return result.Error + } + if result.RowsAffected == 0 { + return ErrNotFound + } + return nil +} diff --git a/backend/internal/service/preference.go b/backend/internal/service/preference.go new file mode 100644 index 000000000..b9b427d19 --- /dev/null +++ b/backend/internal/service/preference.go @@ -0,0 +1,190 @@ +package service + +import ( + "fmt" + "net/url" + "strings" + "time" + + "github.com/google/uuid" + + "github.com/ttstd/infinite-canvas/backend/internal/model" + "github.com/ttstd/infinite-canvas/backend/internal/repository" +) + +const maxAPIKeyEntries = 20 + +// APIKeyView 对外输出的渠道配置,只回传掩码,不含明文密钥。 +type APIKeyView struct { + ID string `json:"id"` + Provider string `json:"provider"` + Label string `json:"label"` + BaseURL string `json:"baseUrl"` + Model string `json:"model"` + Enabled bool `json:"enabled"` + HasKey bool `json:"hasKey"` + KeyMask string `json:"keyMask"` +} + +// PreferenceView 配置与用户偏好。 +type PreferenceView struct { + APIKeys []APIKeyView `json:"apiKeys"` + UpdatedAt time.Time `json:"updatedAt"` +} + +// APIKeyInput 前端提交的渠道配置。APIKey 留空表示沿用已保存的密钥。 +type APIKeyInput struct { + ID string `json:"id"` + Provider string `json:"provider"` + Label string `json:"label"` + BaseURL string `json:"baseUrl"` + APIKey string `json:"apiKey"` + Model string `json:"model"` + Enabled bool `json:"enabled"` +} + +type UpdatePreferenceInput struct { + APIKeys []APIKeyInput `json:"apiKeys"` +} + +type PreferenceService struct { + preferences *repository.PreferenceRepository +} + +func NewPreferenceService(preferences *repository.PreferenceRepository) *PreferenceService { + return &PreferenceService{preferences: preferences} +} + +func (s *PreferenceService) Get() (*PreferenceView, error) { + preference, err := s.preferences.Get() + if err != nil { + return nil, err + } + return toPreferenceView(preference), nil +} + +// Update 校验并覆盖保存;未填写密钥的渠道沿用已保存的值。 +func (s *PreferenceService) Update(input UpdatePreferenceInput) (*PreferenceView, error) { + current, err := s.preferences.Get() + if err != nil { + return nil, err + } + + apiKeys, err := mergeAPIKeys(current.APIKeys, input.APIKeys) + if err != nil { + return nil, err + } + + preference := &model.Preference{ + ID: model.PreferenceID, + APIKeys: apiKeys, + CreatedAt: current.CreatedAt, + } + if err := s.preferences.Save(preference); err != nil { + return nil, err + } + return toPreferenceView(preference), nil +} + +func toPreferenceView(preference *model.Preference) *PreferenceView { + apiKeys := make([]APIKeyView, 0, len(preference.APIKeys)) + for _, item := range preference.APIKeys { + apiKeys = append(apiKeys, APIKeyView{ + ID: item.ID, + Provider: item.Provider, + Label: item.Label, + BaseURL: item.BaseURL, + Model: item.Model, + Enabled: item.Enabled, + HasKey: item.APIKey != "", + KeyMask: maskSecret(item.APIKey), + }) + } + + return &PreferenceView{ + APIKeys: apiKeys, + UpdatedAt: preference.UpdatedAt, + } +} + +func mergeAPIKeys(current []model.APIKeyConfig, inputs []APIKeyInput) ([]model.APIKeyConfig, error) { + if len(inputs) > maxAPIKeyEntries { + return nil, fmt.Errorf("%w: 渠道数量不能超过 %d 个", ErrInvalidInput, maxAPIKeyEntries) + } + + existing := make(map[string]model.APIKeyConfig, len(current)) + for _, item := range current { + existing[item.ID] = item + } + + result := make([]model.APIKeyConfig, 0, len(inputs)) + for _, input := range inputs { + provider := strings.TrimSpace(input.Provider) + if provider == "" { + return nil, fmt.Errorf("%w: 渠道标识不能为空", ErrInvalidInput) + } + if len(provider) > 64 { + return nil, fmt.Errorf("%w: 渠道标识不能超过 64 个字符", ErrInvalidInput) + } + + label := strings.TrimSpace(input.Label) + if label == "" { + label = provider + } + if len([]rune(label)) > 64 { + return nil, fmt.Errorf("%w: 渠道名称不能超过 64 个字符", ErrInvalidInput) + } + + baseURL := strings.TrimSpace(input.BaseURL) + if baseURL != "" && !isHTTPURL(baseURL) { + return nil, fmt.Errorf("%w: Base URL 必须是 http/https 地址", ErrInvalidInput) + } + + apiKey := strings.TrimSpace(input.APIKey) + if len(apiKey) > 512 { + return nil, fmt.Errorf("%w: API Key 长度超出限制", ErrInvalidInput) + } + + id := strings.TrimSpace(input.ID) + if id == "" { + id = uuid.NewString() + } + if apiKey == "" { + if previous, ok := existing[id]; ok { + apiKey = previous.APIKey + } + } + + result = append(result, model.APIKeyConfig{ + ID: id, + Provider: provider, + Label: label, + BaseURL: baseURL, + APIKey: apiKey, + Model: strings.TrimSpace(input.Model), + Enabled: input.Enabled, + }) + } + + return result, nil +} + +// maskSecret 只保留末 4 位,其余用圆点代替。 +func maskSecret(secret string) string { + if secret == "" { + return "" + } + runes := []rune(secret) + if len(runes) <= 4 { + return strings.Repeat("•", len(runes)) + } + return strings.Repeat("•", 4) + string(runes[len(runes)-4:]) +} + +func isHTTPURL(raw string) bool { + parsed, err := url.Parse(raw) + if err != nil { + return false + } + return (parsed.Scheme == "http" || parsed.Scheme == "https") && parsed.Host != "" +} diff --git a/backend/internal/service/prompt.go b/backend/internal/service/prompt.go new file mode 100644 index 000000000..702a8fd1f --- /dev/null +++ b/backend/internal/service/prompt.go @@ -0,0 +1,143 @@ +package service + +import ( + "errors" + "fmt" + "strings" + + "github.com/google/uuid" + + "github.com/ttstd/infinite-canvas/backend/internal/model" + "github.com/ttstd/infinite-canvas/backend/internal/prompts" + "github.com/ttstd/infinite-canvas/backend/internal/repository" +) + +const maxPromptContentRunes = 8000 + +// PromptTemplateView 平台模板视图。模板内置在代码里,这里给出前端需要的元信息与内容。 +type PromptTemplateView struct { + Operation string `json:"operation"` + Name string `json:"name"` + Version int `json:"version"` + Content string `json:"content"` + OutputType string `json:"outputType"` +} + +// PromptPreferenceView 一个任务类型的提示词配置,结构对齐 open-ai-canvas 的 UserPromptPreference。 +type PromptPreferenceView struct { + Definition prompts.Definition `json:"definition"` + Template *PromptTemplateView `json:"template"` + Customization *model.PromptCustomization `json:"customization,omitempty"` + Outdated bool `json:"outdated"` +} + +type PromptService struct { + prompts *repository.PromptRepository +} + +func NewPromptService(promptsRepo *repository.PromptRepository) *PromptService { + return &PromptService{prompts: promptsRepo} +} + +// Preferences 返回全部任务类型及其平台模板与用户定制。 +func (s *PromptService) Preferences() ([]PromptPreferenceView, error) { + rows, err := s.prompts.List() + if err != nil { + return nil, err + } + + byOperation := make(map[string]*model.PromptCustomization, len(rows)) + for index := range rows { + byOperation[rows[index].Operation] = &rows[index] + } + + definitions := prompts.Definitions() + result := make([]PromptPreferenceView, 0, len(definitions)) + for _, definition := range definitions { + result = append(result, buildPromptPreference(definition, byOperation[definition.Operation])) + } + return result, nil +} + +// Customize 保存定制。mode=inherit 视为放弃定制,直接删除已有记录。 +func (s *PromptService) Customize(operation, mode, content string) (*PromptPreferenceView, error) { + definition, ok := prompts.Find(operation) + if !ok { + return nil, repository.ErrNotFound + } + + switch strings.TrimSpace(mode) { + case model.PromptModeInherit: + if err := s.prompts.Delete(operation); err != nil && !errors.Is(err, repository.ErrNotFound) { + return nil, err + } + preference := buildPromptPreference(definition, nil) + return &preference, nil + case model.PromptModeAppend, model.PromptModeRewrite: + default: + return nil, fmt.Errorf("%w: 不支持的定制模式", ErrInvalidInput) + } + + trimmed := strings.TrimSpace(content) + if trimmed == "" { + return nil, fmt.Errorf("%w: 请填写个人提示词内容", ErrInvalidInput) + } + if len([]rune(trimmed)) > maxPromptContentRunes { + return nil, fmt.Errorf("%w: 提示词内容不能超过 %d 个字符", ErrInvalidInput, maxPromptContentRunes) + } + + customization := &model.PromptCustomization{ + ID: uuid.NewString(), + Operation: operation, + Mode: strings.TrimSpace(mode), + Content: trimmed, + BaseTemplateVersion: prompts.TemplateVersion, + } + + // 同一任务类型只保留一条记录:复用原有 ID 与创建时间。 + existing, err := s.prompts.Get(operation) + switch { + case err == nil: + customization.ID = existing.ID + customization.CreatedAt = existing.CreatedAt + case errors.Is(err, repository.ErrNotFound): + default: + return nil, err + } + + if err := s.prompts.Save(customization); err != nil { + return nil, err + } + + preference := buildPromptPreference(definition, customization) + return &preference, nil +} + +// Reset 恢复平台模板。 +func (s *PromptService) Reset(operation string) error { + if _, ok := prompts.Find(operation); !ok { + return repository.ErrNotFound + } + if err := s.prompts.Delete(operation); err != nil && !errors.Is(err, repository.ErrNotFound) { + return err + } + return nil +} + +func buildPromptPreference(definition prompts.Definition, customization *model.PromptCustomization) PromptPreferenceView { + preference := PromptPreferenceView{ + Definition: definition, + Template: &PromptTemplateView{ + Operation: definition.Operation, + Name: "默认" + definition.Label + "模板", + Version: prompts.TemplateVersion, + Content: definition.DefaultContent, + OutputType: definition.OutputType, + }, + Customization: customization, + } + if customization != nil { + preference.Outdated = customization.BaseTemplateVersion < prompts.TemplateVersion + } + return preference +} diff --git a/docs/architecture.md b/docs/architecture.md index d8f77f158..379bad371 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -34,6 +34,8 @@ - **参考素材传 ID 不传 base64**:媒体一律进存储层,画布节点只引用 URL。 - **Provider 统一接口**:新增渠道只实现 `internal/provider` 的接口,不在 service 里写厂商分支。 - **存储接口化**:本地磁盘与 S3-compatible 实现同一接口,通过配置切换。 +- **偏好存数据库,不进环境变量**:环境变量只提供服务端默认渠道;用户在前端配置的渠道密钥存 `preferences` 表(`GET/PUT /api/preferences`),密钥对外只回显掩码,提交时留空表示沿用旧值。 +- **平台提示词模板内置、用户定制落库**:任务类型与默认模板固化在 `backend/internal/prompts`,修改默认内容必须递增 `TemplateVersion`;用户定制单独存 `prompt_customizations` 表,接口为 `GET /api/prompts` 与 `PATCH|DELETE /api/prompts/:operation`。生成时按「跟随平台 / 追加要求 / 高级改写」组装最终提示词,结构对齐 `open-ai-canvas` 的 `internal/prompts`。 ## 运行形态 diff --git a/docs/progress/todo.md b/docs/progress/todo.md index 7c043b12a..7910b0e99 100644 --- a/docs/progress/todo.md +++ b/docs/progress/todo.md @@ -12,6 +12,11 @@ - [done] `desktop/`:Electron 壳 - [done] `deploy/`:nginx 配置与 Compose +## 已完成(迭代) + +- [done] 配置与用户偏好页(`/settings`):模型渠道 API Keys(BYOK,密钥落库且只回显掩码) +- [done] 提示词偏好:按任务类型定制平台模板,支持跟随平台 / 追加要求 / 高级改写、拼接预览与恢复平台模板;任务类型与默认模板内置在 `backend/internal/prompts` + ## 下一批 - [todo] 画布持久化:画布 CRUD、节点/连线变更落库、多画布列表页 diff --git a/web/src/pages/canvas-list/index.tsx b/web/src/pages/canvas-list/index.tsx index 385da727d..aebae4fa4 100644 --- a/web/src/pages/canvas-list/index.tsx +++ b/web/src/pages/canvas-list/index.tsx @@ -1,5 +1,5 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; -import { Plus } from "lucide-react"; +import { Plus, Settings } from "lucide-react"; import { useNavigate } from "react-router"; import { createCanvas, listCanvases } from "@/services/api/canvas"; @@ -26,15 +26,25 @@ export function CanvasListPage() { AI 视频创作工作台

- +
+ + +
{canvasesQuery.isLoading ?

加载中…

: null} diff --git a/web/src/pages/canvas/index.tsx b/web/src/pages/canvas/index.tsx index be919e3e4..82540c423 100644 --- a/web/src/pages/canvas/index.tsx +++ b/web/src/pages/canvas/index.tsx @@ -1,5 +1,5 @@ import { useQuery } from "@tanstack/react-query"; -import { ArrowLeft } from "lucide-react"; +import { ArrowLeft, Settings } from "lucide-react"; import { useEffect } from "react"; import { useNavigate, useParams } from "react-router"; import { InfiniteCanvas } from "@/components/canvas/infinite-canvas"; @@ -65,6 +65,14 @@ export function CanvasPage() { {canvasQuery.data?.name ?? (canvasQuery.isError ? "画布加载失败" : "加载中…")} +
diff --git a/web/src/pages/settings/api-keys-section.tsx b/web/src/pages/settings/api-keys-section.tsx new file mode 100644 index 000000000..ecaf79db7 --- /dev/null +++ b/web/src/pages/settings/api-keys-section.tsx @@ -0,0 +1,187 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Plus, Save, Trash2 } from "lucide-react"; +import { useEffect, useState } from "react"; +import { TextField } from "./form-field"; +import { getPreference, updatePreference } from "@/services/api/preference"; +import { readErrorMessage } from "@/services/http"; +import type { APIKeyDraft, Preference, PreferencePayload } from "@/types/preference"; + +function toDrafts(preference: Preference): APIKeyDraft[] { + // 密钥不回显:apiKey 始终为空,留空提交时后端沿用旧值。 + return preference.apiKeys.map((item) => ({ ...item, apiKey: "" })); +} + +function toPayload(drafts: APIKeyDraft[]): PreferencePayload { + return { + apiKeys: drafts.map(({ id, provider, label, baseUrl, apiKey, model, enabled }) => ({ + id, + provider, + label, + baseUrl, + apiKey, + model, + enabled, + })), + }; +} + +export function ApiKeysSection() { + const queryClient = useQueryClient(); + const preferenceQuery = useQuery({ queryKey: ["preference"], queryFn: getPreference }); + + const [drafts, setDrafts] = useState([]); + const [savedAt, setSavedAt] = useState(null); + + useEffect(() => { + if (preferenceQuery.data) setDrafts(toDrafts(preferenceQuery.data)); + }, [preferenceQuery.data]); + + const saveMutation = useMutation({ + mutationFn: (payload: PreferencePayload) => updatePreference(payload), + onSuccess: (data) => { + queryClient.setQueryData(["preference"], data); + setDrafts(toDrafts(data)); + setSavedAt(Date.now()); + }, + }); + + function applyDrafts(next: APIKeyDraft[]) { + setDrafts(next); + setSavedAt(null); + } + + function updateItem(id: string, patch: Partial) { + applyDrafts(drafts.map((item) => (item.id === id ? { ...item, ...patch } : item))); + } + + function addItem() { + applyDrafts([ + ...drafts, + { + id: crypto.randomUUID(), + provider: "openai-compatible", + label: "", + baseUrl: "", + model: "", + enabled: true, + hasKey: false, + keyMask: "", + apiKey: "", + }, + ]); + } + + return ( +
+
+
+

模型渠道 API Keys

+

+ 密钥保存在本机后端数据库,读取时只回显掩码;输入框留空表示沿用已保存的密钥。 +

+
+ +
+ + {preferenceQuery.isError ? ( +

渠道配置加载失败,请确认后端已启动。

+ ) : null} + + {drafts.length === 0 ? ( +

+ 还没有配置渠道。未配置时使用服务端环境变量里的默认渠道。 +

+ ) : null} + +
    + {drafts.map((item, index) => ( +
  • +
    + 渠道 {index + 1} +
    + + +
    +
    + +
    + updateItem(item.id, { provider: value })} + placeholder="openai-compatible" + /> + updateItem(item.id, { label: value })} + placeholder="例如:自建中转" + /> + updateItem(item.id, { baseUrl: value })} + placeholder="https://api.example.com/v1" + /> + updateItem(item.id, { model: value })} + placeholder="例如:gpt-image-1" + /> +
    + updateItem(item.id, { apiKey: value })} + placeholder={item.hasKey ? `已保存 ${item.keyMask},留空不修改` : "sk-..."} + /> +
    +
    +
  • + ))} +
+ +
+ {savedAt ? 已保存 : null} + {saveMutation.isError ? ( + 保存失败:{readErrorMessage(saveMutation.error)} + ) : null} + +
+
+ ); +} diff --git a/web/src/pages/settings/form-field.tsx b/web/src/pages/settings/form-field.tsx new file mode 100644 index 000000000..42fd2d649 --- /dev/null +++ b/web/src/pages/settings/form-field.tsx @@ -0,0 +1,23 @@ +interface TextFieldProps { + label: string; + value: string; + onChange: (value: string) => void; + placeholder?: string; + type?: "text" | "password" | "url"; +} + +export function TextField({ label, value, onChange, placeholder, type = "text" }: TextFieldProps) { + return ( + + ); +} diff --git a/web/src/pages/settings/index.tsx b/web/src/pages/settings/index.tsx new file mode 100644 index 000000000..eb5d27fc0 --- /dev/null +++ b/web/src/pages/settings/index.tsx @@ -0,0 +1,32 @@ +import { ArrowLeft } from "lucide-react"; +import { useNavigate } from "react-router"; +import { ApiKeysSection } from "./api-keys-section"; +import { PromptPreferencesSection } from "./prompt-preferences-section"; + +export function SettingsPage() { + const navigate = useNavigate(); + + return ( +
+
+ +
+

配置与用户偏好

+

+ 管理模型渠道密钥与提示词偏好,各分区独立保存 +

+
+
+ + + +
+ ); +} diff --git a/web/src/pages/settings/prompt-preferences-section.tsx b/web/src/pages/settings/prompt-preferences-section.tsx new file mode 100644 index 000000000..a3ecb7cb4 --- /dev/null +++ b/web/src/pages/settings/prompt-preferences-section.tsx @@ -0,0 +1,275 @@ +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import { Check, Copy, RotateCcw, Save } from "lucide-react"; +import { useEffect, useState } from "react"; +import { cn } from "@/lib/utils"; +import { + customizePrompt, + listPromptPreferences, + resetPromptCustomization, +} from "@/services/api/prompt"; +import { readErrorMessage } from "@/services/http"; +import type { PromptCustomizationMode, PromptPreference } from "@/types/prompt"; + +const MODE_OPTIONS: { value: PromptCustomizationMode; label: string; description: string }[] = [ + { value: "inherit", label: "跟随平台", description: "直接使用平台默认模板" }, + { value: "append", label: "追加要求", description: "在平台模板后追加个人要求" }, + { value: "rewrite", label: "高级改写", description: "完全使用自己的提示词" }, +]; + +export function PromptPreferencesSection() { + const queryClient = useQueryClient(); + const preferencesQuery = useQuery({ queryKey: ["prompts"], queryFn: listPromptPreferences }); + + const preferences = preferencesQuery.data?.preferences ?? []; + const [activeOperation, setActiveOperation] = useState(""); + const active: PromptPreference | undefined = + preferences.find((item) => item.definition.operation === activeOperation) ?? preferences[0]; + + const [mode, setMode] = useState("inherit"); + const [appendContent, setAppendContent] = useState(""); + const [rewriteContent, setRewriteContent] = useState(""); + const [savedAt, setSavedAt] = useState(null); + const [copied, setCopied] = useState(false); + + // 选中任务类型或服务端数据变化时,用已保存的定制重置草稿。 + useEffect(() => { + const customization = active?.customization; + setMode(customization?.mode ?? "inherit"); + setAppendContent(customization?.mode === "append" ? customization.content : ""); + setRewriteContent( + customization?.mode === "rewrite" ? customization.content : (active?.template?.content ?? ""), + ); + setSavedAt(null); + }, [active]); + + const savedMode = active?.customization?.mode ?? "inherit"; + const savedAppend = savedMode === "append" ? (active?.customization?.content ?? "") : ""; + const savedRewrite = + savedMode === "rewrite" + ? (active?.customization?.content ?? "") + : (active?.template?.content ?? ""); + const draftContent = mode === "append" ? appendContent : mode === "rewrite" ? rewriteContent : ""; + const savedContent = savedMode === "append" ? savedAppend : savedMode === "rewrite" ? savedRewrite : ""; + const dirty = mode !== savedMode || draftContent !== savedContent; + + const templateContent = active?.template?.content ?? "当前没有可用的平台模板"; + const previewContent = + mode === "inherit" + ? templateContent + : mode === "append" + ? `${templateContent}\n\n【用户个性化创作要求】\n${appendContent}` + : rewriteContent; + + const saveMutation = useMutation({ + mutationFn: (input: { operation: string; mode: PromptCustomizationMode; content: string }) => + customizePrompt(input.operation, { mode: input.mode, content: input.content }), + onSuccess: (data) => { + const updated = data.preference; + queryClient.setQueryData<{ preferences: PromptPreference[] }>(["prompts"], (current) => + current + ? { + preferences: current.preferences.map((item) => + item.definition.operation === updated.definition.operation ? updated : item, + ), + } + : current, + ); + setSavedAt(Date.now()); + }, + }); + + const resetMutation = useMutation({ + mutationFn: (operation: string) => resetPromptCustomization(operation), + onSuccess: () => queryClient.invalidateQueries({ queryKey: ["prompts"] }), + }); + + function selectOperation(operation: string) { + if (operation === active?.definition.operation) return; + if (dirty && !window.confirm("当前任务类型还有未保存的修改,切换后将丢失。确定切换吗?")) return; + setActiveOperation(operation); + } + + function handleSave() { + if (!active) return; + saveMutation.mutate({ operation: active.definition.operation, mode, content: draftContent }); + } + + function handleReset() { + if (!active) return; + if (!window.confirm(`将删除「${active.definition.label}」的个人定制,后续跟随平台模板。确定恢复吗?`)) { + return; + } + resetMutation.mutate(active.definition.operation); + } + + async function handleCopy() { + try { + await navigator.clipboard.writeText(previewContent); + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + } catch { + // 剪贴板不可用时忽略 + } + } + + const busy = saveMutation.isPending || resetMutation.isPending; + + return ( +
+

提示词偏好

+

+ 按任务类型定制平台提示词模板。生成时按这里的配置组装最终提示词,可随时恢复平台模板。 +

+ + {preferencesQuery.isError ? ( +

提示词偏好加载失败,请确认后端已启动。

+ ) : null} + + {preferences.length === 0 && !preferencesQuery.isError ? ( +

加载中…

+ ) : null} + + {preferences.length > 0 ? ( +
+ {preferences.map((item) => ( + + ))} +
+ ) : null} + + {active ? ( + <> +
+
+ {active.definition.label} + + {active.definition.category} + + + 平台模板 v{active.template?.version ?? 1} + + {active.outdated ? ( + 平台模板已更新,建议复核定制内容 + ) : null} +
+

{active.definition.description}

+ {active.definition.variables.length > 0 ? ( +

+ 可用变量:{active.definition.variables.map((variable) => variable.placeholder).join(" ")} +

+ ) : null} +
+ +
+ {MODE_OPTIONS.map((option) => ( + + ))} +
+ + {mode === "inherit" ? ( +

+ 当前跟随平台模板,生成时直接使用平台默认内容,无需填写。 +

+ ) : ( +
+ + {mode === "append" ? "个人要求(追加在平台模板之后)" : "个人提示词(完全替换平台模板)"} + +