From eb528d337de0e1897377872ded524348d6b2901d Mon Sep 17 00:00:00 2001 From: Scream034 Date: Sun, 22 Nov 2026 12:20:10 +0500 Subject: [PATCH 1/2] perf: store prompt media on disk and reduce memory usage --- internal/aistudio/upload.go | 8 + internal/aistudio/video_duration.go | 2 +- internal/api/admin_auth.go | 5 +- internal/api/errors.go | 23 +- internal/api/gemini.go | 4 +- internal/api/prompts.go | 61 ++++- internal/app/app.go | 11 +- internal/promptdb/promptdb.go | 314 +++++++++++++++++++++- web/src/api.ts | 8 + web/src/playground/CodeExecutionChunk.vue | 9 +- web/src/playground/FileChunk.vue | 31 ++- web/src/playground/GetCodeDialog.vue | 17 +- web/src/playground/PromptBox.vue | 32 ++- web/src/playground/attachment.ts | 100 ++++++- web/src/playground/media/VideoResult.vue | 19 +- web/src/playground/media/api.ts | 7 +- web/src/playground/pdf.ts | 7 +- web/src/playground/protocols.ts | 3 +- web/src/playground/request.ts | 48 +++- web/src/playground/session.ts | 212 ++++++++++++--- web/src/playground/types.ts | 2 +- 21 files changed, 810 insertions(+), 113 deletions(-) diff --git a/internal/aistudio/upload.go b/internal/aistudio/upload.go index 928dba04..4e44517a 100644 --- a/internal/aistudio/upload.go +++ b/internal/aistudio/upload.go @@ -1187,8 +1187,16 @@ func (s *PooledService) UploadInlineMediaToLease( drive := s.client.transport.(DriveTransport) uploadCtx, cancelUploads := context.WithCancel(targetCtx) resultChannel := make(chan uploadResult, len(pending)) + sem := make(chan struct{}, min(len(pending), 4)) for index, job := range pending { go func(index int, job uploadJob) { + select { + case sem <- struct{}{}: + case <-uploadCtx.Done(): + resultChannel <- uploadResult{index: index, err: uploadCtx.Err()} + return + } + defer func() { <-sem }() file, err := drive.UploadDrive(uploadCtx, targetID, token, UploadRequest{ AccountID: targetID, Name: job.name, diff --git a/internal/aistudio/video_duration.go b/internal/aistudio/video_duration.go index b56d6e44..59d20c31 100644 --- a/internal/aistudio/video_duration.go +++ b/internal/aistudio/video_duration.go @@ -28,7 +28,7 @@ func (scan *mp4Duration) Write(data []byte) (int, error) { take := min(int64(len(data)), scan.moovLeft) scan.moov, scan.moovLeft, data = append(scan.moov, data[:take]...), scan.moovLeft-take, data[take:] if scan.moovLeft == 0 { - scan.duration, scan.done = mvhdDuration(scan.moov), true + scan.duration, scan.done, scan.moov = mvhdDuration(scan.moov), true, nil } case scan.skip > 0: take := min(int64(len(data)), scan.skip) diff --git a/internal/api/admin_auth.go b/internal/api/admin_auth.go index 8e93304e..5e5da6de 100644 --- a/internal/api/admin_auth.go +++ b/internal/api/admin_auth.go @@ -132,7 +132,10 @@ func (auth *adminAuth) handler(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Cache-Control", "no-store") limit := int64(1 << 20) - if r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/api/prompts/") { + switch { + case r.Method == http.MethodPost && r.URL.Path == "/api/prompts/media": + limit = openAIFileMaxBytes + case r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/api/prompts/"): limit = maxPublicBodyBytes } r.Body = http.MaxBytesReader(w, r.Body, limit) diff --git a/internal/api/errors.go b/internal/api/errors.go index 0bab5b80..dd2f549e 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -27,9 +27,30 @@ type errorCodeProvider interface { ErrorCode() string } +// readRequestBody 读取请求正文,已知 ContentLength 时在上限内预分配缓冲 +func readRequestBody(r *http.Request, maxPrealloc int64) ([]byte, error) { + if r.ContentLength <= 0 || maxPrealloc <= 0 { + return io.ReadAll(r.Body) + } + buf := make([]byte, 0, min(r.ContentLength, maxPrealloc)+1) + for { + if len(buf) == cap(buf) { + buf = append(buf, 0)[:len(buf)] + } + n, err := r.Body.Read(buf[len(buf):cap(buf)]) + buf = buf[:len(buf)+n] + if errors.Is(err, io.EOF) { + return buf, nil + } + if err != nil { + return buf, err + } + } +} + // decodeJSON 把请求正文解码为一个 JSON 值;读取或解码失败时以同一正文与读取错误逐段解码,返回其错误 func decodeJSON(r *http.Request, target any) error { - body, readErr := io.ReadAll(r.Body) + body, readErr := readRequestBody(r, 1<<20) if readErr == nil && json.Unmarshal(body, target) == nil { return nil } diff --git a/internal/api/gemini.go b/internal/api/gemini.go index 1f30a0e5..b403c273 100644 --- a/internal/api/gemini.go +++ b/internal/api/gemini.go @@ -485,6 +485,7 @@ func (s *server) handleGeminiAction(w http.ResponseWriter, r *http.Request) { writeGeminiError(w, http.StatusBadRequest, "INVALID_ARGUMENT", err.Error()) return } + request.Contents, request.SystemInstruction = nil, nil cache, ok := s.applyGeminiCache(w, request.CachedContent, &generateRequest) if !ok { return @@ -521,7 +522,7 @@ func (s *server) handleGeminiAction(w http.ResponseWriter, r *http.Request) { // decodeGeminiJSON 读取请求体,按 proto3 JSON 规则统一字段名后解码到 target func decodeGeminiJSON(r *http.Request, target any) error { - body, err := io.ReadAll(r.Body) + body, err := readRequestBody(r, 8<<20) if err == nil { body, err = geminiCamelKeys(body) } @@ -1050,6 +1051,7 @@ func mapGeminiParts(input []geminiPart) ([]aistudio.Part, bool, error) { if err != nil { return nil, false, fmt.Errorf("inlineData.data: %w", err) } + inline.Data = "" mimeType, data := normalizeImagePayload(attachmentMIME(mime, inline.DisplayName, data), data) parts = append(parts, aistudio.Part{ InlineData: aistudio.NewBlob(mimeType, data), diff --git a/internal/api/prompts.go b/internal/api/prompts.go index c2c694a0..e9eaf9d1 100644 --- a/internal/api/prompts.go +++ b/internal/api/prompts.go @@ -4,9 +4,13 @@ import ( "context" "encoding/json" "errors" + "io" + "mime" "net/http" + "os" "regexp" "strconv" + "strings" "time" "github.com/Mag1cFall/AIStudio2API/internal/aistudio" @@ -48,7 +52,7 @@ type SystemInstructionPreset struct { Text string `json:"text"` } -// PromptStore 保存 Playground 对话与系统指令预设 +// PromptStore 保存 Playground 对话、附件媒体与系统指令预设 type PromptStore interface { Prompts(ctx context.Context, pageSize int, pageToken string) ([]PromptSummary, string, error) Prompt(context.Context, string) (Prompt, error) @@ -56,6 +60,8 @@ type PromptStore interface { RenamePrompt(ctx context.Context, id, title, description string) (PromptSummary, error) CopyPrompt(ctx context.Context, source, id, title string) (PromptSummary, error) DeletePrompt(context.Context, string) error + SaveMedia(ctx context.Context, mimeType string, content io.Reader) (string, error) + OpenMedia(ctx context.Context, id string) (*os.File, string, error) SystemInstructions(context.Context) ([]SystemInstructionPreset, error) SaveSystemInstruction(context.Context, SystemInstructionPreset) error DeleteSystemInstruction(context.Context, string) error @@ -65,6 +71,8 @@ func (s *server) registerPrompts(mux *http.ServeMux) { mux.HandleFunc("GET /api/prompts/system-instructions", s.handleSystemInstructions) mux.HandleFunc("PUT /api/prompts/system-instructions/{id}", s.handleSaveSystemInstruction) mux.HandleFunc("DELETE /api/prompts/system-instructions/{id}", s.handleDeleteSystemInstruction) + mux.HandleFunc("POST /api/prompts/media", s.handleUploadPromptMedia) + mux.HandleFunc("GET /api/prompts/media/{id}", s.handlePromptMedia) mux.HandleFunc("GET /api/prompts", s.handlePrompts) mux.HandleFunc("GET /api/prompts/{id}", s.handlePrompt) mux.HandleFunc("PUT /api/prompts/{id}", s.handleSavePrompt) @@ -214,6 +222,57 @@ func (s *server) handleDeletePrompt(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNoContent) } +// handleUploadPromptMedia 流式保存对话附件媒体并返回按内容计算的媒体 ID +func (s *server) handleUploadPromptMedia(w http.ResponseWriter, r *http.Request) { + mimeType := strings.TrimSpace(r.Header.Get("Content-Type")) + if parsed, _, err := mime.ParseMediaType(mimeType); err == nil && parsed != "" { + mimeType = parsed + } else { + mimeType = "application/octet-stream" + } + id, err := s.config.Prompts.SaveMedia(r.Context(), mimeType, r.Body) + if err != nil { + var maxBytes *http.MaxBytesError + if errors.As(err, &maxBytes) { + writeAdminError(w, http.StatusRequestEntityTooLarge, "file_too_large", "Attachment exceeds 512 MB") + return + } + writeAdminError(w, http.StatusInternalServerError, "prompt_store_failed", err.Error()) + return + } + writeJSON(w, http.StatusOK, map[string]string{"id": id}) +} + +// handlePromptMedia 流式返回已保存的对话附件媒体,支持浏览器 Range 播放与跳转 +func (s *server) handlePromptMedia(w http.ResponseWriter, r *http.Request) { + id := r.PathValue("id") + file, mimeType, err := s.config.Prompts.OpenMedia(r.Context(), id) + if err != nil { + writePromptError(w, err) + return + } + defer file.Close() + info, err := file.Stat() + if err != nil { + writeAdminError(w, http.StatusInternalServerError, "prompt_store_failed", err.Error()) + return + } + w.Header().Set("Content-Type", mimeType) + w.Header().Set("X-Frame-Options", "SAMEORIGIN") + if mimeType == "application/pdf" { + w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'") + } else { + w.Header().Set("Content-Security-Policy", "sandbox; frame-ancestors 'self'") + } + w.Header().Set("Cache-Control", "private, max-age=31536000, immutable") + if info.Size() == 0 { + w.Header().Set("Content-Length", "0") + w.WriteHeader(http.StatusOK) + return + } + http.ServeContent(w, r, id, info.ModTime(), file) +} + // handleSystemInstructions 返回保存在对话库中的系统指令预设列表 func (s *server) handleSystemInstructions(w http.ResponseWriter, r *http.Request) { presets, err := s.config.Prompts.SystemInstructions(r.Context()) diff --git a/internal/app/app.go b/internal/app/app.go index 986a0094..90caed60 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -380,13 +380,20 @@ func rootHandler(apiHandler http.Handler) http.Handler { return securityHeaders(root) } -// compressAdmin 以 gzip 压缩管理接口发给接受 gzip 的客户端的 JSON、CSV 与事件流响应 +// compressAdmin 以 gzip 压缩管理接口发给接受 gzip 的客户端的 JSON、CSV 与事件流响应,媒体流原样输出以支持 Range func compressAdmin(next http.Handler) http.Handler { wrap, err := gzhttp.NewWrapper(gzhttp.ContentTypes([]string{"application/json", "text/csv", "text/event-stream"})) if err != nil { panic(err) } - return wrap(next) + compressed := wrap(next) + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.HasPrefix(r.URL.Path, "/api/prompts/media/") { + next.ServeHTTP(w, r) + return + } + compressed.ServeHTTP(w, r) + }) } // securityHeaders 禁止页面被其他站点嵌入并关闭 MIME 嗅探与 Referer diff --git a/internal/promptdb/promptdb.go b/internal/promptdb/promptdb.go index e7a1042e..8d8c8458 100644 --- a/internal/promptdb/promptdb.go +++ b/internal/promptdb/promptdb.go @@ -1,17 +1,24 @@ -// Package promptdb 在本地 SQLite 中保存 Playground 对话 +// Package promptdb 在本地 SQLite 中保存 Playground 对话与附件媒体 package promptdb import ( + "bytes" "context" + "crypto/sha256" "database/sql" + "encoding/hex" "encoding/json" "errors" "fmt" + "io" + "io/fs" "math" "os" "path/filepath" + "regexp" "strconv" "strings" + "sync" "time" "github.com/Mag1cFall/AIStudio2API/internal/api" @@ -23,27 +30,41 @@ CREATE TABLE IF NOT EXISTS prompts ( id TEXT PRIMARY KEY, title TEXT NOT NULL, model TEXT NOT NULL, description TEXT NOT NULL, created INTEGER NOT NULL, updated INTEGER NOT NULL, data BLOB NOT NULL, turns INTEGER, tokens INTEGER); CREATE INDEX IF NOT EXISTS prompts_list ON prompts(updated, id, title, model, description, created, turns, tokens); +CREATE TABLE IF NOT EXISTS media ( + id TEXT PRIMARY KEY, mime TEXT NOT NULL, created INTEGER NOT NULL); +CREATE TABLE IF NOT EXISTS prompt_media ( + prompt_id TEXT NOT NULL, media_id TEXT NOT NULL, PRIMARY KEY (prompt_id, media_id)); +CREATE INDEX IF NOT EXISTS prompt_media_id ON prompt_media(media_id); CREATE TABLE IF NOT EXISTS system_instructions ( id TEXT PRIMARY KEY, title TEXT NOT NULL, text TEXT NOT NULL);` // summaryColumns 是对话列表项的列 const summaryColumns = `id, title, model, description, created, updated, turns, tokens` -// Store 读写对话库 +// mediaIDPattern 匹配按 SHA-256 命名的媒体 ID +var mediaIDPattern = regexp.MustCompile(`^[0-9a-f]{64}$`) + +// orphanMediaGrace 是未关联对话的临时媒体在 Reclaim 回收前的保留时长 +const orphanMediaGrace = 24 * time.Hour + +// Store 读写对话库与附件媒体目录 type Store struct { - db *sql.DB + db *sql.DB + mediaDir string + mediaMu sync.Mutex } // Open 打开或创建对话库 func Open(path string) (*Store, error) { - if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + dir := filepath.Dir(path) + if err := os.MkdirAll(dir, 0o755); err != nil { return nil, err } db, err := sqlitedb.Open(path, schema, 0) if err != nil { return nil, fmt.Errorf("初始化对话库: %w", err) } - return &Store{db: db}, nil + return &Store{db: db, mediaDir: filepath.Join(dir, "prompt-media")}, nil } // Close 关闭对话库 @@ -51,11 +72,103 @@ func (s *Store) Close() error { return s.db.Close() } -// Reclaim 把空闲页交还文件系统 +// Reclaim 回收过期无引用的附件媒体并把空闲页交还文件系统 func (s *Store) Reclaim(ctx context.Context) error { + cutoff := time.Now().Add(-orphanMediaGrace).UnixMilli() + rows, err := s.db.QueryContext(ctx, `SELECT m.id FROM media m +LEFT JOIN prompt_media pm ON pm.media_id = m.id +WHERE pm.media_id IS NULL AND m.created < ?`, cutoff) + if err == nil { + var orphans []string + for rows.Next() { + var id string + if scanErr := rows.Scan(&id); scanErr == nil { + orphans = append(orphans, id) + } + } + rowsErr := rows.Err() + _ = rows.Close() + if rowsErr == nil { + s.deleteUnreferencedMedia(ctx, orphans) + } + } return sqlitedb.Reclaim(ctx, s.db) } +// SaveMedia 流式写入附件媒体文件并返回按 SHA-256 计算的媒体 ID +func (s *Store) SaveMedia(ctx context.Context, mimeType string, content io.Reader) (string, error) { + if err := os.MkdirAll(s.mediaDir, 0o755); err != nil { + return "", err + } + tmp, err := os.CreateTemp(s.mediaDir, ".tmp-*") + if err != nil { + return "", err + } + tmpPath := tmp.Name() + cleanup := true + defer func() { + if cleanup { + _ = os.Remove(tmpPath) + } + }() + hasher := sha256.New() + if _, err := io.Copy(io.MultiWriter(tmp, hasher), content); err != nil { + _ = tmp.Close() + return "", err + } + if err := tmp.Close(); err != nil { + return "", err + } + id := hex.EncodeToString(hasher.Sum(nil)) + if mimeType == "" { + mimeType = "application/octet-stream" + } + finalPath := filepath.Join(s.mediaDir, id) + s.mediaMu.Lock() + defer s.mediaMu.Unlock() + moved := false + if _, err := os.Stat(finalPath); errors.Is(err, fs.ErrNotExist) { + if err := os.Rename(tmpPath, finalPath); err != nil { + return "", err + } + cleanup = false + moved = true + } else if err != nil { + return "", err + } + if _, err := s.db.ExecContext(ctx, `INSERT INTO media (id, mime, created) VALUES (?, ?, ?) +ON CONFLICT(id) DO UPDATE SET mime = excluded.mime, created = excluded.created`, id, mimeType, time.Now().UnixMilli()); err != nil { + if moved { + _ = os.Remove(finalPath) + } + return "", err + } + return id, nil +} + +// OpenMedia 打开已保存的附件媒体文件并返回其 MIME 类型 +func (s *Store) OpenMedia(ctx context.Context, id string) (*os.File, string, error) { + if !mediaIDPattern.MatchString(id) { + return nil, "", api.ErrPromptNotFound + } + var mimeType string + err := s.db.QueryRowContext(ctx, `SELECT mime FROM media WHERE id = ?`, id).Scan(&mimeType) + if errors.Is(err, sql.ErrNoRows) { + return nil, "", api.ErrPromptNotFound + } + if err != nil { + return nil, "", err + } + file, err := os.Open(filepath.Join(s.mediaDir, id)) + if errors.Is(err, fs.ErrNotExist) { + return nil, "", api.ErrPromptNotFound + } + if err != nil { + return nil, "", err + } + return file, mimeType, nil +} + // Prompts 按更新时间倒序列出对话,pageSize 为 0 时列出 pageToken 之后的全部,返回下一页的令牌,没有下一页时为空 func (s *Store) Prompts(ctx context.Context, pageSize int, pageToken string) ([]api.PromptSummary, string, error) { after, id := int64(math.MaxInt64), "" @@ -112,14 +225,52 @@ func (s *Store) Prompt(ctx context.Context, id string) (api.Prompt, error) { return prompt, nil } -// SavePrompt 创建或覆盖一份对话,保留首次创建时间 +// SavePrompt 创建或覆盖一份对话,保留首次创建时间并同步对话的媒体引用 func (s *Store) SavePrompt(ctx context.Context, prompt api.Prompt) (api.PromptSummary, error) { + mediaIDs := promptMediaRefs(prompt.Data) + s.mediaMu.Lock() + defer s.mediaMu.Unlock() + previous, err := s.promptMediaIDs(ctx, prompt.ID) + if err != nil { + return api.PromptSummary{}, err + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return api.PromptSummary{}, err + } now := time.Now().UnixMilli() - return scanSummary(s.db.QueryRowContext(ctx, `INSERT INTO prompts (id, title, model, description, created, updated, data, turns, tokens) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) + summary, err := scanSummary(tx.QueryRowContext(ctx, `INSERT INTO prompts (id, title, model, description, created, updated, data, turns, tokens) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET title = excluded.title, model = excluded.model, description = excluded.description, updated = excluded.updated, data = excluded.data, turns = excluded.turns, tokens = excluded.tokens RETURNING `+summaryColumns, prompt.ID, prompt.Title, prompt.Model, prompt.Description, now, now, []byte(prompt.Data), prompt.Turns, prompt.Tokens)) + if err != nil { + _ = tx.Rollback() + return api.PromptSummary{}, err + } + if _, err := tx.ExecContext(ctx, `DELETE FROM prompt_media WHERE prompt_id = ?`, prompt.ID); err != nil { + _ = tx.Rollback() + return api.PromptSummary{}, err + } + next := make(map[string]struct{}, len(mediaIDs)) + for _, id := range mediaIDs { + next[id] = struct{}{} + if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO prompt_media (prompt_id, media_id) VALUES (?, ?)`, prompt.ID, id); err != nil { + _ = tx.Rollback() + return api.PromptSummary{}, err + } + } + if err := tx.Commit(); err != nil { + return api.PromptSummary{}, err + } + var removed []string + for _, id := range previous { + if _, kept := next[id]; !kept { + removed = append(removed, id) + } + } + s.deleteUnreferencedMediaLocked(ctx, removed) + return summary, nil } // RenamePrompt 改写一份对话的标题与描述,不存在时返回 api.ErrPromptNotFound @@ -128,26 +279,74 @@ func (s *Store) RenamePrompt(ctx context.Context, id, title, description string) title, description, time.Now().UnixMilli(), id)) } -// CopyPrompt 以 id 与 title 复制 source 的模型、描述与内容,source 不存在时返回 api.ErrPromptNotFound +// CopyPrompt 以 id 与 title 复制 source 的模型、描述、内容与附件媒体引用,source 不存在时返回 api.ErrPromptNotFound func (s *Store) CopyPrompt(ctx context.Context, source, id, title string) (api.PromptSummary, error) { + s.mediaMu.Lock() + defer s.mediaMu.Unlock() + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return api.PromptSummary{}, err + } now := time.Now().UnixMilli() - return scanSummary(s.db.QueryRowContext(ctx, `INSERT INTO prompts (id, title, model, description, created, updated, data, turns, tokens) + summary, err := scanSummary(tx.QueryRowContext(ctx, `INSERT INTO prompts (id, title, model, description, created, updated, data, turns, tokens) SELECT ?, ?, model, description, ?, ?, data, turns, tokens FROM prompts WHERE id = ? RETURNING `+summaryColumns, id, title, now, now, source)) + if err != nil { + _ = tx.Rollback() + return api.PromptSummary{}, err + } + if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO prompt_media (prompt_id, media_id) +SELECT ?, media_id FROM prompt_media WHERE prompt_id = ?`, id, source); err != nil { + _ = tx.Rollback() + return api.PromptSummary{}, err + } + if err := tx.Commit(); err != nil { + return api.PromptSummary{}, err + } + return summary, nil } -// DeletePrompt 删除一份对话,不存在时返回 api.ErrPromptNotFound +// DeletePrompt 删除一份对话并清理不再被引用的附件媒体,不存在时返回 api.ErrPromptNotFound func (s *Store) DeletePrompt(ctx context.Context, id string) error { - result, err := s.db.ExecContext(ctx, `DELETE FROM prompts WHERE id = ?`, id) + if err := s.deletePromptLocked(ctx, id); err != nil { + return err + } + return sqlitedb.Reclaim(ctx, s.db) +} + +// deletePromptLocked 在媒体锁与事务内删除对话及其媒体引用并清理孤立文件 +func (s *Store) deletePromptLocked(ctx context.Context, id string) error { + s.mediaMu.Lock() + defer s.mediaMu.Unlock() + previous, err := s.promptMediaIDs(ctx, id) if err != nil { return err } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + result, err := tx.ExecContext(ctx, `DELETE FROM prompts WHERE id = ?`, id) + if err != nil { + _ = tx.Rollback() + return err + } if count, err := result.RowsAffected(); err != nil { + _ = tx.Rollback() return err } else if count == 0 { + _ = tx.Rollback() return api.ErrPromptNotFound } - return sqlitedb.Reclaim(ctx, s.db) + if _, err := tx.ExecContext(ctx, `DELETE FROM prompt_media WHERE prompt_id = ?`, id); err != nil { + _ = tx.Rollback() + return err + } + if err := tx.Commit(); err != nil { + return err + } + s.deleteUnreferencedMediaLocked(ctx, previous) + return nil } // SystemInstructions 按创建顺序读取保存的系统指令预设 @@ -181,6 +380,95 @@ func (s *Store) DeleteSystemInstruction(ctx context.Context, id string) error { return err } +// promptMediaRefs 提取对话轮次与对比窗格中引用的媒体 ID +func promptMediaRefs(data []byte) []string { + if !bytes.Contains(data, []byte(`"mediaId"`)) { + return nil + } + type turnList struct { + Turns []struct { + Parts []struct { + InlineData *struct { + MediaID string `json:"mediaId"` + } `json:"inlineData"` + } `json:"parts"` + } `json:"turns"` + } + var parsed struct { + turnList + Compare *turnList `json:"compare"` + } + if json.Unmarshal(data, &parsed) != nil { + return nil + } + seen := make(map[string]struct{}) + var ids []string + collect := func(list *turnList) { + if list == nil { + return + } + for _, turn := range list.Turns { + for _, part := range turn.Parts { + if part.InlineData == nil { + continue + } + id := part.InlineData.MediaID + if !mediaIDPattern.MatchString(id) { + continue + } + if _, ok := seen[id]; !ok { + seen[id] = struct{}{} + ids = append(ids, id) + } + } + } + } + collect(&parsed.turnList) + collect(parsed.Compare) + return ids +} + +// promptMediaIDs 返回对话当前关联的全部媒体 ID +func (s *Store) promptMediaIDs(ctx context.Context, promptID string) ([]string, error) { + rows, err := s.db.QueryContext(ctx, `SELECT media_id FROM prompt_media WHERE prompt_id = ?`, promptID) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +// deleteUnreferencedMedia 删除不再被任何对话引用的媒体记录与磁盘文件 +func (s *Store) deleteUnreferencedMedia(ctx context.Context, candidates []string) { + if len(candidates) == 0 { + return + } + s.mediaMu.Lock() + defer s.mediaMu.Unlock() + s.deleteUnreferencedMediaLocked(ctx, candidates) +} + +// deleteUnreferencedMediaLocked 在持有 mediaMu 时删除无引用的媒体记录与磁盘文件 +func (s *Store) deleteUnreferencedMediaLocked(ctx context.Context, candidates []string) { + for _, id := range candidates { + res, err := s.db.ExecContext(ctx, `DELETE FROM media WHERE id = ? AND NOT EXISTS (SELECT 1 FROM prompt_media WHERE media_id = ?)`, id, id) + if err != nil { + continue + } + if rows, err := res.RowsAffected(); err == nil && rows > 0 { + _ = os.Remove(filepath.Join(s.mediaDir, id)) + } + } +} + // scanSummary 读取一行对话列表项,没有行时返回 api.ErrPromptNotFound func scanSummary(row interface{ Scan(...any) error }) (api.PromptSummary, error) { var item api.PromptSummary diff --git a/web/src/api.ts b/web/src/api.ts index d22dc56f..73d28cec 100644 --- a/web/src/api.ts +++ b/web/src/api.ts @@ -268,6 +268,14 @@ export const api = { }), deletePrompt: (id: string) => requestCommand(`/api/prompts/${encodeURIComponent(id)}`, { method: 'DELETE' }), + uploadPromptMedia: async (file: Blob, mimeType: string) => + ( + await requestJSON<{ id: string }>('/api/prompts/media', { + method: 'POST', + headers: { 'Content-Type': mimeType || 'application/octet-stream' }, + body: file, + }) + ).id, generateTitle: async (model: string, prompt: string, answer: string) => ( await requestJSON<{ title: string }>('/api/prompts/title', { diff --git a/web/src/playground/CodeExecutionChunk.vue b/web/src/playground/CodeExecutionChunk.vue index 063e8964..38758bca 100644 --- a/web/src/playground/CodeExecutionChunk.vue +++ b/web/src/playground/CodeExecutionChunk.vue @@ -2,7 +2,7 @@ import { computed, ref } from 'vue' import { useI18n } from '@/i18n' import CodeBlock from './CodeBlock.vue' -import { dataURL } from './protocols' +import { attachmentURL } from './attachment' import ToolIoCard from './ToolIoCard.vue' import ToolStepRow from './ToolStepRow.vue' import type { Part } from './types' @@ -60,7 +60,12 @@ const output = computed(() => {
- +
diff --git a/web/src/playground/FileChunk.vue b/web/src/playground/FileChunk.vue index 4392e303..f08d3f3b 100644 --- a/web/src/playground/FileChunk.vue +++ b/web/src/playground/FileChunk.vue @@ -2,7 +2,7 @@ import { computed, onMounted, ref } from 'vue' import { useI18n } from '@/i18n' import UiIcon from '@/playground/ui/UiIcon.vue' -import { attachmentKind, attachmentName, attachmentURL } from './attachment' +import { attachmentKind, attachmentName, attachmentURL, loadAttachmentBlob } from './attachment' import { base64Bytes } from './bytes' import { pdfThumbnail } from './pdf' import { youtubeVideoID } from './sample-media' @@ -31,13 +31,28 @@ const thumbnail = ref('') const textPage = ref('') onMounted(async () => { const inline = props.part.inlineData - if (inline?.mimeType === 'application/pdf') - thumbnail.value = await pdfThumbnail(inline.data, 346).catch(() => '') - else if (inline?.mimeType.startsWith('text/')) - textPage.value = new TextDecoder() - .decode(base64Bytes(inline.data.slice(0, 8000))) - .replace(/\s+/g, ' ') - .slice(0, 5000) + if (inline?.mimeType === 'application/pdf') { + thumbnail.value = await pdfThumbnail(attachmentURL(props.part), 346).catch(() => '') + } else if (inline?.mimeType.startsWith('text/')) { + if (inline.mediaId) { + const response = await fetch(attachmentURL(props.part), { + headers: { Range: 'bytes=0-5999' }, + }).catch(() => undefined) + if (response?.ok) { + textPage.value = (await response.text()).replace(/\s+/g, ' ').slice(0, 5000) + } + } else if (inline.data === '') { + const blob = await loadAttachmentBlob(props.part).catch(() => undefined) + if (blob) { + textPage.value = (await blob.slice(0, 6000).text()).replace(/\s+/g, ' ').slice(0, 5000) + } + } else { + textPage.value = new TextDecoder() + .decode(base64Bytes(inline.data.slice(0, 8000))) + .replace(/\s+/g, ' ') + .slice(0, 5000) + } + } }) diff --git a/web/src/playground/GetCodeDialog.vue b/web/src/playground/GetCodeDialog.vue index ff7d5c75..b0d30236 100644 --- a/web/src/playground/GetCodeDialog.vue +++ b/web/src/playground/GetCodeDialog.vue @@ -41,11 +41,26 @@ const turns = computed(() => { // code 按语言生成当前对话的示例代码,请求与页面运行时以所选协议发送的请求相同 function code(language: CodeLanguage): string { const input = continuation(session.settings.protocol, turns.value) + let localIndex = 0 + const codeTurns = input.turns.map((turn) => ({ + ...turn, + parts: turn.parts.map((part) => + part.inlineData && part.inlineData.data === '' + ? { + ...part, + inlineData: { + ...part.inlineData, + data: btoa(`media:${part.inlineData.mediaId ?? ++localIndex}`), + }, + } + : part, + ), + })) return generateCode(language, { model: currentModel.value, modelID: currentModel.value?.id ?? session.settings.model, baseURL: window.location.origin, - request: buildRequest(session.settings, currentModel.value, input.turns), + request: buildRequest(session.settings, currentModel.value, codeTurns), protocol: session.settings.protocol, stream: session.settings.stream, images: { diff --git a/web/src/playground/PromptBox.vue b/web/src/playground/PromptBox.vue index 62921b11..34ba9074 100644 --- a/web/src/playground/PromptBox.vue +++ b/web/src/playground/PromptBox.vue @@ -1,5 +1,5 @@