feat: 新增配置与提示词偏好页

后端新增 preferences 与 prompt_customizations 表及对应接口,
支持 BYOK 模型渠道密钥落库(仅回显掩码)与按任务类型定制
平台提示词模板;前端新增 /settings 页面及入口。
This commit is contained in:
tongtong committed 2026-09-21 14:29:54 +08:00
1 parent ae6cdf1551
commit b9df2f84ab
27 files changed
+1515 -22

No files matched your search

+20
View File
@@ -38,6 +38,26 @@
- **动效优先纯 CSS**,不要为了视觉效果引入 Three.js。Three.js 只在 3D 导演台功能中按需引入。 - **动效优先纯 CSS**,不要为了视觉效果引入 Three.js。Three.js 只在 3D 导演台功能中按需引入。
- 协作跟随(follow mode)是低成本高感知功能,纳入后续迭代候选。 - 协作跟随(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/` ### 前端 `web/`
+9 -5
View File
@@ -38,6 +38,8 @@ func main() {
canvasRepo := repository.NewCanvasRepository(db) canvasRepo := repository.NewCanvasRepository(db)
taskRepo := repository.NewTaskRepository(db) taskRepo := repository.NewTaskRepository(db)
preferenceRepo := repository.NewPreferenceRepository(db)
promptRepo := repository.NewPromptRepository(db)
broker := sse.NewBroker() broker := sse.NewBroker()
store, err := storage.NewLocal(cfg.FilesDir(), cfg.PublicBaseURL) store, err := storage.NewLocal(cfg.FilesDir(), cfg.PublicBaseURL)
@@ -58,11 +60,13 @@ func main() {
taskService.SetController(pool) taskService.SetController(pool)
router := handler.NewRouter(handler.Deps{ router := handler.NewRouter(handler.Deps{
Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)), Canvas: handler.NewCanvasHandler(service.NewCanvasService(canvasRepo)),
Task: handler.NewTaskHandler(taskService), Task: handler.NewTaskHandler(taskService),
Event: handler.NewEventHandler(broker), Event: handler.NewEventHandler(broker),
Config: cfg, Preference: handler.NewPreferenceHandler(service.NewPreferenceService(preferenceRepo)),
FileDir: store.Root(), Prompt: handler.NewPromptHandler(service.NewPromptService(promptRepo)),
Config: cfg,
FileDir: store.Root(),
}) })
server := &http.Server{ server := &http.Server{
+6 -1
View File
@@ -28,7 +28,12 @@ func Open(cfg config.Config) (*gorm.DB, error) {
return nil, err 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 return nil, err
} }
+41
View File
@@ -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)
}
+52
View File
@@ -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})
}
+14 -5
View File
@@ -14,11 +14,13 @@ import (
) )
type Deps struct { type Deps struct {
Canvas *CanvasHandler Canvas *CanvasHandler
Task *TaskHandler Task *TaskHandler
Event *EventHandler Event *EventHandler
Config config.Config Preference *PreferenceHandler
FileDir string Prompt *PromptHandler
Config config.Config
FileDir string
} }
func NewRouter(deps Deps) *gin.Engine { func NewRouter(deps Deps) *gin.Engine {
@@ -42,6 +44,13 @@ func NewRouter(deps Deps) *gin.Engine {
api.GET("/tasks", deps.Task.List) api.GET("/tasks", deps.Task.List)
api.POST("/tasks", deps.Task.Create) api.POST("/tasks", deps.Task.Create)
api.POST("/tasks/:id/cancel", deps.Task.Cancel) 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 != "" { if deps.FileDir != "" {
+27
View File
@@ -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"`
}
+25
View File
@@ -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"`
}
+219
View File
@@ -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
}
+35
View File
@@ -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
}
+50
View File
@@ -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
}
+190
View File
@@ -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 != ""
}
+143
View File
@@ -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
}
+2
View File
@@ -34,6 +34,8 @@
- **参考素材传 ID 不传 base64**:媒体一律进存储层,画布节点只引用 URL。 - **参考素材传 ID 不传 base64**:媒体一律进存储层,画布节点只引用 URL。
- **Provider 统一接口**:新增渠道只实现 `internal/provider` 的接口,不在 service 里写厂商分支。 - **Provider 统一接口**:新增渠道只实现 `internal/provider` 的接口,不在 service 里写厂商分支。
- **存储接口化**:本地磁盘与 S3-compatible 实现同一接口,通过配置切换。 - **存储接口化**:本地磁盘与 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`。
## 运行形态 ## 运行形态
+5
View File
@@ -12,6 +12,11 @@
- [done] `desktop/`:Electron 壳 - [done] `desktop/`:Electron 壳
- [done] `deploy/`:nginx 配置与 Compose - [done] `deploy/`:nginx 配置与 Compose
## 已完成(迭代)
- [done] 配置与用户偏好页(`/settings`):模型渠道 API Keys(BYOK,密钥落库且只回显掩码)
- [done] 提示词偏好:按任务类型定制平台模板,支持跟随平台 / 追加要求 / 高级改写、拼接预览与恢复平台模板;任务类型与默认模板内置在 `backend/internal/prompts`
## 下一批 ## 下一批
- [todo] 画布持久化:画布 CRUD、节点/连线变更落库、多画布列表页 - [todo] 画布持久化:画布 CRUD、节点/连线变更落库、多画布列表页
+20 -10
View File
@@ -1,5 +1,5 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; 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 { useNavigate } from "react-router";
import { createCanvas, listCanvases } from "@/services/api/canvas"; import { createCanvas, listCanvases } from "@/services/api/canvas";
@@ -26,15 +26,25 @@ export function CanvasListPage() {
AI 视频创作工作台 AI 视频创作工作台
</p> </p>
</div> </div>
<button <div className="flex items-center gap-2">
type="button" <button
onClick={() => createMutation.mutate()} type="button"
disabled={createMutation.isPending} onClick={() => navigate("/settings")}
className="flex items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-sm text-white transition hover:opacity-90 disabled:opacity-50" className="flex items-center gap-1.5 rounded-md border border-[var(--color-panel-border)] px-3 py-1.5 text-sm text-[var(--color-ink-muted)] transition hover:border-[var(--color-accent)] hover:text-[var(--color-ink)]"
> >
<Plus className="h-4 w-4" /> <Settings className="h-4 w-4" />
新建画布 配置
</button> </button>
<button
type="button"
onClick={() => createMutation.mutate()}
disabled={createMutation.isPending}
className="flex items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-sm text-white transition hover:opacity-90 disabled:opacity-50"
>
<Plus className="h-4 w-4" />
新建画布
</button>
</div>
</header> </header>
{canvasesQuery.isLoading ? <p className="text-sm text-[var(--color-ink-muted)]">加载中…</p> : null} {canvasesQuery.isLoading ? <p className="text-sm text-[var(--color-ink-muted)]">加载中…</p> : null}
+9 -1
View File
@@ -1,5 +1,5 @@
import { useQuery } from "@tanstack/react-query"; import { useQuery } from "@tanstack/react-query";
import { ArrowLeft } from "lucide-react"; import { ArrowLeft, Settings } from "lucide-react";
import { useEffect } from "react"; import { useEffect } from "react";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { InfiniteCanvas } from "@/components/canvas/infinite-canvas"; import { InfiniteCanvas } from "@/components/canvas/infinite-canvas";
@@ -65,6 +65,14 @@ export function CanvasPage() {
<span className="text-sm font-medium"> <span className="text-sm font-medium">
{canvasQuery.data?.name ?? (canvasQuery.isError ? "画布加载失败" : "加载中…")} {canvasQuery.data?.name ?? (canvasQuery.isError ? "画布加载失败" : "加载中…")}
</span> </span>
<button
type="button"
onClick={() => navigate("/settings")}
className="ml-auto flex items-center gap-1 text-xs text-[var(--color-ink-muted)] transition hover:text-[var(--color-ink)]"
>
<Settings className="h-3.5 w-3.5" />
配置
</button>
</header> </header>
<div className="flex min-h-0 flex-1"> <div className="flex min-h-0 flex-1">
+187
View File
@@ -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<APIKeyDraft[]>([]);
const [savedAt, setSavedAt] = useState<number | null>(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<APIKeyDraft>) {
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 (
<section className="rounded-lg border border-[var(--color-panel-border)] bg-[var(--color-panel)] p-4">
<header className="flex items-start justify-between gap-3">
<div>
<h2 className="text-sm font-medium">模型渠道 API Keys</h2>
<p className="mt-0.5 text-xs text-[var(--color-ink-muted)]">
密钥保存在本机后端数据库,读取时只回显掩码;输入框留空表示沿用已保存的密钥。
</p>
</div>
<button
type="button"
onClick={addItem}
className="flex shrink-0 items-center gap-1.5 rounded-md border border-[var(--color-panel-border)] px-2.5 py-1.5 text-xs text-[var(--color-ink-muted)] transition hover:border-[var(--color-accent)] hover:text-[var(--color-ink)]"
>
<Plus className="h-3.5 w-3.5" />
添加渠道
</button>
</header>
{preferenceQuery.isError ? (
<p className="mt-3 text-xs text-red-600">渠道配置加载失败,请确认后端已启动。</p>
) : null}
{drafts.length === 0 ? (
<p className="mt-4 text-xs text-[var(--color-ink-muted)]">
还没有配置渠道。未配置时使用服务端环境变量里的默认渠道。
</p>
) : null}
<ul className="mt-4 flex flex-col gap-3">
{drafts.map((item, index) => (
<li key={item.id} className="rounded-md border border-[var(--color-panel-border)] p-3">
<div className="flex items-center justify-between gap-2">
<span className="text-xs font-medium">渠道 {index + 1}</span>
<div className="flex items-center gap-3">
<label className="flex cursor-pointer items-center gap-1.5 text-xs text-[var(--color-ink-muted)]">
<input
type="checkbox"
checked={item.enabled}
onChange={(event) => updateItem(item.id, { enabled: event.target.checked })}
className="accent-[var(--color-accent)]"
/>
启用
</label>
<button
type="button"
onClick={() => applyDrafts(drafts.filter((draft) => draft.id !== item.id))}
title="删除渠道"
aria-label="删除渠道"
className="text-[var(--color-ink-muted)] transition hover:text-red-600"
>
<Trash2 className="h-3.5 w-3.5" />
</button>
</div>
</div>
<div className="mt-3 grid grid-cols-1 gap-3 sm:grid-cols-2">
<TextField
label="渠道标识"
value={item.provider}
onChange={(value) => updateItem(item.id, { provider: value })}
placeholder="openai-compatible"
/>
<TextField
label="显示名称"
value={item.label}
onChange={(value) => updateItem(item.id, { label: value })}
placeholder="例如:自建中转"
/>
<TextField
label="Base URL"
type="url"
value={item.baseUrl}
onChange={(value) => updateItem(item.id, { baseUrl: value })}
placeholder="https://api.example.com/v1"
/>
<TextField
label="默认模型"
value={item.model}
onChange={(value) => updateItem(item.id, { model: value })}
placeholder="例如:gpt-image-1"
/>
<div className="sm:col-span-2">
<TextField
label="API Key"
type="password"
value={item.apiKey}
onChange={(value) => updateItem(item.id, { apiKey: value })}
placeholder={item.hasKey ? `已保存 ${item.keyMask},留空不修改` : "sk-..."}
/>
</div>
</div>
</li>
))}
</ul>
<div className="mt-4 flex items-center justify-end gap-3">
{savedAt ? <span className="text-xs text-emerald-600">已保存</span> : null}
{saveMutation.isError ? (
<span className="text-xs text-red-600">保存失败:{readErrorMessage(saveMutation.error)}</span>
) : null}
<button
type="button"
onClick={() => saveMutation.mutate(toPayload(drafts))}
disabled={saveMutation.isPending}
className="flex shrink-0 items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-sm text-white transition hover:opacity-90 disabled:opacity-50"
>
<Save className="h-3.5 w-3.5" />
{saveMutation.isPending ? "保存中…" : "保存渠道配置"}
</button>
</div>
</section>
);
}
+23
View File
@@ -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 (
<label className="flex flex-col gap-1">
<span className="text-xs text-[var(--color-ink-muted)]">{label}</span>
<input
type={type}
value={value}
placeholder={placeholder}
autoComplete="off"
onChange={(event) => onChange(event.target.value)}
className="rounded-md border border-[var(--color-panel-border)] bg-[var(--color-panel)] px-2.5 py-1.5 text-sm outline-none transition focus:border-[var(--color-accent)]"
/>
</label>
);
}
+32
View File
@@ -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 (
<div className="mx-auto flex min-h-full w-full max-w-4xl flex-col gap-5 px-6 py-10">
<header className="flex items-start gap-3">
<button
type="button"
onClick={() => navigate("/")}
className="mt-1 flex items-center gap-1 text-xs text-[var(--color-ink-muted)] transition hover:text-[var(--color-ink)]"
>
<ArrowLeft className="h-3.5 w-3.5" />
画布列表
</button>
<div>
<h1 className="text-lg font-semibold">配置与用户偏好</h1>
<p className="mt-0.5 text-xs text-[var(--color-ink-muted)]">
管理模型渠道密钥与提示词偏好,各分区独立保存
</p>
</div>
</header>
<ApiKeysSection />
<PromptPreferencesSection />
</div>
);
}
@@ -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<PromptCustomizationMode>("inherit");
const [appendContent, setAppendContent] = useState("");
const [rewriteContent, setRewriteContent] = useState("");
const [savedAt, setSavedAt] = useState<number | null>(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 (
<section className="rounded-lg border border-[var(--color-panel-border)] bg-[var(--color-panel)] p-4">
<h2 className="text-sm font-medium">提示词偏好</h2>
<p className="mt-0.5 text-xs text-[var(--color-ink-muted)]">
按任务类型定制平台提示词模板。生成时按这里的配置组装最终提示词,可随时恢复平台模板。
</p>
{preferencesQuery.isError ? (
<p className="mt-3 text-xs text-red-600">提示词偏好加载失败,请确认后端已启动。</p>
) : null}
{preferences.length === 0 && !preferencesQuery.isError ? (
<p className="mt-4 text-xs text-[var(--color-ink-muted)]">加载中…</p>
) : null}
{preferences.length > 0 ? (
<div className="mt-4 flex flex-wrap gap-1.5">
{preferences.map((item) => (
<button
key={item.definition.operation}
type="button"
onClick={() => selectOperation(item.definition.operation)}
className={cn(
"flex items-center gap-1.5 rounded-md border px-2.5 py-1.5 text-xs transition",
item.definition.operation === active?.definition.operation
? "border-[var(--color-accent)] text-[var(--color-ink)]"
: "border-[var(--color-panel-border)] text-[var(--color-ink-muted)] hover:border-[var(--color-accent)] hover:text-[var(--color-ink)]",
)}
>
{item.definition.label}
{item.customization ? (
<span className="inline-block h-1.5 w-1.5 rounded-full bg-[var(--color-accent)]" />
) : null}
</button>
))}
</div>
) : null}
{active ? (
<>
<div className="mt-4 rounded-md border border-[var(--color-panel-border)] p-3">
<div className="flex flex-wrap items-center gap-2">
<span className="text-xs font-medium">{active.definition.label}</span>
<span className="rounded bg-black/5 px-1.5 py-0.5 text-[10px] text-[var(--color-ink-muted)]">
{active.definition.category}
</span>
<span className="rounded bg-black/5 px-1.5 py-0.5 text-[10px] text-[var(--color-ink-muted)]">
平台模板 v{active.template?.version ?? 1}
</span>
{active.outdated ? (
<span className="text-[10px] text-amber-600">平台模板已更新,建议复核定制内容</span>
) : null}
</div>
<p className="mt-1 text-xs text-[var(--color-ink-muted)]">{active.definition.description}</p>
{active.definition.variables.length > 0 ? (
<p className="mt-1.5 text-[11px] leading-relaxed text-[var(--color-ink-muted)]">
可用变量:{active.definition.variables.map((variable) => variable.placeholder).join(" ")}
</p>
) : null}
</div>
<div className="mt-4 grid grid-cols-1 gap-2 sm:grid-cols-3">
{MODE_OPTIONS.map((option) => (
<button
key={option.value}
type="button"
onClick={() => {
setMode(option.value);
setSavedAt(null);
}}
className={cn(
"rounded-md border px-3 py-2 text-left transition",
mode === option.value
? "border-[var(--color-accent)] bg-[var(--color-accent)]/5"
: "border-[var(--color-panel-border)] hover:border-[var(--color-accent)]",
)}
>
<span className="block text-xs font-medium">{option.label}</span>
<span className="mt-0.5 block text-[11px] leading-relaxed text-[var(--color-ink-muted)]">
{option.description}
</span>
</button>
))}
</div>
{mode === "inherit" ? (
<p className="mt-4 text-xs text-[var(--color-ink-muted)]">
当前跟随平台模板,生成时直接使用平台默认内容,无需填写。
</p>
) : (
<div className="mt-4 flex flex-col gap-1">
<span className="text-xs text-[var(--color-ink-muted)]">
{mode === "append" ? "个人要求(追加在平台模板之后)" : "个人提示词(完全替换平台模板)"}
</span>
<textarea
value={mode === "append" ? appendContent : rewriteContent}
onChange={(event) => {
if (mode === "append") setAppendContent(event.target.value);
else setRewriteContent(event.target.value);
setSavedAt(null);
}}
rows={9}
placeholder={mode === "append" ? "例如:镜头语言偏电影感,避免出现文字" : "以平台模板为起点改写"}
className="w-full resize-y rounded-md border border-[var(--color-panel-border)] bg-[var(--color-panel)] px-2.5 py-2 text-xs leading-relaxed outline-none transition focus:border-[var(--color-accent)]"
/>
</div>
)}
<div className="mt-4">
<div className="flex items-center justify-between">
<span className="text-xs text-[var(--color-ink-muted)]">生成时实际使用的提示词</span>
<button
type="button"
onClick={handleCopy}
className="flex items-center gap-1 text-[11px] text-[var(--color-ink-muted)] transition hover:text-[var(--color-ink)]"
>
{copied ? <Check className="h-3 w-3" /> : <Copy className="h-3 w-3" />}
{copied ? "已复制" : "复制"}
</button>
</div>
<pre className="mt-1.5 max-h-64 overflow-auto whitespace-pre-wrap rounded-md border border-[var(--color-panel-border)] bg-black/[0.02] p-3 text-[11px] leading-relaxed text-[var(--color-ink-muted)]">
{previewContent || "(空)"}
</pre>
</div>
<div className="mt-4 flex items-center justify-end gap-3">
{savedAt ? <span className="text-xs text-emerald-600">已保存</span> : null}
{saveMutation.isError ? (
<span className="text-xs text-red-600">保存失败:{readErrorMessage(saveMutation.error)}</span>
) : null}
{resetMutation.isError ? (
<span className="text-xs text-red-600">恢复失败:{readErrorMessage(resetMutation.error)}</span>
) : null}
{active.customization ? (
<button
type="button"
onClick={handleReset}
disabled={busy}
className="flex items-center gap-1.5 rounded-md border border-[var(--color-panel-border)] px-2.5 py-1.5 text-xs text-[var(--color-ink-muted)] transition hover:border-[var(--color-accent)] hover:text-[var(--color-ink)] disabled:opacity-50"
>
<RotateCcw className="h-3.5 w-3.5" />
恢复平台模板
</button>
) : null}
<button
type="button"
onClick={handleSave}
disabled={!dirty || busy}
className="flex shrink-0 items-center gap-1.5 rounded-md bg-[var(--color-accent)] px-3 py-1.5 text-sm text-white transition hover:opacity-90 disabled:opacity-50"
>
<Save className="h-3.5 w-3.5" />
{saveMutation.isPending ? "保存中…" : "保存提示词偏好"}
</button>
</div>
</>
) : null}
</section>
);
}
+2
View File
@@ -1,8 +1,10 @@
import { createBrowserRouter } from "react-router"; import { createBrowserRouter } from "react-router";
import { CanvasPage } from "@/pages/canvas"; import { CanvasPage } from "@/pages/canvas";
import { CanvasListPage } from "@/pages/canvas-list"; import { CanvasListPage } from "@/pages/canvas-list";
import { SettingsPage } from "@/pages/settings";
export const router = createBrowserRouter([ export const router = createBrowserRouter([
{ path: "/", element: <CanvasListPage /> }, { path: "/", element: <CanvasListPage /> },
{ path: "/canvas/:canvasId", element: <CanvasPage /> }, { path: "/canvas/:canvasId", element: <CanvasPage /> },
{ path: "/settings", element: <SettingsPage /> },
]); ]);
+13
View File
@@ -0,0 +1,13 @@
import { request } from "@/services/http";
import type { Preference, PreferencePayload } from "@/types/preference";
export function getPreference() {
return request<Preference>("/preferences");
}
export function updatePreference(payload: PreferencePayload) {
return request<Preference>("/preferences", {
method: "PUT",
body: JSON.stringify(payload),
});
}
+21
View File
@@ -0,0 +1,21 @@
import { request } from "@/services/http";
import type { PromptCustomizationMode, PromptPreference } from "@/types/prompt";
export function listPromptPreferences() {
return request<{ preferences: PromptPreference[] }>("/prompts");
}
/** 保存定制;mode 传 inherit 即放弃定制,后端会删除已有记录。 */
export function customizePrompt(
operation: string,
input: { mode: PromptCustomizationMode; content: string },
) {
return request<{ preference: PromptPreference }>(`/prompts/${encodeURIComponent(operation)}`, {
method: "PATCH",
body: JSON.stringify(input),
});
}
export function resetPromptCustomization(operation: string) {
return request<{ ok: boolean }>(`/prompts/${encodeURIComponent(operation)}`, { method: "DELETE" });
}
+12
View File
@@ -30,3 +30,15 @@ export async function request<T>(path: string, init: RequestInit = {}): Promise<
} }
export const apiBaseUrl = BASE_URL; export const apiBaseUrl = BASE_URL;
/** 后端错误体形如 {"error":"..."},取出来直接展示;解析失败时退回原始信息。 */
export function readErrorMessage(error: unknown, fallback = "请稍后重试"): string {
if (!(error instanceof Error)) return fallback;
try {
const parsed = JSON.parse(error.message) as { error?: string };
if (parsed?.error) return parsed.error;
} catch {
// 非 JSON 响应,退回原始信息
}
return error.message || fallback;
}
+35
View File
@@ -0,0 +1,35 @@
/** 服务端返回的渠道配置,只含掩码,不含明文密钥。 */
export interface APIKeyConfig {
id: string;
provider: string;
label: string;
baseUrl: string;
model: string;
enabled: boolean;
hasKey: boolean;
keyMask: string;
}
export interface Preference {
apiKeys: APIKeyConfig[];
updatedAt: string;
}
/** 表单内的渠道配置:`apiKey` 只在本地编辑,留空表示沿用已保存的密钥。 */
export interface APIKeyDraft extends APIKeyConfig {
apiKey: string;
}
export interface APIKeyPayload {
id: string;
provider: string;
label: string;
baseUrl: string;
apiKey: string;
model: string;
enabled: boolean;
}
export interface PreferencePayload {
apiKeys: APIKeyPayload[];
}
+48
View File
@@ -0,0 +1,48 @@
/** 提示词任务类型的输出形态。 */
export type PromptOutputType = "text" | "json";
/** 用户定制模式:跟随平台模板 / 在模板后追加要求 / 完全改写。 */
export type PromptCustomizationMode = "inherit" | "append" | "rewrite";
export interface PromptTemplateVariable {
label: string;
placeholder: string;
}
/** 一个提示词任务类型的元信息。任务类型由后端内置目录提供。 */
export interface PromptOperationDefinition {
operation: string;
label: string;
category: string;
description: string;
outputType: PromptOutputType;
variables: PromptTemplateVariable[];
}
/** 平台默认模板。 */
export interface PromptTemplate {
operation: string;
name: string;
version: number;
content: string;
outputType: PromptOutputType;
}
/** 用户对某个任务类型的提示词定制。 */
export interface PromptCustomization {
id: string;
operation: string;
mode: PromptCustomizationMode;
content: string;
baseTemplateVersion: number;
updatedAt: string;
}
/** 一个任务类型的完整提示词配置。 */
export interface PromptPreference {
definition: PromptOperationDefinition;
template: PromptTemplate | null;
customization?: PromptCustomization;
/** 定制依据的平台模板版本已落后于当前版本。 */
outdated: boolean;
}