feat: 完善创作工作台与用户诊断支持 (#295)

* feat(canvas): 参考素材 - 增加移除按钮并删除对应连线

* feat(canvas): 完善节点面板交互与拖拽反馈

* fix(canvas): 画布交互与小地图 - 统一浮层层级并完善节点识别

* feat(prompt-optimizer): 增加 AI 提示词优化器及宿主接入

* feat(canvas): 画布 - 增加自动整理节点按钮并补充文档

* chore(web): 前端 - 修正提示词优化器格式

* chore(backend): 后端 - 修正 Go 格式检查

* feat(workspace): 完善诊断导出与本地排障支持

* chore(web): 格式化诊断导出文件

* fix(web-test): 兼容 Bun 测试运行时

* fix(web-test): 对齐模型目录协议断言
This commit is contained in:
QAyong authored and GitHub committed 2026-08-25 13:49:15 +08:00
1 parent 625a97560b
commit cf6c78d540
70 files changed
+6863 -1708

No files matched your search

+4 -1
View File
@@ -67,6 +67,7 @@ func main() {
r.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
return fmt.Sprintf("%s - [%s] \"%s %s\" %d %s %s\n", param.ClientIP, param.TimeStamp.Format(time.RFC3339), param.Method, redactCanvasSharePath(param.Path), param.StatusCode, param.Latency, param.ErrorMessage)
}), gin.Recovery())
r.Use(handler.RequestCorrelationMiddleware())
corsMiddleware, err := cors()
if err != nil {
log.Fatal(err)
@@ -97,6 +98,7 @@ func main() {
handler.RegisterSessionRoutes(api, svc)
handler.RegisterSkillRoutes(api, svc)
handler.RegisterUserDataRoutes(api, svc)
handler.RegisterDiagnosticsRoutes(api, svc)
handler.RegisterPluginRoutes(api, svc)
handler.RegisterProtocolRoutes(api, svc)
projectAPI := api.Group("")
@@ -131,7 +133,7 @@ func env(key string, fallback string) string {
return value
}
const corsAllowedHeaders = "Accept, Content-Type, Authorization, X-Requested-With, X-Canvas-Scene, X-Idempotency-Key, X-Canvas-Upstream-URL, X-Canvas-Upstream-Format, X-Canvas-Allow-Local-Channel, X-Canvas-Upstream-Base-URL"
const corsAllowedHeaders = "Accept, Content-Type, Authorization, X-Requested-With, X-Canvas-Scene, X-Idempotency-Key, X-Canvas-Trace-ID, X-Canvas-Upstream-URL, X-Canvas-Upstream-Format, X-Canvas-Allow-Local-Channel, X-Canvas-Upstream-Base-URL"
const corsAllowedMethods = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
@@ -157,6 +159,7 @@ func cors() (gin.HandlerFunc, error) {
c.Header("Vary", "Origin, Access-Control-Request-Method, Access-Control-Request-Headers")
}
c.Header("Access-Control-Allow-Headers", corsAllowedHeaders)
c.Header("Access-Control-Expose-Headers", "X-Request-ID, X-Canvas-Trace-ID, X-Diagnostic-Bundle-ID, X-Diagnostic-Schema-Version")
c.Header("Access-Control-Allow-Methods", corsAllowedMethods)
c.Header("Access-Control-Max-Age", "86400")
if c.Request.Method == "OPTIONS" {
+1 -1
View File
@@ -783,7 +783,7 @@ func shortSystemProxyPath(rawPath string) (string, string, bool) {
// as a channel request when a business route returns 404.
func isReservedAPIPathPrefix(value string) bool {
switch strings.ToLower(strings.TrimSpace(value)) {
case "admin", "ai", "announcements", "assets", "auth", "canvas-projects", "channels", "features", "files", "model-catalog", "models", "oauth", "plugins", "projects", "protocols", "public", "resources", "sessions", "settings", "skills", "style-profiles", "tasks", "user-data", "voice-profiles", "wallet":
case "admin", "ai", "announcements", "assets", "auth", "canvas-projects", "channels", "diagnostics", "features", "files", "model-catalog", "models", "oauth", "plugins", "projects", "protocols", "public", "resources", "sessions", "settings", "skills", "style-profiles", "tasks", "user-data", "voice-profiles", "wallet":
return true
default:
return false
+57
View File
@@ -0,0 +1,57 @@
package handler
import (
"fmt"
"net/http"
"infinite-canvas/backend/internal/service"
"github.com/gin-gonic/gin"
)
func RegisterDiagnosticsRoutes(r *gin.RouterGroup, svc *service.Service) {
r.POST("/diagnostics/preview", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<20)
var req service.DiagnosticExportRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
preview, err := svc.PreviewDiagnosticBundle(user.ID, req)
if err != nil {
failService(c, err)
return
}
ok(c, preview)
})
r.POST("/diagnostics/export", func(c *gin.Context) {
user, err := currentUser(c, svc)
if err != nil {
failService(c, err)
return
}
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4<<20)
var req service.DiagnosticExportRequest
if err := c.ShouldBindJSON(&req); err != nil {
fail(c, http.StatusBadRequest, err)
return
}
bundle, err := svc.ExportDiagnosticBundle(user.ID, req)
if err != nil {
failService(c, err)
return
}
c.Header("Cache-Control", "private, no-store")
c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=%q", bundle.FileName))
c.Header("X-Diagnostic-Bundle-ID", bundle.BundleID)
c.Header("X-Diagnostic-Schema-Version", "1")
c.Data(http.StatusOK, "application/zip", bundle.Data)
})
}
@@ -0,0 +1,70 @@
package handler
import (
"crypto/rand"
"encoding/hex"
"regexp"
"strings"
"github.com/gin-gonic/gin"
)
const (
requestIDHeader = "X-Request-ID"
traceIDHeader = "X-Canvas-Trace-ID"
requestIDKey = "canvas.request_id"
traceIDKey = "canvas.trace_id"
)
var correlationIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,96}$`)
// RequestCorrelationMiddleware 为每个请求生成服务端 requestId,并保留一次业务操作的 traceId。
// requestId 不能被客户端覆盖;traceId 只接受有限字符集,避免把任意请求头内容写入日志和诊断包。
func RequestCorrelationMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
requestID := newCorrelationID("req")
traceID := normalizeCorrelationID(c.GetHeader(traceIDHeader))
if traceID == "" {
traceID = newCorrelationID("trace")
}
c.Set(requestIDKey, requestID)
c.Set(traceIDKey, traceID)
c.Header(requestIDHeader, requestID)
c.Header(traceIDHeader, traceID)
c.Next()
}
}
func RequestID(c *gin.Context) string {
if value, ok := c.Get(requestIDKey); ok {
if result, ok := value.(string); ok {
return result
}
}
return ""
}
func TraceID(c *gin.Context) string {
if value, ok := c.Get(traceIDKey); ok {
if result, ok := value.(string); ok {
return result
}
}
return ""
}
func normalizeCorrelationID(value string) string {
value = strings.TrimSpace(value)
if !correlationIDPattern.MatchString(value) {
return ""
}
return value
}
func newCorrelationID(prefix string) string {
var raw [12]byte
if _, err := rand.Read(raw[:]); err != nil {
return prefix + "-unavailable"
}
return prefix + "-" + hex.EncodeToString(raw[:])
}
+4
View File
@@ -43,6 +43,8 @@ func RegisterTaskRoutes(r *gin.RouterGroup, svc *service.Service) {
fail(c, http.StatusBadRequest, err)
return
}
req.TraceID = TraceID(c)
req.RequestID = RequestID(c)
task, err := svc.CreateTask(user.ID, req)
if err != nil {
fail(c, http.StatusBadRequest, err)
@@ -294,6 +296,8 @@ func RegisterSessionRoutes(r *gin.RouterGroup, svc *service.Service) {
fail(c, http.StatusBadRequest, err)
return
}
req.TraceID = TraceID(c)
req.RequestID = RequestID(c)
detail, err := svc.CreateSession(user.ID, req)
if err != nil {
fail(c, http.StatusBadRequest, err)
@@ -12,6 +12,7 @@ func TestShortSystemProxyPath(t *testing.T) {
{path: "/api/channel-1/chat/completions", channel: "channel-1", provider: "/chat/completions", ok: true},
{path: "/api/channel-1/v1/models", channel: "channel-1", provider: "/v1/models", ok: true},
{path: "/api/tasks/123", ok: false},
{path: "/api/diagnostics/export", ok: false},
{path: "/api/channel-1", ok: false},
{path: "/api//chat/completions", ok: false},
{path: "/other/channel-1/chat/completions", ok: false},
+14 -12
View File
@@ -6,18 +6,18 @@ import (
)
type ModelChannel struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36"`
Scope ChannelScope `json:"scope" gorm:"index;size:24"`
Enabled bool `json:"enabled" gorm:"index"`
Name string `json:"name" gorm:"size:80"`
BaseURL string `json:"baseUrl"`
AllowLocalChannel bool `json:"allowLocalChannel" gorm:"default:false"`
APIKey string `json:"-"`
SecretKey string `json:"-"`
APIFormat string `json:"apiFormat" gorm:"size:24"`
ConcurrencyLimit int `json:"concurrencyLimit"`
ModelsJSON string `json:"modelsJson" gorm:"type:text"`
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36"`
Scope ChannelScope `json:"scope" gorm:"index;size:24"`
Enabled bool `json:"enabled" gorm:"index"`
Name string `json:"name" gorm:"size:80"`
BaseURL string `json:"baseUrl"`
AllowLocalChannel bool `json:"allowLocalChannel" gorm:"default:false"`
APIKey string `json:"-"`
SecretKey string `json:"-"`
APIFormat string `json:"apiFormat" gorm:"size:24"`
ConcurrencyLimit int `json:"concurrencyLimit"`
ModelsJSON string `json:"modelsJson" gorm:"type:text"`
// RetiredModelsJSON 记录已被一个模型家族吸收的上游 SKU,防止目录拉取时重新创建重复记录。
RetiredModelsJSON string `json:"-" gorm:"type:text"`
HeadersJSON string `json:"-" gorm:"type:text"`
@@ -83,6 +83,8 @@ type ChannelModelPriceTier struct {
type ApiCallLog struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36;index:idx_api_logs_user_created,priority:1"`
TraceID string `json:"traceId,omitempty" gorm:"index;size:96"`
RequestID string `json:"requestId,omitempty" gorm:"index;size:96"`
UserDisplayName string `json:"userDisplayName,omitempty" gorm:"-"`
UserAccount string `json:"userAccount,omitempty" gorm:"-"`
ChannelID string `json:"channelId" gorm:"index;size:36;index:idx_api_logs_channel_created,priority:1"`
+6 -6
View File
@@ -32,12 +32,12 @@ type CreditLedgerEntry struct {
}
type BillingOrder struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"size:36;index;uniqueIndex:idx_billing_user_idempotency,priority:1"`
IdempotencyKey string `json:"idempotencyKey" gorm:"size:160;uniqueIndex:idx_billing_user_idempotency,priority:2"`
TaskID string `json:"taskId,omitempty" gorm:"index;size:36"`
ChannelID string `json:"channelId" gorm:"index;size:36"`
ChannelModelID string `json:"channelModelId" gorm:"index;size:36"`
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"size:36;index;uniqueIndex:idx_billing_user_idempotency,priority:1"`
IdempotencyKey string `json:"idempotencyKey" gorm:"size:160;uniqueIndex:idx_billing_user_idempotency,priority:2"`
TaskID string `json:"taskId,omitempty" gorm:"index;size:36"`
ChannelID string `json:"channelId" gorm:"index;size:36"`
ChannelModelID string `json:"channelModelId" gorm:"index;size:36"`
// PriceTierID/Version 记录任务实际命中的规格档;金额字段仍是不可变结算快照。
PriceTierID string `json:"priceTierId,omitempty" gorm:"index;size:36"`
PriceTierVersion int64 `json:"priceTierVersion"`
+16 -16
View File
@@ -85,21 +85,21 @@ type RouteAttempt struct {
// 当 pricePolicy = unified 时,用户价格由此 SKU 决定,而非渠道价格。
// SelectorJSON 统一使用结构化意图选择器,支持复杂的能力组合定价。
type LogicalModelPriceSKU struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
LogicalModelRevisionID string `json:"logicalModelRevisionId" gorm:"size:36;index;uniqueIndex:idx_logical_sku_active,priority:1,where:deleted_at IS NULL"`
Code string `json:"code" gorm:"size:80"`
Name string `json:"name" gorm:"size:160"`
SelectorKey string `json:"selectorKey" gorm:"size:500;not null;default:{};uniqueIndex:idx_logical_sku_active,priority:2,where:deleted_at IS NULL"`
SelectorJSON string `json:"-" gorm:"type:text;not null;default:{}"`
BillingMode string `json:"billingMode" gorm:"size:32"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
InputTokenPriceMicrocredits int64 `json:"inputTokenPriceMicrocredits"`
OutputTokenPriceMicrocredits int64 `json:"outputTokenPriceMicrocredits"`
CachedTokenPriceMicrocredits int64 `json:"cachedTokenPriceMicrocredits"`
Priority int `json:"priority" gorm:"index"`
Enabled bool `json:"enabled" gorm:"index"`
Version int `json:"version"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
ID string `json:"id" gorm:"primaryKey;size:36"`
LogicalModelRevisionID string `json:"logicalModelRevisionId" gorm:"size:36;index;uniqueIndex:idx_logical_sku_active,priority:1,where:deleted_at IS NULL"`
Code string `json:"code" gorm:"size:80"`
Name string `json:"name" gorm:"size:160"`
SelectorKey string `json:"selectorKey" gorm:"size:500;not null;default:{};uniqueIndex:idx_logical_sku_active,priority:2,where:deleted_at IS NULL"`
SelectorJSON string `json:"-" gorm:"type:text;not null;default:{}"`
BillingMode string `json:"billingMode" gorm:"size:32"`
UnitPriceMicrocredits int64 `json:"unitPriceMicrocredits"`
InputTokenPriceMicrocredits int64 `json:"inputTokenPriceMicrocredits"`
OutputTokenPriceMicrocredits int64 `json:"outputTokenPriceMicrocredits"`
CachedTokenPriceMicrocredits int64 `json:"cachedTokenPriceMicrocredits"`
Priority int `json:"priority" gorm:"index"`
Enabled bool `json:"enabled" gorm:"index"`
Version int `json:"version"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
DeletedAt *time.Time `json:"-" gorm:"index"`
}
+4
View File
@@ -5,6 +5,8 @@ import "time"
type Task struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36;index:idx_tasks_user_created,priority:1"`
TraceID string `json:"-" gorm:"index;size:96"`
RequestID string `json:"-" gorm:"index;size:96"`
SessionID string `json:"sessionId" gorm:"index;size:36"`
ProjectID string `json:"projectId" gorm:"index;size:80"`
Type string `json:"type" gorm:"index;size:64"`
@@ -82,6 +84,8 @@ type TaskLog struct {
ID string `json:"id" gorm:"primaryKey;size:36"`
UserID string `json:"userId" gorm:"index;size:36"`
TaskID string `json:"taskId" gorm:"index;size:36"`
TraceID string `json:"-" gorm:"index;size:96"`
RequestID string `json:"-" gorm:"index;size:96"`
Level string `json:"level" gorm:"size:24"`
Message string `json:"message"`
Payload string `json:"payload" gorm:"type:text"`
@@ -0,0 +1,63 @@
package repository
import (
"strings"
"time"
"infinite-canvas/backend/internal/model"
)
const (
diagnosticTaskLimit = 100
diagnosticTaskLogLimit = 2000
diagnosticAPICallLimit = 1000
)
func (r *Repository) DiagnosticTasks(userID string, from time.Time, to time.Time, taskID string, projectID string) ([]model.Task, error) {
var tasks []model.Task
query := r.db.Model(&model.Task{}).Select(
"id", "user_id", "trace_id", "request_id", "project_id", "type", "status", "stage", "progress",
"operation", "provider", "model", "logical_model_id", "provider_request_id", "error", "attempts",
"started_at", "completed_at", "created_at", "updated_at",
)
if taskID = strings.TrimSpace(taskID); taskID != "" {
query = query.Where("user_id = ? AND id = ?", userID, taskID)
} else {
query = query.Where("user_id = ? AND created_at >= ? AND created_at <= ?", userID, from, to)
if projectID = strings.TrimSpace(projectID); projectID != "" {
query = query.Where("project_id = ?", projectID)
}
}
err := query.Order("created_at asc").Limit(diagnosticTaskLimit).Find(&tasks).Error
return tasks, err
}
func (r *Repository) DiagnosticTaskLogs(userID string, from time.Time, to time.Time, taskID string, projectID string) ([]model.TaskLog, error) {
var logs []model.TaskLog
query := r.db.Where("user_id = ?", userID)
if taskID = strings.TrimSpace(taskID); taskID != "" {
query = query.Where("task_id = ?", taskID)
} else {
query = query.Where("created_at >= ? AND created_at <= ?", from, to)
if projectID = strings.TrimSpace(projectID); projectID != "" {
query = query.Where("task_id IN (SELECT id FROM tasks WHERE user_id = ? AND project_id = ?)", userID, projectID)
}
}
err := query.Order("created_at asc").Limit(diagnosticTaskLogLimit).Find(&logs).Error
return logs, err
}
func (r *Repository) DiagnosticAPICallLogs(userID string, from time.Time, to time.Time, taskID string, projectID string) ([]model.ApiCallLog, error) {
var logs []model.ApiCallLog
query := r.db.Where("user_id = ?", userID)
if taskID = strings.TrimSpace(taskID); taskID != "" {
query = query.Where("task_id = ?", taskID)
} else {
query = query.Where("created_at >= ? AND created_at <= ?", from, to)
if projectID = strings.TrimSpace(projectID); projectID != "" {
query = query.Where("task_id IN (SELECT id FROM tasks WHERE user_id = ? AND project_id = ?)", userID, projectID)
}
}
err := query.Omit("RequestBody", "ResponseBody").Order("created_at asc").Limit(diagnosticAPICallLimit).Find(&logs).Error
return logs, err
}
+570
View File
@@ -0,0 +1,570 @@
package service
import (
"archive/zip"
"bytes"
"encoding/json"
"errors"
"fmt"
"net/url"
"strings"
"time"
"infinite-canvas/backend/internal/model"
"gorm.io/gorm"
)
const (
diagnosticSchemaVersion = 1
diagnosticRedactionVersion = 1
diagnosticMaxWindow = 24 * time.Hour
diagnosticMaxClientEvents = 500
diagnosticMaxBundleBytes = 10 << 20
diagnosticMaxDescription = 1000
diagnosticMaxEventText = 4000
)
type DiagnosticClientEvent struct {
ID string `json:"id"`
Timestamp string `json:"timestamp"`
Level string `json:"level"`
Category string `json:"category"`
Code string `json:"code,omitempty"`
Message string `json:"message"`
Route string `json:"route,omitempty"`
DurationMs int64 `json:"durationMs,omitempty"`
HTTPStatus int `json:"httpStatus,omitempty"`
RequestID string `json:"requestId,omitempty"`
TraceID string `json:"traceId,omitempty"`
TaskID string `json:"taskId,omitempty"`
ProjectID string `json:"projectId,omitempty"`
CanvasID string `json:"canvasId,omitempty"`
Stack string `json:"stack,omitempty"`
}
type DiagnosticRuntime struct {
AppVersion string `json:"appVersion,omitempty"`
BuildCommit string `json:"buildCommit,omitempty"`
Browser string `json:"browser,omitempty"`
OS string `json:"os,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
type DiagnosticExportRequest struct {
From string `json:"from"`
To string `json:"to"`
TaskID string `json:"taskId,omitempty"`
ProjectID string `json:"projectId,omitempty"`
Description string `json:"description,omitempty"`
Runtime DiagnosticRuntime `json:"runtime"`
ClientEvents []DiagnosticClientEvent `json:"clientEvents"`
}
type DiagnosticPreview struct {
ClientEventLimit int `json:"clientEventLimit"`
TaskCount int `json:"taskCount"`
TaskLogCount int `json:"taskLogCount"`
APICallCount int `json:"apiCallCount"`
EstimatedBytes int64 `json:"estimatedBytes"`
WillTruncate bool `json:"willTruncate"`
}
type DiagnosticBundle struct {
BundleID string
FileName string
Data []byte
}
type diagnosticWindow struct {
From time.Time
To time.Time
}
type diagnosticCollection struct {
Window diagnosticWindow
Description string
TaskID string
ProjectID string
Runtime diagnosticRuntimeRecord
ClientEvents []diagnosticClientEventRecord
Tasks []diagnosticTaskRecord
TaskLogs []diagnosticTaskLogRecord
APICalls []diagnosticAPICallRecord
Truncated bool
}
type diagnosticRuntimeRecord struct {
AppVersion string `json:"appVersion,omitempty"`
BuildCommit string `json:"buildCommit,omitempty"`
Browser string `json:"browser,omitempty"`
OS string `json:"os,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
type diagnosticClientEventRecord struct {
ID string `json:"id,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Level string `json:"level,omitempty"`
Category string `json:"category,omitempty"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Route string `json:"route,omitempty"`
DurationMs int64 `json:"durationMs,omitempty"`
HTTPStatus int `json:"httpStatus,omitempty"`
RequestID string `json:"requestId,omitempty"`
TraceID string `json:"traceId,omitempty"`
TaskID string `json:"taskId,omitempty"`
ProjectID string `json:"projectId,omitempty"`
CanvasID string `json:"canvasId,omitempty"`
Stack string `json:"stack,omitempty"`
}
type diagnosticTaskRecord struct {
ID string `json:"id"`
TraceID string `json:"traceId,omitempty"`
RequestID string `json:"requestId,omitempty"`
ProjectID string `json:"projectId,omitempty"`
Type string `json:"type,omitempty"`
Status string `json:"status,omitempty"`
Stage string `json:"stage,omitempty"`
Progress int `json:"progress,omitempty"`
Operation string `json:"operation,omitempty"`
Provider string `json:"provider,omitempty"`
Model string `json:"model,omitempty"`
LogicalModelID string `json:"logicalModelId,omitempty"`
ProviderRequestID string `json:"providerRequestId,omitempty"`
Error string `json:"error,omitempty"`
Attempts int `json:"attempts,omitempty"`
StartedAt *time.Time `json:"startedAt,omitempty"`
CompletedAt *time.Time `json:"completedAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
UpdatedAt time.Time `json:"updatedAt"`
}
type diagnosticTaskLogRecord struct {
ID string `json:"id"`
TaskID string `json:"taskId,omitempty"`
TraceID string `json:"traceId,omitempty"`
RequestID string `json:"requestId,omitempty"`
Level string `json:"level,omitempty"`
Message string `json:"message,omitempty"`
Payload string `json:"payload,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
type diagnosticAPICallRecord struct {
ID string `json:"id"`
TraceID string `json:"traceId,omitempty"`
RequestID string `json:"requestId,omitempty"`
ChannelID string `json:"channelId,omitempty"`
TaskID string `json:"taskId,omitempty"`
Source string `json:"source,omitempty"`
Capability string `json:"capability,omitempty"`
Operation string `json:"operation,omitempty"`
RequestKind string `json:"requestKind,omitempty"`
APIFormat string `json:"apiFormat,omitempty"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Model string `json:"model,omitempty"`
Status string `json:"status,omitempty"`
StatusCode int `json:"statusCode,omitempty"`
DurationMs int64 `json:"durationMs,omitempty"`
PollCount int `json:"pollCount,omitempty"`
ProviderStatus string `json:"providerStatus,omitempty"`
ProviderRequestID string `json:"providerRequestId,omitempty"`
ErrorCode string `json:"errorCode,omitempty"`
Error string `json:"error,omitempty"`
StartedAt time.Time `json:"startedAt"`
CreatedAt time.Time `json:"createdAt"`
}
type diagnosticManifest struct {
SchemaVersion int `json:"schemaVersion"`
BundleID string `json:"bundleId"`
GeneratedAt time.Time `json:"generatedAt"`
AppVersion string `json:"appVersion,omitempty"`
BuildCommit string `json:"buildCommit,omitempty"`
TimeRange diagnosticTimeRange `json:"timeRange"`
TaskID string `json:"taskId,omitempty"`
ProjectID string `json:"projectId,omitempty"`
Description string `json:"description,omitempty"`
RedactionVersion int `json:"redactionVersion"`
Truncated bool `json:"truncated,omitempty"`
Counts diagnosticCounts `json:"counts"`
}
type diagnosticTimeRange struct {
From time.Time `json:"from"`
To time.Time `json:"to"`
}
type diagnosticCounts struct {
ClientEvents int `json:"clientEvents"`
Tasks int `json:"tasks"`
TaskLogs int `json:"taskLogs"`
APICalls int `json:"upstreamCalls"`
}
func (s *Service) PreviewDiagnosticBundle(userID string, req DiagnosticExportRequest) (*DiagnosticPreview, error) {
collection, err := s.collectDiagnosticData(userID, req)
if err != nil {
return nil, err
}
return &DiagnosticPreview{
ClientEventLimit: diagnosticMaxClientEvents,
TaskCount: len(collection.Tasks), TaskLogCount: len(collection.TaskLogs), APICallCount: len(collection.APICalls),
EstimatedBytes: int64(2048 + len(collection.ClientEvents)*420 + len(collection.Tasks)*620 + len(collection.TaskLogs)*700 + len(collection.APICalls)*520),
WillTruncate: collection.Truncated,
}, nil
}
func (s *Service) ExportDiagnosticBundle(userID string, req DiagnosticExportRequest) (*DiagnosticBundle, error) {
collection, err := s.collectDiagnosticData(userID, req)
if err != nil {
return nil, err
}
bundleID := "DIAG_" + strings.ToUpper(newID()[:8])
manifest := diagnosticManifest{
SchemaVersion: diagnosticSchemaVersion, BundleID: bundleID, GeneratedAt: time.Now().UTC(),
AppVersion: collection.Runtime.AppVersion, BuildCommit: collection.Runtime.BuildCommit,
TimeRange: diagnosticTimeRange{From: collection.Window.From, To: collection.Window.To},
TaskID: collection.TaskID, ProjectID: collection.ProjectID, Description: collection.Description,
RedactionVersion: diagnosticRedactionVersion, Truncated: collection.Truncated,
Counts: diagnosticCounts{ClientEvents: len(collection.ClientEvents), Tasks: len(collection.Tasks), TaskLogs: len(collection.TaskLogs), APICalls: len(collection.APICalls)},
}
data, err := buildDiagnosticZIP(bundleID, manifest, collection)
if err != nil {
return nil, err
}
if len(data) > diagnosticMaxBundleBytes {
return nil, BadAuthRequest("诊断包超过 10 MB,请缩短时间范围后重试")
}
fileName := fmt.Sprintf("yingce-diagnostics-%s-%s.zip", time.Now().UTC().Format("20060102-150405"), bundleID)
return &DiagnosticBundle{BundleID: bundleID, FileName: fileName, Data: data}, nil
}
func (s *Service) collectDiagnosticData(userID string, req DiagnosticExportRequest) (*diagnosticCollection, error) {
window, err := normalizeDiagnosticWindow(req.From, req.To)
if err != nil {
return nil, err
}
taskID := strings.TrimSpace(req.TaskID)
projectID := strings.TrimSpace(req.ProjectID)
if len(taskID) > 96 || len(projectID) > 96 {
return nil, BadAuthRequest("诊断上下文无效")
}
if taskID != "" {
task, taskErr := s.repo.TaskForUser(userID, taskID)
if errors.Is(taskErr, gorm.ErrRecordNotFound) {
return nil, BadAuthRequest("任务不存在或无权访问")
}
if taskErr != nil {
return nil, taskErr
}
if projectID != "" && task.ProjectID != projectID {
return nil, BadAuthRequest("任务不属于当前项目")
}
if projectID == "" {
projectID = task.ProjectID
}
}
tasks, err := s.repo.DiagnosticTasks(userID, window.From, window.To, taskID, projectID)
if err != nil {
return nil, err
}
taskLogs, err := s.repo.DiagnosticTaskLogs(userID, window.From, window.To, taskID, projectID)
if err != nil {
return nil, err
}
apiCalls, err := s.repo.DiagnosticAPICallLogs(userID, window.From, window.To, taskID, projectID)
if err != nil {
return nil, err
}
clientEvents := req.ClientEvents
truncated := false
if len(clientEvents) > diagnosticMaxClientEvents {
clientEvents = clientEvents[len(clientEvents)-diagnosticMaxClientEvents:]
truncated = true
}
collection := &diagnosticCollection{
Window: window, Description: redactDiagnosticText(req.Description, diagnosticMaxDescription), TaskID: taskID, ProjectID: projectID, Truncated: truncated,
Runtime: diagnosticRuntimeRecord{
AppVersion: redactDiagnosticText(req.Runtime.AppVersion, 120), BuildCommit: redactDiagnosticText(req.Runtime.BuildCommit, 120),
Browser: redactDiagnosticText(req.Runtime.Browser, 240), OS: redactDiagnosticText(req.Runtime.OS, 120), Timezone: redactDiagnosticText(req.Runtime.Timezone, 80),
},
}
for _, event := range clientEvents {
collection.ClientEvents = append(collection.ClientEvents, sanitizeDiagnosticClientEvent(event))
}
for _, task := range tasks {
collection.Tasks = append(collection.Tasks, sanitizeDiagnosticTask(task))
}
for _, taskLog := range taskLogs {
collection.TaskLogs = append(collection.TaskLogs, sanitizeDiagnosticTaskLog(taskLog))
}
for _, apiCall := range apiCalls {
collection.APICalls = append(collection.APICalls, sanitizeDiagnosticAPICall(apiCall))
}
return collection, nil
}
func normalizeDiagnosticWindow(fromRaw string, toRaw string) (diagnosticWindow, error) {
now := time.Now().UTC()
from, to := now.Add(-30*time.Minute), now
var err error
if strings.TrimSpace(fromRaw) != "" {
from, err = time.Parse(time.RFC3339Nano, strings.TrimSpace(fromRaw))
if err != nil {
return diagnosticWindow{}, BadAuthRequest("诊断开始时间格式无效")
}
}
if strings.TrimSpace(toRaw) != "" {
to, err = time.Parse(time.RFC3339Nano, strings.TrimSpace(toRaw))
if err != nil {
return diagnosticWindow{}, BadAuthRequest("诊断结束时间格式无效")
}
}
from, to = from.UTC(), to.UTC()
if to.After(now) {
to = now
}
if !to.After(from) {
return diagnosticWindow{}, BadAuthRequest("诊断时间范围无效")
}
if to.Sub(from) > diagnosticMaxWindow {
return diagnosticWindow{}, BadAuthRequest("诊断时间范围不能超过 24 小时")
}
return diagnosticWindow{From: from, To: to}, nil
}
func sanitizeDiagnosticClientEvent(event DiagnosticClientEvent) diagnosticClientEventRecord {
return diagnosticClientEventRecord{
ID: sanitizeDiagnosticIdentifier(event.ID), Timestamp: redactDiagnosticText(event.Timestamp, 80), Level: redactDiagnosticText(event.Level, 24), Category: redactDiagnosticText(event.Category, 32),
Code: redactDiagnosticText(event.Code, 120), Message: redactDiagnosticText(event.Message, diagnosticMaxEventText), Route: sanitizeDiagnosticPath(event.Route),
DurationMs: boundedDiagnosticInt64(event.DurationMs, 0, 86_400_000), HTTPStatus: boundedDiagnosticInt(event.HTTPStatus, 0, 599),
RequestID: sanitizeDiagnosticIdentifier(event.RequestID), TraceID: sanitizeDiagnosticIdentifier(event.TraceID), TaskID: sanitizeDiagnosticIdentifier(event.TaskID), ProjectID: sanitizeDiagnosticIdentifier(event.ProjectID), CanvasID: sanitizeDiagnosticIdentifier(event.CanvasID),
Stack: redactDiagnosticText(event.Stack, diagnosticMaxEventText),
}
}
func sanitizeDiagnosticTask(task model.Task) diagnosticTaskRecord {
return diagnosticTaskRecord{
ID: task.ID, TraceID: sanitizeDiagnosticIdentifier(task.TraceID), RequestID: sanitizeDiagnosticIdentifier(task.RequestID), ProjectID: sanitizeDiagnosticIdentifier(task.ProjectID),
Type: redactDiagnosticText(task.Type, 80), Status: redactDiagnosticText(string(task.Status), 32), Stage: redactDiagnosticText(task.Stage, 160), Progress: boundedDiagnosticInt(task.Progress, 0, 100),
Operation: redactDiagnosticText(task.Operation, 120), Provider: redactDiagnosticText(task.Provider, 120), Model: redactDiagnosticText(task.Model, 160), LogicalModelID: sanitizeDiagnosticIdentifier(task.LogicalModelID),
ProviderRequestID: sanitizeDiagnosticIdentifier(task.ProviderRequestID), Error: redactDiagnosticText(task.Error, diagnosticMaxEventText), Attempts: boundedDiagnosticInt(task.Attempts, 0, 100),
StartedAt: task.StartedAt, CompletedAt: task.CompletedAt, CreatedAt: task.CreatedAt, UpdatedAt: task.UpdatedAt,
}
}
func sanitizeDiagnosticTaskLog(taskLog model.TaskLog) diagnosticTaskLogRecord {
return diagnosticTaskLogRecord{ID: taskLog.ID, TaskID: sanitizeDiagnosticIdentifier(taskLog.TaskID), TraceID: sanitizeDiagnosticIdentifier(taskLog.TraceID), RequestID: sanitizeDiagnosticIdentifier(taskLog.RequestID), Level: redactDiagnosticText(taskLog.Level, 24), Message: redactDiagnosticText(taskLog.Message, diagnosticMaxEventText), Payload: redactDiagnosticText(taskLog.Payload, diagnosticMaxEventText), CreatedAt: taskLog.CreatedAt}
}
func sanitizeDiagnosticAPICall(log model.ApiCallLog) diagnosticAPICallRecord {
return diagnosticAPICallRecord{
ID: log.ID, TraceID: sanitizeDiagnosticIdentifier(log.TraceID), RequestID: sanitizeDiagnosticIdentifier(log.RequestID), ChannelID: sanitizeDiagnosticIdentifier(log.ChannelID), TaskID: sanitizeDiagnosticIdentifier(log.TaskID),
Source: redactDiagnosticText(log.Source, 80), Capability: redactDiagnosticText(log.Capability, 48), Operation: redactDiagnosticText(log.Operation, 120), RequestKind: redactDiagnosticText(log.RequestKind, 48), APIFormat: redactDiagnosticText(log.APIFormat, 48),
Method: redactDiagnosticText(log.Method, 16), Path: sanitizeDiagnosticPath(log.Path), Model: redactDiagnosticText(log.Model, 160), Status: redactDiagnosticText(string(log.Status), 32), StatusCode: boundedDiagnosticInt(log.StatusCode, 0, 599),
DurationMs: boundedDiagnosticInt64(log.DurationMs, 0, 86_400_000), PollCount: boundedDiagnosticInt(log.PollCount, 0, 10000), ProviderStatus: redactDiagnosticText(log.ProviderStatus, 80),
ProviderRequestID: sanitizeDiagnosticIdentifier(log.ProviderRequestID), ErrorCode: redactDiagnosticText(log.ErrorCode, 120), Error: redactDiagnosticText(log.Error, diagnosticMaxEventText), StartedAt: log.StartedAt, CreatedAt: log.CreatedAt,
}
}
func buildDiagnosticZIP(bundleID string, manifest diagnosticManifest, collection *diagnosticCollection) ([]byte, error) {
var buffer bytes.Buffer
archive := zip.NewWriter(&buffer)
manifestData, err := json.MarshalIndent(manifest, "", " ")
if err != nil {
return nil, err
}
if err := writeDiagnosticZipFile(archive, "manifest.json", append(manifestData, byte(10))); err != nil {
return nil, err
}
newline := string(rune(10))
readme := fmt.Sprintf("影策用户诊断包%s%s诊断编号:%s%s时间范围:%s 至 %s%s%s该文件由用户主动导出,仅包含有限时间范围内的脱敏诊断摘要。%s", newline, newline, bundleID, newline, collection.Window.From.Format(time.RFC3339), collection.Window.To.Format(time.RFC3339), newline, newline, newline)
if err := writeDiagnosticZipFile(archive, "README.txt", []byte(readme)); err != nil {
return nil, err
}
if err := writeDiagnosticJSONL(archive, "client/events.jsonl", collection.ClientEvents); err != nil {
return nil, err
}
if err := writeDiagnosticJSONL(archive, "backend/tasks.jsonl", collection.Tasks); err != nil {
return nil, err
}
if err := writeDiagnosticJSONL(archive, "backend/task-logs.jsonl", collection.TaskLogs); err != nil {
return nil, err
}
if err := writeDiagnosticJSONL(archive, "backend/upstream-calls.jsonl", collection.APICalls); err != nil {
return nil, err
}
runtimeData, err := json.MarshalIndent(collection.Runtime, "", " ")
if err != nil {
return nil, err
}
if err := writeDiagnosticZipFile(archive, "context/runtime.json", append(runtimeData, byte(10))); err != nil {
return nil, err
}
if err := archive.Close(); err != nil {
return nil, err
}
return buffer.Bytes(), nil
}
func writeDiagnosticJSONL[T any](archive *zip.Writer, name string, records []T) error {
var data bytes.Buffer
for _, record := range records {
encoded, err := json.Marshal(record)
if err != nil {
return err
}
data.Write(encoded)
data.WriteByte(10)
}
return writeDiagnosticZipFile(archive, name, data.Bytes())
}
func writeDiagnosticZipFile(archive *zip.Writer, name string, data []byte) error {
file, err := archive.Create(name)
if err != nil {
return err
}
_, err = file.Write(data)
return err
}
func sanitizeDiagnosticIdentifier(value string) string {
value = strings.TrimSpace(value)
if value == "" || len(value) > 96 {
return ""
}
for _, char := range value {
if (char >= 'a' && char <= 'z') || (char >= 'A' && char <= 'Z') || (char >= '0' && char <= '9') || strings.ContainsRune("._:-", char) {
continue
}
return ""
}
return value
}
func sanitizeDiagnosticPath(value string) string {
value = strings.TrimSpace(value)
if value == "" {
return ""
}
if index := strings.IndexAny(value, "?#"); index >= 0 {
value = value[:index]
}
return redactDiagnosticText(value, 300)
}
func redactDiagnosticText(value string, limit int) string {
value = strings.TrimSpace(value)
if value == "" {
return ""
}
for _, marker := range []string{"authorization", "cookie", "set-cookie", "x-goog-api-key", "x-canvas-upstream-headers", "api_key", "api-key", "apikey", "access_key", "access-key", "secret_key", "secret-key", "password", "token="} {
value = redactDiagnosticMarker(value, marker)
}
return truncateRunes(redactDiagnosticURLs(value), limit)
}
func redactDiagnosticMarker(value string, marker string) string {
searchFrom := 0
for searchFrom < len(value) {
lower := strings.ToLower(value)
index := strings.Index(lower[searchFrom:], strings.ToLower(marker))
if index < 0 {
break
}
index += searchFrom
end := index + len(marker)
for end < len(value) && isDiagnosticSeparator(value[end]) {
end++
}
valueEnd := end
for valueEnd < len(value) && !isDiagnosticValueDelimiter(value[valueEnd]) {
valueEnd++
}
if valueEnd == end {
searchFrom = end
continue
}
value = value[:end] + "[REDACTED]" + value[valueEnd:]
searchFrom = end + len("[REDACTED]")
}
return value
}
func redactDiagnosticURLs(value string) string {
searchFrom := 0
for searchFrom < len(value) {
startHTTP := strings.Index(value[searchFrom:], "http://")
startHTTPS := strings.Index(value[searchFrom:], "https://")
start := -1
if startHTTP >= 0 {
start = startHTTP
}
if startHTTPS >= 0 && (start < 0 || startHTTPS < start) {
start = startHTTPS
}
if start < 0 {
break
}
start += searchFrom
end := start
for end < len(value) && !isDiagnosticURLDelimiter(value[end]) {
end++
}
raw := value[start:end]
parsed, err := url.Parse(raw)
if err != nil {
searchFrom = end
continue
}
parsed.RawQuery = ""
parsed.Fragment = ""
safe := parsed.String()
value = value[:start] + safe + value[end:]
searchFrom = start + len(safe)
}
return value
}
func isDiagnosticSeparator(value byte) bool {
return value == ' ' || value == 9 || value == ':' || value == '='
}
func isDiagnosticValueDelimiter(value byte) bool {
switch value {
case ' ', 9, 13, 10, ',', ';', '"', 39, '<', '>', '}', ']':
return true
default:
return false
}
}
func isDiagnosticURLDelimiter(value byte) bool {
return value == ' ' || value == 9 || value == 13 || value == 10 || value == '"' || value == 39 || value == '<' || value == '>'
}
func boundedDiagnosticInt(value int, min int, max int) int {
if value < min {
return min
}
if value > max {
return max
}
return value
}
func boundedDiagnosticInt64(value int64, min int64, max int64) int64 {
if value < min {
return min
}
if value > max {
return max
}
return value
}
@@ -0,0 +1,104 @@
package service
import (
"archive/zip"
"bytes"
"io"
"strings"
"testing"
"time"
"infinite-canvas/backend/internal/model"
"infinite-canvas/backend/internal/repository"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func TestExportDiagnosticBundleRedactsSensitiveValues(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:diagnostics-test?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Task{}, &model.TaskLog{}, &model.ApiCallLog{}); err != nil {
t.Fatal(err)
}
now := time.Now().UTC()
if err := db.Create(&model.Task{
ID: "task-1", UserID: "user-1", TraceID: "trace-1", RequestID: "req-1", ProjectID: "project-1", Type: "video_generate",
Status: model.TaskStatusFailed, Error: "authorization: task-secret", Prompt: "secret prompt", CreatedAt: now.Add(-time.Minute), UpdatedAt: now,
}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.TaskLog{ID: "task-log-1", UserID: "user-1", TaskID: "task-1", TraceID: "trace-1", Message: "任务失败", Payload: "apiKey=log-secret", CreatedAt: now}).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(&model.ApiCallLog{ID: "api-log-1", UserID: "user-1", TraceID: "trace-1", RequestID: "req-1", TaskID: "task-1", Path: "/v1/generations", RequestBody: "apiKey=body-secret", ResponseBody: "response-secret", UpstreamURL: "https://provider.example/result?signature=secret", Error: "token=api-secret", CreatedAt: now}).Error; err != nil {
t.Fatal(err)
}
svc := &Service{repo: repository.New(db)}
bundle, err := svc.ExportDiagnosticBundle("user-1", DiagnosticExportRequest{
From: now.Add(-2 * time.Minute).Format(time.RFC3339Nano), To: now.Add(time.Minute).Format(time.RFC3339Nano), TaskID: "task-1",
Description: "页面报错", ClientEvents: []DiagnosticClientEvent{{ID: "event-1", Message: "cookie=client-secret", TraceID: "trace-1"}},
})
if err != nil {
t.Fatal(err)
}
files := readDiagnosticTestZIP(t, bundle.Data)
manifest := files["manifest.json"]
if !strings.Contains(manifest, `"bundleId": "`+bundle.BundleID+`"`) {
t.Fatalf("manifest = %s", manifest)
}
all := strings.Join([]string{manifest, files["client/events.jsonl"], files["backend/tasks.jsonl"], files["backend/task-logs.jsonl"], files["backend/upstream-calls.jsonl"]}, "\n")
for _, secret := range []string{"task-secret", "secret prompt", "log-secret", "body-secret", "response-secret", "api-secret", "signature=secret", "client-secret"} {
if strings.Contains(all, secret) {
t.Fatalf("diagnostic bundle leaked %q: %s", secret, all)
}
}
if strings.Contains(files["backend/upstream-calls.jsonl"], "requestBody") || strings.Contains(files["backend/upstream-calls.jsonl"], "result?signature") {
t.Fatalf("upstream call contains excluded payload or query: %s", files["backend/upstream-calls.jsonl"])
}
}
func TestExportDiagnosticBundleRejectsForeignTask(t *testing.T) {
db, err := gorm.Open(sqlite.Open("file:diagnostics-ownership-test?mode=memory&cache=shared"), &gorm.Config{})
if err != nil {
t.Fatal(err)
}
if err := db.AutoMigrate(&model.Task{}); err != nil {
t.Fatal(err)
}
if err := db.Create(&model.Task{ID: "foreign-task", UserID: "user-2", CreatedAt: time.Now(), UpdatedAt: time.Now()}).Error; err != nil {
t.Fatal(err)
}
_, err = (&Service{repo: repository.New(db)}).ExportDiagnosticBundle("user-1", DiagnosticExportRequest{TaskID: "foreign-task"})
if err == nil || !strings.Contains(err.Error(), "任务不存在或无权访问") {
t.Fatalf("foreign task error = %v", err)
}
}
func readDiagnosticTestZIP(t *testing.T, data []byte) map[string]string {
t.Helper()
archive, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatal(err)
}
files := make(map[string]string, len(archive.File))
for _, file := range archive.File {
reader, err := file.Open()
if err != nil {
t.Fatal(err)
}
content, readErr := io.ReadAll(reader)
closeErr := reader.Close()
if readErr != nil {
t.Fatal(readErr)
}
if closeErr != nil {
t.Fatal(closeErr)
}
files[file.Name] = string(content)
}
return files
}
+12 -2
View File
@@ -73,6 +73,17 @@ func (item *EagleItem) UnmarshalJSON(data []byte) error {
return nil
}
func normalizeEagleStringSlice(values []string) []string {
normalized := make([]string, len(values))
copy(normalized, values)
return normalized
}
func normalizeEagleItemCollections(item *EagleItem) {
item.FolderIDs = normalizeEagleStringSlice(item.FolderIDs)
item.Tags = normalizeEagleStringSlice(item.Tags)
}
type EagleItemQuery struct {
FolderID string
Keyword string
@@ -168,8 +179,7 @@ func (s *Service) EagleItems(rawBaseURL string, query EagleItemQuery) ([]EagleIt
for index := range response.Data {
item := &response.Data[index]
item.Extension = strings.TrimPrefix(strings.ToLower(strings.TrimSpace(item.Extension)), ".")
item.FolderIDs = append([]string(nil), item.FolderIDs...)
item.Tags = append([]string(nil), item.Tags...)
normalizeEagleItemCollections(item)
}
return response.Data, nil
}
+15
View File
@@ -0,0 +1,15 @@
package service
import "testing"
func TestNormalizeEagleItemCollectionsKeepsEmptyArrays(t *testing.T) {
item := &EagleItem{}
normalizeEagleItemCollections(item)
if item.FolderIDs == nil || len(item.FolderIDs) != 0 {
t.Fatalf("folder IDs = %#v, want a non-nil empty slice", item.FolderIDs)
}
if item.Tags == nil || len(item.Tags) != 0 {
t.Fatalf("tags = %#v, want a non-nil empty slice", item.Tags)
}
}
+1
View File
@@ -11,6 +11,7 @@ type AppError struct {
Retryable bool
Cause error
}
func (e *AppError) Error() string {
if e == nil {
return ""
@@ -132,6 +132,30 @@ func TestCustomChannelTaskInputRequiresFeature(t *testing.T) {
}
}
func TestCreateTaskDoesNotClassifyCustomChannelAsMissingSystemModel(t *testing.T) {
svc, _ := newFeatureAvailabilityTestService(t)
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
if _, err := svc.UpdateFeatureAvailability(actor, FeatureAvailability{ShortDramaEnabled: true, TaskCenterEnabled: true, CreditsEnabled: true, CustomChannelsEnabled: false}); err != nil {
t.Fatal(err)
}
_, err := svc.CreateTask("user-1", CreateTaskRequest{
Type: "canvas_text",
Prompt: "test custom channel",
Input: map[string]any{
"mode": "text",
"config": providerConfig{BaseURL: "https://example.com/v1", APIKey: "private-key", Model: "text-model"},
},
})
if err == nil {
t.Fatal("CreateTask() error = nil")
}
var authErr *AuthError
if !errors.As(err, &authErr) || authErr.Message != "自定义渠道暂未开放" {
t.Fatalf("CreateTask() error = %#v, want custom channel feature error", err)
}
}
func TestTaskBillingOrderSkipsPricingWhenCreditsDisabled(t *testing.T) {
svc, _ := newFeatureAvailabilityTestService(t)
actor := &model.User{ID: "admin-1", Role: model.UserRoleAdmin}
@@ -19,7 +19,7 @@ func TestValidateChannelModelPriceSupportsArkVideoTokensOnly(t *testing.T) {
}
func TestHasValidPriceUsesChannelProtocolForTokenTiers(t *testing.T) {
tier := model.ChannelModelPriceTier{Enabled: true, BillingMode: "token", OutputTokenPriceMicrocredits: 16_000_000}
tier := model.ChannelModelPriceTier{Enabled: true, PriceConfigured: true, BillingMode: "token", OutputTokenPriceMicrocredits: 16_000_000}
ark := &model.ChannelModel{Capability: "video", Protocol: model.ChannelInterfaceVolcengineArkVideo, PriceTiers: []model.ChannelModelPriceTier{tier}}
if !HasValidPrice(ark) {
t.Fatal("Volcengine Ark video Token tier should be valid")
+4 -2
View File
@@ -143,6 +143,8 @@ type providerAnalyticsContext struct {
Billing taskBillingLifecycle
UserID string
TaskID string
TraceID string
RequestID string
BillingOrderID string
BillingMode string
Capability string
@@ -156,7 +158,7 @@ type providerAnalyticsContext struct {
}
func withProviderAnalytics(ctx context.Context, service *Service, task model.Task) context.Context {
metadata := providerAnalyticsContext{Service: service, UserID: task.UserID, TaskID: task.ID, BillingOrderID: task.BillingOrderID, Capability: capabilityFromTaskType(task.Type), Operation: task.Operation, Model: task.Model, ProviderRequestID: task.ProviderRequestID}
metadata := providerAnalyticsContext{Service: service, UserID: task.UserID, TaskID: task.ID, TraceID: task.TraceID, RequestID: task.RequestID, BillingOrderID: task.BillingOrderID, Capability: capabilityFromTaskType(task.Type), Operation: task.Operation, Model: task.Model, ProviderRequestID: task.ProviderRequestID}
if service != nil {
metadata.Billing = service.taskBilling()
}
@@ -4004,7 +4006,7 @@ func recordProviderRequest(req *http.Request, startedAt time.Time, statusCode in
apiFormat = "gemini"
}
callLog := model.ApiCallLog{
UserID: metadata.UserID, ChannelID: metadata.ChannelID, TaskID: metadata.TaskID, BillingOrderID: metadata.BillingOrderID,
UserID: metadata.UserID, TraceID: metadata.TraceID, RequestID: metadata.RequestID, ChannelID: metadata.ChannelID, TaskID: metadata.TaskID, BillingOrderID: metadata.BillingOrderID,
Source: "backend-task", Capability: metadata.Capability, Operation: metadata.Operation,
RequestKind: requestKind, Billable: req.Method == http.MethodPost && requestKind != "cancel",
APIFormat: apiFormat, Method: req.Method, Path: req.URL.Path, Model: metadata.Model,
@@ -83,7 +83,7 @@ func (s *Service) prepareArkPrivateAssetReferences(ctx context.Context, userID s
if resourceID == "" {
continue
}
resource, err := s.ResourceForUser(&model.User{ID: userID}, resourceID)
resource, err := s.Resource(userID, resourceID)
if err != nil {
return fmt.Errorf("读取方舟参考素材失败:%w", err)
}
@@ -142,7 +142,7 @@ func (s *Service) SyncResourceToArkPrivateAsset(ctx context.Context, actor *mode
if resourceID == "" {
return nil, BadAuthRequest("请选择要同步的图片素材")
}
resource, err := s.ResourceForUser(actor, resourceID)
resource, err := s.Resource(actor.ID, resourceID)
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, NotFound("图片素材不存在或无权访问")
}
@@ -221,7 +221,7 @@ func (s *Service) ensureArkPrivateAsset(ctx context.Context, userID string, reso
return "", s.failArkPrivateAssetBinding(binding, err)
}
binding.AssetGroupID = groupID
resourceURL, err := s.providerResourceURL(resource, time.Now().Add(time.Hour))
resourceURL, err := s.directResourceURL(resource, time.Now().Add(time.Hour))
if err != nil {
return "", s.failArkPrivateAssetBinding(binding, fmt.Errorf("生成方舟素材临时地址失败:%w", err))
}
+13 -1
View File
@@ -64,6 +64,8 @@ type CreateSessionRequest struct {
Characters []storyboardCharacterCard `json:"characters"`
Config providerConfig `json:"config"`
LogicalModelID string `json:"logicalModelId"`
TraceID string `json:"-"`
RequestID string `json:"-"`
}
type CreateTaskRequest struct {
@@ -76,6 +78,8 @@ type CreateTaskRequest struct {
Model string `json:"model"`
LogicalModelID string `json:"logicalModelId"`
Input map[string]any `json:"input"`
TraceID string `json:"-"`
RequestID string `json:"-"`
}
type SessionDetail struct {
@@ -267,7 +271,15 @@ func stringValue(value any) string {
}
func (s *Service) log(userID string, taskID string, level string, message string, payload string) error {
return s.repo.Create(&model.TaskLog{ID: newID(), UserID: userID, TaskID: taskID, Level: level, Message: message, Payload: truncateTaskLogPayload(payload)})
traceID := ""
requestID := ""
if taskID != "" {
if task, err := s.repo.Task(taskID); err == nil {
traceID = task.TraceID
requestID = task.RequestID
}
}
return s.repo.Create(&model.TaskLog{ID: newID(), UserID: userID, TaskID: taskID, TraceID: traceID, RequestID: requestID, Level: level, Message: message, Payload: truncateTaskLogPayload(payload)})
}
func truncateTaskLogPayload(payload string) string {
+1 -1
View File
@@ -49,7 +49,7 @@ func (w *sessionCreationCoordinator) create(userID string, req CreateSessionRequ
if err := w.persistDraft(userID, prompt, snapshotJSON, session, policy); err != nil {
return nil, err
}
taskReq := CreateTaskRequest{SessionID: session.ID, ProjectID: req.ProjectID, Type: "agent_storyboard", Operation: "storyboard", Prompt: prompt, Provider: "openai-compatible", Model: req.Config.Model, LogicalModelID: req.LogicalModelID, Input: map[string]any{"mode": "text", "references": req.References, "canvasSnapshot": compactedSnapshot, "requirements": req.Requirements, "canvasAssets": req.CanvasAssets, "projectStyle": req.ProjectStyle, "characters": req.Characters, "config": req.Config}}
taskReq := CreateTaskRequest{SessionID: session.ID, ProjectID: req.ProjectID, TraceID: req.TraceID, RequestID: req.RequestID, Type: "agent_storyboard", Operation: "storyboard", Prompt: prompt, Provider: "openai-compatible", Model: req.Config.Model, LogicalModelID: req.LogicalModelID, Input: map[string]any{"mode": "text", "references": req.References, "canvasSnapshot": compactedSnapshot, "requirements": req.Requirements, "canvasAssets": req.CanvasAssets, "projectStyle": req.ProjectStyle, "characters": req.Characters, "config": req.Config}}
if _, err := s.CreateTask(userID, taskReq); err != nil {
if cleanupErr := w.deleteDraft(userID, session.ID); cleanupErr != nil {
return nil, fmt.Errorf("创建会话任务失败:%v;清理会话失败:%w", err, cleanupErr)
+9 -5
View File
@@ -51,9 +51,13 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
if logicalModelID != "" {
return nil, ModelCatalogMismatch("模型目录已更新,请重新选择")
}
// 必须校验 channelId + model 属于启用的系统渠道模型
if err := s.validateSystemChannelModelSelection(normalizedInput); err != nil {
return nil, err
// 自定义渠道没有系统 channelId;它会在后续由自定义渠道功能开关、
// 能力校验和 provider 配置校验共同处理,不能误报为“缺少系统渠道”。
if !taskInputUsesCustomChannel(normalizedInput) {
// 非自定义任务必须校验 channelId + model 属于启用的系统渠道模型。
if err := s.validateSystemChannelModelSelection(normalizedInput); err != nil {
return nil, err
}
}
}
@@ -87,7 +91,7 @@ func (s *Service) CreateTask(userID string, req CreateTaskRequest) (*model.Task,
if activeTasks >= int64(policy.Task.ActiveTaskLimit) {
return nil, BadAuthRequest(fmt.Sprintf("同时排队或运行的任务最多 %d 个,请等待已有任务完成", policy.Task.ActiveTaskLimit))
}
task := model.Task{ID: newID(), UserID: userID, SessionID: req.SessionID, ProjectID: req.ProjectID, Type: taskType, Status: model.TaskStatusQueued, Stage: "等待队列调度", Progress: 5, Prompt: prompt, Operation: req.Operation, Provider: req.Provider, Model: req.Model}
task := model.Task{ID: newID(), UserID: userID, TraceID: req.TraceID, RequestID: req.RequestID, SessionID: req.SessionID, ProjectID: req.ProjectID, Type: taskType, Status: model.TaskStatusQueued, Stage: "等待队列调度", Progress: 5, Prompt: prompt, Operation: req.Operation, Provider: req.Provider, Model: req.Model}
if routed != nil {
task.LogicalModelID = routed.LogicalModel.ID
task.LogicalModelRevisionID = routed.Revision.ID
@@ -215,7 +219,7 @@ func (s *Service) createTextReplayTask(userID string, req CreateTaskRequest, nor
return nil, err
}
task := model.Task{
ID: newID(), UserID: userID, SessionID: req.SessionID, ProjectID: req.ProjectID,
ID: newID(), UserID: userID, TraceID: req.TraceID, RequestID: req.RequestID, SessionID: req.SessionID, ProjectID: req.ProjectID,
Type: taskType, Status: model.TaskStatusTextReplay, Stage: "文本持久化(前端自管)", Progress: 5,
Prompt: prompt, Operation: req.Operation, Provider: req.Provider, Model: strings.TrimSpace(req.Model),
}