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..8fd4f423 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,60 @@ 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, params, err := mime.ParseMediaType(mimeType); err == nil && parsed != "" {
+ if formatted := mime.FormatMediaType(parsed, params); formatted != "" {
+ mimeType = formatted
+ } else {
+ 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" || strings.HasPrefix(mimeType, "application/pdf;") {
+ w.Header().Set("Content-Security-Policy", "frame-ancestors 'self'")
+ } else {
+ w.Header().Set("Content-Security-Policy", "sandbox; frame-ancestors 'self'")
+ }
+ 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..29216b33 100644
--- a/internal/promptdb/promptdb.go
+++ b/internal/promptdb/promptdb.go
@@ -1,17 +1,23 @@
-// Package promptdb 在本地 SQLite 中保存 Playground 对话
+// Package promptdb 在本地 SQLite 中保存 Playground 对话与附件媒体
package promptdb
import (
"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 +29,45 @@ 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, pending INTEGER NOT NULL DEFAULT 0);
+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
+
+// orphanReclaimInterval 是运行期间触发未关联媒体回收的最小间隔
+const orphanReclaimInterval = time.Hour
+
+// Store 读写对话库与附件媒体目录
type Store struct {
- db *sql.DB
+ db *sql.DB
+ mediaDir string
+ mediaMu sync.Mutex
+ lastReclaim time.Time
}
// 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"), lastReclaim: time.Now()}, nil
}
// Close 关闭对话库
@@ -51,11 +75,156 @@ func (s *Store) Close() error {
return s.db.Close()
}
-// Reclaim 把空闲页交还文件系统
+// Reclaim 回收过期无引用与磁盘遗留的附件媒体,并把空闲页交还文件系统
func (s *Store) Reclaim(ctx context.Context) error {
+ s.mediaMu.Lock()
+ s.reclaimOrphanMediaLocked(ctx)
+ s.mediaMu.Unlock()
return sqlitedb.Reclaim(ctx, s.db)
}
+// reclaimOrphanMediaLocked 在持有 mediaMu 时回收过期无引用的媒体记录,以及磁盘上不在媒体表内或已过期的临时文件
+func (s *Store) reclaimOrphanMediaLocked(ctx context.Context) {
+ now := time.Now()
+ s.lastReclaim = now
+ cutoffTime := now.Add(-orphanMediaGrace)
+ cutoff := cutoffTime.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.deleteUnreferencedMediaLocked(ctx, orphans, cutoff)
+ }
+ }
+ entries, err := os.ReadDir(s.mediaDir)
+ if err != nil || len(entries) == 0 {
+ return
+ }
+ live := make(map[string]struct{})
+ liveRows, err := s.db.QueryContext(ctx, `SELECT id FROM media`)
+ if err != nil {
+ return
+ }
+ for liveRows.Next() {
+ var id string
+ if scanErr := liveRows.Scan(&id); scanErr == nil {
+ live[id] = struct{}{}
+ }
+ }
+ liveErr := liveRows.Err()
+ _ = liveRows.Close()
+ if liveErr != nil {
+ return
+ }
+ for _, entry := range entries {
+ if entry.IsDir() {
+ continue
+ }
+ name := entry.Name()
+ if mediaIDPattern.MatchString(name) {
+ if _, ok := live[name]; !ok {
+ _ = os.Remove(filepath.Join(s.mediaDir, name))
+ }
+ continue
+ }
+ if strings.HasPrefix(name, ".tmp-") {
+ if info, statErr := entry.Info(); statErr == nil && info.ModTime().Before(cutoffTime) {
+ _ = os.Remove(filepath.Join(s.mediaDir, name))
+ }
+ }
+ }
+}
+
+// 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, pending) VALUES (?, ?, ?, 1)
+ON CONFLICT(id) DO UPDATE SET
+ mime = CASE WHEN media.mime = '' OR media.mime = 'application/octet-stream' THEN excluded.mime ELSE media.mime END,
+ created = excluded.created,
+ pending = media.pending + 1`, id, mimeType, time.Now().UnixMilli()); err != nil {
+ if moved {
+ _ = os.Remove(finalPath)
+ }
+ return "", err
+ }
+ if time.Since(s.lastReclaim) >= orphanReclaimInterval {
+ s.reclaimOrphanMediaLocked(ctx)
+ }
+ 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 +281,75 @@ 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, err := promptMediaRefs(prompt.Data)
+ if err != nil {
+ return api.PromptSummary{}, err
+ }
+ 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
+ }
+ defer func() { _ = tx.Rollback() }()
+ for _, id := range mediaIDs {
+ var exists int
+ if err := tx.QueryRowContext(ctx, `SELECT 1 FROM media WHERE id = ?`, id).Scan(&exists); errors.Is(err, sql.ErrNoRows) {
+ return api.PromptSummary{}, fmt.Errorf("%w: media %s", api.ErrPromptNotFound, id)
+ } else 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 {
+ return api.PromptSummary{}, err
+ }
+ prevSet := make(map[string]struct{}, len(previous))
+ for _, id := range previous {
+ prevSet[id] = struct{}{}
+ }
+ next := make(map[string]struct{}, len(mediaIDs))
+ for _, id := range mediaIDs {
+ next[id] = struct{}{}
+ if _, had := prevSet[id]; had {
+ continue
+ }
+ res, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO prompt_media (prompt_id, media_id) VALUES (?, ?)`, prompt.ID, id)
+ if err != nil {
+ return api.PromptSummary{}, err
+ }
+ if rows, err := res.RowsAffected(); err == nil && rows > 0 {
+ if _, err := tx.ExecContext(ctx, `UPDATE media SET pending = MAX(0, pending - 1) WHERE id = ?`, id); err != nil {
+ return api.PromptSummary{}, err
+ }
+ }
+ }
+ var removed []string
+ for _, id := range previous {
+ if _, kept := next[id]; kept {
+ continue
+ }
+ removed = append(removed, id)
+ if _, err := tx.ExecContext(ctx, `DELETE FROM prompt_media WHERE prompt_id = ? AND media_id = ?`, prompt.ID, id); err != nil {
+ return api.PromptSummary{}, err
+ }
+ }
+ if err := tx.Commit(); err != nil {
+ return api.PromptSummary{}, err
+ }
+ s.deleteUnreferencedMediaLocked(ctx, removed, time.Now().Add(-orphanMediaGrace).UnixMilli())
+ return summary, nil
}
// RenamePrompt 改写一份对话的标题与描述,不存在时返回 api.ErrPromptNotFound
@@ -128,17 +358,54 @@ 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
+ }
+ defer func() { _ = tx.Rollback() }()
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 {
+ 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 {
+ 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
+ }
+ defer func() { _ = tx.Rollback() }()
+ result, err := tx.ExecContext(ctx, `DELETE FROM prompts WHERE id = ?`, id)
if err != nil {
return err
}
@@ -147,7 +414,14 @@ func (s *Store) DeletePrompt(ctx context.Context, id string) error {
} else if count == 0 {
return api.ErrPromptNotFound
}
- return sqlitedb.Reclaim(ctx, s.db)
+ if _, err := tx.ExecContext(ctx, `DELETE FROM prompt_media WHERE prompt_id = ?`, id); err != nil {
+ return err
+ }
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+ s.deleteUnreferencedMediaLocked(ctx, previous, time.Now().Add(-orphanMediaGrace).UnixMilli())
+ return nil
}
// SystemInstructions 按创建顺序读取保存的系统指令预设
@@ -181,6 +455,87 @@ func (s *Store) DeleteSystemInstruction(ctx context.Context, id string) error {
return err
}
+// promptMediaRefs 提取对话轮次与对比窗格中引用的媒体 ID,JSON 无效时返回错误以免误删旧引用
+func promptMediaRefs(data []byte) ([]string, error) {
+ if len(data) == 0 {
+ return nil, 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 err := json.Unmarshal(data, &parsed); err != nil {
+ return nil, fmt.Errorf("解析对话媒体引用: %w", err)
+ }
+ 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, nil
+}
+
+// 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()
+}
+
+// deleteUnreferencedMediaLocked 在持有 mediaMu 时删除无引用且已无待保存上传(或超过宽限期)的媒体记录与磁盘文件
+func (s *Store) deleteUnreferencedMediaLocked(ctx context.Context, candidates []string, cutoff int64) {
+ 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 = ?)
+AND (pending <= 0 OR created < ?)`, id, id, cutoff)
+ 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(() => {